{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "markdown-parse",
  "title": "Markdown parse",
  "description": "Markdown as a tree, CommonMark with GFM’s tables, task lists, strikethrough and autolinks, with every node’s offsets into the source. While the text streams, what is cut at its end is closed in the tree, and only the last block is parsed again. Raw HTML is kept as text.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/lib/markdown-parse.ts",
      "content": "/*\n * Markdown as a tree: CommonMark, with GFM's tables, task lists,\n * strikethrough and autolinks. Every node carries its offsets into the\n * source, so a mark can be placed on it. Raw HTML is kept as text.\n *\n * While the text streams, what is cut at its end is closed in the tree, not\n * patched in the string: an open fence is code still being written, an open\n * emphasis wraps what follows it, a half link shows its text, and a marker\n * that may still become something else waits for its next character.\n */\n\n/** A range of the source, from `from` up to `to`. */\nexport interface MarkdownRange {\n  from: number\n  to: number\n}\n\nexport type MarkdownInline =\n  | (MarkdownRange & { type: 'text'; value: string })\n  | (MarkdownRange & { type: 'code'; value: string })\n  | (MarkdownRange & {\n      type: 'emphasis' | 'strong' | 'delete'\n      children: MarkdownInline[]\n    })\n  | (MarkdownRange & {\n      type: 'link'\n      /** Null while the link's address is still arriving. */\n      href: string | null\n      title: string | null\n      children: MarkdownInline[]\n    })\n  | (MarkdownRange & {\n      type: 'image'\n      src: string\n      alt: string\n      title: string | null\n    })\n  | (MarkdownRange & { type: 'break' })\n\nexport type MarkdownAlign = 'left' | 'center' | 'right' | null\n\nexport interface MarkdownItem extends MarkdownRange {\n  /** A task's state, or null for a plain item. */\n  checked: boolean | null\n  children: MarkdownBlock[]\n}\n\nexport type MarkdownBlock =\n  | (MarkdownRange & { type: 'paragraph'; children: MarkdownInline[] })\n  | (MarkdownRange & {\n      type: 'heading'\n      depth: 1 | 2 | 3 | 4 | 5 | 6\n      children: MarkdownInline[]\n    })\n  | (MarkdownRange & {\n      type: 'code'\n      language: string | null\n      value: string\n      /** True while its closing fence hasn't arrived. */\n      open: boolean\n    })\n  | (MarkdownRange & { type: 'quote'; children: MarkdownBlock[] })\n  | (MarkdownRange & {\n      type: 'list'\n      ordered: boolean\n      start: number\n      tight: boolean\n      items: MarkdownItem[]\n    })\n  | (MarkdownRange & {\n      type: 'table'\n      align: MarkdownAlign[]\n      head: MarkdownInline[][]\n      rows: MarkdownInline[][][]\n    })\n  | (MarkdownRange & { type: 'rule' })\n  | (MarkdownRange & { type: 'html'; value: string })\n\ninterface Definition {\n  href: string\n  title: string | null\n  /** Where it is defined in the source. */\n  at: number\n}\n\n/** A parsed text, which the next parse of the same text grown longer starts from. */\nexport interface MarkdownDocument {\n  source: string\n  streaming: boolean\n  blocks: MarkdownBlock[]\n  /** Where the line of each top-level block starts. */\n  starts: number[]\n  definitions: Map<string, Definition>\n}\n\n/* Characters and patterns */\n\nconst ESCAPABLE = '[!-/:-@[-`{-~]'\nconst ENTITY = '&(?:#[xX][a-fA-F0-9]{1,6}|#[0-9]{1,7}|[A-Za-z][A-Za-z0-9]{1,31});'\nconst reEscapeOrEntity = new RegExp(`\\\\\\\\${ESCAPABLE}|${ENTITY}`, 'g')\nconst reEntityHere = new RegExp(`^${ENTITY}`)\nconst reEscapable = new RegExp(`^${ESCAPABLE}`)\n\nconst TAG_NAME = '[A-Za-z][A-Za-z0-9-]*'\nconst ATTRIBUTE =\n  '(?:\\\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\\\s*=\\\\s*(?:[^\"\\'=<>`\\\\x00-\\\\x20]+|\\'[^\\']*\\'|\"[^\"]*\"))?)'\nconst OPEN_TAG = `<${TAG_NAME}${ATTRIBUTE}*\\\\s*/?>`\nconst CLOSE_TAG = `</${TAG_NAME}\\\\s*[>]`\nconst reHtmlTag = new RegExp(\n  `^(?:${OPEN_TAG}|${CLOSE_TAG}|<!-->|<!--->|<!--[\\\\s\\\\S]*?-->|[<][?][\\\\s\\\\S]*?[?][>]|<![A-Za-z][^>]*>|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>)`,\n  'i',\n)\nconst reHtmlBlockOpen = [\n  /^<(?:script|pre|textarea|style)(?:\\s|>|$)/i,\n  /^<!--/,\n  /^<[?]/,\n  /^<![A-Za-z]/,\n  /^<!\\[CDATA\\[/,\n  /^<[/]?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\\s|[/]?[>]|$)/i,\n  new RegExp(`^(?:${OPEN_TAG}|${CLOSE_TAG})\\\\s*$`, 'i'),\n]\nconst reHtmlBlockClose = [\n  /<\\/(?:script|pre|textarea|style)>/i,\n  /-->/,\n  /\\?>/,\n  />/,\n  /\\]\\]>/,\n]\n\nconst reThematicBreak = /^(?:\\*[ \\t]*){3,}$|^(?:_[ \\t]*){3,}$|^(?:-[ \\t]*){3,}$/\nconst reAtxHeading = /^#{1,6}(?:[ \\t]+|$)/\nconst reFenceOpen = /^`{3,}(?!.*`)|^~{3,}/\nconst reFenceClose = /^(?:`{3,}|~{3,})(?=[ \\t]*$)/\nconst reSetext = /^(?:=+|-+)[ \\t]*$/\n// eslint-disable-next-line no-control-regex -- CommonMark rules control characters out of an address\nconst reUriAutolink = /^<([a-zA-Z][a-zA-Z0-9.+-]{1,31}:[^<>\\x00-\\x20]*)>/\nconst reLinkTitle =\n  // eslint-disable-next-line no-control-regex -- CommonMark rules out NUL in a title\n  /^(?:\"(?:\\\\[\\s\\S]|[^\"\\\\\\x00])*\"|'(?:\\\\[\\s\\S]|[^'\\\\\\x00])*'|\\((?:\\\\[\\s\\S]|[^()\\\\\\x00])*\\))/\nconst reMaybeSpecial = /^[#`~*+_=<>0-9|:-]/\nconst reDelimiterRow = /^\\|?[ \\t]*:?-+:?[ \\t]*(?:\\|[ \\t]*:?-+:?[ \\t]*)*\\|?[ \\t]*$/\n\n// Named references a reply is likely to use; any other stays as written.\nconst NAMED: Record<string, string> = {\n  amp: '&',\n  lt: '<',\n  gt: '>',\n  quot: '\"',\n  apos: \"'\",\n  nbsp: '\\u00a0',\n  copy: '©',\n  reg: '®',\n  trade: '™',\n  hellip: '…',\n  mdash: '—',\n  ndash: '–',\n  lsquo: '‘',\n  rsquo: '’',\n  ldquo: '“',\n  rdquo: '”',\n  laquo: '«',\n  raquo: '»',\n  times: '×',\n  divide: '÷',\n  deg: '°',\n  plusmn: '±',\n  middot: '·',\n  bull: '•',\n  euro: '€',\n  pound: '£',\n  yen: '¥',\n  cent: '¢',\n  sect: '§',\n  para: '¶',\n  frac12: '½',\n  frac14: '¼',\n  frac34: '¾',\n  larr: '←',\n  rarr: '→',\n  uarr: '↑',\n  darr: '↓',\n  harr: '↔',\n  ne: '≠',\n  le: '≤',\n  ge: '≥',\n  infin: '∞',\n}\n\nfunction decodeEntity(entity: string): string {\n  const name = entity.slice(1, -1)\n  if (name[0] !== '#') return NAMED[name] ?? entity\n  const code =\n    name[1] === 'x' || name[1] === 'X'\n      ? parseInt(name.slice(2), 16)\n      : parseInt(name.slice(1), 10)\n  return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)\n    ? '\\ufffd'\n    : String.fromCodePoint(code)\n}\n\nfunction unescape(text: string): string {\n  return text.replace(reEscapeOrEntity, (match) =>\n    match[0] === '\\\\' ? match[1] : decodeEntity(match),\n  )\n}\n\n/** A reference's label as it is matched: case folded, its spaces collapsed. */\nfunction normalizeLabel(label: string): string {\n  return label.slice(1, -1).trim().replace(/\\s+/g, ' ').toLowerCase().toUpperCase()\n}\n\nfunction normalizeHref(href: string): string {\n  return href.replace(/%(?![0-9a-fA-F]{2})|[^\\w\\-.~:/?#@!$&'()*+,;=%]/g, (char) =>\n    char === '%' ? '%25' : encodeURIComponent(char),\n  )\n}\n\nconst isSpace = (char: string | undefined) => char === ' ' || char === '\\t'\n\n/* Blocks */\n\ntype Kind =\n  | 'document'\n  | 'quote'\n  | 'list'\n  | 'item'\n  | 'paragraph'\n  | 'heading'\n  | 'fence'\n  | 'indented'\n  | 'html'\n  | 'table'\n  | 'rule'\n\ninterface ListData {\n  ordered: boolean\n  marker: string\n  start: number\n  padding: number\n  offset: number\n}\n\ninterface Container {\n  kind: Kind\n  parent: Container | null\n  children: Container[]\n  open: boolean\n  from: number\n  to: number\n  /** The line it started on. */\n  line: number\n  lastLineBlank: boolean\n  checkedBlank: boolean\n  /** Text and the source offset of each of its characters. */\n  text: string\n  map: number[]\n  list?: ListData\n  level?: number\n  /** `named`: its opening line, which names the language, has ended. */\n  fence?: {\n    char: string\n    length: number\n    offset: number\n    closed: boolean\n    named: boolean\n  }\n  htmlType?: number\n  table?: { align: MarkdownAlign[]; rows: { text: string; map: number[] }[] }\n  checked?: boolean | null\n}\n\nfunction container(kind: Kind, parent: Container | null, from: number, line: number) {\n  const block: Container = {\n    kind,\n    parent,\n    children: [],\n    open: true,\n    from,\n    to: from,\n    line,\n    lastLineBlank: false,\n    checkedBlank: false,\n    text: '',\n    map: [],\n  }\n  parent?.children.push(block)\n  return block\n}\n\nconst acceptsLines = (kind: Kind) =>\n  kind === 'paragraph' ||\n  kind === 'fence' ||\n  kind === 'indented' ||\n  kind === 'html' ||\n  kind === 'table'\n\nconst canContain = (parent: Kind, child: Kind) =>\n  parent === 'document' || parent === 'quote' || parent === 'item'\n    ? child !== 'item'\n    : parent === 'list'\n      ? child === 'item'\n      : false\n\nclass BlockParser {\n  root: Container\n  tip: Container\n  oldTip: Container\n  lastMatched: Container\n  allClosed = true\n  definitions = new Map<string, Definition>()\n\n  line = ''\n  lineStart = 0\n  lineNumber = 0\n  offset = 0\n  column = 0\n  nextNonspace = 0\n  nextNonspaceColumn = 0\n  indent = 0\n  indented = false\n  blank = false\n  partialTab = false\n  previousLineEnd = 0\n  lineEnded = true\n\n  private base: number\n\n  constructor(base: number) {\n    this.base = base\n    this.root = container('document', null, base, 0)\n    this.tip = this.root\n    this.oldTip = this.root\n    this.lastMatched = this.root\n  }\n\n  findNextNonspace() {\n    let i = this.offset\n    let cols = this.column\n    let char: string | undefined\n    while ((char = this.line[i]) !== undefined) {\n      if (char === ' ') {\n        i++\n        cols++\n      } else if (char === '\\t') {\n        i++\n        cols += 4 - (cols % 4)\n      } else break\n    }\n    this.blank = char === undefined\n    this.nextNonspace = i\n    this.nextNonspaceColumn = cols\n    this.indent = cols - this.column\n    this.indented = this.indent >= 4\n  }\n\n  advanceNextNonspace() {\n    this.offset = this.nextNonspace\n    this.column = this.nextNonspaceColumn\n    this.partialTab = false\n  }\n\n  advanceOffset(count: number, columns: boolean) {\n    let char: string | undefined\n    while (count > 0 && (char = this.line[this.offset]) !== undefined) {\n      if (char === '\\t') {\n        const toTab = 4 - (this.column % 4)\n        if (columns) {\n          this.partialTab = toTab > count\n          const advance = toTab > count ? count : toTab\n          this.column += advance\n          this.offset += this.partialTab ? 0 : 1\n          count -= advance\n        } else {\n          this.partialTab = false\n          this.column += toTab\n          this.offset += 1\n          count -= 1\n        }\n      } else {\n        this.partialTab = false\n        this.offset += 1\n        this.column += 1\n        count -= 1\n      }\n    }\n  }\n\n  addLine() {\n    const tip = this.tip\n    if (this.partialTab) {\n      this.offset += 1\n      const toTab = 4 - (this.column % 4)\n      for (let i = 0; i < toTab; i++) {\n        tip.text += ' '\n        tip.map.push(this.lineStart + this.offset - 1)\n      }\n    }\n    tip.text += this.line.slice(this.offset) + '\\n'\n    for (let i = this.offset; i <= this.line.length; i++) tip.map.push(this.lineStart + i)\n  }\n\n  addChild(kind: Kind, from: number) {\n    while (!canContain(this.tip.kind, kind)) this.finalize(this.tip, this.previousLineEnd)\n    const block = container(kind, this.tip, from, this.lineNumber)\n    this.tip = block\n    return block\n  }\n\n  closeUnmatched() {\n    if (this.allClosed) return\n    while (this.oldTip !== this.lastMatched) {\n      const parent = this.oldTip.parent!\n      this.finalize(this.oldTip, this.previousLineEnd)\n      this.oldTip = parent\n    }\n    this.allClosed = true\n  }\n\n  /** 0: it goes on; 1: it doesn't; 2: it ended on this line. */\n  continues(block: Container): 0 | 1 | 2 {\n    switch (block.kind) {\n      case 'document':\n      case 'list':\n        return 0\n      case 'quote':\n        if (!this.indented && this.line[this.nextNonspace] === '>') {\n          this.advanceNextNonspace()\n          this.advanceOffset(1, false)\n          if (isSpace(this.line[this.offset])) this.advanceOffset(1, true)\n          return 0\n        }\n        return 1\n      case 'item': {\n        const list = block.list!\n        if (this.blank) {\n          if (block.children.length === 0) return 1\n          this.advanceNextNonspace()\n          return 0\n        }\n        if (this.indent >= list.offset + list.padding) {\n          this.advanceOffset(list.offset + list.padding, true)\n          return 0\n        }\n        return 1\n      }\n      case 'fence': {\n        const fence = block.fence!\n        const rest = this.line.slice(this.nextNonspace)\n        const close =\n          this.indent <= 3 && rest[0] === fence.char ? reFenceClose.exec(rest) : null\n        if (close && close[0].length >= fence.length) {\n          fence.closed = true\n          this.finalize(block, this.lineStart + this.line.length)\n          return 2\n        }\n        let skip = fence.offset\n        while (skip > 0 && isSpace(this.line[this.offset])) {\n          this.advanceOffset(1, true)\n          skip--\n        }\n        return 0\n      }\n      case 'indented':\n        if (this.indent >= 4) this.advanceOffset(4, true)\n        else if (this.blank) this.advanceNextNonspace()\n        else return 1\n        return 0\n      case 'html':\n        return this.blank && (block.htmlType === 6 || block.htmlType === 7) ? 1 : 0\n      case 'paragraph':\n      case 'table':\n        return this.blank ? 1 : 0\n      default:\n        return 1\n    }\n  }\n\n  /** 0: none; 1: a container started; 2: a leaf started. */\n  start(parent: Container): 0 | 1 | 2 {\n    const rest = this.line.slice(this.nextNonspace)\n    const from = this.lineStart + this.nextNonspace\n    const paragraphLike = parent.kind === 'paragraph' || parent.kind === 'table'\n    if (this.indented) {\n      if (this.tip.kind === 'paragraph' || this.tip.kind === 'table' || this.blank)\n        return 0\n      this.advanceOffset(4, true)\n      this.closeUnmatched()\n      this.addChild('indented', this.lineStart + this.offset)\n      return 2\n    }\n    const first = rest[0]\n    if (first === '>') {\n      this.advanceNextNonspace()\n      this.advanceOffset(1, false)\n      if (isSpace(this.line[this.offset])) this.advanceOffset(1, true)\n      this.closeUnmatched()\n      this.addChild('quote', from)\n      return 1\n    }\n    let match: RegExpExecArray | null\n    if (first === '#' && (match = reAtxHeading.exec(rest))) {\n      this.advanceNextNonspace()\n      this.advanceOffset(match[0].length, false)\n      this.closeUnmatched()\n      const heading = this.addChild('heading', from)\n      heading.level = match[0].trim().length\n      // The text, without the closing sequence of #s.\n      let text = this.line.slice(this.offset)\n      const start = this.lineStart + this.offset\n      text = text.replace(/^[ \\t]*#+[ \\t]*$/, '').replace(/[ \\t]+#+[ \\t]*$/, '')\n      const lead = text.length - text.trimStart().length\n      text = text.trim()\n      heading.text = text\n      heading.map = Array.from({ length: text.length }, (_, i) => start + lead + i)\n      this.advanceOffset(this.line.length - this.offset, false)\n      return 2\n    }\n    if ((first === '`' || first === '~') && (match = reFenceOpen.exec(rest))) {\n      this.closeUnmatched()\n      const fence = this.addChild('fence', from)\n      fence.fence = {\n        char: first,\n        length: match[0].length,\n        offset: this.indent,\n        closed: false,\n        named: this.lineEnded,\n      }\n      this.advanceNextNonspace()\n      this.advanceOffset(match[0].length, false)\n      return 2\n    }\n    if (first === '<') {\n      for (let type = 1; type <= 7; type++) {\n        if (reHtmlBlockOpen[type - 1].test(rest) && (type < 7 || !paragraphLike)) {\n          this.closeUnmatched()\n          this.addChild('html', from).htmlType = type\n          return 2\n        }\n      }\n    }\n    if (parent.kind === 'paragraph' && reSetext.test(rest)) {\n      this.closeUnmatched()\n      this.takeDefinitions(parent)\n      if (parent.text) {\n        parent.kind = 'heading'\n        parent.level = rest[0] === '=' ? 1 : 2\n        trimEnd(parent)\n        this.advanceOffset(this.line.length - this.offset, false)\n        return 2\n      }\n      return 0\n    }\n    if (reThematicBreak.test(rest)) {\n      this.closeUnmatched()\n      this.addChild('rule', from)\n      this.advanceOffset(this.line.length - this.offset, false)\n      return 2\n    }\n    if (\n      parent.kind === 'paragraph' &&\n      reDelimiterRow.test(rest) &&\n      this.startTable(parent, rest)\n    )\n      return 2\n    if (parent.kind === 'list' || !this.indented) {\n      const list = this.listMarker(parent)\n      if (list) {\n        this.closeUnmatched()\n        if (\n          this.tip.kind !== 'list' ||\n          this.tip.list!.ordered !== list.ordered ||\n          this.tip.list!.marker !== list.marker\n        ) {\n          this.addChild('list', from).list = list\n        }\n        this.addChild('item', from).list = list\n        return 1\n      }\n    }\n    return 0\n  }\n\n  listMarker(parent: Container): ListData | null {\n    const rest = this.line.slice(this.nextNonspace)\n    let match: RegExpExecArray | null\n    let data: ListData\n    if ((match = /^[*+-]/.exec(rest))) {\n      data = {\n        ordered: false,\n        marker: match[0],\n        start: 1,\n        padding: 0,\n        offset: this.indent,\n      }\n    } else if (\n      (match = /^(\\d{1,9})([.)])/.exec(rest)) &&\n      (parent.kind !== 'paragraph' || match[1] === '1')\n    ) {\n      data = {\n        ordered: true,\n        marker: match[2],\n        start: parseInt(match[1], 10),\n        padding: 0,\n        offset: this.indent,\n      }\n    } else return null\n    const next = this.line[this.nextNonspace + match[0].length]\n    if (next !== undefined && !isSpace(next)) return null\n    if (\n      parent.kind === 'paragraph' &&\n      !/\\S/.test(this.line.slice(this.nextNonspace + match[0].length))\n    )\n      return null\n    this.advanceNextNonspace()\n    this.advanceOffset(match[0].length, true)\n    const spacesColumn = this.column\n    const spacesOffset = this.offset\n    let char: string | undefined\n    do {\n      this.advanceOffset(1, true)\n      char = this.line[this.offset]\n    } while (this.column - spacesColumn < 5 && isSpace(char))\n    const blankItem = this.line[this.offset] === undefined\n    const spaces = this.column - spacesColumn\n    if (spaces >= 5 || spaces < 1 || blankItem) {\n      data.padding = match[0].length + 1\n      this.column = spacesColumn\n      this.offset = spacesOffset\n      this.partialTab = false\n      if (isSpace(this.line[this.offset])) this.advanceOffset(1, true)\n    } else {\n      data.padding = match[0].length + spaces\n    }\n    return data\n  }\n\n  startTable(paragraph: Container, delimiter: string): boolean {\n    const lines = splitLines(paragraph)\n    const header = lines.at(-1)!\n    const head = splitCells(header.text, header.map)\n    const align = splitCells(delimiter, []).map(({ text }): MarkdownAlign => {\n      const left = text.startsWith(':')\n      const right = text.endsWith(':')\n      return left && right ? 'center' : left ? 'left' : right ? 'right' : null\n    })\n    if (head.length !== align.length) return false\n    this.closeUnmatched()\n    // The lines above the header stay a paragraph.\n    const above = lines.slice(0, -1)\n    const parent = paragraph.parent!\n    if (above.length) {\n      paragraph.text = above.map((line) => line.text + '\\n').join('')\n      paragraph.map = above.flatMap((line) => [...line.map, line.end])\n      this.finalize(paragraph, header.map[0] - 1)\n      this.tip = parent\n    } else {\n      parent.children.pop()\n      this.tip = parent\n    }\n    const table = this.addChild('table', header.map[0] ?? header.end)\n    table.table = { align, rows: [{ text: header.text, map: header.map }] }\n    this.advanceOffset(this.line.length - this.offset, false)\n    return true\n  }\n\n  finalize(block: Container, end: number) {\n    const above = block.parent\n    block.open = false\n    block.to = Math.max(block.from, end)\n    if (block.kind === 'paragraph') {\n      this.takeDefinitions(block)\n      if (!block.text.trim()) above!.children.splice(above!.children.indexOf(block), 1)\n    } else if (block.kind === 'indented') {\n      const trimmed = block.text.replace(/(\\n[ \\t]*)+$/, '\\n')\n      block.text = trimmed\n      block.map.length = trimmed.length\n    }\n    this.tip = above ?? block\n  }\n\n  takeDefinitions(block: Container) {\n    let consumed: number\n    while (\n      block.text[0] === '[' &&\n      (consumed = this.definition(block.text, block.map[0]))\n    ) {\n      block.text = block.text.slice(consumed)\n      block.map = block.map.slice(consumed)\n    }\n  }\n\n  /** The length of a link reference definition at the start of `text`, or 0. */\n  definition(text: string, at: number): number {\n    const label = /^\\[(?:[^\\\\[\\]]|\\\\.){0,999}\\]/.exec(text)\n    if (!label || !/\\S/.test(label[0].slice(1, -1)) || text[label[0].length] !== ':')\n      return 0\n    const inline = new InlineParser(text, [], this.definitions, false)\n    inline.pos = label[0].length + 1\n    inline.spaces()\n    const href = inline.destination()\n    if (href === null) return 0\n    const beforeTitle = inline.pos\n    inline.spaces()\n    let title: string | null = null\n    if (inline.pos !== beforeTitle) title = inline.title()\n    if (title === null) inline.pos = beforeTitle\n    let end = /^[ \\t]*(?:\\n|$)/.exec(text.slice(inline.pos))\n    if (!end) {\n      if (title === null) return 0\n      title = null\n      inline.pos = beforeTitle\n      end = /^[ \\t]*(?:\\n|$)/.exec(text.slice(inline.pos))\n      if (!end) return 0\n    }\n    const key = normalizeLabel(label[0])\n    if (!this.definitions.has(key)) this.definitions.set(key, { href, title, at })\n    return inline.pos + end[0].length\n  }\n\n  incorporate(line: string, lineStart: number) {\n    this.line = line\n    this.lineStart = lineStart\n    this.offset = 0\n    this.column = 0\n    this.blank = false\n    this.partialTab = false\n    this.lineNumber += 1\n    this.oldTip = this.tip\n\n    let block: Container = this.root\n    let last: Container | undefined\n    while ((last = block.children.at(-1)) && last.open) {\n      this.findNextNonspace()\n      const result = this.continues(last)\n      if (result === 1) break\n      if (result === 2) {\n        this.previousLineEnd = lineStart + line.length\n        return\n      }\n      block = last\n    }\n    this.allClosed = block === this.oldTip\n    this.lastMatched = block\n\n    let matchedLeaf =\n      block.kind !== 'paragraph' && block.kind !== 'table' && acceptsLines(block.kind)\n    while (!matchedLeaf) {\n      this.findNextNonspace()\n      if (!this.indented && !reMaybeSpecial.test(line.slice(this.nextNonspace))) {\n        this.advanceNextNonspace()\n        break\n      }\n      const result = this.start(block)\n      if (result === 0) {\n        this.advanceNextNonspace()\n        break\n      }\n      block = this.tip\n      if (result === 2) matchedLeaf = true\n    }\n\n    if (!this.allClosed && !this.blank && this.tip.kind === 'paragraph') {\n      this.addLine()\n    } else {\n      this.closeUnmatched()\n      const kind = block.kind\n      if (this.blank && block.children.length) block.children.at(-1)!.lastLineBlank = true\n      const lastLineBlank =\n        this.blank &&\n        !(\n          kind === 'quote' ||\n          kind === 'fence' ||\n          (kind === 'item' && !block.children.length && block.line === this.lineNumber)\n        )\n      for (let up: Container | null = block; up; up = up.parent)\n        up.lastLineBlank = lastLineBlank\n      if (kind === 'table') {\n        // The delimiter row that started it is not a row.\n        if (block.line === this.lineNumber)\n          return void (this.previousLineEnd = lineStart + line.length)\n        const start = lineStart + this.offset\n        block.table!.rows.push({\n          text: line.slice(this.offset),\n          map: Array.from({ length: line.length - this.offset }, (_, i) => start + i),\n        })\n      } else if (acceptsLines(kind)) {\n        this.addLine()\n        if (\n          kind === 'html' &&\n          block.htmlType! <= 5 &&\n          reHtmlBlockClose[block.htmlType! - 1].test(line.slice(this.offset))\n        ) {\n          this.finalize(block, lineStart + line.length)\n        }\n      } else if (this.offset < line.length && !this.blank) {\n        this.addChild('paragraph', lineStart + this.nextNonspace)\n        this.advanceNextNonspace()\n        this.addLine()\n      }\n    }\n    this.previousLineEnd = lineStart + line.length\n  }\n\n  run(source: string) {\n    let lineStart = 0\n    while (lineStart < source.length) {\n      let end = source.indexOf('\\n', lineStart)\n      if (end === -1) end = source.length\n      this.lineEnded = end < source.length\n      this.incorporate(source.slice(lineStart, end), this.base + lineStart)\n      lineStart = end + 1\n    }\n    while (this.tip !== this.root) this.finalize(this.tip, this.base + source.length)\n    this.finalize(this.root, this.base + source.length)\n  }\n}\n\nfunction trimEnd(block: Container) {\n  const trimmed = block.text.replace(/[ \\t\\n]+$/, '')\n  block.text = trimmed.replace(/^[ \\t]+/gm, '')\n  // Leading spaces on each line go too, so the map is rebuilt line by line.\n  const map: number[] = []\n  let i = 0\n  for (const line of trimmed.split('\\n')) {\n    const lead = line.length - line.trimStart().length\n    for (let j = lead; j < line.length; j++) map.push(block.map[i + j])\n    map.push(block.map[i + line.length])\n    i += line.length + 1\n  }\n  map.length = block.text.length\n  block.map = map\n}\n\nfunction splitLines(block: Container) {\n  const lines: { text: string; map: number[]; end: number }[] = []\n  let start = 0\n  const text = block.text\n  while (start < text.length) {\n    const end = text.indexOf('\\n', start)\n    const stop = end === -1 ? text.length : end\n    lines.push({\n      text: text.slice(start, stop),\n      map: block.map.slice(start, stop),\n      end: block.map[stop] ?? block.map[stop - 1] + 1,\n    })\n    start = stop + 1\n  }\n  return lines\n}\n\n/** A table row's cells: split on pipes that aren't escaped or in code, each trimmed. */\nfunction splitCells(text: string, map: number[]) {\n  const cells: { text: string; map: number[] }[] = []\n  let i = 0\n  const trimmed = text.replace(/[ \\t]+$/, '')\n  let end = trimmed.length\n  while (i < end && isSpace(trimmed[i])) i++\n  if (trimmed[i] === '|') i++\n  if (end > i && trimmed[end - 1] === '|' && trimmed[end - 2] !== '\\\\') end--\n  let start = i\n  for (; i <= end; i++) {\n    if (i === end || (trimmed[i] === '|' && trimmed[i - 1] !== '\\\\')) {\n      let a = start\n      let b = i\n      while (a < b && isSpace(trimmed[a])) a++\n      while (b > a && isSpace(trimmed[b - 1])) b--\n      // An escaped pipe is a pipe in the cell.\n      let cell = ''\n      const cellMap: number[] = []\n      for (let j = a; j < b; j++) {\n        if (trimmed[j] === '\\\\' && trimmed[j + 1] === '|') continue\n        cell += trimmed[j]\n        cellMap.push(map[j])\n      }\n      cells.push({ text: cell, map: cellMap })\n      start = i + 1\n    }\n  }\n  return cells\n}\n\n/* Inlines */\n\ninterface Node {\n  inline: MarkdownInline\n  prev: Node | null\n  next: Node | null\n}\n\ninterface Delimiter {\n  char: string\n  count: number\n  original: number\n  node: Node\n  canOpen: boolean\n  canClose: boolean\n  prev: Delimiter | null\n  next: Delimiter | null\n}\n\ninterface Bracket {\n  node: Node\n  image: boolean\n  index: number\n  active: boolean\n  bracketAfter: boolean\n  delimiter: Delimiter | null\n  prev: Bracket | null\n}\n\nconst rePunctuation = /^[\\p{P}\\p{S}]/u\nconst reWhitespace = /^\\s/u\nconst reText = /^[^\\n`[\\]\\\\!<&*_~]+/\n\nclass InlineParser {\n  pos = 0\n  first: Node | null = null\n  last: Node | null = null\n  delimiters: Delimiter | null = null\n  brackets: Bracket | null = null\n  /** Where the cut end starts, when the text is still streaming. */\n  cut: number\n\n  s: string\n  private map: number[]\n  private definitions: Map<string, Definition>\n  private streaming: boolean\n\n  constructor(\n    s: string,\n    map: number[],\n    definitions: Map<string, Definition>,\n    streaming: boolean,\n  ) {\n    this.s = s\n    this.map = map\n    this.definitions = definitions\n    this.streaming = streaming\n    this.cut = s.length\n    if (streaming) {\n      // Markers at the very end may still become something else: they wait.\n      const tail = /(?:[*_~`[\\\\<]|!\\[?)+$/.exec(s)\n      if (tail) this.cut = tail.index\n      this.s = s.slice(0, this.cut)\n    }\n  }\n\n  at(i: number) {\n    if (i < this.map.length) return this.map[i]\n    return this.map.length ? this.map[this.map.length - 1] + 1 : 0\n  }\n\n  end(i: number) {\n    return i > 0 ? this.map[i - 1] + 1 : this.at(0)\n  }\n\n  peek() {\n    return this.s[this.pos]\n  }\n\n  spaces() {\n    const match = /^[ \\t]*(?:\\n[ \\t]*)?/.exec(this.s.slice(this.pos))!\n    this.pos += match[0].length\n    return true\n  }\n\n  append(inline: MarkdownInline): Node {\n    const node: Node = { inline, prev: this.last, next: null }\n    if (this.last) this.last.next = node\n    else this.first = node\n    this.last = node\n    return node\n  }\n\n  text(value: string, from: number, to: number) {\n    return this.append({ type: 'text', value, from: this.at(from), to: this.end(to) })\n  }\n\n  parse(): MarkdownInline[] {\n    while (this.pos < this.s.length) this.step()\n    this.processEmphasis(null, this.streaming)\n    if (this.streaming) this.closeCut()\n    return finish(collect(this.first), false)\n  }\n\n  step() {\n    const start = this.pos\n    const char = this.s[start]\n    let match: RegExpExecArray | null\n    switch (char) {\n      case '\\n':\n        return this.newline()\n      case '\\\\':\n        this.pos++\n        if (this.peek() === '\\n') {\n          this.pos++\n          this.append({ type: 'break', from: this.at(start), to: this.end(this.pos) })\n          this.skipLeadingSpaces()\n        } else if (this.peek() !== undefined && reEscapable.test(this.peek()!)) {\n          this.pos++\n          this.text(this.s[start + 1], start, this.pos)\n        } else this.text('\\\\', start, this.pos)\n        return\n      case '`':\n        return this.backticks()\n      case '*':\n      case '_':\n      case '~':\n        return this.delimiter(char)\n      case '[':\n        this.pos++\n        this.pushBracket(this.text('[', start, this.pos), start, false)\n        return\n      case '!':\n        this.pos++\n        if (this.peek() === '[') {\n          this.pos++\n          this.pushBracket(this.text('![', start, this.pos), start + 1, true)\n        } else this.text('!', start, this.pos)\n        return\n      case ']':\n        return this.closeBracket()\n      case '<':\n        if ((match = reUriAutolink.exec(this.s.slice(start)))) {\n          return this.autolink(match[0], match[1], normalizeHref(match[1]))\n        }\n        if (\n          (match =\n            /^<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/.exec(\n              this.s.slice(start),\n            ))\n        ) {\n          return this.autolink(match[0], match[1], 'mailto:' + normalizeHref(match[1]))\n        }\n        if ((match = reHtmlTag.exec(this.s.slice(start)))) {\n          this.pos += match[0].length\n          this.text(match[0], start, this.pos)\n          return\n        }\n        this.pos++\n        this.text('<', start, this.pos)\n        return\n      case '&':\n        if ((match = reEntityHere.exec(this.s.slice(start)))) {\n          this.pos += match[0].length\n          this.text(decodeEntity(match[0]), start, this.pos)\n        } else {\n          this.pos++\n          this.text('&', start, this.pos)\n        }\n        return\n      default:\n        match = reText.exec(this.s.slice(start))\n        this.pos += match ? match[0].length : 1\n        this.text(this.s.slice(start, this.pos), start, this.pos)\n    }\n  }\n\n  autolink(raw: string, label: string, href: string) {\n    const start = this.pos\n    this.pos += raw.length\n    this.append({\n      type: 'link',\n      href,\n      title: null,\n      from: this.at(start),\n      to: this.end(this.pos),\n      children: [\n        {\n          type: 'text',\n          value: label,\n          from: this.at(start + 1),\n          to: this.end(this.pos - 1),\n        },\n      ],\n    })\n  }\n\n  newline() {\n    const start = this.pos\n    this.pos++\n    const last = this.last?.inline\n    if (last?.type === 'text' && last.value.endsWith(' ')) {\n      const hard = last.value.endsWith('  ')\n      const kept = last.value.replace(/ +$/, '')\n      last.to -= last.value.length - kept.length\n      last.value = kept\n      if (!kept) this.remove(this.last!)\n      if (hard) {\n        this.append({ type: 'break', from: this.at(start), to: this.end(this.pos) })\n        this.skipLeadingSpaces()\n        return\n      }\n    }\n    this.text('\\n', start, this.pos)\n    this.skipLeadingSpaces()\n  }\n\n  skipLeadingSpaces() {\n    while (this.peek() === ' ') this.pos++\n  }\n\n  backticks() {\n    const start = this.pos\n    const ticks = /^`+/.exec(this.s.slice(start))![0]\n    const after = start + ticks.length\n    const re = /`+/g\n    re.lastIndex = after\n    let match: RegExpExecArray | null\n    while ((match = re.exec(this.s))) {\n      if (match[0].length === ticks.length) {\n        this.pos = match.index + ticks.length\n        this.code(this.s.slice(after, match.index), start, this.pos)\n        return\n      }\n    }\n    if (this.streaming && this.cut < Infinity) {\n      // A code span still being written: what has arrived is its code.\n      this.pos = this.s.length\n      this.code(this.s.slice(after), start, this.pos, true)\n      return\n    }\n    this.pos = after\n    this.text(ticks, start, after)\n  }\n\n  code(raw: string, start: number, end: number, open = false) {\n    let value = raw.replace(/\\n/g, ' ')\n    if (\n      !open &&\n      value.length > 2 &&\n      value[0] === ' ' &&\n      value.at(-1) === ' ' &&\n      /[^ ]/.test(value)\n    ) {\n      value = value.slice(1, -1)\n    }\n    this.append({ type: 'code', value, from: this.at(start), to: this.end(end) })\n  }\n\n  delimiter(char: string) {\n    const start = this.pos\n    while (this.s[this.pos] === char) this.pos++\n    const count = this.pos - start\n    const before = start === 0 ? '\\n' : this.s[start - 1]\n    const after = this.pos >= this.s.length ? '\\n' : this.s[this.pos]\n    const afterSpace = reWhitespace.test(after)\n    const afterPunct = rePunctuation.test(after)\n    const beforeSpace = reWhitespace.test(before)\n    const beforePunct = rePunctuation.test(before)\n    const leftFlanking = !afterSpace && (!afterPunct || beforeSpace || beforePunct)\n    const rightFlanking = !beforeSpace && (!beforePunct || afterSpace || afterPunct)\n    let canOpen = leftFlanking\n    let canClose = rightFlanking\n    if (char === '_') {\n      canOpen = leftFlanking && (!rightFlanking || beforePunct)\n      canClose = rightFlanking && (!leftFlanking || afterPunct)\n    }\n    if (char === '~' && count > 2) canOpen = canClose = false\n    const node = this.text(this.s.slice(start, this.pos), start, this.pos)\n    if (canOpen || canClose) {\n      const delimiter: Delimiter = {\n        char,\n        count,\n        original: count,\n        node,\n        canOpen,\n        canClose,\n        prev: this.delimiters,\n        next: null,\n      }\n      if (this.delimiters) this.delimiters.next = delimiter\n      this.delimiters = delimiter\n    }\n  }\n\n  removeDelimiter(delimiter: Delimiter) {\n    if (delimiter.prev) delimiter.prev.next = delimiter.next\n    if (delimiter.next) delimiter.next.prev = delimiter.prev\n    else this.delimiters = delimiter.prev\n  }\n\n  remove(node: Node) {\n    if (node.prev) node.prev.next = node.next\n    else this.first = node.next\n    if (node.next) node.next.prev = node.prev\n    else this.last = node.prev\n  }\n\n  /** Moves the nodes after `opener` and before `closer` into a new node between them. */\n  wrap(\n    opener: Node,\n    closer: Node | null,\n    inline: MarkdownInline & { children: MarkdownInline[] },\n  ) {\n    const children: MarkdownInline[] = []\n    let node = opener.next\n    while (node && node !== closer) {\n      children.push(node.inline)\n      node = node.next\n    }\n    inline.children = children\n    const wrapped: Node = { inline, prev: opener, next: closer }\n    opener.next = wrapped\n    if (closer) closer.prev = wrapped\n    else this.last = wrapped\n    return wrapped\n  }\n\n  /** Matches emphasis above `bottom`. Openers left unmatched stay on the stack when `keep` is set. */\n  processEmphasis(bottom: Delimiter | null, keep = false) {\n    const openersBottom: Record<string, Delimiter | null> = {}\n    let closer = this.delimiters\n    while (closer && closer.prev !== bottom) closer = closer.prev\n    while (closer) {\n      if (!closer.canClose) {\n        closer = closer.next\n        continue\n      }\n      const key = `${closer.char}${closer.canOpen ? 1 : 0}${closer.original % 3}`\n      let opener = closer.prev\n      let found = false\n      while (opener && opener !== bottom && opener !== openersBottom[key]) {\n        const oddMatch =\n          (closer.canOpen || opener.canClose) &&\n          closer.original % 3 !== 0 &&\n          (opener.original + closer.original) % 3 === 0\n        if (\n          opener.char === closer.char &&\n          opener.canOpen &&\n          !oddMatch &&\n          (closer.char !== '~' || opener.count === closer.count)\n        ) {\n          found = true\n          break\n        }\n        opener = opener.prev\n      }\n      const oldCloser = closer\n      if (found && opener) {\n        const used =\n          closer.char === '~'\n            ? closer.count\n            : closer.count >= 2 && opener.count >= 2\n              ? 2\n              : 1\n        const openerText = opener.node.inline as {\n          value: string\n          to: number\n          from: number\n        }\n        const closerText = closer.node.inline as {\n          value: string\n          to: number\n          from: number\n        }\n        opener.count -= used\n        closer.count -= used\n        openerText.value = openerText.value.slice(0, opener.count)\n        openerText.to -= used\n        closerText.value = closerText.value.slice(0, closer.count)\n        closerText.from += used\n        this.wrap(opener.node, closer.node, {\n          type: closer.char === '~' ? 'delete' : used === 2 ? 'strong' : 'emphasis',\n          from: openerText.to,\n          to: closerText.from,\n          children: [],\n        })\n        // Delimiters between the two are used up.\n        let between = closer.prev\n        while (between && between !== opener) {\n          const prev = between.prev\n          this.removeDelimiter(between)\n          between = prev\n        }\n        if (opener.count === 0) {\n          this.remove(opener.node)\n          this.removeDelimiter(opener)\n        }\n        if (closer.count === 0) {\n          const next = closer.next\n          this.remove(closer.node)\n          this.removeDelimiter(closer)\n          closer = next\n        }\n      } else {\n        closer = closer.next\n        if (!found) {\n          openersBottom[key] = oldCloser.prev\n          if (!oldCloser.canOpen) this.removeDelimiter(oldCloser)\n        }\n      }\n    }\n    if (keep) return\n    while (this.delimiters && this.delimiters !== bottom)\n      this.removeDelimiter(this.delimiters)\n  }\n\n  pushBracket(node: Node, index: number, image: boolean) {\n    if (this.brackets) this.brackets.bracketAfter = true\n    this.brackets = {\n      node,\n      image,\n      index: index + 1,\n      active: true,\n      bracketAfter: false,\n      delimiter: this.delimiters,\n      prev: this.brackets,\n    }\n  }\n\n  destination(): string | null {\n    const rest = this.s.slice(this.pos)\n    // eslint-disable-next-line no-control-regex -- CommonMark rules these characters out here\n    const angle = /^<(?:[^<>\\n\\\\\\x00]|\\\\.)*>/.exec(rest)\n    if (angle) {\n      this.pos += angle[0].length\n      return normalizeHref(unescape(angle[0].slice(1, -1)))\n    }\n    if (rest[0] === '<') return null\n    let depth = 0\n    let i = 0\n    for (; i < rest.length; i++) {\n      const char = rest[i]\n      if (char === '\\\\' && reEscapable.test(rest[i + 1] ?? '')) i++\n      else if (char === '(') depth++\n      else if (char === ')') {\n        if (depth === 0) break\n        depth--\n        // eslint-disable-next-line no-control-regex -- CommonMark rules these characters out here\n      } else if (/[\\x00-\\x20]/.test(char)) break\n    }\n    if (i === 0 && rest[0] !== ')') return null\n    if (depth !== 0) return null\n    this.pos += i\n    return normalizeHref(unescape(rest.slice(0, i)))\n  }\n\n  title(): string | null {\n    const match = reLinkTitle.exec(this.s.slice(this.pos))\n    if (!match) return null\n    this.pos += match[0].length\n    return unescape(match[0].slice(1, -1))\n  }\n\n  label(): number {\n    const match = /^\\[(?:[^\\\\[\\]]|\\\\.){0,999}\\]/s.exec(this.s.slice(this.pos))\n    return match ? match[0].length : 0\n  }\n\n  closeBracket() {\n    const start = this.pos\n    this.pos++\n    const opener = this.brackets\n    if (!opener) {\n      this.text(']', start, this.pos)\n      return\n    }\n    if (!opener.active) {\n      this.text(']', start, this.pos)\n      this.brackets = opener.prev\n      return\n    }\n    const after = this.pos\n    let href: string | null = null\n    let title: string | null = null\n    let matched = false\n    let pending = false\n    if (this.peek() === '(') {\n      this.pos++\n      this.spaces()\n      const dest = this.destination()\n      if (dest !== null) {\n        const beforeTitle = this.pos\n        this.spaces()\n        if (this.pos !== beforeTitle) title = this.title()\n        this.spaces()\n        if (this.peek() === ')') {\n          this.pos++\n          href = dest\n          matched = true\n        }\n      }\n      if (!matched && this.streaming && !this.s.slice(after).includes(')')) {\n        // The address is still arriving.\n        this.pos = this.s.length\n        matched = pending = true\n        title = null\n      }\n      if (!matched) this.pos = after\n    } else if (this.streaming && after === this.s.length) {\n      matched = pending = true\n    }\n    if (!matched) {\n      const beforeLabel = this.pos\n      const length = this.label()\n      let reference: string | null = null\n      if (length > 2) reference = this.s.slice(beforeLabel, beforeLabel + length)\n      else if (!opener.bracketAfter) reference = this.s.slice(opener.index - 1, start + 1)\n      this.pos = length ? beforeLabel + length : after\n      const definition = reference\n        ? this.definitions.get(normalizeLabel(reference))\n        : undefined\n      if (definition) {\n        href = definition.href\n        title = definition.title\n        matched = true\n      } else this.pos = after\n    }\n    if (!matched) {\n      this.brackets = opener.prev\n      this.text(']', start, after)\n      return\n    }\n    const from = this.at(opener.index - (opener.image ? 2 : 1))\n    const to = this.end(this.pos)\n    this.processEmphasis(opener.delimiter)\n    const children = finish(collect(opener.node.next), true)\n    const node: Node = {\n      inline: opener.image\n        ? { type: 'image', src: href ?? '', alt: plain(children), title, from, to }\n        : { type: 'link', href: pending ? null : href, title, from, to, children },\n      prev: null,\n      next: null,\n    }\n    // The link takes the place of everything from its opening bracket on.\n    const before = opener.node.prev\n    node.prev = before\n    if (before) before.next = node\n    else this.first = node\n    this.last = node\n    this.brackets = opener.prev\n    if (!opener.image) {\n      for (let up = this.brackets; up; up = up.prev) if (!up.image) up.active = false\n    }\n    if (pending && opener.image) this.remove(node)\n  }\n\n  /** Closes what is still open at the cut end of a streaming text. */\n  closeCut() {\n    // Brackets still open: the text after them is a link still being written.\n    const open: { node: Node; kind: 'bracket' | 'delimiter'; delimiter?: Delimiter }[] =\n      []\n    for (let bracket = this.brackets; bracket; bracket = bracket.prev) {\n      if (bracket.active) open.push({ node: bracket.node, kind: 'bracket' })\n    }\n    // Emphasis left open after processing: what follows the opener is its content.\n    for (let delimiter = this.delimiters; delimiter; delimiter = delimiter.prev) {\n      if (delimiter.canOpen && delimiter.count > 0)\n        open.push({ node: delimiter.node, kind: 'delimiter', delimiter })\n    }\n    // Innermost first: the one that starts last.\n    open.sort((a, b) => b.node.inline.from - a.node.inline.from)\n    for (const item of open) {\n      const marker = item.node.inline as { value: string; from: number; to: number }\n      if (item.kind === 'bracket') {\n        const image = marker.value === '!['\n        const wrapped = this.wrap(item.node, null, {\n          type: 'link',\n          href: null,\n          title: null,\n          from: marker.from,\n          to: this.end(this.s.length),\n          children: [],\n        })\n        this.remove(item.node)\n        if (image) this.remove(wrapped)\n        continue\n      }\n      const delimiter = item.delimiter!\n      type Wrapper = Extract<MarkdownInline, { type: 'emphasis' | 'strong' | 'delete' }>\n      let inline: Wrapper\n      const make = (type: Wrapper['type']): Wrapper => ({\n        type,\n        from: marker.to,\n        to: this.end(this.s.length),\n        children: [],\n      })\n      if (delimiter.char === '~') inline = make('delete')\n      else inline = make(delimiter.count >= 2 ? 'strong' : 'emphasis')\n      this.wrap(item.node, null, inline)\n      if (delimiter.char !== '~' && delimiter.count >= 3) {\n        inline.children = [{ ...make('emphasis'), children: inline.children }]\n      }\n      this.remove(item.node)\n    }\n    this.delimiters = null\n    this.brackets = null\n  }\n}\n\nfunction collect(first: Node | null): MarkdownInline[] {\n  const list: MarkdownInline[] = []\n  for (let node = first; node; node = node.next) list.push(node.inline)\n  return list\n}\n\n/** Joins text runs that sit side by side in the source, drops empty ones, and finds bare links. */\nfunction finish(list: MarkdownInline[], inLink: boolean): MarkdownInline[] {\n  const out: MarkdownInline[] = []\n  for (const inline of list) {\n    if (inline.type === 'text') {\n      if (!inline.value) continue\n      const last = out.at(-1)\n      if (\n        last?.type === 'text' &&\n        last.to === inline.from &&\n        last.value.length === last.to - last.from &&\n        inline.value.length === inline.to - inline.from &&\n        inline.value !== '\\n' &&\n        last.value !== '\\n'\n      ) {\n        last.value += inline.value\n        last.to = inline.to\n        continue\n      }\n      out.push({ ...inline })\n    } else if ('children' in inline) {\n      inline.children = finish(inline.children, inLink || inline.type === 'link')\n      out.push(inline)\n    } else out.push(inline)\n  }\n  return inLink ? out : out.flatMap(bareLinks)\n}\n\nconst reBareLink =\n  /(?:^|(?<=[\\s*_~(]))(?:(?:https?:\\/\\/|www\\.)[\\w-]+(?:\\.[\\w-]+)*[^\\s<]*|[\\w.+-]+@[\\w-]+(?:\\.[\\w-]+)*\\.[\\w-]*[a-zA-Z0-9])/g\n\n/** GFM's autolinks: bare `www.`, `http://` and email addresses in plain text. */\nfunction bareLinks(inline: MarkdownInline): MarkdownInline[] {\n  if (inline.type !== 'text' || inline.value.length !== inline.to - inline.from)\n    return [inline]\n  const out: MarkdownInline[] = []\n  let last = 0\n  const value = inline.value\n  for (const match of value.matchAll(reBareLink)) {\n    let link = match[0]\n    const email = !/^(?:https?:\\/\\/|www\\.)/.test(link)\n    if (!email) {\n      // Trailing punctuation isn't part of the link, nor a parenthesis it doesn't open.\n      link = link.replace(/[?!.,:*_~]+$/, '')\n      while (link.endsWith(')') && count(link, '(') < count(link, ')'))\n        link = link.slice(0, -1)\n      link = link.replace(/&[a-zA-Z0-9]+;$/, '').replace(/[?!.,:*_~]+$/, '')\n      if (!/^(?:https?:\\/\\/|www\\.)[\\w-]+(?:\\.[\\w-]+)/.test(link)) continue\n      if (/_[^.]*\\.[^.]*$/.test(link.replace(/^(?:https?:\\/\\/)?/, '').split('/')[0]))\n        continue\n    } else if (/[-_]/.test(value[match.index + link.length] ?? '')) continue\n    const start = match.index\n    if (start > last)\n      out.push({\n        type: 'text',\n        value: value.slice(last, start),\n        from: inline.from + last,\n        to: inline.from + start,\n      })\n    const from = inline.from + start\n    const to = from + link.length\n    out.push({\n      type: 'link',\n      href: email ? 'mailto:' + link : link.startsWith('www.') ? 'http://' + link : link,\n      title: null,\n      from,\n      to,\n      children: [{ type: 'text', value: link, from, to }],\n    })\n    last = start + link.length\n  }\n  if (last === 0) return [inline]\n  if (last < value.length)\n    out.push({\n      type: 'text',\n      value: value.slice(last),\n      from: inline.from + last,\n      to: inline.to,\n    })\n  return out\n}\n\nconst count = (text: string, char: string) => text.split(char).length - 1\n\n/** The text of inlines with no marks, for an image's alt text. */\nexport function plain(list: MarkdownInline[]): string {\n  return list\n    .map((inline) =>\n      inline.type === 'text' || inline.type === 'code'\n        ? inline.value\n        : inline.type === 'image'\n          ? inline.alt\n          : inline.type === 'break'\n            ? '\\n'\n            : plain(inline.children),\n    )\n    .join('')\n}\n\n/* The tree */\n\nfunction inlines(\n  text: string,\n  map: number[],\n  definitions: Map<string, Definition>,\n  streaming: boolean,\n): MarkdownInline[] {\n  return new InlineParser(\n    text.replace(/[ \\t\\n]+$/, ''),\n    map,\n    definitions,\n    streaming,\n  ).parse()\n}\n\nfunction toBlocks(\n  block: Container,\n  definitions: Map<string, Definition>,\n  streamEnd: Container | null,\n): MarkdownBlock[] {\n  return block.children.flatMap((child): MarkdownBlock[] => {\n    const range = { from: child.from, to: child.to }\n    const cut = child === streamEnd\n    switch (child.kind) {\n      case 'paragraph':\n        return [\n          {\n            type: 'paragraph',\n            ...range,\n            children: inlines(\n              child.text.trim() ? child.text.replace(/^[ \\t]+/gm, '') : '',\n              mapWithoutIndent(child),\n              definitions,\n              cut,\n            ),\n          },\n        ]\n      case 'heading':\n        return [\n          {\n            type: 'heading',\n            ...range,\n            depth: child.level as 1 | 2 | 3 | 4 | 5 | 6,\n            children: inlines(child.text, child.map, definitions, cut),\n          },\n        ]\n      case 'fence': {\n        const newline = child.text.indexOf('\\n')\n        const info = unescape(\n          (newline === -1 ? child.text : child.text.slice(0, newline)).trim(),\n        )\n        const closedInfo = child.fence!.named || child.fence!.closed\n        return [\n          {\n            type: 'code',\n            ...range,\n            language: closedInfo ? info.split(/\\s+/)[0] || null : null,\n            value: newline === -1 ? '' : child.text.slice(newline + 1),\n            open: !child.fence!.closed,\n          },\n        ]\n      }\n      case 'indented':\n        return [\n          { type: 'code', ...range, language: null, value: child.text, open: false },\n        ]\n      case 'html':\n        return [{ type: 'html', ...range, value: child.text.replace(/\\n$/, '') }]\n      case 'rule':\n        return [{ type: 'rule', ...range }]\n      case 'quote':\n        return [\n          { type: 'quote', ...range, children: toBlocks(child, definitions, streamEnd) },\n        ]\n      case 'list':\n        return [\n          {\n            type: 'list',\n            ...range,\n            ordered: child.list!.ordered,\n            start: child.list!.start,\n            tight: isTight(child),\n            items: child.children.map((item) => toItem(item, definitions, streamEnd)),\n          },\n        ]\n      case 'table': {\n        const { align, rows } = child.table!\n        const cells = (row: { text: string; map: number[] }, last: boolean) => {\n          const split = splitCells(row.text, row.map).slice(0, align.length)\n          while (split.length < align.length) split.push({ text: '', map: [] })\n          return split.map((cell, i) =>\n            inlines(cell.text, cell.map, definitions, last && i === split.length - 1),\n          )\n        }\n        return [\n          {\n            type: 'table',\n            ...range,\n            align,\n            head: cells(rows[0], false),\n            rows: rows.slice(1).map((row, i) => cells(row, cut && i === rows.length - 2)),\n          },\n        ]\n      }\n      default:\n        return []\n    }\n  })\n}\n\nfunction mapWithoutIndent(block: Container): number[] {\n  const map: number[] = []\n  let atLineStart = true\n  for (let i = 0; i < block.text.length; i++) {\n    const char = block.text[i]\n    if (atLineStart && isSpace(char)) continue\n    atLineStart = char === '\\n'\n    map.push(block.map[i])\n  }\n  return map\n}\n\nfunction toItem(\n  item: Container,\n  definitions: Map<string, Definition>,\n  streamEnd: Container | null,\n): MarkdownItem {\n  const children = toBlocks(item, definitions, streamEnd)\n  let checked: boolean | null = null\n  const first = item.children[0]\n  const task =\n    first?.kind === 'paragraph'\n      ? /^\\[([ xX])\\](?=[ \\t\\n]|$)[ \\t]*/.exec(first.text)\n      : null\n  if (task && children[0]?.type === 'paragraph') {\n    checked = task[1] !== ' '\n    const end = first.map[task[0].length - 1] + 1\n    const paragraph = children[0]\n    paragraph.children = paragraph.children\n      .map((inline) => {\n        if (inline.to <= end) return null\n        if (inline.type === 'text' && inline.from < end) {\n          const cut = end - inline.from\n          return { ...inline, value: inline.value.slice(cut), from: end }\n        }\n        return inline\n      })\n      .filter((inline): inline is MarkdownInline => inline !== null)\n  }\n  return { from: item.from, to: item.to, checked, children }\n}\n\nfunction endsWithBlankLine(block: Container | undefined): boolean {\n  while (block) {\n    if (block.lastLineBlank) return true\n    if (!block.checkedBlank && (block.kind === 'list' || block.kind === 'item')) {\n      block.checkedBlank = true\n      block = block.children.at(-1)\n    } else {\n      block.checkedBlank = true\n      break\n    }\n  }\n  return false\n}\n\nfunction isTight(list: Container): boolean {\n  const items = list.children\n  for (let i = 0; i < items.length; i++) {\n    const item = items[i]\n    const nextItem = i < items.length - 1\n    if (endsWithBlankLine(item) && nextItem) return false\n    const children = item.children\n    for (let j = 0; j < children.length; j++) {\n      if (endsWithBlankLine(children[j]) && (nextItem || j < children.length - 1))\n        return false\n    }\n  }\n  return true\n}\n\n/** The leaf a streaming text is cut in: the last, when nothing but blank lines follows it. */\nfunction cutLeaf(root: Container, text: string, base: number): Container | null {\n  let last = root.children.at(-1)\n  while (last && last.children.length) last = last.children.at(-1)\n  return last && !/\\S/.test(text.slice(last.to - base)) ? last : null\n}\n\n/** A line still arriving that may turn into a different block once it ends, or a fence whose language is still arriving. */\nconst reUnsettledLine =\n  /^[ \\t>]*(?:[-=_*+]+|#{1,6}|[`~]{1,2}|`{3,}[^`]*|~{3,}.*|\\d{1,9}[.)]?|[|:\\- \\t]+|\\|.*|(?:[-*+]|\\d{1,9}[.)])[ \\t]+\\[[ xX]?\\]?)?[ \\t]*$/\n\nfunction parseBlocks(\n  source: string,\n  base: number,\n  streaming: boolean,\n  definitions: Map<string, Definition>,\n) {\n  let text = source\n  if (streaming) {\n    const lineStart = text.lastIndexOf('\\n') + 1\n    if (reUnsettledLine.test(text.slice(lineStart)) && text.slice(lineStart).trim()) {\n      text = text.slice(0, lineStart)\n    }\n  }\n  let parser = new BlockParser(base)\n  parser.definitions = new Map(definitions)\n  parser.run(text)\n  if (streaming) {\n    // A table's header waits for its delimiter row, so it never shows as text first.\n    const leaf = cutLeaf(parser.root, text, base)\n    if (leaf?.kind === 'paragraph') {\n      const lines = splitLines(leaf)\n      let keep = lines.length\n      while (keep > 0 && /^\\s*\\|/.test(lines[keep - 1].text)) keep--\n      if (keep < lines.length) {\n        const cutAt = lines[keep].map[0] - base\n        const lineStart = text.lastIndexOf('\\n', cutAt - 1) + 1\n        text = text.slice(0, lineStart)\n        parser = new BlockParser(base)\n        parser.definitions = new Map(definitions)\n        parser.run(text)\n      }\n    }\n  }\n  return { parser, cutEnd: streaming ? cutLeaf(parser.root, text, base) : null }\n}\n\n/**\n * Parses `source`. Given the parse of an earlier, shorter version of the same\n * text, only its last top-level block is parsed again, and the blocks before\n * it are the same objects as before.\n */\nexport function parseMarkdown(\n  source: string,\n  {\n    streaming = false,\n    previous,\n  }: { streaming?: boolean; previous?: MarkdownDocument } = {},\n): MarkdownDocument {\n  if (previous && previous.streaming && source.startsWith(previous.source)) {\n    const { blocks, starts } = previous\n    let last = blocks.length - 1\n    // A block that broke into a paragraph may turn back into its next line: the paragraph is parsed again too.\n    const before = blocks[last - 1]\n    if (\n      before?.type === 'paragraph' &&\n      !/\\n[ \\t]*\\n/.test(source.slice(before.to, starts[last]))\n    )\n      last--\n    const restart = starts[last] ?? 0\n    const kept = blocks.slice(0, last)\n    const keptStarts = starts.slice(0, last)\n    // The definitions above the last block hold; the last block's are found again.\n    const above = new Map([...previous.definitions].filter(([, { at }]) => at < restart))\n    const { parser, cutEnd } = parseBlocks(\n      source.slice(restart),\n      restart,\n      streaming,\n      above,\n    )\n    // A definition that is new or changed can turn text above into a link: parse it all again.\n    if (sameDefinitions(parser.definitions, previous.definitions)) {\n      const blocks = toBlocks(parser.root, parser.definitions, cutEnd)\n      return {\n        source,\n        streaming,\n        blocks: [...kept, ...blocks],\n        starts: [...keptStarts, ...lineStarts(source, parser.root)],\n        definitions: parser.definitions,\n      }\n    }\n  }\n  const { parser, cutEnd } = parseBlocks(source, 0, streaming, new Map())\n  return {\n    source,\n    streaming,\n    blocks: toBlocks(parser.root, parser.definitions, cutEnd),\n    starts: lineStarts(source, parser.root),\n    definitions: parser.definitions,\n  }\n}\n\nfunction sameDefinitions(a: Map<string, Definition>, b: Map<string, Definition>) {\n  if (a.size !== b.size) return false\n  for (const [key, value] of a) {\n    const other = b.get(key)\n    if (!other || other.href !== value.href || other.title !== value.title) return false\n  }\n  return true\n}\n\nfunction lineStarts(source: string, root: Container): number[] {\n  return root.children.map((child) => source.lastIndexOf('\\n', child.from - 1) + 1)\n}\n",
      "type": "registry:lib",
      "target": "@lib/markdown-parse.ts"
    }
  ],
  "type": "registry:lib"
}