{"version":3,"file":"parseMarkup.mjs","sources":["../../../src/Markup/utils/parseMarkup.ts"],"sourcesContent":["import { ALLOWED_TAGS, ALLOWED_TARGETS, MAX_NESTING_DEPTH, TAG_ALIASES } from '../constants';\nimport { MarkupNode } from '../Markup.types';\n\nexport { MAX_NESTING_DEPTH };\nexport const MAX_INPUT_LENGTH = 10_000;\nexport const MAX_ACCESSIBILITY_LABEL_LENGTH = 250;\n\nconst OBJECT_PROTOTYPE_KEYS = new Set(Object.getOwnPropertyNames(Object.prototype));\n\n// eslint-disable-next-line regexp/no-control-character\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f-\\x9f]/g;\nconst HTML_METACHAR = /[<>\"']/g;\n\n/**\n * Matches opening and closing tags from the ALLOWED_TAGS allow-list.\n *\n * Capture groups:\n *  1. `/` if this is a closing tag, undefined otherwise\n *  2. Tag name\n *  3. Raw attribute string between the tag name and `>` (empty for closing tags)\n *\n * The lookahead `(?=[\\s>/])` after the tag name ensures we don't match partial\n * words — e.g. `<stronger>` won't be matched as `<strong>`.\n *\n * Global flag (`g`) allows iterative matching via `exec()`.\n */\nconst TAG_REGEX = new RegExp(\n  `<(\\\\/)?(${ALLOWED_TAGS.join('|')})(?=[\\\\s>/])((?:[^>\"']*(?:\"[^\"]*\"|'[^']*'))*[^>\"']*)>`,\n  'g',\n);\n\ntype Token =\n  | { type: 'text'; content: string }\n  | { type: 'newline' }\n  | { type: 'open'; tag: string; attrs: string }\n  | { type: 'close'; tag: string };\n\n/**\n * Splits the input string into a flat list of tokens by scanning for known tags.\n * Text between tags is emitted as text/newline tokens. Unrecognised tags are never\n * tokenised — they remain part of the surrounding text content.\n */\nfunction tokenise(input: string): Token[] {\n  const tokens: Token[] = [];\n  let lastIndex = 0;\n\n  TAG_REGEX.lastIndex = 0;\n  let match = TAG_REGEX.exec(input);\n\n  while (match !== null) {\n    if (match.index > lastIndex) {\n      pushTextWithNewlines(tokens, input.slice(lastIndex, match.index));\n    }\n\n    const isClose = match[1] === '/';\n    const tag = match[2];\n    const attrs = match[3] || '';\n\n    if (isClose) {\n      tokens.push({ type: 'close', tag });\n    } else {\n      tokens.push({ type: 'open', tag, attrs });\n    }\n\n    lastIndex = TAG_REGEX.lastIndex;\n    match = TAG_REGEX.exec(input);\n  }\n\n  if (lastIndex < input.length) {\n    pushTextWithNewlines(tokens, input.slice(lastIndex));\n  }\n\n  return tokens;\n}\n\n/** Splits a text fragment on newline characters, interleaving newline tokens between parts. */\nfunction pushTextWithNewlines(tokens: Token[], text: string): void {\n  const parts = text.split('\\n');\n  for (let index = 0; index < parts.length; index += 1) {\n    if (index > 0) {\n      tokens.push({ type: 'newline' });\n    }\n    if (parts[index]) {\n      tokens.push({ type: 'text', content: parts[index] });\n    }\n  }\n}\n\ntype ParseResult = { closed: true; nodes: MarkupNode[] } | { closed: false; nodes: MarkupNode[] };\n\n/**\n * Recursive descent parser that consumes tokens and builds a MarkupNode tree.\n *\n * When `untilTag` is provided, the function collects nodes until it finds a matching\n * close token — returning `{ closed: true }`. If it exhausts all tokens without finding\n * the close, it returns `{ closed: false }` so the caller can fall back to plain text\n * (graceful degradation for malformed input).\n *\n * The shared `position` object acts as a cursor across recursive calls, avoiding the\n * need to slice or copy the token array.\n */\nfunction parse(\n  tokens: Token[],\n  position: { index: number },\n  untilTag?: string,\n  depth = 0,\n): ParseResult {\n  const nodes: MarkupNode[] = [];\n\n  while (position.index < tokens.length) {\n    const token = tokens[position.index];\n\n    if (token.type === 'text') {\n      nodes.push({ type: 'text', content: token.content });\n      position.index += 1;\n    } else if (token.type === 'newline') {\n      nodes.push({ type: 'newline' });\n      position.index += 1;\n    } else if (token.type === 'close') {\n      if (token.tag === untilTag) {\n        position.index += 1;\n        return { closed: true, nodes };\n      }\n      // Mismatched close tag — render as literal text\n      nodes.push({ type: 'text', content: `</${token.tag}>` });\n      position.index += 1;\n    } else if (token.type === 'open') {\n      if (depth >= MAX_NESTING_DEPTH) {\n        nodes.push({ type: 'text', content: `<${token.tag}${token.attrs}>` });\n        position.index += 1;\n      } else {\n        position.index += 1;\n        const result = parse(tokens, position, token.tag, depth + 1);\n\n        if (result.closed) {\n          const node = buildNode(token.tag, token.attrs, result.nodes);\n          nodes.push(node);\n        } else {\n          nodes.push({ type: 'text', content: `<${token.tag}${token.attrs}>` });\n          nodes.push(...result.nodes);\n        }\n      }\n    }\n  }\n\n  if (untilTag) {\n    return { closed: false, nodes };\n  }\n\n  return { closed: true, nodes };\n}\n\n/**\n * Maps a raw tag name to a typed MarkupNode. Resolves aliases first (p→paragraph, a→link),\n * then builds the appropriate node shape. Link nodes carry full attributes; other element\n * nodes extract only accessibilityLabel.\n */\nfunction buildNode(rawTag: string, attrs: string, children: MarkupNode[]): MarkupNode {\n  const tag = TAG_ALIASES[rawTag] || rawTag;\n\n  if (tag === 'link') {\n    return { type: 'link', children, ...parseAttributes(attrs) };\n  }\n\n  if (tag === 'paragraph') {\n    return { type: 'paragraph', children };\n  }\n\n  const { accessibilityLabel } = parseAttributes(attrs);\n\n  return {\n    type: tag as MarkupNode['type'],\n    children,\n    ...(accessibilityLabel && { accessibilityLabel }),\n  } as MarkupNode;\n}\n\n/**\n * Matches allow-listed attributes from the raw attribute string captured by TAG_REGEX.\n * Requires whitespace before each attribute name to prevent matching inside quoted values.\n *\n * Example: for input ` href=\"https://wise.com\" target=\"_blank\"`\n *  - Match 1: groups = ['href', 'https://wise.com', undefined]\n *  - Match 2: groups = ['target', '_blank', undefined]\n *\n * Capture groups:\n *  1. Attribute name (href, action, target, or accessibilityLabel)\n *  2. Double-quoted value (if present)\n *  3. Single-quoted value (if present)\n */\nconst ATTR_REGEX = /(?<=\\s)(href|action|target|accessibilityLabel)=(?:\"([^\"]*)\"|'([^']*)')/g;\n\ntype ParsedAttributes = {\n  href?: string;\n  action?: string;\n  target?: string;\n  accessibilityLabel?: string;\n};\n\n/**\n * Extracts allowed attributes from a raw attribute string.\n * Supports both double- and single-quoted values. Any attribute not in the\n * allow-list (href, action, target, accessibilityLabel) is silently discarded.\n * First occurrence wins — duplicates are ignored.\n */\nfunction parseAttributes(attrs: string): ParsedAttributes {\n  const result: ParsedAttributes = {};\n  ATTR_REGEX.lastIndex = 0;\n  let match = ATTR_REGEX.exec(attrs);\n\n  while (match !== null) {\n    const key = match[1] as 'href' | 'action' | 'target' | 'accessibilityLabel';\n    const value = match[2] ?? match[3];\n\n    if (!(key in result)) {\n      const sanitized = sanitizeAttributeValue(key, value);\n      if (sanitized !== undefined) {\n        result[key] = sanitized;\n      }\n    }\n\n    match = ATTR_REGEX.exec(attrs);\n  }\n\n  return result;\n}\n\nfunction sanitizeAttributeValue(\n  key: 'href' | 'action' | 'target' | 'accessibilityLabel',\n  value: string,\n): string | undefined {\n  switch (key) {\n    case 'href':\n      return value.replace(CONTROL_CHARS, '');\n    case 'action':\n      if (OBJECT_PROTOTYPE_KEYS.has(value)) {\n        return undefined;\n      }\n      return value;\n    case 'target':\n      if (!ALLOWED_TARGETS.includes(value)) {\n        return undefined;\n      }\n      return value;\n    case 'accessibilityLabel':\n      return value.replace(HTML_METACHAR, '').slice(0, MAX_ACCESSIBILITY_LABEL_LENGTH);\n    default:\n      return undefined;\n  }\n}\n\n/** Entry point: tokenises the input string, then parses the token stream into a MarkupNode tree. */\nexport function parseMarkup(input: string): MarkupNode[] {\n  if (!input) {\n    return [];\n  }\n\n  if (input.length > MAX_INPUT_LENGTH) {\n    return [{ type: 'text', content: input }];\n  }\n\n  const tokens = tokenise(input);\n  const position = { index: 0 };\n  return parse(tokens, position).nodes;\n}\n"],"names":["MAX_INPUT_LENGTH","MAX_ACCESSIBILITY_LABEL_LENGTH","OBJECT_PROTOTYPE_KEYS","Set","Object","getOwnPropertyNames","prototype","CONTROL_CHARS","HTML_METACHAR","TAG_REGEX","RegExp","ALLOWED_TAGS","join","tokenise","input","tokens","lastIndex","match","exec","index","pushTextWithNewlines","slice","isClose","tag","attrs","push","type","length","text","parts","split","content","parse","position","untilTag","depth","nodes","token","closed","MAX_NESTING_DEPTH","result","node","buildNode","rawTag","children","TAG_ALIASES","parseAttributes","accessibilityLabel","ATTR_REGEX","key","value","sanitized","sanitizeAttributeValue","undefined","replace","has","ALLOWED_TARGETS","includes","parseMarkup"],"mappings":";;AAIO,MAAMA,gBAAgB,GAAG;AACzB,MAAMC,8BAA8B,GAAG;AAE9C,MAAMC,qBAAqB,GAAG,IAAIC,GAAG,CAACC,MAAM,CAACC,mBAAmB,CAACD,MAAM,CAACE,SAAS,CAAC,CAAC;AAEnF;AACA,MAAMC,aAAa,GAAG,uBAAuB;AAC7C,MAAMC,aAAa,GAAG,SAAS;AAE/B;;;;;;;;;;;;AAYG;AACH,MAAMC,SAAS,GAAG,IAAIC,MAAM,CAC1B,CAAA,QAAA,EAAWC,YAAY,CAACC,IAAI,CAAC,GAAG,CAAC,CAAA,qDAAA,CAAuD,EACxF,GAAG,CACJ;AAQD;;;;AAIG;AACH,SAASC,QAAQA,CAACC,KAAa,EAAA;EAC7B,MAAMC,MAAM,GAAY,EAAE;EAC1B,IAAIC,SAAS,GAAG,CAAC;EAEjBP,SAAS,CAACO,SAAS,GAAG,CAAC;AACvB,EAAA,IAAIC,KAAK,GAAGR,SAAS,CAACS,IAAI,CAACJ,KAAK,CAAC;EAEjC,OAAOG,KAAK,KAAK,IAAI,EAAE;AACrB,IAAA,IAAIA,KAAK,CAACE,KAAK,GAAGH,SAAS,EAAE;AAC3BI,MAAAA,oBAAoB,CAACL,MAAM,EAAED,KAAK,CAACO,KAAK,CAACL,SAAS,EAAEC,KAAK,CAACE,KAAK,CAAC,CAAC;AACnE,IAAA;AAEA,IAAA,MAAMG,OAAO,GAAGL,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;AAChC,IAAA,MAAMM,GAAG,GAAGN,KAAK,CAAC,CAAC,CAAC;AACpB,IAAA,MAAMO,KAAK,GAAGP,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE;AAE5B,IAAA,IAAIK,OAAO,EAAE;MACXP,MAAM,CAACU,IAAI,CAAC;AAAEC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