'use strict';

require('../../../../unist-util-visit@4.1.2/node_modules/unist-util-visit/index.js');
require('../../../../unist-util-position@4.0.4/node_modules/unist-util-position/index.js');
require('../../../../unist-util-generated@2.0.1/node_modules/unist-util-generated/index.js');
require('../../../../mdast-util-definitions@5.1.2/node_modules/mdast-util-definitions/index.js');
var index = require('./handlers/index.js');
var index$1 = require('../../../../mdast-util-definitions@5.1.2/node_modules/mdast-util-definitions/lib/index.js');
var index$2 = require('../../../../unist-util-visit@4.1.2/node_modules/unist-util-visit/lib/index.js');
var index$3 = require('../../../../unist-util-generated@2.0.1/node_modules/unist-util-generated/lib/index.js');
var index$4 = require('../../../../unist-util-position@4.0.4/node_modules/unist-util-position/lib/index.js');

/**
 * @typedef {import('hast').Content} HastContent
 * @typedef {import('hast').Element} HastElement
 * @typedef {import('hast').ElementContent} HastElementContent
 * @typedef {import('hast').Properties} HastProperties
 * @typedef {import('hast').Root} HastRoot
 * @typedef {import('hast').Text} HastText
 *
 * @typedef {import('mdast').Content} MdastContent
 * @typedef {import('mdast').Definition} MdastDefinition
 * @typedef {import('mdast').FootnoteDefinition} MdastFootnoteDefinition
 * @typedef {import('mdast').Parent} MdastParent
 * @typedef {import('mdast').Root} MdastRoot
 */


const own = {}.hasOwnProperty;

/**
 * Create `state` from an mdast tree.
 *
 * @param {MdastNodes} tree
 *   mdast node to transform.
 * @param {Options | null | undefined} [options]
 *   Configuration.
 * @returns {State}
 *   `state` function.
 */
