TypeScript
perf(web): chat Markdown parses about twice as fast with the same output (#27685)
Julius Marminge5b357b3b894e
diff --git a/apps/web/package.json b/apps/web/package.jsonindex b49479a9a6b..b2ad7e1c687 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -68,6 +68,8 @@"katex": "^0.16.47","lucide": "^0.564.0","lucide-react": "^0.564.0",+ "mdast-util-from-markdown": "^2.0.3",+ "micromark-util-combine-extensions": "^2.0.1","morphicons": "^1.7.1","pdfjs-dist": "6.4.299","pele": "^1.8.0",@@ -105,6 +107,7 @@"@vitejs/plugin-react": "^6.1.2","@vitest/browser-playwright": "5.0.5","compression": "^1.8.2",+ "micromark-util-types": "catalog:","oxc-transform-react": "~0.152.0","playwright": "1.60.0","tailwindcss": "^4.0.0",diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsxindex 53612806029..e5ba98d141f 100644--- a/apps/web/src/components/chat/markdownRenderer.test.tsx+++ b/apps/web/src/components/chat/markdownRenderer.test.tsx@@ -6,6 +6,7 @@ import { renderToStaticMarkup } from "react-dom/server";import ReactMarkdown from "react-markdown";import { describe, expect, it } from "vite-plus/test";+import { createIncrementalMarkdownPlugin } from "../../markdown-incremental";import { createMarkdownRenderer } from "./markdownRenderer";// Visible in the markup, so every URL attribute must pass through it.@@ -26,6 +27,14 @@ describe("createMarkdownRenderer", () => {"| a | b |\n| - | - |\n| <br> | [x](#frag) |\n\n- [ ] task\n- [x] done",'```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful <a>bare</a>',"Footnote[^1] and ~~strike~~\n\n[^1]: the note",+ // Each GFM construct the parser skips when its text cannot match, next to one that can.+ "Mail [email protected], see www.example.com and HTTPS://example.com/a, not [x](https://y.z).",+ "A table without pipes\n:--",+ "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done",+ "Escaped www\\.example.com and me@example.com",+ "\ufeffA byte order mark\n\n| a |\n| - |\n| b |",+ "> - | a |\r\n> | - |\r\n> | [email protected] |\r\n\n-\t[ ] tab\n\n ~~lazy~~",])("renders what react-markdown renders: %j", (source) => {const expected = renderToStaticMarkup(<ReactMarkdown@@ -41,6 +50,33 @@ describe("createMarkdownRenderer", () => {expect(render(source, true)).toBe(element);});+ it("renders what react-markdown renders while a reply streams through the incremental parser", () => {+ const reply =+ "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| [email protected] | www.x.io |\n\nDone ~~now~~.";+ // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update.+ const incremental = createIncrementalMarkdownPlugin();+ for (let end = 1; end <= reply.length; end++) {+ const source = reply.slice(0, end);+ const streamed = createMarkdownRenderer({+ remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental],+ rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS,+ components: {},+ urlTransform,+ })(source, false);+ expect(renderToStaticMarkup(streamed)).toBe(+ renderToStaticMarkup(+ <ReactMarkdown+ remarkPlugins={CHAT_MARKDOWN_REMARK_PLUGINS}+ rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}+ urlTransform={urlTransform}+ >+ {source}+ </ReactMarkdown>,+ ),+ );+ }+ });+it("keeps cached messages when one far larger than the cache is rendered", () => {const element = render("Kept *message*", true);render("x".repeat(600_000), true);diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.tsindex 4567152fa46..ab4083f2adf 100644--- a/apps/web/src/components/chat/markdownRenderer.ts+++ b/apps/web/src/components/chat/markdownRenderer.ts@@ -8,6 +8,8 @@ import remarkRehype from "remark-rehype";import { type PluggableList, unified } from "unified";import { VFile } from "vfile";+import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates";+export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string;interface MarkdownRendererOptions {@@ -50,6 +52,7 @@ export function createMarkdownRenderer({}: MarkdownRendererOptions) {const processor = unified().use(remarkParse)+ .use(remarkParseWithoutUnusedSyntax).use(remarkPlugins).use(remarkRehype, { allowDangerousHtml: true }).use(rehypePlugins)@@ -59,23 +62,24 @@ export function createMarkdownRenderer({// Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them.const prepare = (node: Nodes) => {if (!("children" in node)) return;- node.children.forEach((child, index) => {+ const { children } = node;+ for (let index = 0; index < children.length; index++) {+ const child = children[index]!;if (child.type === "raw") {- node.children[index] = { type: "text", value: child.value };- return;+ children[index] = { type: "text", value: child.value };+ continue;}- if (child.type === "element") {- for (const [key, tags] of Object.entries(urlAttributes)) {- if (- Object.hasOwn(child.properties, key) &&- (tags === null || tags.includes(child.tagName))- ) {- child.properties[key] = urlTransform(String(child.properties[key] || ""), key, child);- }+ if (child.type !== "element") continue;+ const { properties } = child;+ for (const key in properties) {+ if (!Object.hasOwn(urlAttributes, key)) continue;+ const tags = urlAttributes[key];+ if (tags === null || tags?.includes(child.tagName)) {+ properties[key] = urlTransform(String(properties[key] || ""), key, child);}}prepare(child);- });+ }};return (text: string, cache: boolean): ReactElement => {diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.tsnew file mode 100644index 00000000000..57587a51b9d--- /dev/null+++ b/apps/web/src/components/chat/markdownSyntaxGates.ts@@ -0,0 +1,204 @@+import type { Nodes as MdastNodes } from "mdast";+import {+ type Extension as MdastExtension,+ fromMarkdown,+ type Options as FromMarkdownOptions,+ type Transform,+} from "mdast-util-from-markdown";+import { combineExtensions } from "micromark-util-combine-extensions";+import type { Construct, Extension, TokenizeContext } from "micromark-util-types";+import type { Processor } from "unified";++// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent.+// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes.+const DELIMITER_LINE = /^[ \t>|:-]+$/gm;+const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line);+const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y;++function hasDelimiterRow(text: string) {+ for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true;+ return false;+}+const PROTOCOL = /https?:\/\//iy;+const WWW = /www\./iy;+const EMAIL_ATEXT = /[\w+.-]*@/y;++const matchesAt = (pattern: RegExp, text: string, offset: number) => {+ pattern.lastIndex = offset;+ return pattern.test(text);+};++interface Gate {+ readonly names: ReadonlyArray<string>;+ /** False when the construct cannot match anywhere in the text. */+ readonly inText: (text: string) => boolean;+ /** False when it cannot start at this offset, which keeps micromark from trying it there. */+ readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean;+}++// micromark tries these at every candidate character: email autolinks at every word, tables+// at every line. That is most of what GFM adds to a parse, and most texts cannot match them.+const GATES: ReadonlyArray<Gate> = [+ {+ names: ["emailAutolink"],+ inText: (text) => text.includes("@"),+ at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset),+ },+ {+ names: ["protocolAutolink"],+ inText: (text) => /https?:\/\//i.test(text),+ at: (_, text, offset) => matchesAt(PROTOCOL, text, offset),+ },+ {+ names: ["wwwAutolink"],+ inText: (text) => /www\./i.test(text),+ at: (_, text, offset) => matchesAt(WWW, text, offset),+ },+ {+ names: ["table"],+ inText: hasDelimiterRow,+ at: (context, text, offset) => {+ NEXT_LINE.lastIndex = offset;+ const nextLine = NEXT_LINE.exec(text)?.[1];+ return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context);+ },+ },+ { names: ["strikethrough"], inText: (text) => text.includes("~") },+ {+ names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"],+ inText: (text) => text.includes("[^"),+ },+ { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) },+];++// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's+// lib/syntax.js: recheck it when that package changes.+function continuesTable({ events }: TokenizeContext) {+ let index = events.length - 1;+ while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--;+ // The table extension's token types are not in micromark's map unless its types are loaded.+ const tail: string | undefined = events[index]?.[1].type;+ return tail === "tableHead" || tail === "tableRow";+}++let parsing = "";+const gated = new WeakMap<Construct, Construct>();++function gatedConstruct(construct: Construct, gate: Gate): Construct {+ const at = gate.at;+ if (!at) return construct;+ let wrapped = gated.get(construct);+ if (!wrapped) {+ const { previous, tokenize } = construct;+ wrapped = {+ ...construct,+ tokenize(effects, ok, nok) {+ return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok;+ },+ ...(previous && {+ previous(code) {+ return previous.call(this, code) && at(this, parsing, this.now().offset);+ },+ }),+ };+ gated.set(construct, wrapped);+ }+ return wrapped;+}++type ConstructMap = Record<string, Construct | Construct[] | undefined>;++function gateExtension(extension: Extension, absent: ReadonlySet<Gate>): Extension {+ const gateOf = (name: string | undefined) =>+ GATES.find((gate) => name && gate.names.includes(name));+ const result: Record<string, unknown> = {};+ for (const [field, value] of Object.entries(extension)) {+ if (field === "disable" || field === "attentionMarkers" || !value) {+ result[field] = value;+ continue;+ }+ const map: ConstructMap = {};+ for (const [code, entry] of Object.entries(value as ConstructMap)) {+ const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => {+ const gate = construct && gateOf(construct.name);+ if (!construct || !gate) return construct ? [construct] : [];+ return absent.has(gate) ? [] : [gatedConstruct(construct, gate)];+ });+ if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0];+ }+ result[field] = map;+ }+ return result as Extension;+}++type MdastExtensions = NonNullable<FromMarkdownOptions["mdastExtensions"]>;++// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key.+function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension {+ const merged = {+ canContainEols: [] as string[],+ enter: {},+ exit: {},+ transforms: [] as Transform[],+ };+ for (const extension of extensions.flat()) {+ merged.canContainEols.push(...(extension.canContainEols ?? []));+ Object.assign(merged.enter, extension.enter);+ Object.assign(merged.exit, extension.exit);+ // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io`+ // links too. Most texts have URLs only in link destinations and code, where it finds nothing.+ for (const transform of extension.transforms ?? []) {+ merged.transforms.push(+ extension.enter?.literalAutolink+ ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined)+ : transform,+ );+ }+ }+ return merged;+}++const AUTOLINK_TEXT = /@|https?:\/\/|www\./i;++function hasAutolinkText(node: MdastNodes): boolean {+ if (node.type === "text") return AUTOLINK_TEXT.test(node.value);+ if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false;+ return node.children.some(hasAutolinkText);+}++/**+ * Parses as remark-parse does, without the syntax extension constructs that cannot match the+ * text. Same tree, in about half the time.+ */+function attachParserWithoutUnusedSyntax(this: Processor) {+ const data = this.data();+ const byMask = new Map<number, FromMarkdownOptions["extensions"]>();+ let mdastExtensions: MdastExtension[] | undefined;+ this.parser = (document) => {+ let mask = 0;+ GATES.forEach((gate, index) => {+ if (!gate.inText(document)) mask |= 1 << index;+ });+ let extensions = byMask.get(mask);+ if (!extensions) {+ const absent = new Set(GATES.filter((_, index) => mask & (1 << index)));+ extensions = [+ combineExtensions(+ (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)),+ ),+ ];+ byMask.set(mask, extensions);+ }+ mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])];+ const outer = parsing;+ // Gates read micromark offsets, which skip a leading byte order mark.+ parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document;+ try {+ return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions });+ } finally {+ parsing = outer;+ }+ };+}++export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax;diff --git a/apps/web/src/textDirection.ts b/apps/web/src/textDirection.tsindex 58147ea0035..9f0adedd30e 100644--- a/apps/web/src/textDirection.ts+++ b/apps/web/src/textDirection.ts@@ -10,6 +10,7 @@ const LETTER = /\p{L}/u;* Count words so mixed prose follows its main language; break ties with the first word.*/export function textDirection(text: string): TextDirection | undefined {+ if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined;let rtlWords = 0;let ltrWords = 0;let first: TextDirection | undefined;diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex cc113b00fe4..3171bea334d 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -526,6 +526,7 @@"mdast-util-to-hast": "^13.2.1","micromark-extension-directive": "catalog:","micromark-util-character": "catalog:",+ "property-information": "^7.2.0","rehype-raw": "catalog:","rehype-sanitize": "catalog:","remark-breaks": "catalog:",diff --git a/packages/shared/src/markdownListIndentation.ts b/packages/shared/src/markdownListIndentation.tsindex 540f3c47422..f41e6d2eddd 100644--- a/packages/shared/src/markdownListIndentation.ts+++ b/packages/shared/src/markdownListIndentation.ts@@ -113,6 +113,10 @@ function attachListItemIndentationNormalizer(this: MarkdownParser) {if (!node.children) {return;}+ if (!node.children.some((child) => isSameLineOverIndentedCode(child, node, source))) {+ for (const child of node.children) visit(child, source);+ return;+ }node.children = node.children.flatMap((child) => {if (isSameLineOverIndentedCode(child, node, source)) {const recovered = blocksFromIndentedCode(child, this);diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.tsindex aa753e6303f..214f55f8f42 100644--- a/packages/shared/src/markdownPipeline.test.ts+++ b/packages/shared/src/markdownPipeline.test.ts@@ -1,5 +1,6 @@import { expect, it } from "vite-plus/test";import { unified } from "unified";+import rehypeRaw from "rehype-raw";import remarkParse from "remark-parse";import remarkRehype from "remark-rehype";import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS } from "./markdownPipeline.ts";@@ -38,6 +39,58 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () =>expect(JSON.stringify(tree)).not.toContain("javascript:");});+it("builds the tree rehype-raw builds for markdown without HTML", () => {+ type Node = {+ type: string;+ tagName?: string;+ value?: string;+ position?: unknown;+ data?: unknown;+ children?: Node[];+ };+ // What the round trip changes that renders the same; see `needsHtmlParser`.+ const comparable = (node: Node): Node => {+ const { position, children, data, ...rest } = node;+ const result: Node =+ node.type === "text" || node.type === "root" ? rest : { ...rest, position, data };+ if (!children) return result;+ const merged: Node[] = [];+ for (const child of children.map(comparable)) {+ const last = merged.at(-1);+ if (child.type === "text" && last?.type === "text") last.value += child.value ?? "";+ else merged.push(child);+ }+ // Blank text inside a table moves in front of it; the JSX runtime drops it in tables.+ const inTable = /^(?:table|thead|tbody|tfoot|tr)$/.test(node.tagName ?? "");+ result.children = merged.filter(+ (child, index) =>+ child.type !== "text" ||+ child.value?.trim() ||+ !(inTable || merged[index + 1]?.tagName === "table"),+ );+ return result;+ };+ const tree = (rehypePlugins: typeof CHAT_MARKDOWN_REHYPE_PLUGINS, markdown: string) => {+ const processor = unified()+ .use(remarkParse)+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)+ .use(remarkRehype, { allowDangerousHtml: true })+ .use(rehypePlugins);+ return comparable(processor.runSync(processor.parse(markdown)) as Node);+ };+ const [first, , ...rest] = CHAT_MARKDOWN_REHYPE_PLUGINS;+ const withRaw = [first!, rehypeRaw, ...rest];+ for (const markdown of [+ "- [ ] open\n- [x] done\n\nNote[^1]\n\n[^1]: The note.",+ "| a | b |\n| :- | -: |\n| `c` |  |\n\n```ts title=x\nconst a = 1;\n```",+ // The HTML parser moves the footnote's link out of the label's link.+ "[note[^x]](https://example.com)\n\n[^x]: text",+ "**a** **b**\r\n> - | a |\r\n> | - |\r\n> | b |\r\n\n-\tx\n\n y",+ ]) {+ expect(tree(CHAT_MARKDOWN_REHYPE_PLUGINS, markdown)).toEqual(tree(withRaw, markdown));+ }+});+it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {const processor = unified().use(remarkParse)diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.tsindex fe3d73ddac6..89ebdcf6089 100644--- a/packages/shared/src/markdownPipeline.ts+++ b/packages/shared/src/markdownPipeline.ts@@ -1,8 +1,9 @@import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";-import { type PluggableList, unified } from "unified";+import { type PluggableList, type Processor, unified } from "unified";import remarkParse from "remark-parse";import remarkRehype from "remark-rehype";+import { find, html } from "property-information";import rehypeRaw from "rehype-raw";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkBreaks from "remark-breaks";@@ -185,9 +186,79 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [remarkNormalizeLinksAndTagInlineCode,];+// Start tags an HTML parser closes an open `<p>` for.+const CLOSES_PARAGRAPH = new Set(+ "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(+ " ",+ ),+);+const HEADING = /^h[1-6]$/;++interface HtmlScope {+ readonly anchor: boolean;+ readonly paragraph: boolean;+ readonly heading: boolean;+}++/**+ * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a+ * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and+ * drops `data`, both repeated here, and moves blank text that renders the same.+ */+function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {+ if (node.type === "raw") return true;+ let inner = scope;+ if (node.type === "element" && node.tagName) {+ const { tagName } = node;+ const heading = HEADING.test(tagName);+ if (+ (tagName === "a" && scope.anchor) ||+ (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||+ (heading && scope.heading)+ ) {+ return true;+ }+ inner = {+ anchor: scope.anchor || tagName === "a",+ paragraph: scope.paragraph || tagName === "p",+ heading: scope.heading || heading,+ };+ const properties = node.properties ?? {};+ for (const key of Object.keys(properties)) {+ const value = properties[key];+ const info = find(html, key);+ if (+ value === false ||+ value === null ||+ value === undefined ||+ Number.isNaN(value) ||+ (!value && info.boolean)+ ) {+ delete properties[key];+ } else if (value === true && !info.boolean && !info.overloadedBoolean) {+ properties[key] = "";+ }+ }+ delete (node as { data?: unknown }).data;+ }+ return (node.children ?? []).some((child) => needsHtmlParser(child, inner));+}++const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };++/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */+function rehypeRawWhenPresent(this: Processor) {+ const transform = rehypeRaw.call(this) as unknown as (+ tree: MarkdownImageHastNode,+ file: unknown,+ ) => unknown;+ return (tree: MarkdownImageHastNode, file: unknown) =>+ needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;+}+export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [rehypePreserveBareAnchorPlaceholders,- rehypeRaw,+ rehypeRawWhenPresent,rehypePreserveImageSourceMeta,[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],];@@ -209,6 +280,7 @@ const startsLine = (node: PhrasingContent | undefined) =>function breakLinesAroundImages(paragraph: Paragraph) {const children = paragraph.children;+ if (!children.some(isImageNode)) return;const ownsLine = (index: number) =>isImageNode(children[index]) &&endsLine(children[index - 1]) &&diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000000..2d0d0b336d7--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,44 @@+diff --git a/lib/state.js b/lib/state.js+index 0d9c9df..1279783 100644+--- a/lib/state.js++++ b/lib/state.js+@@ -176,7 +176,6 @@+ */++ import structuredClone from '@ungap/structured-clone'+-import {visit} from 'unist-util-visit'+ import {position} from 'unist-util-position'+ import {handlers as defaultHandlers} from './handlers/index.js'++@@ -223,7 +222,16 @@ export function createState(tree, options) {+ wrap+ }++- visit(tree, function (node) {++ // A plain walk in the same order: `visit` costs more than the rest of this setup.++ collectDefinitions(tree)++++ return state++++ /**++ * @param {MdastNodes} node++ * @returns {undefined}++ */++ function collectDefinitions(node) {+ if (node.type === 'definition' || node.type === 'footnoteDefinition') {+ const map = node.type === 'definition' ? definitionById : footnoteById+ const id = String(node.identifier).toUpperCase()+@@ -235,9 +243,11 @@ export function createState(tree, options) {+ map.set(id, node)+ }+ }+- })++- return state++ if ('children' in node) {++ for (const child of node.children) collectDefinitions(child)++ }++ }++ /**+ * Transform an mdast node into a hast node.diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000000..0b3c56fd544--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,87 @@+diff --git a/dev/lib/parse.js b/dev/lib/parse.js+index ffb0f88..c63f0a3 100644+--- a/dev/lib/parse.js++++ b/dev/lib/parse.js+@@ -1,6 +1,7 @@+ /**+ * @import {+ * Create,++ * Extension,+ * FullNormalizedExtension,+ * InitialConstruct,+ * ParseContext,+@@ -16,6 +17,11 @@ import {string, text} from './initialize/text.js'+ import * as defaultConstructs from './constructs.js'+ import {createTokenizer} from './create-tokenizer.js'+++/** @type {WeakMap<ReadonlyArray<Extension>, FullNormalizedExtension>} */++const combined = new WeakMap()++/** @type {Array<Extension>} */++const noExtensions = []+++ /**+ * @param {ParseOptions | null | undefined} [options]+ * Configuration (optional).+@@ -24,9 +30,16 @@ import {createTokenizer} from './create-tokenizer.js'+ */+ export function parse(options) {+ const settings = options || {}+- const constructs = /** @type {FullNormalizedExtension} */ (+- combineExtensions([defaultConstructs, ...(settings.extensions || [])])+- )++ const extensions = settings.extensions || noExtensions++ // Parsers are made per document; their constructs only depend on the extensions, which must++ // not change once parsed with (unified fills them while attaching plugins, before parsing).++ let constructs = combined.get(extensions)++ if (!constructs) {++ constructs = /** @type {FullNormalizedExtension} */ (++ combineExtensions([defaultConstructs, ...extensions])++ )++ combined.set(extensions, constructs)++ }++ /** @type {ParseContext} */+ const parser = {+diff --git a/lib/parse.js b/lib/parse.js+index 4682319..11062f2 100644+--- a/lib/parse.js++++ b/lib/parse.js+@@ -1,6 +1,7 @@+ /**+ * @import {+ * Create,++ * Extension,+ * FullNormalizedExtension,+ * InitialConstruct,+ * ParseContext,+@@ -16,6 +17,11 @@ import { string, text } from './initialize/text.js';+ import * as defaultConstructs from './constructs.js';+ import { createTokenizer } from './create-tokenizer.js';+++/** @type {WeakMap<ReadonlyArray<Extension>, FullNormalizedExtension>} */++const combined = new WeakMap();++/** @type {Array<Extension>} */++const noExtensions = [];+++ /**+ * @param {ParseOptions | null | undefined} [options]+ * Configuration (optional).+@@ -24,8 +30,16 @@ import { createTokenizer } from './create-tokenizer.js';+ */+ export function parse(options) {+ const settings = options || {};+- const constructs = /** @type {FullNormalizedExtension} */+- combineExtensions([defaultConstructs, ...(settings.extensions || [])]);++ const extensions = settings.extensions || noExtensions;++ // Parsers are made per document; their constructs only depend on the extensions, which must++ // not change once parsed with (unified fills them while attaching plugins, before parsing).++ let constructs = combined.get(extensions);++ if (!constructs) {++ constructs = /** @type {FullNormalizedExtension} */ (++ combineExtensions([defaultConstructs, ...extensions])++ );++ combined.set(extensions, constructs);++ }++ /** @type {ParseContext} */+ const parser = {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bcf96647f21..39c062c66db 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -268,6 +268,8 @@ overrides:react-native-image-viewing: 0.2.2mdast-util-math: 3.0.0micromark-extension-llm-math: 3.1.0+ micromark: 4.0.2+ mdast-util-to-hast: 13.2.1alchemy: 2.0.0-beta.84expo-audio: 58.0.9expo-network: 58.0.3@@ -379,8 +381,10 @@ patchedDependencies:[email protected]: e80ec3ef8c4af50a607beea1c0917e71ba679844efdb702b45d17a5f03cf466c[email protected]: 8bf49067f93742855e15f29559ac75c8b50230b47069060993c9ea01dac11171[email protected]: afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c+ [email protected]: 57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1[email protected]: 9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8[email protected]: 7beb6ac4ba52166286593a494531aace81547e55fdddecf892824c25bd84d15a+ [email protected]: cb79edde7eca83bbcaaafb6ceb7b044b81b987314cde4910823b15257ecada67[email protected]: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651[email protected]: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626[email protected]: 419f35ee91eac88ced9438058281db5eb09d9c799d8974c1172926068c9448cf@@ -1171,6 +1175,12 @@ importers:lucide-react:specifier: ^0.564.0version: 0.564.0([email protected])+ mdast-util-from-markdown:+ specifier: ^2.0.3+ version: 2.0.3([email protected])+ micromark-util-combine-extensions:+ specifier: ^2.0.1+ version: 2.0.1morphicons:specifier: ^1.7.1version: 1.7.1([email protected]([email protected](@babel/[email protected]([email protected]))(@react-native/[email protected](@babel/[email protected]([email protected]))([email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected]([email protected]))(@react-native/[email protected](@babel/[email protected]([email protected]))([email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -1277,6 +1287,9 @@ importers:compression:specifier: ^1.8.2version: 1.8.2([email protected])+ micromark-util-types:+ specifier: 'catalog:'+ version: 2.0.2oxc-transform-react:specifier: ~0.152.0version: 0.152.0@@ -2000,14 +2013,17 @@ importers:specifier: 'catalog:'version: 3.1.0([email protected])mdast-util-to-hast:- specifier: ^13.2.1- version: 13.2.1+ specifier: 13.2.1+ version: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1)micromark-extension-directive:specifier: 'catalog:'version: 4.0.0micromark-util-character:specifier: 'catalog:'version: 2.1.1+ property-information:+ specifier: ^7.2.0+ version: 7.2.0rehype-raw:specifier: 'catalog:'version: 7.0.0@@ -19129,7 +19145,7 @@ snapshots:hast-util-from-parse5: 8.0.3hast-util-to-parse5: 8.0.1html-void-elements: 3.0.0- mdast-util-to-hast: 13.2.1+ mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1)parse5: 7.3.0unist-util-position: 5.0.0unist-util-visit: 5.1.0@@ -19151,7 +19167,7 @@ snapshots:comma-separated-tokens: 2.0.3hast-util-whitespace: 3.0.0html-void-elements: 3.0.0- mdast-util-to-hast: 13.2.1+ mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1)property-information: 7.2.0space-separated-tokens: 2.0.2stringify-entities: 4.0.4@@ -19718,7 +19734,7 @@ snapshots:decode-named-character-reference: 1.3.0devlop: 1.1.0mdast-util-to-string: 4.0.0- micromark: 4.0.2([email protected])+ micromark: 4.0.2(patch_hash=cb79edde7eca83bbcaaafb6ceb7b044b81b987314cde4910823b15257ecada67)([email protected])micromark-util-decode-numeric-character-reference: 2.0.2micromark-util-decode-string: 2.0.1micromark-util-normalize-identifier: 2.0.1@@ -19846,7 +19862,7 @@ snapshots:'@types/mdast': 4.0.4unist-util-is: 6.0.1+ [email protected](patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1):dependencies:'@types/hast': 3.0.5'@types/mdast': 4.0.4@@ -20247,7 +20263,7 @@ snapshots:+ [email protected](patch_hash=cb79edde7eca83bbcaaafb6ceb7b044b81b987314cde4910823b15257ecada67)([email protected]):dependencies:'@types/debug': 4.1.13debug: 4.4.3([email protected])@@ -21160,7 +21176,7 @@ snapshots:devlop: 1.1.0hast-util-to-jsx-runtime: 2.3.6([email protected])html-url-attributes: 3.0.1- mdast-util-to-hast: 13.2.1+ mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1)react: 19.3.0remark-parse: 11.0.0([email protected])remark-rehype: 11.1.2@@ -21455,7 +21471,7 @@ snapshots:dependencies:'@types/hast': 3.0.5'@types/mdast': 4.0.4- mdast-util-to-hast: 13.2.1+ mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1)unified: 11.0.5vfile: 6.0.3diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex acd8c742f83..be4d3c29ea7 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -234,6 +234,8 @@ overrides:react-native-image-viewing: 0.2.2mdast-util-math: 3.0.0micromark-extension-llm-math: 3.1.0+ micromark: 4.0.2+ mdast-util-to-hast: 13.2.1alchemy: "catalog:"expo-audio: 58.0.9expo-network: 58.0.3@@ -357,6 +359,8 @@ patchedDependencies:[email protected]: patches/[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected]+ [email protected]: patches/[email protected]+ [email protected]: patches/[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected]