import * as A from "fp-ts-esm/Array";
import { flow, pipe } from "fp-ts-esm/function";
import { RichContent } from "./../../../../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { createDecoration, initializeMetadata, reduceDecorations } from "../../../node-utils.js";
import { getChildNodes, toAst } from "./parse5-utils.js";
const contextOf = (rules, decorations, interceptorFn) => ({
  visit: visit(rules, decorations, interceptorFn),
  decorations: reduceDecorations(decorations),
  addDecoration: addDecoration(rules, decorations, interceptorFn)
});
const htmlToNodes = (rules, decorations, interceptorFn) => (contentNode) => {
  const filteredRules = rules.filter(([_if]) => {
    try {
      return !!contentNode && _if(contentNode);
    } catch (e) {
      console.error(e, contentNode);
      return false;
    }
  });
  if (filteredRules.length === 0) {
    const context = contextOf(rules, decorations, interceptorFn);
    return interceptorFn({ contentNode, context, result: [] });
  }
  return filteredRules.flatMap(([, then]) => {
    const context = contextOf(rules, decorations, interceptorFn);
    const result = then(context)(contentNode);
    return interceptorFn({ contentNode, context, result });
  });
};
const addDecoration = (rules, decorations, interceptorFn) => (type, data = {}, element) => {
  const decoration = createDecoration(type, data);
  return visit(rules, [decoration, ...decorations], interceptorFn)(element);
};
const visit = (rules, decorations, interceptorFn) => (element) => pipe(element, getChildNodes, A.chain(htmlToNodes(rules, decorations, interceptorFn)));
const traverse = (rules, interceptorFn) => visit(rules, [], interceptorFn);
const toRichContent = (nodes) => ({ nodes, metadata: initializeMetadata() });
const parser = (rules, interceptorFn) => flow(toAst, traverse(rules, interceptorFn), toRichContent, RichContent.fromJSON);
export {
  parser
};
//# sourceMappingURL=parser.js.map