function createState(tree, options) {
  const settings = options || {};
  const dangerous = settings.allowDangerousHtml || false;
  /** @type {Record<string, MdastFootnoteDefinition>} */
  const footnoteById = {};

  // To do: next major: add `options` to state, remove:
  // `dangerous`, `clobberPrefix`, `footnoteLabel`, `footnoteLabelTagName`,
  // `footnoteLabelProperties`, `footnoteBackLabel`, `passThrough`,
  // `unknownHandler`.

  // To do: next major: move to `state.options.allowDangerousHtml`.
  state.dangerous = dangerous;
  // To do: next major: move to `state.options`.
  state.clobberPrefix =
    settings.clobberPrefix === undefined || settings.clobberPrefix === null
      ? 'user-content-'
      : settings.clobberPrefix;
  // To do: next major: move to `state.options`.
  state.footnoteLabel = settings.footnoteLabel || 'Footnotes';
  // To do: next major: move to `state.options`.
  state.footnoteLabelTagName = settings.footnoteLabelTagName || 'h2';
  // To do: next major: move to `state.options`.
  state.footnoteLabelProperties = settings.footnoteLabelProperties || {
    className: ['sr-only']
  };
  // To do: next major: move to `state.options`.
  state.footnoteBackLabel = settings.footnoteBackLabel || 'Back to content';
  // To do: next major: move to `state.options`.
  state.unknownHandler = settings.unknownHandler;
  // To do: next major: move to `state.options`.
  state.passThrough = settings.passThrough;

  state.handlers = {...index.handlers, ...settings.handlers};

  // To do: next major: replace utility with `definitionById` object, so we
  // only walk once (as we need footnotes too).
  state.definition = index$1.definitions(tree);
  state.footnoteById = footnoteById;
  /** @type {Array<string>} */
  state.footnoteOrder = [];
  /** @type {Record<string, number>} */
  state.footnoteCounts = {};

  state.patch = patch;
  state.applyData = applyData;
  state.one = oneBound;
  state.all = allBound;
  state.wrap = wrap;
  // To do: next major: remove `augment`.
  state.augment = augment;

  index$2.visit(tree, 'footnoteDefinition', (definition) => {
    const id = String(definition.identifier).toUpperCase();

    // Mimick CM behavior of link definitions.
    // See: <https://github.com/syntax-tree/mdast-util-definitions/blob/8290999/index.js#L26>.
    if (!own.call(footnoteById, id)) {
      footnoteById[id] = definition;
    }
  });

  // @ts-expect-error Hush, it’s fine!
  return state

  /**
   * Finalise the created `right`, a hast node, from `left`, an mdast node.
   *
   * @param {MdastNodeWithData | PositionLike | null | undefined} left
   * @param {HastElementContent} right
   * @returns {HastElementContent}
   */
  /* c8 ignore start */
  // To do: next major: remove.
  function augment(left, right) {
    // Handle `data.hName`, `data.hProperties, `data.hChildren`.
    if (left && 'data' in left && left.data) {
      /** @type {MdastData} */
      const data = left.data;

      if (data.hName) {
        if (right.type !== 'element') {
          right = {
            type: 'element',
            tagName: '',
            properties: {},
            children: []
          };
        }

        right.tagName = data.hName;
      }

      if (right.type === 'element' && data.hProperties) {
        right.properties = {...right.properties, ...data.hProperties};
      }

      if ('children' in right && right.children && data.hChildren) {
        right.children = data.hChildren;
      }
    }

    if (left) {
      const ctx = 'type' in left ? left : {position: left};

      if (!index$3.generated(ctx)) {
        // @ts-expect-error: fine.
        right.position = {start: index$4.pointStart(ctx), end: index$4.pointEnd(ctx)};
      }
    }

    return right
  }
  /* c8 ignore stop */

  /**
   * Create an element for `node`.
   *
   * @type {HFunctionProps}
   */
  /* c8 ignore start */
  // To do: next major: remove.
  function state(node, tagName, props, children) {
    if (Array.isArray(props)) {
      children = props;
      props = {};
    }

    // @ts-expect-error augmenting an element yields an element.
    return augment(node, {
      type: 'element',
      tagName,
      properties: props || {},
      children: children || []
    })
  }
  /* c8 ignore stop */

  /**
   * Transform an mdast node into a hast node.
   *
   * @param {MdastNodes} node
   *   mdast node.
   * @param {MdastParents | null | undefined} [parent]
   *   Parent of `node`.
   * @returns {HastElementContent | Array<HastElementContent> | null | undefined}
   *   Resulting hast node.
   */
  function oneBound(node, parent) {
    // @ts-expect-error: that’s a state :)
    return one(state, node, parent)
  }

  /**
   * Transform the children of an mdast node into hast nodes.
   *
   * @param {MdastNodes} parent
   *   mdast node to compile
   * @returns {Array<HastElementContent>}
   *   Resulting hast nodes.
   */
  function allBound(parent) {
    // @ts-expect-error: that’s a state :)
    return all(state, parent)
  }
}

/**
 * Copy a node’s positional info.
 *
 * @param {MdastNodes} from
 *   mdast node to copy from.
 * @param {HastNodes} to
 *   hast node to copy into.
 * @returns {void}
 *   Nothing.
 */
function patch(from, to) {
  if (from.position) to.position = index$4.position(from);
}

/**
 * Honor the `data` of `from` and maybe generate an element instead of `to`.
 *
 * @template {HastNodes} Type
 *   Node type.
 * @param {MdastNodes} from
 *   mdast node to use data from.
 * @param {Type} to
 *   hast node to change.
 * @returns {Type | HastElement}
 *   Nothing.
 */
function applyData(from, to) {
  /** @type {Type | HastElement} */
  let result = to;

  // Handle `data.hName`, `data.hProperties, `data.hChildren`.
  if (from && from.data) {
    const hName = from.data.hName;
    const hChildren = from.data.hChildren;
    const hProperties = from.data.hProperties;

    if (typeof hName === 'string') {
      // Transforming the node resulted in an element with a different name
      // than wanted:
      if (result.type === 'element') {
        result.tagName = hName;
      }
      // Transforming the node resulted in a non-element, which happens for
      // raw, text, and root nodes (unless custom handlers are passed).
      // The intent is likely to keep the content around (otherwise: pass
      // `hChildren`).
      else {
        result = {
          type: 'element',
          tagName: hName,
          properties: {},
          children: []
        };

        // To do: next major: take the children from the `root`, or inject the
        // raw/text/comment or so into the element?
        // if ('children' in node) {
        //   // @ts-expect-error: assume `children` are allowed in elements.
        //   result.children = node.children
        // } else {
        //   // @ts-expect-error: assume `node` is allowed in elements.
        //   result.children.push(node)
        // }
      }
    }

    if (result.type === 'element' && hProperties) {
      result.properties = {...result.properties, ...hProperties};
    }

    if (
      'children' in result &&
      result.children &&
      hChildren !== null &&
      hChildren !== undefined
    ) {
      // @ts-expect-error: assume valid children are defined.
      result.children = hChildren;
    }
  }

  return result
}

/**
 * Transform an mdast node into a hast node.
 *
 * @param {State} state
 *   Info passed around.
 * @param {MdastNodes} node
 *   mdast node.
 * @param {MdastParents | null | undefined} [parent]
 *   Parent of `node`.
 * @returns {HastElementContent | Array<HastElementContent> | null | undefined}
 *   Resulting hast node.
 */
// To do: next major: do not expose, keep bound.
function one(state, node, parent) {
  const type = node && node.type;

  // Fail on non-nodes.
  if (!type) {
    throw new Error('Expected node, got `' + node + '`')
  }

  if (own.call(state.handlers, type)) {
    return state.handlers[type](state, node, parent)
  }

  if (state.passThrough && state.passThrough.includes(type)) {
    // To do: next major: deep clone.
    // @ts-expect-error: types of passed through nodes are expected to be added manually.
    return 'children' in node ? {...node, children: all(state, node)} : node
  }

  if (state.unknownHandler) {
    return state.unknownHandler(state, node, parent)
  }

  return defaultUnknownHandler(state, node)
}

/**
 * Transform the children of an mdast node into hast nodes.
 *
 * @param {State} state
 *   Info passed around.
 * @param {MdastNodes} parent
 *   mdast node to compile
 * @returns {Array<HastElementContent>}
 *   Resulting hast nodes.
 */
// To do: next major: do not expose, keep bound.
function all(state, parent) {
  /** @type {Array<HastElementContent>} */
  const values = [];

  if ('children' in parent) {
    const nodes = parent.children;
    let index = -1;
    while (++index < nodes.length) {
      const result = one(state, nodes[index], parent);

      // To do: see if we van clean this? Can we merge texts?
      if (result) {
        if (index && nodes[index - 1].type === 'break') {
          if (!Array.isArray(result) && result.type === 'text') {
            result.value = result.value.replace(/^\s+/, '');
          }

          if (!Array.isArray(result) && result.type === 'element') {
            const head = result.children[0];

            if (head && head.type === 'text') {
              head.value = head.value.replace(/^\s+/, '');
            }
          }
        }

        if (Array.isArray(result)) {
          values.push(...result);
        } else {
          values.push(result);
        }
      }
    }
  }

  return values
}

/**
 * Transform an unknown node.
 *
 * @param {State} state
 *   Info passed around.
 * @param {MdastNodes} node
 *   Unknown mdast node.
 * @returns {HastText | HastElement}
 *   Resulting hast node.
 */
function defaultUnknownHandler(state, node) {
  const data = node.data || {};
  /** @type {HastText | HastElement} */
  const result =
    'value' in node &&
    !(own.call(data, 'hProperties') || own.call(data, 'hChildren'))
      ? {type: 'text', value: node.value}
      : {
          type: 'element',
          tagName: 'div',
          properties: {},
          children: all(state, node)
        };

  state.patch(node, result);
  return state.applyData(node, result)
}

/**
 * Wrap `nodes` with line endings between each node.
 *
 * @template {HastContent} Type
 *   Node type.
 * @param {Array<Type>} nodes
 *   List of nodes to wrap.
 * @param {boolean | null | undefined} [loose=false]
 *   Whether to add line endings at start and end.
 * @returns {Array<Type | HastText>}
 *   Wrapped nodes.
 */
function wrap(nodes, loose) {
  /** @type {Array<Type | HastText>} */
  const result = [];
  let index = -1;

  if (loose) {
    result.push({type: 'text', value: '\n'});
  }

  while (++index < nodes.length) {
    if (index) result.push({type: 'text', value: '\n'});
    result.push(nodes[index]);
  }

  if (loose && nodes.length > 0) {
    result.push({type: 'text', value: '\n'});
  }

  return result
}

exports.all = all;
exports.createState = createState;
exports.one = one;
exports.wrap = wrap;
//# sourceMappingURL=state.js.map
