From e339302e6c32830dfed323ad82bb156a6b8141a2 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Wed, 11 Nov 2026 21:43:04 +0000
Subject: [PATCH 01/74] perf(md): convert a page to markdown in about half the
time
The markdown is unchanged; only where the time goes is.
- Parse with parse5 and hast-util-from-parse5 directly, without source
positions. Nothing read them, and computing them dominated some pages.
- Skip toMdast's structured clone and whitespace pass: it is handed an
empty root whose handler converts our own cheap copy, minified by a
port of hast-util-minify-whitespace that tests tag names against sets.
- Find chrome and shown tab panels by walking properties instead of css
selectors over the whole page; resolveStreamed walks directly too.
hast-util-from-html stays as a devDependency for one test.
Co-Authored-By: Claude
---
.changeset/md-faster-conversion.md | 9 +
packages/md/package.json | 4 +-
packages/md/src/convert/index.ts | 114 ++++++++--
packages/md/src/convert/whitespace.ts | 229 +++++++++++++++++++++
packages/md/test/convert-big-pages.test.ts | 24 +++
vlt-lock.json | 64 +++---
6 files changed, 390 insertions(+), 54 deletions(-)
create mode 100644 .changeset/md-faster-conversion.md
create mode 100644 packages/md/src/convert/whitespace.ts
diff --git a/.changeset/md-faster-conversion.md b/.changeset/md-faster-conversion.md
new file mode 100644
index 0000000..e0d8931
--- /dev/null
+++ b/.changeset/md-faster-conversion.md
@@ -0,0 +1,9 @@
+---
+'@affordances/md': patch
+---
+
+Converting a page to markdown takes about half the time, and far less on some pages. The markdown is the same.
+
+- The html is parsed without each node's place in the source. Nothing read it, and on a page of many lines working it out took longer than everything else together.
+- The tree is no longer structured-cloned before it's converted, and its whitespace is collapsed without rebuilding the tag tests for every node.
+- A page's chrome and its shown tab panels are found by reading each element's properties rather than with css selectors over the whole page.
diff --git a/packages/md/package.json b/packages/md/package.json
index 81ba932..790dd7b 100644
--- a/packages/md/package.json
+++ b/packages/md/package.json
@@ -56,7 +56,7 @@
"test": "vitest run"
},
"dependencies": {
- "hast-util-from-html": "^2.0.3",
+ "hast-util-from-parse5": "^8.0.3",
"hast-util-select": "^6.0.4",
"hast-util-to-mdast": "^10.1.2",
"hast-util-to-string": "^3.0.1",
@@ -66,6 +66,7 @@
"micromark-extension-gfm": "^3.0.0",
"micromark-util-decode-string": "^2.0.1",
"micromark-util-normalize-identifier": "^2.0.1",
+ "parse5": "^7.3.0",
"unist-util-visit": "^5.2.0"
},
"devDependencies": {
@@ -73,6 +74,7 @@
"@types/mdast": "^4",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
+ "hast-util-from-html": "^2.0.3",
"next": "^16.4.3",
"react": "^19.3.1",
"react-dom": "^19.3.1"
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index c73a8af..d5d225a 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -1,4 +1,4 @@
-import type { Element, ElementContent, Nodes as HastNodes, Root as HastRoot } from 'hast'
+import type { Element, ElementContent, Root as HastRoot } from 'hast'
import type {
Html,
List,
@@ -9,17 +9,19 @@ import type {
Root as MdastRoot,
TableCell,
} from 'mdast'
-import { fromHtml } from 'hast-util-from-html'
+import { fromParse5 } from 'hast-util-from-parse5'
import { select, selectAll } from 'hast-util-select'
-import { defaultHandlers, toMdast, type Handle } from 'hast-util-to-mdast'
+import { defaultHandlers, defaultNodeHandlers, toMdast, type Handle } from 'hast-util-to-mdast'
import { toString } from 'hast-util-to-string'
import { gfmToMarkdown } from 'mdast-util-gfm'
import { toMarkdown } from 'mdast-util-to-markdown'
import { parse, postprocess, preprocess } from 'micromark'
+import { parse as parseHtml } from 'parse5'
import { gfm } from 'micromark-extension-gfm'
import { decodeString } from 'micromark-util-decode-string'
import { normalizeIdentifier } from 'micromark-util-normalize-identifier'
import { visit } from 'unist-util-visit'
+import { minifyWhitespace } from './whitespace.ts'
export type Handlers = Record
@@ -60,10 +62,17 @@ const ALWAYS_DROP = new Set([
'video',
'source',
])
-const CHROME =
- 'nav, header, footer, aside, dialog, [role=navigation], [role=banner], [role=contentinfo], [role=complementary], [aria-hidden=true], [hidden]'
+const CHROME_TAGS = new Set(['nav', 'header', 'footer', 'aside', 'dialog'])
+const CHROME_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary'])
const isElement = (node: unknown): node is Element => (node as Element)?.type === 'element'
+// asked of every element on a page, so read from its properties: a css selector over a whole page costs as much as
+// parsing it
+const chrome = (el: Element) =>
+ CHROME_TAGS.has(el.tagName) ||
+ CHROME_ROLES.has(String(el.properties.role)) ||
+ String(el.properties.ariaHidden) === 'true' ||
+ (el.properties.hidden != null && el.properties.hidden !== false)
const mode = (node: Element) =>
node.tagName === 'affordances-md'
? String(node.properties.dataMode ?? '')
@@ -274,11 +283,19 @@ const prune = (parent: HastRoot | Element, literal = false) => {
let tabs: Set | undefined
const page: Pruning = {
byId: () => (byId ??= ids(parent)),
- tabs: () =>
- (tabs ??= new Set(selectAll('[data-affordances-md=show]', parent).flatMap(labelledBy))),
+ tabs: () => (tabs ??= new Set(shownPanels(parent).flatMap(labelledBy))),
}
pruneWith(parent, page, literal)
}
+// everything marked data-affordances-md="show", in page order
+const shownPanels = (parent: HastRoot | Element, found: Element[] = []) => {
+ for (const child of parent.children) {
+ if (!isElement(child)) continue
+ if (String(child.properties.dataAffordancesMd) === 'show') found.push(child)
+ shownPanels(child, found)
+ }
+ return found
+}
// what prune reads from the whole page, once it needs it: its ids, and the tabs that label a shown panel
type Pruning = { byId: () => Map; tabs: () => Set }
// a tablist whose panels are shown: each panel is headed by its tab, so the tabs aren't said again
@@ -422,15 +439,22 @@ const resolveStreamed = (tree: HastRoot) => {
const templates: Element[] = []
const byId = new Map()
const parents = new Map()
- visit(tree, 'element', (node, _, parent) => {
- if (parent) parents.set(node, parent as HastRoot | Element)
- const id = node.properties.id
- if (id != null) byId.set(String(id), node)
- if (node.tagName === 'script') scripts.push(node)
- if (node.tagName !== 'template') return
- if (id != null) templates.push(node)
- if (node.properties.dataBid != null || node.properties.dataPid != null) instructions.push(node)
- })
+ const walk = (parent: HastRoot | Element) => {
+ for (const node of parent.children) {
+ if (!isElement(node)) continue
+ parents.set(node, parent)
+ const id = node.properties.id
+ if (id != null) byId.set(String(id), node)
+ if (node.tagName === 'script') scripts.push(node)
+ if (node.tagName === 'template') {
+ if (id != null) templates.push(node)
+ if (node.properties.dataBid != null || node.properties.dataPid != null)
+ instructions.push(node)
+ }
+ walk(node)
+ }
+ }
+ walk(tree)
const boundaries = new Map()
const placeholders = new Map()
for (const script of scripts)
@@ -500,10 +524,9 @@ const extract = (body: HastRoot, how: Options['extract']): HastRoot => {
const main = landmarks.find((m) => m.tagName === 'main') ?? landmarks[0]
if (main) return { type: 'root', children: [main] }
// the page has no landmark: take the body and drop its chrome, but keep what was marked for agents
- const chrome = new Set(selectAll(CHROME, body).filter((el) => !unhidden(el)))
const strip = (parent: HastRoot | Element) => {
const kept = (parent.children as ElementContent[]).filter(
- (child) => !(isElement(child) && chrome.has(child)),
+ (child) => !(isElement(child) && chrome(child) && !unhidden(child)),
)
parent.children = kept
for (const child of kept) if (isElement(child)) strip(child)
@@ -540,7 +563,7 @@ const PUSH = new RegExp(String.raw`^${CALL}([\s\S]*)\)\s*;?\s*$`)
const PUSHED = new RegExp(String.raw`^${CALL}`)
// the html tokenizer's raw text (rawtext and rcdata) elements: their text runs to their own end tag. noscript isn't
-// one: the page is parsed with scripting off, as hast-util-from-html parses it
+// one: the page is parsed with scripting off (fromHtml)
const RAW = new Set(['style', 'xmp', 'iframe', 'noembed', 'noframes', 'title', 'textarea'])
// a start tag that ends foreign content (svg, math) and is an html element again
const BREAKOUT = new Set(
@@ -1154,6 +1177,11 @@ const rowScanner = () => {
}
}
+// html as a tree, parsed as hast-util-from-html parses it (scripting off) but without each node's place in the source:
+// nothing reads it, and working it out costs more than the parse (most of a conversion, on a page of many lines)
+const fromHtml = (html: string) =>
+ fromParse5(parseHtml(html, { scriptingEnabled: false })) as HastRoot
+
// a page's html with its flight pushes taken out, parsed: the tree and the error rows' digests, or why they can't be
// trusted
const strippedTree = (html: string, swapped: Swapped) => {
@@ -2364,9 +2392,11 @@ const readTree = (
// so a filled slot's children are left out before converting, which copies and walks all of what it's given:
// a slot's fallback (a skeleton, last night's table) can be most of a page
const filled = new Set(markers.filter((node) => fillOf(node) !== undefined))
- const mdast = toMdast((filled.size ? emptied(content, filled) : content) as HastNodes, {
- handlers: { ...handlers, 'affordances-md': marker, ...options.handlers },
- }) as MdastRoot
+ const mdast = converted(filled.size ? emptied(content, filled) : content, {
+ ...handlers,
+ 'affordances-md': marker,
+ ...options.handlers,
+ })
const url = meta.canonical ?? options.url
if (absolutize(mdast, options.url ?? meta.canonical, options.link)) {
inCells(mdast)
@@ -2377,6 +2407,46 @@ const readTree = (
}
}
+// a tree as hast-util-to-mdast converts it, without what it does first: a structured clone of all it's given, so its
+// whitespace pass can change it, then that pass. it does both to an empty root instead, whose handler converts this
+// copy: only what the whitespace pass changes (children, a text's value) is new, and a node's place in the html, which
+// nothing reads, isn't copied at all
+const converted = (tree: HastRoot, elements: Handlers): MdastRoot => {
+ const copy = copied(tree)
+ minifyWhitespace(copy)
+ // the first root it converts is the empty one, or rather its clone
+ let entered = false
+ return toMdast(
+ { type: 'root', children: [] },
+ {
+ handlers: elements,
+ nodeHandlers: {
+ root: (state, node) => {
+ if (entered) return defaultNodeHandlers.root(state, node)
+ entered = true
+ // the page's ids, as toMdast collects them for its own handlers
+ const collect = (parent: HastRoot | Element) => {
+ for (const child of parent.children) {
+ if (!isElement(child)) continue
+ const id = String(child.properties.id || '')
+ if (id && !state.elementById.has(id)) state.elementById.set(id, child)
+ collect(child)
+ }
+ }
+ collect(copy)
+ return defaultNodeHandlers.root(state, copy)
+ },
+ },
+ },
+ ) as MdastRoot
+}
+const copied = (node: T): T =>
+ (node.type === 'text'
+ ? { type: 'text', value: node.value }
+ : 'children' in node
+ ? { ...node, position: undefined, children: node.children.map(copied) }
+ : node) as T
+
// a copy of a tree with these elements' children gone, sharing every part that doesn't hold one
const emptied = (node: T, empty: Set): T => {
if (isElement(node) && empty.has(node)) return { ...node, children: [] }
diff --git a/packages/md/src/convert/whitespace.ts b/packages/md/src/convert/whitespace.ts
new file mode 100644
index 0000000..346011d
--- /dev/null
+++ b/packages/md/src/convert/whitespace.ts
@@ -0,0 +1,229 @@
+import type { Element, Nodes, Parents, Text } from 'hast'
+
+// html's insignificant whitespace, collapsed and trimmed in place as css would lay it out: what hast-util-to-mdast
+// does to a tree before converting it, with hast-util-minify-whitespace (MIT, Titus Wormer). that one builds its
+// tag-name tests again for every node it asks about, which was a quarter of a conversion; this is its algorithm,
+// rule for rule, over sets. the names are its lists'
+const BLOCKS = new Set([
+ 'address',
+ 'article',
+ 'aside',
+ 'blockquote',
+ 'body',
+ 'br',
+ 'caption',
+ 'center',
+ 'col',
+ 'colgroup',
+ 'dd',
+ 'dialog',
+ 'dir',
+ 'div',
+ 'dl',
+ 'dt',
+ 'figcaption',
+ 'figure',
+ 'footer',
+ 'form',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'head',
+ 'header',
+ 'hgroup',
+ 'hr',
+ 'html',
+ 'legend',
+ 'li',
+ 'listing',
+ 'main',
+ 'menu',
+ 'nav',
+ 'ol',
+ 'optgroup',
+ 'option',
+ 'p',
+ 'plaintext',
+ 'pre',
+ 'section',
+ 'summary',
+ 'table',
+ 'tbody',
+ 'td',
+ 'tfoot',
+ 'th',
+ 'thead',
+ 'tr',
+ 'ul',
+ 'wbr',
+ 'xmp',
+])
+// what contributes content of its own, so whitespace beside it counts: embedded content and form controls
+const CONTENT = new Set([
+ 'audio',
+ 'canvas',
+ 'embed',
+ 'iframe',
+ 'img',
+ 'math',
+ 'object',
+ 'picture',
+ 'svg',
+ 'video',
+ 'button',
+ 'input',
+ 'select',
+ 'textarea',
+])
+const SKIPPABLE = new Set([
+ 'area',
+ 'base',
+ 'basefont',
+ 'dialog',
+ 'datalist',
+ 'head',
+ 'link',
+ 'meta',
+ 'noembed',
+ 'noframes',
+ 'param',
+ 'rp',
+ 'script',
+ 'source',
+ 'style',
+ 'template',
+ 'track',
+ 'title',
+])
+
+type Whitespace = 'normal' | 'nowrap' | 'pre' | 'pre-wrap'
+// before, after: whether a break comes before or after the node, so whitespace at that edge says nothing
+type State = { whitespace: Whitespace; before: boolean | undefined; after: boolean | undefined }
+type Result = { ignore: boolean; stripAtStart: boolean; remove: boolean }
+
+const isElement = (node: Nodes | undefined): node is Element => node?.type === 'element'
+const ignorable = (node: Nodes) => node.type === 'comment' || node.type === 'doctype'
+const content = (node: Nodes | undefined) => isElement(node) && CONTENT.has(node.tagName)
+const blocklike = (node: Nodes) => isElement(node) && BLOCKS.has(node.tagName)
+const skippable = (node: Parents) =>
+ (isElement(node) && (Boolean(node.properties.hidden) || SKIPPABLE.has(node.tagName))) ||
+ ignorable(node)
+const blank = (value: string) => !/[^ \t\n\f\r]/.test(value)
+const collapse = (value: string) => String(value).replace(/[\t\n\v\f\r ]+/g, ' ')
+const removable = (character: string) => character === ' ' || character === '\n'
+
+export const minifyWhitespace = (tree: Nodes) => {
+ minify(tree, { whitespace: 'normal', before: undefined, after: undefined })
+}
+
+const minify = (node: Nodes, state: State): Result => {
+ if ('children' in node) {
+ const edge = node.type === 'root' || blocklike(node)
+ return all(node, {
+ whitespace: whitespaceOf(node, state),
+ before: edge || state.before,
+ after: edge || state.after,
+ })
+ }
+ if (node.type === 'text') {
+ if (state.whitespace === 'normal') return minifyText(node, state)
+ // (not `pre-wrap` or `pre`: those keep their whitespace)
+ if (state.whitespace === 'nowrap') node.value = collapse(node.value)
+ }
+ return { ignore: ignorable(node), stripAtStart: false, remove: false }
+}
+
+const minifyText = (node: Text, state: State): Result => {
+ const value = collapse(node.value)
+ const result = { ignore: false, stripAtStart: false, remove: false }
+ let start = 0
+ let end = value.length
+ if (state.before && removable(value.charAt(0))) start++
+ if (start !== end && removable(value.charAt(end - 1))) {
+ if (state.after) end--
+ else result.stripAtStart = true
+ }
+ if (start === end) result.remove = true
+ else node.value = value.slice(start, end)
+ return result
+}
+
+const all = (parent: Parents, state: State): Result => {
+ let before = state.before
+ const { after, whitespace } = state
+ const children = parent.children
+ let length = children.length
+ let index = -1
+ while (++index < length) {
+ const result = minify(children[index]!, {
+ whitespace,
+ before,
+ after: collapsableAfter(children, index, after),
+ })
+ if (result.remove) {
+ children.splice(index, 1)
+ index--
+ length--
+ } else if (!result.ignore) {
+ before = result.stripAtStart
+ }
+ // an element that contributes content somehow, a or an , allows whitespace again
+ if (content(children[index])) before = false
+ }
+ return { ignore: false, stripAtStart: Boolean(before || after), remove: false }
+}
+
+// whether a break comes after the node at index: true where whitespace there says nothing
+const collapsableAfter = (
+ nodes: Nodes[],
+ index: number,
+ after?: boolean | undefined,
+): boolean | undefined => {
+ while (++index < nodes.length) {
+ const node = nodes[index]!
+ let result = boundary(node)
+ if (result === undefined && 'children' in node && !skippable(node))
+ result = collapsableAfter(node.children, -1)
+ if (typeof result === 'boolean') return result
+ }
+ return after
+}
+
+// true: whitespace around the node says nothing; false: it does; undefined: its siblings or children decide
+const boundary = (node: Nodes): boolean | undefined => {
+ if (node.type === 'element') {
+ if (content(node)) return false
+ if (blocklike(node)) return true
+ } else if (node.type === 'text') {
+ if (!blank(node.value)) return false
+ } else if (!ignorable(node)) {
+ return false
+ }
+ return undefined
+}
+
+// see
+const whitespaceOf = (node: Parents, state: State): Whitespace => {
+ if (isElement(node))
+ switch (node.tagName) {
+ case 'listing':
+ case 'plaintext':
+ case 'script':
+ case 'style':
+ case 'xmp':
+ return 'pre'
+ case 'nobr':
+ return 'nowrap'
+ case 'pre':
+ return node.properties.wrap ? 'pre-wrap' : 'pre'
+ case 'td':
+ case 'th':
+ return node.properties.noWrap ? 'nowrap' : state.whitespace
+ case 'textarea':
+ return 'pre-wrap'
+ }
+ return state.whitespace
+}
diff --git a/packages/md/test/convert-big-pages.test.ts b/packages/md/test/convert-big-pages.test.ts
index 3c231c2..b887782 100644
--- a/packages/md/test/convert-big-pages.test.ts
+++ b/packages/md/test/convert-big-pages.test.ts
@@ -86,3 +86,27 @@ test('a filled slot’s children are left out, and the page can be converted aga
// generous for a loaded machine: converting the fallback instead takes seconds
expect(performance.now() - started).toBeLessThan(1500)
})
+
+test('converting works on a copy: the page reads the same every time, user handlers and all', () => {
+ const page = readPage(
+ ' Spaced\n out one\n two three
kept\n as written ' +
+ ` a note
${slot(1)} `,
+ {
+ frontmatter: false,
+ // a handler that changes what it's given changes the copy, never the page
+ handlers: {
+ em: (state, node) => {
+ const children = state.all(node)
+ node.children = []
+ return { type: 'emphasis', children } as never
+ },
+ },
+ },
+ )
+ const first = page.markdown().markdown
+ expect(first).toBe(
+ '# Spaced out\n\none _two_ three\n\n```\n kept\n as written\n```\n\na note\n\n| n |\n| --- |\n| row |\n',
+ )
+ expect(page.markdown({ table: 'Filled' }).markdown).toContain('Filled')
+ expect(page.markdown().markdown).toBe(first)
+})
diff --git a/vlt-lock.json b/vlt-lock.json
index 87c93ba..e8a04a8 100644
--- a/vlt-lock.json
+++ b/vlt-lock.json
@@ -300,35 +300,35 @@
"~npm~@tailwindcss+oxide@4.3.3": [2,"@tailwindcss/oxide","sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="],
"~npm~@tailwindcss+postcss@4.3.3": [2,"@tailwindcss/postcss","sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg=="],
"~npm~@ts-morph+common@0.27.0": [0,"@ts-morph/common","sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="],
- "~npm~@types+chai@5.2.3": [2,"@types/chai","sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
- "~npm~@types+d3-array@3.2.2": [0,"@types/d3-array","sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
- "~npm~@types+d3-color@3.1.3": [0,"@types/d3-color","sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
- "~npm~@types+d3-ease@3.0.2": [0,"@types/d3-ease","sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="],
- "~npm~@types+d3-interpolate@3.0.4": [0,"@types/d3-interpolate","sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="],
- "~npm~@types+d3-path@3.1.1": [0,"@types/d3-path","sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
- "~npm~@types+d3-scale@4.0.9": [0,"@types/d3-scale","sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],
- "~npm~@types+d3-shape@3.2.0": [0,"@types/d3-shape","sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw=="],
- "~npm~@types+d3-time@3.0.4": [0,"@types/d3-time","sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
- "~npm~@types+d3-timer@3.0.2": [0,"@types/d3-timer","sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="],
- "~npm~@types+debug@4.1.13": [0,"@types/debug","sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
- "~npm~@types+deep-eql@4.0.2": [2,"@types/deep-eql","sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
- "~npm~@types+esrecurse@4.3.1": [2,"@types/esrecurse","sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
- "~npm~@types+estree-jsx@1.0.5": [0,"@types/estree-jsx","sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],
- "~npm~@types+estree@1.0.9": [0,"@types/estree","sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
- "~npm~@types+hast@3.0.5": [0,"@types/hast","sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="],
- "~npm~@types+json-schema@7.0.15": [2,"@types/json-schema","sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
- "~npm~@types+mdast@4.0.4": [0,"@types/mdast","sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],
- "~npm~@types+mdx@2.0.14": [0,"@types/mdx","sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg=="],
- "~npm~@types+ms@2.1.0": [0,"@types/ms","sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
- "~npm~@types+node@24.19.2": [2,"@types/node","sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ=="],
- "~npm~@types+react-dom@19.3.0~peer.f18d9ecf01787eaa": [0,"@types/react-dom","sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="],
- "~npm~@types+react@19.3.0": [0,"@types/react","sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
- "~npm~@types+unist@2.0.11": [0,"@types/unist","sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
- "~npm~@types+unist@3.0.3": [0,"@types/unist","sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
- "~npm~@types+use-sync-external-store@0.0.6": [0,"@types/use-sync-external-store","sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
- "~npm~@types+validate-npm-package-name@4.0.2": [0,"@types/validate-npm-package-name","sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="],
- "~npm~@types+whatwg-mimetype@3.0.2": [2,"@types/whatwg-mimetype","sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
- "~npm~@types+ws@8.18.2": [2,"@types/ws","sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
+ "~npm~@types+chai@5.2.3": [2,"@types/chai","sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",null,null,null,null,null,null,null,"chai"],
+ "~npm~@types+d3-array@3.2.2": [0,"@types/d3-array","sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",null,null,null,null,null,null,null,"d3-array"],
+ "~npm~@types+d3-color@3.1.3": [0,"@types/d3-color","sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",null,null,null,null,null,null,null,"d3-color"],
+ "~npm~@types+d3-ease@3.0.2": [0,"@types/d3-ease","sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",null,null,null,null,null,null,null,"d3-ease"],
+ "~npm~@types+d3-interpolate@3.0.4": [0,"@types/d3-interpolate","sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",null,null,null,null,null,null,null,"d3-interpolate"],
+ "~npm~@types+d3-path@3.1.1": [0,"@types/d3-path","sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",null,null,null,null,null,null,null,"d3-path"],
+ "~npm~@types+d3-scale@4.0.9": [0,"@types/d3-scale","sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",null,null,null,null,null,null,null,"d3-scale"],
+ "~npm~@types+d3-shape@3.2.0": [0,"@types/d3-shape","sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==",null,null,null,null,null,null,null,"d3-shape"],
+ "~npm~@types+d3-time@3.0.4": [0,"@types/d3-time","sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",null,null,null,null,null,null,null,"d3-time"],
+ "~npm~@types+d3-timer@3.0.2": [0,"@types/d3-timer","sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",null,null,null,null,null,null,null,"d3-timer"],
+ "~npm~@types+debug@4.1.13": [0,"@types/debug","sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",null,null,null,null,null,null,null,"debug"],
+ "~npm~@types+deep-eql@4.0.2": [2,"@types/deep-eql","sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",null,null,null,null,null,null,null,"deep-eql"],
+ "~npm~@types+esrecurse@4.3.1": [2,"@types/esrecurse","sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",null,null,null,null,null,null,null,"esrecurse"],
+ "~npm~@types+estree-jsx@1.0.5": [0,"@types/estree-jsx","sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",null,null,null,null,null,null,null,"estree-jsx"],
+ "~npm~@types+estree@1.0.9": [0,"@types/estree","sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",null,null,null,null,null,null,null,"estree"],
+ "~npm~@types+hast@3.0.5": [0,"@types/hast","sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",null,null,null,null,null,null,null,"hast"],
+ "~npm~@types+json-schema@7.0.15": [2,"@types/json-schema","sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",null,null,null,null,null,null,null,"json-schema"],
+ "~npm~@types+mdast@4.0.4": [0,"@types/mdast","sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",null,null,null,null,null,null,null,"mdast"],
+ "~npm~@types+mdx@2.0.14": [0,"@types/mdx","sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==",null,null,null,null,null,null,null,"mdx"],
+ "~npm~@types+ms@2.1.0": [0,"@types/ms","sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",null,null,null,null,null,null,null,"ms"],
+ "~npm~@types+node@24.19.2": [2,"@types/node","sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",null,null,null,null,null,null,null,"node"],
+ "~npm~@types+react-dom@19.3.0~peer.f18d9ecf01787eaa": [0,"@types/react-dom","sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",null,null,null,null,null,null,null,"react-dom"],
+ "~npm~@types+react@19.3.0": [0,"@types/react","sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",null,null,null,null,null,null,null,"react"],
+ "~npm~@types+unist@2.0.11": [0,"@types/unist","sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",null,null,null,null,null,null,null,"unist"],
+ "~npm~@types+unist@3.0.3": [0,"@types/unist","sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",null,null,null,null,null,null,null,"unist"],
+ "~npm~@types+use-sync-external-store@0.0.6": [0,"@types/use-sync-external-store","sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",null,null,null,null,null,null,null,"use-sync-external-store"],
+ "~npm~@types+validate-npm-package-name@4.0.2": [0,"@types/validate-npm-package-name","sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==",null,null,null,null,null,null,null,"validate-npm-package-name"],
+ "~npm~@types+whatwg-mimetype@3.0.2": [2,"@types/whatwg-mimetype","sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",null,null,null,null,null,null,null,"whatwg-mimetype"],
+ "~npm~@types+ws@8.18.2": [2,"@types/ws","sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",null,null,null,null,null,null,null,"ws"],
"~npm~@typescript+typescript-aix-ppc64@7.0.2": [3,"@typescript/typescript-aix-ppc64","sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",null,null,null,null,{ "engines": { "node": ">=16.20.0" }, "os": [ "aix" ], "cpu": [ "ppc64" ]}],
"~npm~@typescript+typescript-darwin-arm64@7.0.2": [3,"@typescript/typescript-darwin-arm64","sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",null,null,null,null,{ "engines": { "node": ">=16.20.0" }, "os": [ "darwin" ], "cpu": [ "arm64" ]}],
"~npm~@typescript+typescript-darwin-x64@7.0.2": [3,"@typescript/typescript-darwin-x64","sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",null,null,null,null,{ "engines": { "node": ">=16.20.0" }, "os": [ "darwin" ], "cpu": [ "x64" ]}],
@@ -568,7 +568,7 @@
"~npm~hasown@2.0.4": [0,"hasown","sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
"~npm~hast-util-embedded@3.0.0": [0,"hast-util-embedded","sha512-naH8sld4Pe2ep03qqULEtvYr7EjrLK2QHY8KJR6RJkTUjPGObe1vnx585uzem2hGra+s1q08DZZpfgDVYRbaXA=="],
"~npm~hast-util-from-dom@5.0.1": [0,"hast-util-from-dom","sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q=="],
- "~npm~hast-util-from-html@2.0.3": [0,"hast-util-from-html","sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw=="],
+ "~npm~hast-util-from-html@2.0.3": [2,"hast-util-from-html","sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw=="],
"~npm~hast-util-from-parse5@8.0.3": [0,"hast-util-from-parse5","sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg=="],
"~npm~hast-util-has-property@3.0.0": [0,"hast-util-has-property","sha512-MNilsvEKLFpV604hwfhVStK0usFY/QmM5zX16bo7EjnAEGofr5YyI37kzopBlZJkHD4t887i+q/C8/tr5Q94cA=="],
"~npm~hast-util-is-body-ok-link@3.0.1": [0,"hast-util-is-body-ok-link","sha512-0qpnzOBLztXHbHQenVB8uNuxTnm/QBFUOmdOSsEn7GnBtyY07+ENTWVFBAnXd/zEgd9/SUG3lRY7hSIBWRgGpQ=="],
@@ -1077,10 +1077,11 @@
"workspace~packages+md @types/mdast": "dev ^4 ~npm~@types+mdast@4.0.4",
"workspace~packages+md @types/react-dom": "dev ^19.3.0 ~npm~@types+react-dom@19.3.0~peer.f18d9ecf01787eaa",
"workspace~packages+md @types/react": "dev ^19.3.0 ~npm~@types+react@19.3.0",
+ "workspace~packages+md hast-util-from-html": "dev ^2.0.3 ~npm~hast-util-from-html@2.0.3",
"workspace~packages+md next": "dev ^16.4.3 ~npm~next@16.4.3~peer.945c44dd448424f8",
"workspace~packages+md react-dom": "dev ^19.3.1 ~npm~react-dom@19.3.1~peer.ac52619a787f06cf",
"workspace~packages+md react": "dev ^19.3.1 ~npm~react@19.3.1",
- "workspace~packages+md hast-util-from-html": "prod ^2.0.3 ~npm~hast-util-from-html@2.0.3",
+ "workspace~packages+md hast-util-from-parse5": "prod ^8.0.3 ~npm~hast-util-from-parse5@8.0.3",
"workspace~packages+md hast-util-select": "prod ^6.0.4 ~npm~hast-util-select@6.0.4",
"workspace~packages+md hast-util-to-mdast": "prod ^10.1.2 ~npm~hast-util-to-mdast@10.1.2",
"workspace~packages+md hast-util-to-string": "prod ^3.0.1 ~npm~hast-util-to-string@3.0.1",
@@ -1090,6 +1091,7 @@
"workspace~packages+md micromark-util-decode-string": "prod ^2.0.1 ~npm~micromark-util-decode-string@2.0.1",
"workspace~packages+md micromark-util-normalize-identifier": "prod ^2.0.1 ~npm~micromark-util-normalize-identifier@2.0.1",
"workspace~packages+md micromark": "prod ^4.0.3 ~npm~micromark@4.0.3",
+ "workspace~packages+md parse5": "prod ^7.3.0 ~npm~parse5@7.3.0",
"workspace~packages+md unist-util-visit": "prod ^5.2.0 ~npm~unist-util-visit@5.2.0",
"workspace~packages+next next": "dev ^16.4.3 ~npm~next@16.4.3~peer.945c44dd448424f8",
"workspace~packages+next react-dom": "dev ^19.3.1 ~npm~react-dom@19.3.1~peer.ac52619a787f06cf",
From 0ca5c24c9000ccc9d5a5def7517b352732f85ed9 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Thu, 12 Nov 2026 03:54:21 +0000
Subject: [PATCH 02/74] feat(md-core): experimental single-pass html to
markdown converter
A private workspace for a converter that aims to produce @affordances/md's
markdown at a fraction of the cost: a skip-scanning, spec-accurate parser
that builds only what can be content, and an emitter that writes markdown
straight from that tree.
- parse.ts matches a parse5-based oracle on the corpus and under fuzz.
- emit.ts matches @affordances/md byte for byte on 7 of 10 benchmark
pages; markers, the form summary, shown tabs and streamed boundaries
are not built yet.
- bench/ times it against mdream, turndown, node-html-markdown and
@affordances/md, and reports output parity.
First end-to-end number: 130 ms for the 10-page corpus, against 35 ms
for mdream and about 1500 ms for @affordances/md.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_018hJ9SEkCX16tDcRNj1QfjV
---
packages/md-core/.gitignore | 2 +
packages/md-core/bench/README.md | 74 +
packages/md-core/bench/corpus.ts | 47 +
packages/md-core/bench/corpus/synthetic.d.mts | 2 +
packages/md-core/bench/corpus/synthetic.mjs | 67 +
packages/md-core/bench/corpus/urls.txt | 10 +
packages/md-core/bench/fetch.ts | 35 +
packages/md-core/bench/parity.ts | 216 ++
packages/md-core/bench/run.ts | 372 +++
packages/md-core/bench/shims.d.ts | 12 +
packages/md-core/bench/table.ts | 20 +
packages/md-core/package.json | 28 +
packages/md-core/src/attr.ts | 62 +
packages/md-core/src/emit-convert.ts | 1205 +++++++
packages/md-core/src/emit-markdown.ts | 1378 ++++++++
packages/md-core/src/emit-prune.ts | 670 ++++
packages/md-core/src/emit.ts | 143 +
packages/md-core/src/entities-table.ts | 2235 +++++++++++++
packages/md-core/src/entities.ts | 84 +
packages/md-core/src/index.ts | 13 +
packages/md-core/src/parse.ts | 2886 +++++++++++++++++
packages/md-core/src/types.ts | 71 +
packages/md-core/test/emit-pages.ts | 62 +
packages/md-core/test/emit-parity.ts | 110 +
packages/md-core/test/emit-phases.ts | 38 +
packages/md-core/test/emit.test.ts | 313 ++
packages/md-core/test/parse-entities-gen.ts | 62 +
packages/md-core/test/parse-fuzz.ts | 224 ++
packages/md-core/test/parse-support.ts | 38 +
packages/md-core/test/parse-time.ts | 32 +
packages/md-core/test/parse.test.ts | 532 +++
packages/md-core/test/support/oracle.ts | 85 +
packages/md-core/tsconfig.json | 4 +
vlt-lock.json | 62 +
34 files changed, 11194 insertions(+)
create mode 100644 packages/md-core/.gitignore
create mode 100644 packages/md-core/bench/README.md
create mode 100644 packages/md-core/bench/corpus.ts
create mode 100644 packages/md-core/bench/corpus/synthetic.d.mts
create mode 100644 packages/md-core/bench/corpus/synthetic.mjs
create mode 100644 packages/md-core/bench/corpus/urls.txt
create mode 100644 packages/md-core/bench/fetch.ts
create mode 100644 packages/md-core/bench/parity.ts
create mode 100644 packages/md-core/bench/run.ts
create mode 100644 packages/md-core/bench/shims.d.ts
create mode 100644 packages/md-core/bench/table.ts
create mode 100644 packages/md-core/package.json
create mode 100644 packages/md-core/src/attr.ts
create mode 100644 packages/md-core/src/emit-convert.ts
create mode 100644 packages/md-core/src/emit-markdown.ts
create mode 100644 packages/md-core/src/emit-prune.ts
create mode 100644 packages/md-core/src/emit.ts
create mode 100644 packages/md-core/src/entities-table.ts
create mode 100644 packages/md-core/src/entities.ts
create mode 100644 packages/md-core/src/index.ts
create mode 100644 packages/md-core/src/parse.ts
create mode 100644 packages/md-core/src/types.ts
create mode 100644 packages/md-core/test/emit-pages.ts
create mode 100644 packages/md-core/test/emit-parity.ts
create mode 100644 packages/md-core/test/emit-phases.ts
create mode 100644 packages/md-core/test/emit.test.ts
create mode 100644 packages/md-core/test/parse-entities-gen.ts
create mode 100644 packages/md-core/test/parse-fuzz.ts
create mode 100644 packages/md-core/test/parse-support.ts
create mode 100644 packages/md-core/test/parse-time.ts
create mode 100644 packages/md-core/test/parse.test.ts
create mode 100644 packages/md-core/test/support/oracle.ts
create mode 100644 packages/md-core/tsconfig.json
diff --git a/packages/md-core/.gitignore b/packages/md-core/.gitignore
new file mode 100644
index 0000000..3936e5e
--- /dev/null
+++ b/packages/md-core/.gitignore
@@ -0,0 +1,2 @@
+bench/corpus/.cache
+bench/.results
diff --git a/packages/md-core/bench/README.md b/packages/md-core/bench/README.md
new file mode 100644
index 0000000..f5f2578
--- /dev/null
+++ b/packages/md-core/bench/README.md
@@ -0,0 +1,74 @@
+# md-core bench
+
+Speed and output parity for `@affordances/md-core`. Run everything from `packages/md-core`.
+
+| command | what it does |
+| ---------------------- | -------------------------------------------------------------------------------------------------------- |
+| `node bench/fetch.ts` | downloads the pages in `corpus/urls.txt` into `corpus/.cache/` (skips cached files; `--force` refetches) |
+| `node bench/run.ts` | speed: every tool on every page, median of n runs |
+| `node bench/parity.ts` | output: md-core against `@affordances/md`, the reference |
+
+## Corpus
+
+The real pages in `corpus/.cache/` (8 docs pages, ~3.7 MB) plus two synthetic docs-like pages from
+`corpus/synthetic.mjs` (`synthetic/50` and `synthetic/200`, by section count). Page names are short:
+the site and the last path segment, e.g. `react/useEffect`.
+
+## run.ts
+
+```
+node bench/run.ts # all tools, all pages (~35 s, most of it the slow tools)
+node bench/run.ts --tool core,mdream # the quick loop: comma-separated substrings
+node bench/run.ts --page react # one page
+node bench/run.ts --save before # store the run in .results/before.json
+node bench/run.ts --compare before # print deltas against it
+node bench/run.ts --json # machine-readable, nothing else on stdout
+```
+
+Other flags: `--runs` (timed runs per page, default 20), `--warmup` (default 3), `--budget` (ms a
+slow tool may spend on one page before it stops at 3 runs, default 300), `--no-gc`.
+
+Tools: md-core, `@affordances/md`, mdream, turndown with the gfm plugin, node-html-markdown. When
+`src/parse.ts` (`parse(html)`) and `src/emit.ts` (`emit(doc, options)`) exist, `md-core parse` and
+`md-core emit` time the two stages alone; emit runs on a tree parsed outside the clock.
+
+Reading the output:
+
+- the first table is the median ms per page; with `--compare`, each cell has its change in brackets
+- `total ms` is the sum of the page medians; `MB/s` is HTML bytes in over that time
+- `out KB` is the markdown produced; it differs a lot between tools, which is why only speed is compared
+- `spread` is half the interquartile range, summed over pages, as a share of the total: a rough ± for
+ the total. A few percent is normal; more means the machine was busy, so rerun
+- `runs` is the range of timed runs per page; slow tools stop early (see `--budget`)
+- the last line is md-core's total over mdream's on the same pages
+
+How it measures: one untimed pass over the corpus warms the jit. Then, page by page, each tool gets
+a full gc, its warm-up runs and its timed runs back to back, so it's timed in its own steady state
+and pays only for its own garbage. The tool order rotates from page to page. Every output feeds a
+sink that's read at the end, so no tool can be optimised away. A tool that throws on a page is
+recorded as an error and the rest carry on; a tool that throws `not implemented…` is shown as such.
+
+## parity.ts
+
+```
+node bench/parity.ts # table and overall score
+node bench/parity.ts --diff react # unified diff for that page (first 40 hunks; --hunks n)
+node bench/parity.ts --write # both outputs to .results/parity/.{reference,core}.md
+```
+
+Both converters get `{ url: 'https://site.test/a' }`. `exact` is a byte-for-byte match of the
+markdown. `lines kept` is the share of the reference's lines md-core reproduces in order (a line
+LCS), rounded down so only an exact page shows 100.0%. `notes` flags a differing `title` or `url`.
+The overall score weights pages by their line count.
+
+## Caveats
+
+- The real pages are third-party and not committed (`corpus/.cache/` is gitignored); `fetch.ts`
+ gets them again, but the sites change, so numbers from different fetches don't compare.
+- The tools aren't feature-equivalent: they extract different content and write different markdown.
+ This compares speed, not quality; parity against `@affordances/md` is the quality check.
+- The pages are converted from one string each in a warm process: startup, module loading and
+ first-call jit cost are excluded.
+- Slow tools (`@affordances/md`, turndown, node-html-markdown) get only 3–10 runs a page, and their
+ totals move by up to ~10% between runs. The fast tools get all 20 and repeat to about 1%.
+- A busy machine (other agents, builds) moves everything; compare runs made back to back.
diff --git a/packages/md-core/bench/corpus.ts b/packages/md-core/bench/corpus.ts
new file mode 100644
index 0000000..c90c6b8
--- /dev/null
+++ b/packages/md-core/bench/corpus.ts
@@ -0,0 +1,47 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import { page } from './corpus/synthetic.mjs'
+
+export type Page = { name: string; html: string; url?: string }
+
+export const cacheDir = new URL('./corpus/.cache/', import.meta.url)
+
+// the cache file name for a url: every non-alphanumeric character becomes _, so it's stable and flat
+export const fileName = (url: string) => url.replace(/[^a-zA-Z0-9]/g, '_') + '.html'
+
+export const readUrls = (): string[] =>
+ readFileSync(new URL('./corpus/urls.txt', import.meta.url), 'utf8')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line && !line.startsWith('#'))
+
+// short and readable: the site's main label and the last path segment, e.g. react/useEffect
+const shortName = (url: string) => {
+ const { hostname, pathname } = new URL(url)
+ const labels = hostname.split('.')
+ const site = labels.at(-2) ?? hostname
+ const last = (pathname.split('/').filter(Boolean).at(-1) ?? '').replace(/\.html?$/, '')
+ return last ? `${site}/${last}` : site
+}
+
+const synthetic = [50, 200]
+
+export const loadCorpus = (): Page[] => {
+ const byFile = new Map(readUrls().map((url) => [fileName(url), url]))
+ let files: string[] = []
+ try {
+ files = readdirSync(cacheDir).filter((file) => file.endsWith('.html'))
+ } catch {
+ // no cache yet: synthetic pages only, and run.ts says how to fetch
+ }
+ const pages: Page[] = files.toSorted().map((file) => {
+ const url = byFile.get(file)
+ const html = readFileSync(new URL(file, cacheDir), 'utf8')
+ return url ? { name: shortName(url), html, url } : { name: file.replace(/\.html$/, ''), html }
+ })
+ for (const sections of synthetic)
+ pages.push({ name: `synthetic/${sections}`, html: page(sections) })
+ return pages
+}
+
+export const filterPages = (pages: Page[], substring: string | undefined) =>
+ substring ? pages.filter((p) => p.name.toLowerCase().includes(substring.toLowerCase())) : pages
diff --git a/packages/md-core/bench/corpus/synthetic.d.mts b/packages/md-core/bench/corpus/synthetic.d.mts
new file mode 100644
index 0000000..f520812
--- /dev/null
+++ b/packages/md-core/bench/corpus/synthetic.d.mts
@@ -0,0 +1,2 @@
+// types for synthetic.mjs, so the bench typechecks without allowJs
+export declare const page: (sections?: number) => string
diff --git a/packages/md-core/bench/corpus/synthetic.mjs b/packages/md-core/bench/corpus/synthetic.mjs
new file mode 100644
index 0000000..3fa9337
--- /dev/null
+++ b/packages/md-core/bench/corpus/synthetic.mjs
@@ -0,0 +1,67 @@
+// synthetic docs-like page: chrome, prose with links, highlighted code, tables, lists, forms
+export const page = (sections = 200) => {
+ const out = [
+ 'Big page · Site ',
+ ]
+ out.push(
+ '' +
+ Array.from({ length: 80 }, (_, i) => `Nav ${i} `).join('') +
+ ' ',
+ )
+ out.push(
+ '' +
+ Array.from({ length: 300 }, (_, i) => `Doc ${i} `).join('') +
+ ' Big page ',
+ )
+ for (let i = 0; i < sections; i++) {
+ out.push(``)
+ out.push(
+ `Some bold and emphasised prose with a relative link , an absolute one , and inline_code(${i}). Characters like * and _ and [brackets] need escaping.
`,
+ )
+ out.push(
+ 'express 5.3.0 yarn ',
+ )
+ out.push(
+ 'file.ts ' +
+ Array.from(
+ { length: 12 },
+ (_, l) =>
+ `const value${l} = ${l} ; `,
+ ).join('\n') +
+ ' ',
+ )
+ out.push(
+ '' +
+ Array.from(
+ { length: 6 },
+ (_, l) =>
+ `Item ${l} with a link `,
+ ).join('') +
+ ' ',
+ )
+ if (i % 4 === 0)
+ out.push(
+ 'Name Version Notes ' +
+ Array.from(
+ { length: 10 },
+ (_, r) =>
+ `pkg-${r} 1.${r}.0 Note | with pipe ${r} `,
+ ).join('') +
+ '
',
+ )
+ if (i % 10 === 0)
+ out.push(
+ ``,
+ )
+ out.push(
+ 'decor
hidden
',
+ )
+ }
+ out.push(' ')
+ for (let i = 0; i < sections; i++)
+ out.push(
+ ``,
+ )
+ out.push('')
+ return out.join('')
+}
diff --git a/packages/md-core/bench/corpus/urls.txt b/packages/md-core/bench/corpus/urls.txt
new file mode 100644
index 0000000..74510cd
--- /dev/null
+++ b/packages/md-core/bench/corpus/urls.txt
@@ -0,0 +1,10 @@
+# real pages for the benchmark corpus, one url per line. bench/fetch.ts saves each to .cache/ under a name derived from
+# its url (every non-alphanumeric character becomes _), so keep these stable or the cache names change
+https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
+https://docs.npmjs.com/cli/v11/commands/npm-install
+https://en.wikipedia.org/wiki/Markdown
+https://github.com/vercel/next.js
+https://nextjs.org/docs/app/getting-started/installation
+https://react.dev/reference/react/useEffect
+https://tailwindcss.com/docs/flex
+https://www.typescriptlang.org/docs/handbook/2/generics.html
diff --git a/packages/md-core/bench/fetch.ts b/packages/md-core/bench/fetch.ts
new file mode 100644
index 0000000..6be472c
--- /dev/null
+++ b/packages/md-core/bench/fetch.ts
@@ -0,0 +1,35 @@
+// re-downloads the real pages listed in corpus/urls.txt into corpus/.cache. existing files are kept unless --force,
+// so a refetch is an explicit choice: a site changing its page changes every number
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
+import { parseArgs } from 'node:util'
+import { cacheDir, fileName, readUrls } from './corpus.ts'
+
+const { values } = parseArgs({ options: { force: { type: 'boolean', default: false } } })
+
+mkdirSync(cacheDir, { recursive: true })
+let failed = 0
+for (const url of readUrls()) {
+ const file = new URL(fileName(url), cacheDir)
+ if (existsSync(file) && !values.force) {
+ console.log(`skip ${url} (cached; --force to refetch)`)
+ continue
+ }
+ try {
+ const res = await fetch(url, {
+ headers: {
+ // a browser-like agent: some sites serve a stripped page to unknown clients
+ 'user-agent':
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36',
+ accept: 'text/html',
+ },
+ })
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
+ const html = await res.text()
+ writeFileSync(file, html)
+ console.log(`fetch ${url} (${(html.length / 1024).toFixed(0)} KB)`)
+ } catch (error) {
+ failed++
+ console.error(`error ${url}: ${(error as Error).message}`)
+ }
+}
+if (failed) process.exitCode = 1
diff --git a/packages/md-core/bench/parity.ts b/packages/md-core/bench/parity.ts
new file mode 100644
index 0000000..b48057a
--- /dev/null
+++ b/packages/md-core/bench/parity.ts
@@ -0,0 +1,216 @@
+// output parity: md-core against @affordances/md (the reference) on every corpus page
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { parseArgs } from 'node:util'
+import { htmlToMarkdown as reference } from '@affordances/md'
+import { filterPages, loadCorpus } from './corpus.ts'
+import { table } from './table.ts'
+
+const { values } = parseArgs({
+ options: {
+ page: { type: 'string' },
+ diff: { type: 'string' },
+ hunks: { type: 'string', default: '40' },
+ write: { type: 'boolean', default: false },
+ },
+})
+
+const options = { url: 'https://site.test/a' }
+const outDir = new URL('./.results/parity/', import.meta.url)
+
+type Convert = (
+ html: string,
+ o: typeof options,
+) => { markdown: string; title?: string; url?: string }
+let core: Convert | undefined
+let coreFailure = ''
+try {
+ core = (await import('../src/index.ts')).htmlToMarkdown
+} catch (error) {
+ coreFailure = `import failed: ${(error as Error).message.split('\n')[0]}`
+}
+
+// lines as small ints, so the lcs compares numbers, not strings
+const intern = (a: string[], b: string[]) => {
+ const ids = new Map()
+ const id = (line: string) => {
+ let n = ids.get(line)
+ if (n === undefined) ids.set(line, (n = ids.size))
+ return n
+ }
+ return [Int32Array.from(a, id), Int32Array.from(b, id)] as const
+}
+
+type Op = { kind: ' ' | '-' | '+'; line: string }
+
+// an lcs over lines with the common prefix and suffix trimmed first: near-identical outputs (the goal) cost almost
+// nothing, and the middle is an o(n·m) table of one byte a cell. the reference pages are ~1k lines, so even a fully
+// different page is a few mb
+const diffLines = (a: string[], b: string[]): { common: number; ops: Op[] } => {
+ const [x, y] = intern(a, b)
+ let pre = 0
+ while (pre < x.length && pre < y.length && x[pre] === y[pre]) pre++
+ let suf = 0
+ while (
+ suf < x.length - pre &&
+ suf < y.length - pre &&
+ x[x.length - 1 - suf] === y[y.length - 1 - suf]
+ )
+ suf++
+ const n = x.length - pre - suf
+ const m = y.length - pre - suf
+ // lengths of the lcs of x[i..] and y[j..], two rows at a time; dir records the way back
+ const dir = new Uint8Array((n + 1) * (m + 1))
+ let next = new Int32Array(m + 1)
+ let cur = new Int32Array(m + 1)
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ const k = i * (m + 1) + j
+ if (x[pre + i] === y[pre + j]) {
+ cur[j] = next[j + 1]! + 1
+ dir[k] = 0
+ } else if (next[j]! >= cur[j + 1]!) {
+ cur[j] = next[j]!
+ dir[k] = 1
+ } else {
+ cur[j] = cur[j + 1]!
+ dir[k] = 2
+ }
+ }
+ ;[next, cur] = [cur, next]
+ }
+ const ops: Op[] = []
+ for (let i = 0; i < pre; i++) ops.push({ kind: ' ', line: a[i]! })
+ let i = 0
+ let j = 0
+ while (i < n && j < m) {
+ const d = dir[i * (m + 1) + j]
+ if (d === 0) {
+ ops.push({ kind: ' ', line: a[pre + i++]! })
+ j++
+ } else if (d === 1) ops.push({ kind: '-', line: a[pre + i++]! })
+ else ops.push({ kind: '+', line: b[pre + j++]! })
+ }
+ while (i < n) ops.push({ kind: '-', line: a[pre + i++]! })
+ while (j < m) ops.push({ kind: '+', line: b[pre + j++]! })
+ for (let s = x.length - suf; s < x.length; s++) ops.push({ kind: ' ', line: a[s]! })
+ return { common: pre + suf + (next[0] ?? 0), ops }
+}
+
+// unified-style hunks with three lines of context
+const hunks = (ops: Op[], limit: number) => {
+ const context = 3
+ const out: string[] = []
+ let count = 0
+ let k = 0
+ // line numbers in the reference (a) and md-core (b) before ops[k]
+ const at: [number, number][] = []
+ for (let a = 1, b = 1, i = 0; i < ops.length; i++) {
+ at.push([a, b])
+ if (ops[i]!.kind !== '+') a++
+ if (ops[i]!.kind !== '-') b++
+ }
+ while (k < ops.length && count < limit) {
+ while (k < ops.length && ops[k]!.kind === ' ') k++
+ if (k >= ops.length) break
+ const start = Math.max(0, k - context)
+ // extend through every change that's within two contexts of the last one
+ let last = k
+ for (let i = k; i < ops.length && i - last <= context * 2; i++)
+ if (ops[i]!.kind !== ' ') last = i
+ const end = Math.min(ops.length, last + 1 + context)
+ const slice = ops.slice(start, end)
+ const [a, b] = at[start]!
+ const aLen = slice.filter((o) => o.kind !== '+').length
+ const bLen = slice.filter((o) => o.kind !== '-').length
+ out.push(`@@ -${a},${aLen} +${b},${bLen} @@`)
+ for (const o of slice) out.push(`${o.kind}${o.line}`)
+ count++
+ k = end
+ }
+ const total = (() => {
+ let n = 0
+ for (let i = 0; i < ops.length; i++)
+ if (ops[i]!.kind !== ' ' && (i === 0 || ops[i - 1]!.kind === ' ')) n++
+ return n
+ })()
+ return { text: out.join('\n'), shown: count, total }
+}
+
+// rounded down, so a page that isn't exact never shows 100.0%
+const floor1 = (n: number) => (Math.floor(n * 10) / 10).toFixed(1)
+
+const pages = filterPages(loadCorpus(), values.page)
+if (values.write) mkdirSync(outDir, { recursive: true })
+
+const rows: string[][] = []
+let refLines = 0
+let common = 0
+let exact = 0
+let compared = 0
+let notImplemented = false
+let diffShown = false
+
+for (const page of pages) {
+ const ref = reference(page.html, options)
+ const file = page.name.replace(/[^a-zA-Z0-9.-]+/g, '_')
+ if (values.write) writeFileSync(new URL(`${file}.reference.md`, outDir), ref.markdown)
+ const refSplit = ref.markdown.split('\n')
+ let got: ReturnType | undefined
+ let failure = coreFailure
+ if (core && !failure) {
+ try {
+ got = core(page.html, options)
+ } catch (error) {
+ const message = (error as Error).message.split('\n')[0] ?? String(error)
+ failure = message.startsWith('not implemented') ? 'not implemented' : `error: ${message}`
+ if (failure === 'not implemented') notImplemented = true
+ }
+ }
+ if (!got) {
+ rows.push([page.name, String(refSplit.length), '-', '-', '-', failure])
+ continue
+ }
+ if (values.write) writeFileSync(new URL(`${file}.core.md`, outDir), got.markdown)
+ const same = got.markdown === ref.markdown
+ const { common: c, ops } = same
+ ? { common: refSplit.length, ops: [] as Op[] }
+ : diffLines(refSplit, got.markdown.split('\n'))
+ const fields = [
+ got.title === ref.title
+ ? ''
+ : `title ${JSON.stringify(got.title)} vs ${JSON.stringify(ref.title)}`,
+ got.url === ref.url ? '' : `url ${got.url} vs ${ref.url}`,
+ ].filter(Boolean)
+ compared++
+ refLines += refSplit.length
+ common += c
+ if (same) exact++
+ rows.push([
+ page.name,
+ String(refSplit.length),
+ String(got.markdown.split('\n').length),
+ same ? 'yes' : 'no',
+ `${floor1((c / refSplit.length) * 100)}%`,
+ fields.join('; '),
+ ])
+ if (values.diff && !same && page.name.toLowerCase().includes(values.diff.toLowerCase())) {
+ const h = hunks(ops, Number(values.hunks))
+ console.log(`--- ${page.name} (reference)\n+++ ${page.name} (md-core)\n${h.text}`)
+ if (h.shown < h.total) console.log(`... ${h.total - h.shown} more hunks`)
+ console.log()
+ diffShown = true
+ }
+}
+
+if (values.diff && !diffShown)
+ console.log(`no differing page matches '${values.diff}' (or md-core produced nothing to diff)\n`)
+
+console.log(
+ table(['page', 'ref lines', 'core lines', 'exact', 'lines kept', 'notes'], rows, ['notes']),
+)
+console.log(
+ compared
+ ? `\nparity: ${exact}/${pages.length} exact, ${floor1((common / refLines) * 100)}% of reference lines reproduced in order (over ${compared} page${compared > 1 ? 's' : ''} md-core converted)`
+ : `\nparity: n/a, md-core ${notImplemented ? 'not implemented' : coreFailure || 'failed on every page'}`,
+)
+if (values.write) console.log(`outputs written to ${outDir.pathname}`)
diff --git a/packages/md-core/bench/run.ts b/packages/md-core/bench/run.ts
new file mode 100644
index 0000000..8fc46b2
--- /dev/null
+++ b/packages/md-core/bench/run.ts
@@ -0,0 +1,372 @@
+// speed benchmark: every tool on every corpus page, median of n timed runs per page
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { cpus } from 'node:os'
+import { parseArgs } from 'node:util'
+import { setFlagsFromString } from 'node:v8'
+import { runInNewContext } from 'node:vm'
+import { filterPages, loadCorpus, type Page } from './corpus.ts'
+import { kb, ms, pct, table } from './table.ts'
+
+const { values } = parseArgs({
+ options: {
+ runs: { type: 'string', default: '20' },
+ warmup: { type: 'string', default: '3' },
+ budget: { type: 'string', default: '300' },
+ tool: { type: 'string' },
+ page: { type: 'string' },
+ json: { type: 'boolean', default: false },
+ save: { type: 'string' },
+ compare: { type: 'string' },
+ 'no-gc': { type: 'boolean', default: false },
+ },
+})
+
+const runs = Number(values.runs)
+const warmup = Number(values.warmup)
+// a slow tool stops early once it has minRuns samples and has spent this long (ms) on one page: keeps a full run
+// short. tools under ~15 ms a page, the ones the comparison is about, always get all their runs
+const budget = Number(values.budget)
+const minRuns = Math.min(3, runs)
+const url = 'https://site.test/a'
+const resultsDir = new URL('./.results/', import.meta.url)
+
+// a full gc before every sample, so one tool's garbage is never collected on another's clock
+let gc: (() => void) | undefined
+if (!values['no-gc']) {
+ setFlagsFromString('--expose-gc')
+ gc = runInNewContext('gc') as () => void
+}
+
+// setup turns a page into the function that's timed; it may do untimed work first (emit needs a parsed tree)
+type Tool = { name: string; setup: (html: string) => () => unknown }
+type Status = 'ok' | 'not implemented' | `import failed: ${string}`
+
+const tools: { tool: Tool; status: Status }[] = []
+const add = (tool: Tool, status: Status = 'ok') => tools.push({ tool, status })
+const failure = (error: unknown) => (error as Error).message.split('\n')[0] ?? String(error)
+
+const isNotImplemented = (error: unknown) =>
+ error instanceof Error && error.message.startsWith('not implemented')
+
+// md-core is imported dynamically: it's mid-rewrite and must not take the whole bench down
+try {
+ const core = await import('../src/index.ts')
+ add({ name: 'md-core', setup: (html) => () => core.htmlToMarkdown(html, { url }).markdown })
+} catch (error) {
+ add({ name: 'md-core', setup: () => () => '' }, `import failed: ${failure(error)}`)
+}
+
+// the two stages on their own, when they exist. missing files are skipped without a word; a file that exists but
+// fails to load is reported, since that's a bug, not a missing stage
+const stage = async (file: string) => {
+ const target = new URL(file, import.meta.url)
+ try {
+ return (await import(target.href)) as Record
+ } catch (error) {
+ const err = error as { code?: string; url?: string; message: string }
+ if (err.code === 'ERR_MODULE_NOT_FOUND' && err.message.includes(target.pathname))
+ return undefined
+ console.error(`${file}: failed to load: ${failure(error)}`)
+ return undefined
+ }
+}
+const parseMod = await stage('../src/parse.ts')
+const emitMod = await stage('../src/emit.ts')
+const parse =
+ typeof parseMod?.parse === 'function' ? (parseMod.parse as (h: string) => unknown) : undefined
+const emit =
+ typeof emitMod?.emit === 'function'
+ ? (emitMod.emit as (doc: unknown, options: { url: string }) => unknown)
+ : undefined
+if (parse) add({ name: 'md-core parse', setup: (html) => () => parse(html) })
+if (parse && emit) {
+ // the tree is parsed once, outside the clock. emit runs on the same tree each time, so anything it caches on the
+ // tree (attr maps) is warm after the first run
+ add({
+ name: 'md-core emit',
+ setup: (html) => {
+ const doc = parse(html)
+ return () => emit(doc, { url })
+ },
+ })
+}
+
+{
+ const md = await import('@affordances/md')
+ add({ name: '@affordances/md', setup: (html) => () => md.htmlToMarkdown(html, { url }).markdown })
+ const mdream = await import('mdream')
+ add({
+ name: 'mdream',
+ setup: (html) => () => mdream.htmlToMarkdown(html, { origin: 'https://site.test' }),
+ })
+ const { default: Turndown } = await import('turndown')
+ const { gfm } = await import('turndown-plugin-gfm')
+ const turndown = new Turndown().use(gfm)
+ add({ name: 'turndown+gfm', setup: (html) => () => turndown.turndown(html) })
+ const { NodeHtmlMarkdown } = await import('node-html-markdown')
+ const nhm = new NodeHtmlMarkdown()
+ add({ name: 'node-html-markdown', setup: (html) => () => nhm.translate(html) })
+}
+
+// comma-separated substrings, any of which selects a tool: --tool core,mdream is the quick loop
+const wanted = values.tool?.toLowerCase().split(',').filter(Boolean)
+const selected = wanted
+ ? tools.filter(({ tool }) => wanted.some((w) => tool.name.toLowerCase().includes(w)))
+ : tools
+const corpus = loadCorpus()
+const pages = filterPages(corpus, values.page)
+if (!corpus.some((p) => p.url))
+ console.error('no real pages in bench/corpus/.cache: run `node bench/fetch.ts` (synthetic only)')
+if (!pages.length || !selected.length) {
+ console.error('nothing to run: check --tool and --page')
+ process.exit(1)
+}
+
+// every output goes here, so no engine can prove a result unused and skip the work
+let sink = 0
+const keep = (out: unknown) => {
+ if (typeof out === 'string') sink += out.length
+ else if (out !== null && typeof out === 'object') sink += 1
+ return out
+}
+const outBytes = (out: unknown) => (typeof out === 'string' ? Buffer.byteLength(out) : undefined)
+
+type Cell = {
+ median: number
+ p25: number
+ p75: number
+ runs: number
+ outBytes?: number | undefined
+ error?: string | undefined
+}
+type ToolResult = {
+ name: string
+ status: Status
+ total?: number
+ mbps?: number
+ outBytes?: number
+ spread?: number
+ pages: Record
+}
+type Run = {
+ date: string
+ node: string
+ cpu: string
+ runs: number
+ warmup: number
+ gc: boolean
+ pages: { name: string; bytes: number }[]
+ tools: ToolResult[]
+}
+
+const delta = (now: number | undefined, then: number | undefined) =>
+ now !== undefined && then ? ` (${pct(now / then - 1)})` : ''
+
+const quantile = (sorted: number[], q: number) => {
+ const i = (sorted.length - 1) * q
+ const lo = Math.floor(i)
+ const hi = Math.ceil(i)
+ return (sorted[lo] ?? 0) + ((sorted[hi] ?? 0) - (sorted[lo] ?? 0)) * (i - lo)
+}
+
+const live = selected.map(({ tool, status }) => ({
+ tool,
+ status,
+ cells: {} as Record,
+}))
+
+// one untimed pass over the corpus first (capped at half a second a tool): the jit sees every kind of page before
+// any timing, and it finds tools that can't run at all
+for (const entry of live) {
+ if (entry.status !== 'ok') continue
+ const t0 = performance.now()
+ for (const page of pages) {
+ if (performance.now() - t0 > 500) break
+ try {
+ keep(entry.tool.setup(page.html)())
+ } catch (error) {
+ if (isNotImplemented(error)) {
+ entry.status = 'not implemented'
+ break
+ }
+ }
+ }
+}
+
+// one tool at a time per page: a full gc, warm-up runs (which also regrow the heap the gc shrank: a gc before every
+// sample measured @affordances/md ~50% slow), then the timed runs back to back, so each tool is timed in its own
+// steady state and pays only for its own garbage. the tool order rotates page by page, so drift over the run (thermal,
+// other load) doesn't always land on the same tool
+const bench = (page: Page, index: number) => {
+ const active = live.filter((e) => e.status === 'ok')
+ for (let k = 0; k < active.length; k++) {
+ const e = active[(index + k) % active.length]!
+ gc?.()
+ const samples: number[] = []
+ let out: unknown
+ let error: string | undefined
+ try {
+ const fn = e.tool.setup(page.html)
+ for (let w = 0, spent = 0; w < warmup && (w === 0 || spent < budget / 2); w++) {
+ const t0 = performance.now()
+ out = keep(fn())
+ spent += performance.now() - t0
+ }
+ for (let r = 0, spent = 0; r < runs && (r < minRuns || spent < budget); r++) {
+ const t0 = performance.now()
+ const result = fn()
+ const dt = performance.now() - t0
+ keep(result)
+ samples.push(dt)
+ spent += dt
+ }
+ } catch (err) {
+ error = failure(err)
+ }
+ const sorted = samples.toSorted((a, b) => a - b)
+ e.cells[page.name] = error
+ ? { median: 0, p25: 0, p75: 0, runs: 0, error }
+ : {
+ median: quantile(sorted, 0.5),
+ p25: quantile(sorted, 0.25),
+ p75: quantile(sorted, 0.75),
+ runs: sorted.length,
+ outBytes: outBytes(out),
+ }
+ }
+}
+
+const progress = !values.json && process.stderr.isTTY
+for (const [i, page] of pages.entries()) {
+ if (progress) process.stderr.write(`\r\x1b[Ktiming ${page.name}`)
+ bench(page, i)
+}
+if (progress) process.stderr.write('\r\x1b[K')
+
+const bytes = new Map(pages.map((p) => [p.name, Buffer.byteLength(p.html)]))
+const result: Run = {
+ date: new Date().toISOString(),
+ node: process.version,
+ cpu: cpus()[0]?.model ?? 'unknown',
+ runs,
+ warmup,
+ gc: Boolean(gc),
+ pages: pages.map((p) => ({ name: p.name, bytes: bytes.get(p.name) ?? 0 })),
+ tools: live.map((e) => {
+ const r: ToolResult = { name: e.tool.name, status: e.status, pages: e.cells }
+ const ok = Object.entries(e.cells).filter(([, c]) => !c.error)
+ if (e.status === 'ok' && ok.length) {
+ r.total = ok.reduce((s, [, c]) => s + c.median, 0)
+ r.mbps = ok.reduce((s, [n]) => s + (bytes.get(n) ?? 0), 0) / 1e6 / (r.total / 1000)
+ r.outBytes = ok.reduce((s, [, c]) => s + (c.outBytes ?? 0), 0)
+ r.spread = ok.reduce((s, [, c]) => s + (c.p75 - c.p25), 0) / r.total
+ }
+ return r
+ }),
+}
+
+if (values.save) {
+ mkdirSync(resultsDir, { recursive: true })
+ writeFileSync(new URL(`${values.save}.json`, resultsDir), JSON.stringify(result, null, 2) + '\n')
+}
+
+let base: Run | undefined
+if (values.compare) {
+ try {
+ base = JSON.parse(readFileSync(new URL(`${values.compare}.json`, resultsDir), 'utf8')) as Run
+ } catch {
+ console.error(`no saved run '${values.compare}' in bench/.results`)
+ process.exit(1)
+ }
+}
+
+// no process.exit after a big write: it can cut off output going to a pipe
+if (values.json) console.log(JSON.stringify(result, null, 2))
+else {
+ const errors = (r: ToolResult) => Object.values(r.pages).filter((c) => c.error).length
+ const complete = (r: ToolResult) => r.status === 'ok' && errors(r) === 0
+ const rank = (r: ToolResult) => (r.status !== 'ok' ? 2 : errors(r) ? 1 : 0)
+ // the stage rows sit under md-core, since they're parts of it, not rivals
+ const isStage = (t: ToolResult) => t.name.startsWith('md-core ')
+ const sorted = result.tools
+ .filter((t) => !isStage(t))
+ .toSorted((a, b) => rank(a) - rank(b) || (a.total ?? Infinity) - (b.total ?? Infinity))
+ .flatMap((t) => (t.name === 'md-core' ? [t, ...result.tools.filter(isStage)] : [t]))
+ if (!sorted.some((t) => t.name === 'md-core')) sorted.push(...result.tools.filter(isStage))
+ const baseTool = (name: string) => base?.tools.find((t) => t.name === name)
+
+ const cell = (t: ToolResult, page: string) => {
+ const c = t.pages[page]
+ if (t.status !== 'ok') return '-'
+ if (!c) return ''
+ if (c.error) return 'error'
+ return ms(c.median) + delta(c.median, baseTool(t.name)?.pages[page]?.median)
+ }
+
+ console.log(
+ `median ms per page; ${runs} runs after ${warmup} warm-up${gc ? ', gc before each tool on each page' : ''}; ${result.node}, ${result.cpu}${base ? `; deltas vs '${values.compare}' (${base.date.slice(0, 16)})` : ''}\n`,
+ )
+ console.log(
+ table(
+ ['page', 'KB', ...sorted.map((t) => t.name)],
+ pages.map((p) => [p.name, kb(bytes.get(p.name) ?? 0), ...sorted.map((t) => cell(t, p.name))]),
+ ),
+ )
+ console.log()
+
+ const totalBytes = [...bytes.values()].reduce((a, b) => a + b, 0)
+ console.log(
+ table(
+ ['tool', 'total ms', 'MB/s', 'out KB', 'spread', 'runs', 'notes'],
+ sorted.map((t) => {
+ if (t.status !== 'ok') return [t.name, '-', '-', '-', '-', '-', t.status]
+ const cells = Object.values(t.pages).filter((c) => !c.error)
+ const counts = cells.map((c) => c.runs)
+ const n = errors(t)
+ const prev = baseTool(t.name)
+ const samePages =
+ prev && result.pages.every((p) => prev.pages[p.name] && !prev.pages[p.name]!.error)
+ const notes = [
+ n ? `errors on ${n} page${n > 1 ? 's' : ''} (total is partial)` : '',
+ prev && !samePages ? 'different pages from the saved run' : '',
+ ].filter(Boolean)
+ return [
+ t.name,
+ (t.total === undefined ? '-' : ms(t.total)) +
+ (samePages && complete(t) ? delta(t.total, prev?.total) : ''),
+ t.mbps?.toFixed(1) ?? '-',
+ kb(t.outBytes ?? 0),
+ t.spread === undefined ? '-' : `±${(t.spread * 50).toFixed(0)}%`,
+ counts.length ? `${Math.min(...counts)}-${Math.max(...counts)}` : '-',
+ notes.join('; '),
+ ]
+ }),
+ ['notes'],
+ ),
+ )
+ console.log(`\ncorpus: ${pages.length} pages, ${(totalBytes / 1e6).toFixed(2)} MB`)
+
+ const errorLines = result.tools.flatMap((t) =>
+ Object.entries(t.pages)
+ .filter(([, c]) => c.error)
+ .map(([page, c]) => ` ${t.name} on ${page}: ${c.error}`),
+ )
+ if (errorLines.length) console.log(`\nerrors:\n${errorLines.join('\n')}`)
+
+ const core = result.tools.find((t) => t.name === 'md-core')
+ const mdream = result.tools.find((t) => t.name === 'mdream')
+ if (core && mdream) {
+ if (core.status !== 'ok') console.log(`\nmd-core / mdream: md-core ${core.status}`)
+ else if (!complete(core) || !complete(mdream) || !core.total || !mdream.total)
+ console.log('\nmd-core / mdream: not comparable (errors on some pages)')
+ else {
+ const ratio = core.total / mdream.total
+ console.log(
+ `\nmd-core / mdream: ${ratio.toFixed(2)}x (${ratio <= 1 ? `${(1 / ratio).toFixed(2)}x faster` : `${ratio.toFixed(2)}x slower`})`,
+ )
+ }
+ }
+}
+
+// read, so the sink is observably used
+if (sink < 0) console.log(sink)
diff --git a/packages/md-core/bench/shims.d.ts b/packages/md-core/bench/shims.d.ts
new file mode 100644
index 0000000..b9c3706
--- /dev/null
+++ b/packages/md-core/bench/shims.d.ts
@@ -0,0 +1,12 @@
+// turndown ships no types and @types/turndown isn't installed; the bench needs only this much
+declare module 'turndown' {
+ export default class TurndownService {
+ constructor(options?: Record)
+ use(plugin: unknown): this
+ turndown(html: string): string
+ }
+}
+
+declare module 'turndown-plugin-gfm' {
+ export const gfm: unknown
+}
diff --git a/packages/md-core/bench/table.ts b/packages/md-core/bench/table.ts
new file mode 100644
index 0000000..a7dc6a5
--- /dev/null
+++ b/packages/md-core/bench/table.ts
@@ -0,0 +1,20 @@
+// a plain-text table: the first column left-aligned, the rest right-aligned (they're numbers) unless named in left
+export const table = (head: string[], rows: string[][], left: string[] = []) => {
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)))
+ const line = (cells: string[]) =>
+ cells
+ .map((c, i) =>
+ i === 0 || left.includes(head[i] ?? '')
+ ? c.padEnd(widths[i] ?? 0)
+ : c.padStart(widths[i] ?? 0),
+ )
+ .join(' ')
+ .trimEnd()
+ return [line(head), widths.map((w) => '-'.repeat(w)).join(' '), ...rows.map(line)].join('\n')
+}
+
+export const ms = (n: number) => (n < 1 ? n.toFixed(2) : n < 100 ? n.toFixed(1) : n.toFixed(0))
+
+export const kb = (bytes: number) => (bytes / 1024).toFixed(0)
+
+export const pct = (n: number) => `${n >= 0 ? '+' : ''}${(n * 100).toFixed(0)}%`
diff --git a/packages/md-core/package.json b/packages/md-core/package.json
new file mode 100644
index 0000000..c04f19e
--- /dev/null
+++ b/packages/md-core/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@affordances/md-core",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Experimental single-pass HTML to markdown converter for @affordances/md",
+ "license": "MIT",
+ "type": "module",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run --passWithNoTests",
+ "bench": "node bench/run.ts",
+ "bench:parity": "node bench/parity.ts",
+ "bench:fetch": "node bench/fetch.ts"
+ },
+ "devDependencies": {
+ "@affordances/md": "workspace:*",
+ "hast-util-from-parse5": "^8.0.3",
+ "mdream": "^2.1.0",
+ "node-html-markdown": "^2.0.0",
+ "parse5": "^7.3.0",
+ "turndown": "^7.2.5",
+ "turndown-plugin-gfm": "^1.0.2"
+ }
+}
diff --git a/packages/md-core/src/attr.ts b/packages/md-core/src/attr.ts
new file mode 100644
index 0000000..b5a44f9
--- /dev/null
+++ b/packages/md-core/src/attr.ts
@@ -0,0 +1,62 @@
+import { decode } from './entities.ts'
+import type { Element } from './types.ts'
+
+// an element's attribute by lowercase name: its decoded value, '' for one without a value, undefined when absent.
+// the first of a repeated name wins, as in html. parsed from the tag's source on first use
+export const attr = (el: Element, name: string): string | undefined =>
+ el.attrs === '' ? undefined : (el.map ??= parseAttrs(el.attrs)).get(name)
+
+export const hasAttrs = (el: Element) => el.attrs !== ''
+
+const space = (c: number) => c === 32 || c === 10 || c === 9 || c === 12 || c === 13
+
+// the tokenizer lowercases ascii only, and reads a nul as U+FFFD
+const clean = (text: string) => {
+ let upper = false
+ for (let i = 0; i < text.length; i++) {
+ const c = text.charCodeAt(i)
+ if ((c >= 65 && c <= 90) || c === 0) upper = true
+ }
+ return upper
+ ? text.replace(/[A-Z\0]/g, (c) =>
+ c === '\0' ? '\uFFFD' : String.fromCharCode(c.charCodeAt(0) | 32),
+ )
+ : text
+}
+
+// the html tokenizer's attribute states, over a start tag's source after its name
+export const parseAttrs = (source: string): Map => {
+ const map = new Map()
+ const n = source.length
+ let i = 0
+ while (i < n) {
+ let c = source.charCodeAt(i)
+ if (space(c) || c === 47) {
+ i++
+ continue
+ }
+ // a name runs to whitespace, '/' or '='; an '=' first is part of it
+ const start = i++
+ while (i < n && !space((c = source.charCodeAt(i))) && c !== 47 && c !== 61) i++
+ const name = clean(source.slice(start, i))
+ while (i < n && space(source.charCodeAt(i))) i++
+ let value = ''
+ if (source.charCodeAt(i) === 61) {
+ i++
+ while (i < n && space(source.charCodeAt(i))) i++
+ const quote = source.charCodeAt(i)
+ if (quote === 34 || quote === 39) {
+ const end = source.indexOf(quote === 34 ? '"' : "'", i + 1)
+ value = source.slice(i + 1, end < 0 ? n : end)
+ i = end < 0 ? n : end + 1
+ } else {
+ const from = i
+ while (i < n && !space(source.charCodeAt(i))) i++
+ value = source.slice(from, i)
+ }
+ if (value.indexOf('\0') >= 0) value = value.replaceAll('\0', '\uFFFD')
+ }
+ if (!map.has(name)) map.set(name, decode(value, true))
+ }
+ return map
+}
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts
new file mode 100644
index 0000000..3ebc41d
--- /dev/null
+++ b/packages/md-core/src/emit-convert.ts
@@ -0,0 +1,1205 @@
+import {
+ BREAK,
+ CODE,
+ DELETE,
+ EMPHASIS,
+ HEADING,
+ HTML,
+ IMAGE,
+ INLINE_CODE,
+ isPhrasing,
+ LINK,
+ LIST,
+ LIST_ITEM,
+ Md,
+ PARAGRAPH,
+ ROOT,
+ STRONG,
+ TABLE,
+ TABLE_CELL,
+ TABLE_ROW,
+ TEXT,
+ THEMATIC_BREAK,
+ BLOCKQUOTE,
+} from './emit-markdown.ts'
+import {
+ classes,
+ DATA_TITLE,
+ flags,
+ kidsOf,
+ linkLabel,
+ MDAST,
+ NOWRAP as NOWRAP_ATTR,
+ read,
+ SPAN,
+ ALIGN,
+ text,
+ TITLE,
+} from './emit-prune.ts'
+import type { Element, Node, Options } from './types.ts'
+
+// the page's content as the emitter's tree, as hast-util-to-mdast (MIT, Titus Wormer) converts it with
+// @affordances/md's handlers. whitespace is collapsed on the way, as hast-util-minify-whitespace would before: the
+// state it carries from one text to the next (`before`), and what comes after an element, are threaded through the walk
+
+// whitespace, as css lays it out
+const BLOCKS = new Set(
+ 'address article aside blockquote body br caption center col colgroup dd dialog dir div dl dt figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html legend li listing main menu nav ol optgroup option p plaintext pre section summary table tbody td tfoot th thead tr ul wbr xmp'.split(
+ ' ',
+ ),
+)
+// what has content of its own, so whitespace beside it counts
+const CONTENT = new Set(
+ 'audio canvas embed iframe img math object picture svg video button input select textarea'.split(
+ ' ',
+ ),
+)
+const SKIPPABLE = new Set(
+ 'area base basefont dialog datalist head link meta noembed noframes param rp script source style template track title'.split(
+ ' ',
+ ),
+)
+const NORMAL = 0
+const NOWRAP = 1
+const PRE = 2
+
+// the whitespace walk's state: whether whitespace at the start of the next text says nothing, whether it does at the
+// end of the element being converted, and how whitespace is laid out there
+let before: boolean | undefined
+let after: boolean | undefined
+let mode = NORMAL
+
+const whitespaceOf = (el: Element, current: number) => {
+ switch (el.tag) {
+ case 'listing':
+ case 'plaintext':
+ case 'xmp':
+ return PRE
+ case 'nobr':
+ return NOWRAP
+ case 'pre':
+ return PRE
+ case 'td':
+ case 'th':
+ return flags(el) & NOWRAP_ATTR ? NOWRAP : current
+ case 'textarea':
+ return PRE
+ }
+ return current
+}
+
+const blank = (value: string) => {
+ for (let i = 0; i < value.length; i++) {
+ const code = value.charCodeAt(i)
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 12 && code !== 13) return false
+ }
+ return true
+}
+// runs of whitespace as one space
+const SPREAD = /[\t\n\v\f\r]| {2}/
+const collapse = (value: string) =>
+ SPREAD.test(value) ? value.replace(/[\t\n\v\f\r ]+/g, ' ') : value
+
+// whether whitespace at the end of nodes[index] says nothing: a block comes next (true), or content (false)
+const collapsableAfter = (
+ nodes: Node[],
+ index: number,
+ end: boolean | undefined,
+): boolean | undefined => {
+ while (++index < nodes.length) {
+ const node = nodes[index]!
+ if (typeof node === 'string') {
+ if (!blank(node)) return false
+ continue
+ }
+ if (CONTENT.has(node.tag)) return false
+ if (BLOCKS.has(node.tag)) return true
+ if (!SKIPPABLE.has(node.tag)) {
+ const result = collapsableAfter(kidsOf(node), -1, undefined)
+ if (result !== undefined) return result
+ }
+ }
+ return end
+}
+
+// a text as whitespace leaves it, or undefined when nothing's left
+const minified = (value: string, nodes: Node[], index: number): string | undefined => {
+ if (mode !== NORMAL) {
+ before = false
+ return mode === NOWRAP ? collapse(value) : value
+ }
+ value = collapse(value)
+ let start = 0
+ let end = value.length
+ let strip = false
+ if (before && value.charCodeAt(0) === 32) start++
+ if (start !== end && value.charCodeAt(end - 1) === 32) {
+ if (collapsableAfter(nodes, index, after)) end--
+ else strip = true
+ }
+ if (start === end) return undefined
+ before = strip
+ return start === 0 && end === value.length ? value : value.slice(start, end)
+}
+
+// an element's whitespace: set up for what's in it, then what it leaves for what follows
+const enterElement = (el: Element, nodes: Node[], index: number) => {
+ const block = BLOCKS.has(el.tag)
+ const end = block ? true : collapsableAfter(nodes, index, after)
+ const saved = { after, mode }
+ before = block || before
+ after = end
+ mode = whitespaceOf(el, mode)
+ return saved
+}
+const exitElement = (el: Element, saved: { after: boolean | undefined; mode: number }) => {
+ const strip = Boolean(before || after)
+ after = saved.after
+ mode = saved.mode
+ before = CONTENT.has(el.tag) ? false : strip
+}
+// an element whose children are converted on their own, as if in place: a block, so the same whatever's beside it
+const asBlock = (el: Element, convert: () => T): T => {
+ const saved = { after, mode }
+ before = true
+ after = true
+ mode = whitespaceOf(el, mode)
+ const result = convert()
+ after = saved.after
+ mode = saved.mode
+ before = true
+ return result
+}
+
+// what a conversion needs from the page and the options
+let base: string | undefined
+let relink: Options['link']
+// a table's cells are a table's: one inside is its text
+let inTable = false
+// elements left out where they are (a details' summary, a figure's caption made the code's title), and controls
+// left out of a form's prose
+let skips = new Set()
+let controls = 0
+let titledCode: Element | undefined
+let titledAs = ''
+export const startConvert = (options: Options, page: string | undefined) => {
+ base = page
+ relink = options.link
+ inTable = false
+ skips = new Set()
+ controls = 0
+ titledCode = undefined
+ before = undefined
+ after = undefined
+ mode = NORMAL
+ urls.clear()
+ setBase(page)
+}
+
+const node = (type: number, kids?: Md[], value?: string) => new Md(type, kids, value)
+const textNode = (value: string) => new Md(TEXT, undefined, value)
+// a text that may hold a line ending (one not collapsed: preformatted, or from an attribute), flagged in its depth
+const unsafeText = (value: string) => {
+ const made = new Md(TEXT, undefined, value)
+ made.depth = 1
+ return made
+}
+const pushOne = (out: Md[], result: Md) => {
+ const last = out[out.length - 1]
+ if (result.type === TEXT && last !== undefined && last.type === TEXT) {
+ last.value += result.value
+ last.depth |= result.depth
+ } else out.push(result)
+}
+const push = (out: Md[], results: Md[]) => {
+ for (const result of results) pushOne(out, result)
+}
+
+// an element's children, converted, appended to out
+export const all = (parent: Element, out: Md[] = []): Md[] => {
+ const kids = kidsOf(parent)
+ for (let i = 0; i < kids.length; i++) {
+ const kid = kids[i]!
+ if (typeof kid === 'string') {
+ const collapsed = mode === NORMAL ? 0 : 1
+ const value = minified(kid, kids, i)
+ if (value === undefined) continue
+ const last = out[out.length - 1]
+ if (last !== undefined && last.type === TEXT) {
+ last.value += value
+ last.depth |= collapsed
+ } else {
+ const fresh = new Md(TEXT, undefined, value)
+ fresh.depth = collapsed
+ out.push(fresh)
+ }
+ continue
+ }
+ if (skips.size !== 0 && skips.has(kid)) {
+ before = true
+ continue
+ }
+ // whitespace in it: a block's edges say nothing; an inline element's end says what follows it says
+ const info = INFO.get(kid.tag) ?? 0
+ const kind = info & KIND_MASK
+ const block = (info & IS_BLOCK) !== 0
+ const savedAfter = after
+ const savedMode = mode
+ const end = block ? true : collapsableAfter(kids, i, after)
+ if (block) before = true
+ after = end
+ if (info & IS_SPACED) mode = whitespaceOf(kid, mode)
+ let result: Md | Md[] | undefined
+ if (controls !== 0 && CONTROL_TAGS.has(kid.tag)) result = walkOnly(kid)
+ else if (kind === PASS && !(flags(kid) & MDAST)) all(kid, out)
+ else result = one(kid, kind, parent)
+ const strip = before || end
+ after = savedAfter
+ mode = savedMode
+ before = info & IS_CONTENT ? false : Boolean(strip)
+ if (result === undefined) continue
+ if (result instanceof Md) pushOne(out, result)
+ else push(out, result)
+ }
+ return out
+}
+// the whitespace an element leaves, without what it says
+const walkOnly = (el: Element): undefined => {
+ if (!BLOCKS.has(el.tag) && !CONTENT.has(el.tag)) all(el)
+ return undefined
+}
+const CONTROL_TAGS = new Set([
+ 'input',
+ 'select',
+ 'textarea',
+ 'button',
+ 'label',
+ 'legend',
+ 'option',
+ 'datalist',
+ 'output',
+])
+
+// what each tag becomes, as hast-util-to-mdast's handlers (and @affordances/md's) say
+const PASS = 0
+const IGNORE = 1
+const FLOW = 2
+const PARAGRAPH_TAG = 3
+const HEADING_TAG = 4
+const LINK_TAG = 5
+const IMAGE_TAG = 6
+const BREAK_TAG = 7
+const RULE = 8
+const WBR = 9
+const STRONG_TAG = 10
+const QUOTE = 11
+const LIST_TAG = 12
+const ITEM = 13
+const DEFINITIONS = 14
+const CODE_BLOCK = 15
+const TABLE_TAG = 16
+const ROW = 17
+const CELL = 18
+const Q = 19
+const RAW = 20
+const DETAILS = 21
+const TITLED = 22
+const FORM = 23
+const CODE_TAG = 24
+const EMPHASIS_TAG = 25
+const DELETE_TAG = 26
+const KIND = new Map()
+const kinds = (kind: number, tags: string) => {
+ for (const tag of tags.split(' ')) KIND.set(tag, kind)
+}
+kinds(
+ IGNORE,
+ 'applet area basefont bgsound caption col colgroup command content datalist dialog element embed frame frameset isindex keygen link math menu menuitem meta nextid noembed noframes optgroup option param script shadow source spacer style svg template title track input select textarea button base',
+)
+kinds(
+ FLOW,
+ 'address article aside body center fieldset figcaption footer header hgroup html legend main multicol nav picture section',
+)
+kinds(PARAGRAPH_TAG, 'p summary')
+kinds(HEADING_TAG, 'h1 h2 h3 h4 h5 h6')
+kinds(LINK_TAG, 'a')
+kinds(IMAGE_TAG, 'img image')
+kinds(BREAK_TAG, 'br')
+kinds(RULE, 'hr')
+kinds(WBR, 'wbr')
+kinds(STRONG_TAG, 'b strong')
+kinds(QUOTE, 'blockquote')
+kinds(LIST_TAG, 'ul ol dir')
+kinds(ITEM, 'li dt dd')
+kinds(DEFINITIONS, 'dl')
+kinds(CODE_BLOCK, 'pre listing plaintext xmp')
+kinds(TABLE_TAG, 'table')
+kinds(ROW, 'tr')
+kinds(CELL, 'td th')
+kinds(Q, 'q')
+kinds(RAW, 'sup sub')
+kinds(DETAILS, 'details')
+kinds(TITLED, 'div figure')
+kinds(FORM, 'form')
+kinds(CODE_TAG, 'code kbd samp tt var')
+kinds(EMPHASIS_TAG, 'em i mark u')
+kinds(DELETE_TAG, 'del s strike')
+// with each tag's kind, how whitespace sees it: a block, content, or an element with whitespace of its own
+const KIND_MASK = 255
+const IS_BLOCK = 256
+const IS_CONTENT = 512
+const IS_SPACED = 1024
+const INFO = new Map()
+for (const tag of new Set([...KIND.keys(), ...BLOCKS, ...CONTENT, 'nobr', 'textarea']))
+ INFO.set(
+ tag,
+ (KIND.get(tag) ?? PASS) |
+ (BLOCKS.has(tag) ? IS_BLOCK : 0) |
+ (CONTENT.has(tag) ? IS_CONTENT : 0) |
+ (['pre', 'listing', 'plaintext', 'xmp', 'td', 'th', 'nobr', 'textarea'].includes(tag)
+ ? IS_SPACED
+ : 0),
+ )
+
+const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined => {
+ if (el.attrs !== '' && flags(el) & MDAST && read(el, 'data-mdast') === 'ignore')
+ return walkOnly(el)
+ switch (kind) {
+ case PASS:
+ return all(el)
+ case IGNORE:
+ return walkOnly(el)
+ case FLOW:
+ return toFlow(all(el))
+ case PARAGRAPH_TAG: {
+ const kids = dropBreaks(all(el))
+ return kids.length ? node(PARAGRAPH, kids) : undefined
+ }
+ case HEADING_TAG: {
+ const heading = node(HEADING, dropBreaks(all(el)))
+ heading.depth = el.tag.charCodeAt(1) - 48
+ return heading
+ }
+ case LINK_TAG:
+ return link(el, parent)
+ case IMAGE_TAG:
+ return image(el)
+ case BREAK_TAG:
+ return node(BREAK)
+ case RULE:
+ return node(THEMATIC_BREAK)
+ case WBR:
+ return textNode('\u200B')
+ case STRONG_TAG:
+ return node(STRONG, all(el))
+ case QUOTE:
+ return node(BLOCKQUOTE, toFlow(all(el)))
+ case LIST_TAG:
+ return list(el)
+ case ITEM:
+ return listItem(el)
+ case DEFINITIONS:
+ return definitions(el)
+ case CODE_BLOCK:
+ return code(el)
+ case TABLE_TAG:
+ return table(el)
+ case ROW:
+ return node(TABLE_ROW, specific(all(el), TABLE_CELL))
+ case CELL:
+ return cell(el)
+ case Q: {
+ const contents = all(el)
+ const head = contents[0]
+ const tail = contents[contents.length - 1]
+ if (head?.type === TEXT) head.value = '"' + head.value
+ else contents.unshift(textNode('"'))
+ if (tail?.type === TEXT) tail.value += '"'
+ else contents.push(textNode('"'))
+ return contents
+ }
+ case RAW:
+ return [
+ node(HTML, undefined, `<${el.tag}>`),
+ ...all(el),
+ node(HTML, undefined, `${el.tag}>`),
+ ]
+ case DETAILS:
+ return details(el)
+ case TITLED:
+ return titled(el)
+ case FORM:
+ return form(el)
+ case CODE_TAG:
+ return node(INLINE_CODE, undefined, toText(el))
+ case EMPHASIS_TAG:
+ return node(EMPHASIS, all(el))
+ case DELETE_TAG:
+ return node(DELETE, all(el))
+ }
+ return all(el)
+}
+
+const dropBreaks = (nodes: Md[]) => {
+ let start = 0
+ let end = nodes.length
+ while (start < end && nodes[start]!.type === BREAK) start++
+ while (end > start && nodes[end - 1]!.type === BREAK) end--
+ return start === 0 && end === nodes.length ? nodes : nodes.slice(start, end)
+}
+
+// flow content: runs of phrasing become paragraphs; a link or deletion holding blocks is pushed inside each block
+const LEAVES = new Set([TEXT, INLINE_CODE, BREAK, IMAGE, HTML, CODE, THEMATIC_BREAK])
+const wrapNeeded = (nodes: Md[]): boolean => {
+ for (const item of nodes)
+ if (!isPhrasing(item) || (item.kids.length && wrapNeeded(item.kids))) return true
+ return false
+}
+const clone = (from: Md): Md => {
+ const copy = new Md(from.type, [], from.value)
+ copy.url = from.url
+ copy.title = from.title
+ copy.lang = from.lang
+ copy.meta = from.meta
+ copy.depth = from.depth
+ copy.ordered = from.ordered
+ copy.spread = from.spread
+ copy.checked = from.checked
+ copy.align = from.align && [...from.align]
+ copy.rowSpan = from.rowSpan
+ copy.colSpan = from.colSpan
+ return copy
+}
+const flatten = (nodes: Md[]): Md[] => {
+ let out: Md[] | undefined
+ for (let i = 0; i < nodes.length; i++) {
+ const item = nodes[i]!
+ if ((item.type === DELETE || item.type === LINK) && wrapNeeded(item.kids)) {
+ out ??= nodes.slice(0, i)
+ out.push(...split(item))
+ } else out?.push(item)
+ }
+ return out ?? nodes
+}
+const split = (parent: Md): Md[] =>
+ runs(
+ parent.kids,
+ (run) => {
+ const copy = clone(parent)
+ copy.kids = run
+ return [copy]
+ },
+ (child) => {
+ if (!LEAVES.has(child.type)) {
+ const outer = clone(parent)
+ const inner = clone(child)
+ outer.kids = child.kids
+ inner.kids.push(outer)
+ return inner
+ }
+ return clone(child)
+ },
+ )
+const runs = (nodes: Md[], onPhrasing: (run: Md[]) => Md[], onOther: (item: Md) => Md): Md[] => {
+ const flat = flatten(nodes)
+ const result: Md[] = []
+ let queue: Md[] = []
+ for (const item of flat) {
+ if (isPhrasing(item)) queue.push(item)
+ else {
+ if (queue.length) {
+ result.push(...onPhrasing(queue))
+ queue = []
+ }
+ result.push(onOther(item))
+ }
+ }
+ if (queue.length) result.push(...onPhrasing(queue))
+ return result
+}
+const whitespaceOnly = (value: string) => /^[ \t\n\f\r]*$/.test(value)
+const toFlow = (nodes: Md[]): Md[] =>
+ runs(
+ nodes,
+ (run) =>
+ run.every((item) => item.type === TEXT && whitespaceOnly(item.value))
+ ? []
+ : [node(PARAGRAPH, dropBreaks(run))],
+ (item) => item,
+ )
+const rootKids = (nodes: Md[]) => (wrapNeeded(nodes) ? toFlow(nodes) : nodes)
+
+// children of one type, with what isn't one moved into the next (or the last)
+const specific = (nodes: Md[], type: number): Md[] => {
+ const results: Md[] = []
+ let queue: Md[] = []
+ for (const item of nodes) {
+ if (item.type === type) {
+ if (queue.length) {
+ item.kids.unshift(...queue)
+ queue = []
+ }
+ results.push(item)
+ } else queue.push(item)
+ }
+ if (queue.length) {
+ let last = results[results.length - 1]
+ if (!last) results.push((last = node(type)))
+ last.kids.push(...queue)
+ }
+ return results
+}
+
+// urls: what a browser makes of an href, read without parsing when it's a shape a browser leaves as written (a
+// #fragment, an /absolute/path, an http(s) url with a plain host) and made only of characters it never escapes
+const urls = new Map()
+const parse = (url: string, against: string): URL | null => {
+ let parsed = urls.get(url)
+ if (parsed === undefined) {
+ try {
+ parsed = new URL(url, against)
+ } catch {
+ parsed = null
+ }
+ urls.set(url, parsed)
+ }
+ return parsed
+}
+// characters no part of an http(s) url escapes (no dot segment either: those are resolved)
+const PLAIN = /^[A-Za-z0-9\-._~!$&()*+,;=:@%/?#]*$/
+const DOT_SEGMENT = /\/\.|%2e/i
+const HTTP = /^(https?):\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?=[/?#]|$)/
+const NUMERIC_LABEL = /(?:^|\.)(?:0x[0-9a-f]*|\d+)\.?$/
+// the shape an href is, when it's one of those: 'fragment', 'path', or an http url's length up to its path
+const shape = (url: string): 'fragment' | 'path' | number | undefined => {
+ const head = url.charCodeAt(0)
+ if (head === 35) return PLAIN.test(url) && url.indexOf('#', 1) < 0 ? 'fragment' : undefined
+ if (head === 47) {
+ if (url.charCodeAt(1) === 47 || !PLAIN.test(url) || DOT_SEGMENT.test(url)) return undefined
+ return 'path'
+ }
+ if (head !== 104) return undefined
+ const match = HTTP.exec(url)
+ if (!match || NUMERIC_LABEL.test(match[2]!)) return undefined
+ if (!PLAIN.test(url) || DOT_SEGMENT.test(url.slice(match[0].length))) return undefined
+ return match[0].length
+}
+const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:'])
+const IMAGE_SCHEMES = new Set(['http:', 'https:'])
+// whether a url's scheme is one of these, as a browser reads it; a relative url is the page's own, http(s)
+const RELATIVE = 'https://relative.invalid/'
+const allowed = (url: string, schemes: Set) => {
+ if (shape(url) !== undefined) return true
+ let scheme: string | undefined
+ try {
+ scheme = new URL(url, RELATIVE).protocol
+ } catch {
+ return false
+ }
+ return schemes.has(scheme)
+}
+// the page's url, as the shapes above need it
+let baseHref = ''
+let baseOrigin = ''
+let plainBase = false
+const setBase = (page: string | undefined) => {
+ plainBase = false
+ if (!page) return
+ try {
+ const url = new URL(page)
+ baseHref = url.href.split('#')[0]!
+ baseOrigin = url.protocol + '//' + url.host
+ plainBase =
+ (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password
+ } catch {
+ // a base that isn't a url leaves links as written
+ }
+}
+// a link's url once it's absolute, then through the link hook
+const resolve = (url: string, image: boolean) => {
+ if (!base) return url
+ let href: string | undefined
+ const kind = plainBase ? shape(url) : undefined
+ if (kind === 'fragment') href = baseHref + url
+ else if (kind === 'path') href = baseOrigin + url
+ else if (typeof kind === 'number')
+ href =
+ kind === url.length
+ ? url + '/'
+ : url.charCodeAt(kind) === 47
+ ? url
+ : url.slice(0, kind) + '/' + url.slice(kind)
+ else {
+ const absolute = parse(url, base)
+ if (!absolute) return url
+ href = absolute.href
+ }
+ if (!image && relink && !url.startsWith('#')) {
+ const swapped = relink(new URL(href))
+ if (swapped) return swapped
+ }
+ return href
+}
+
+const HEADINGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
+const link = (el: Element, parent: Element) => {
+ const href = (read(el, 'href') ?? '').trim()
+ const children = all(el)
+ if (!href || href === '#' || !allowed(href, LINK_SCHEMES)) return children
+ // a heading's link to its own anchor is the heading
+ if (href.startsWith('#') && HEADINGS.has(parent.tag)) return children
+ const result = node(LINK, children)
+ result.url = resolve(href, false)
+ result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null
+ // an icon or avatar link reads as its label
+ if (!children.some((child) => child.type !== TEXT || child.value.trim())) {
+ const name = linkLabel(el)
+ if (!name) return undefined
+ result.kids = [unsafeText(name)]
+ }
+ return result
+}
+
+const image = (el: Element) => {
+ const alt = (read(el, 'alt') ?? '').trim()
+ const src = read(el, 'src')
+ if (!alt || !src || !allowed(src, IMAGE_SCHEMES)) return undefined
+ const result = node(IMAGE, undefined, alt)
+ result.url = resolve(src, true)
+ result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null
+ return result
+}
+
+// the first child that isn't whitespace the walk drops
+const firstKid = (el: Element): Node | undefined => {
+ for (const kid of kidsOf(el))
+ if (typeof kid !== 'string' || !/^[\t\n\v\f\r ]*$/.test(kid)) return kid
+ return undefined
+}
+const checkbox = (kid: Node | undefined): Element | undefined => {
+ if (kid === undefined || typeof kid === 'string') return undefined
+ if (kid.tag === 'input') {
+ const type = read(kid, 'type')
+ return type === 'checkbox' || type === 'radio' ? kid : undefined
+ }
+ return kid.tag === 'p' ? checkbox(firstKid(kid)) : undefined
+}
+// hast-util-phrasing's elements
+const PHRASING_TAGS = new Set(
+ 'a abbr area b bdi bdo br button cite code data datalist del dfn em i input ins kbd keygen label map mark meter noscript output progress q ruby s samp script select small span strong sub sup template textarea time u var wbr audio canvas embed iframe img math object picture svg video'.split(
+ ' ',
+ ),
+)
+// whether an item is loose: a , or a second block, at any depth
+const spreadOut = (el: Element): boolean => {
+ let seenFlow = false
+ for (const kid of kidsOf(el)) {
+ if (typeof kid === 'string' || PHRASING_TAGS.has(kid.tag)) continue
+ if (kid.tag === 'p' || seenFlow || spreadOut(kid)) return true
+ seenFlow = true
+ }
+ return false
+}
+const listItem = (el: Element) => {
+ const box = checkbox(firstKid(el))
+ const item = node(LIST_ITEM)
+ item.checked = box ? read(box, 'checked') !== undefined : null
+ item.spread = spreadOut(el)
+ item.kids = toFlow(all(el))
+ return item
+}
+const list = (el: Element) => {
+ const result = node(LIST, specific(all(el), LIST_ITEM))
+ result.ordered = el.tag === 'ol'
+ if (result.ordered) {
+ const start = read(el, 'start')
+ // as hast reads it: a number when it is one, and 0 is no start
+ const value =
+ start !== undefined && start !== '' && !Number.isNaN(Number(start)) ? Number(start) : start
+ result.depth = value ? Number.parseInt(String(value), 10) : 1
+ }
+ result.spread = result.kids.length > 1 && result.kids.some((item) => item.spread)
+ return result
+}
+
+// **term**: definition, one paragraph per pair
+const FLOW_TYPES = new Set([PARAGRAPH, HEADING, LIST, BLOCKQUOTE, CODE, TABLE, THEMATIC_BREAK])
+const says = (item: Md): boolean =>
+ item.type === TEXT ? item.value.trim() !== '' : LEAVES.has(item.type) || item.kids.some(says)
+const definitions = (el: Element) => {
+ const out: Md[] = []
+ let terms: Md[][] = []
+ const pairs = kidsOf(el).flatMap((kid) =>
+ typeof kid !== 'string' && kid.tag === 'div' ? kidsOf(kid) : [kid],
+ )
+ for (const kid of pairs) {
+ if (typeof kid === 'string') continue
+ if (kid.tag === 'dt') terms.push(asBlock(kid, () => all(kid)))
+ else if (kid.tag === 'dd') {
+ const strong: Md[] = []
+ for (const term of terms.filter((parts) =>
+ parts.some((part) => part.type !== TEXT || part.value.trim()),
+ )) {
+ if (strong.length) strong.push(textNode(', '))
+ strong.push(node(STRONG, term))
+ }
+ const lead = strong.length ? [...strong, textNode(': ')] : strong
+ const first = node(PARAGRAPH, [...lead])
+ const flow: Md[] = [first]
+ let open: Md | undefined = first
+ for (const part of asBlock(kid, () => all(kid))) {
+ if (part.type === PARAGRAPH && open === first && first.kids.length === lead.length) {
+ first.kids.push(...part.kids)
+ open = undefined
+ } else if (FLOW_TYPES.has(part.type)) {
+ flow.push(part)
+ open = undefined
+ } else if (open) open.kids.push(part)
+ else flow.push((open = node(PARAGRAPH, [part])))
+ }
+ out.push(...flow.filter((block) => block.type !== PARAGRAPH || block.kids.length))
+ terms = []
+ }
+ }
+ return out
+}
+
+const details = (el: Element) => {
+ const summary = kidsOf(el).find(
+ (kid): kid is Element => typeof kid !== 'string' && kid.tag === 'summary',
+ )
+ const head: Md[] = []
+ if (summary) {
+ const inherited = before
+ head.push(
+ node(PARAGRAPH, [
+ node(
+ STRONG,
+ asBlock(summary, () => all(summary)),
+ ),
+ ]),
+ )
+ before = inherited
+ skips.add(summary)
+ }
+ const rest = all(el)
+ if (summary) skips.delete(summary)
+ return [...head, ...toFlow(rest)]
+}
+
+// a form says what it says, without its controls (the field summary is @affordances/md's alone, for now)
+const form = (el: Element) => {
+ controls++
+ const flow = toFlow(all(el))
+ controls--
+ return flow
+}
+
+// a code block's language: a language-* class on its , data-language on it or the , or a class on the
+const classLanguage = (el: Element | undefined) =>
+ el &&
+ classes(el)
+ .find((name) => name.startsWith('language-'))
+ ?.slice('language-'.length)
+const codeOf = (pre: Element) =>
+ kidsOf(pre).find((kid): kid is Element => typeof kid !== 'string' && kid.tag === 'code')
+const languageOf = (pre: Element) => {
+ const inner = codeOf(pre)
+ const said = [inner && read(inner, 'data-language'), read(pre, 'data-language')]
+ .map((language) => (language ?? '').trim())
+ .find(Boolean)
+ return (classLanguage(inner) ?? said ?? classLanguage(pre))?.split(/\s/)[0] || null
+}
+const code = (el: Element) => {
+ const result = node(CODE, undefined, toText(el).replace(/[\r\n]+$/, ''))
+ if (el.tag !== 'pre') return result
+ result.lang = languageOf(el)
+ const title = el === titledCode ? titledAs : read(el, 'data-title')
+ if (title) result.meta = `title=${JSON.stringify(title)}`
+ return result
+}
+// a code block's title where highlighters put it: a figcaption before it in its figure, or data-title on what holds it
+const descendants = (el: Element, found: Element[], tags: Set) => {
+ for (const kid of kidsOf(el))
+ if (typeof kid !== 'string') {
+ if (tags.has(kid.tag)) found.push(kid)
+ descendants(kid, found, tags)
+ }
+ return found
+}
+const PRE_TAGS = new Set(['pre'])
+const CAPTION_OR_PRE = new Set(['figcaption', 'pre'])
+const titled = (el: Element) => {
+ const flow = () => toFlow(all(el))
+ if (el.tag !== 'figure' && !(flags(el) & DATA_TITLE)) return flow()
+ const [pre, ...more] = descendants(el, [], PRE_TAGS)
+ if (!pre || more.length || read(pre, 'data-title') || pre === titledCode || !languageOf(pre))
+ return flow()
+ let caption: Element | undefined
+ if (el.tag === 'figure') {
+ const order = descendants(el, [], CAPTION_OR_PRE)
+ caption = order.slice(0, order.indexOf(pre)).find((at) => at.tag === 'figcaption')
+ }
+ const title = text(caption) || (read(el, 'data-title') ?? '').trim()
+ if (!title) return flow()
+ const saved = titledCode
+ const savedAs = titledAs
+ titledCode = pre
+ titledAs = title
+ if (caption) skips.add(caption)
+ const result = flow()
+ if (caption) skips.delete(caption)
+ titledCode = saved
+ titledAs = savedAs
+ return result
+}
+
+// a cell is one line: blocks in it are separated by a space
+const cell = (el: Element) => {
+ const result = node(TABLE_CELL, all(el))
+ if (flags(el) & SPAN) {
+ const rowSpan = read(el, 'rowspan')
+ const colSpan = read(el, 'colspan')
+ if (rowSpan) result.rowSpan = Number.parseInt(rowSpan, 10) || 1
+ if (colSpan) result.colSpan = Number.parseInt(colSpan, 10) || 1
+ }
+ if (!result.kids.some((kid) => kid.type === PARAGRAPH)) return result
+ const parts: Md[][] = []
+ let run: Md[] = []
+ for (const kid of result.kids) {
+ if (kid.type !== PARAGRAPH) {
+ run.push(kid)
+ continue
+ }
+ parts.push(run, kid.kids)
+ run = []
+ }
+ parts.push(run)
+ const said = parts.filter((part) => part.some(says))
+ const kids: Md[] = []
+ said.forEach((part, i) => {
+ const last = i ? said[i - 1]!.at(-1) : undefined
+ if (i && !(last?.type === TEXT && /\s$/.test(last.value))) kids.push(textNode(' '))
+ kids.push(...part)
+ })
+ result.kids = kids
+ return result
+}
+
+const table = (el: Element): Md => {
+ if (inTable) return unsafeText(toText(el))
+ inTable = true
+ const { align, headless } = inspect(el)
+ const rows = specific(all(el), TABLE_ROW)
+ if (headless) rows.unshift(node(TABLE_ROW))
+ for (const row of rows) row.kids = specific(row.kids, TABLE_CELL)
+ let columns = 1
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+ const cells = rows[rowIndex]!.kids
+ for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) {
+ const at = cells[cellIndex]!
+ const colSpan = at.colSpan || 1
+ const rowSpan = at.rowSpan || 1
+ if (colSpan > 1 || rowSpan > 1) {
+ for (let other = rowIndex; other < rowIndex + rowSpan; other++) {
+ for (let col = cellIndex; col < cellIndex + colSpan; col++) {
+ if (!rows[other]) break
+ const added = other !== rowIndex || col !== cellIndex ? [node(TABLE_CELL)] : []
+ rows[other]!.kids.splice(col, 0, ...added)
+ }
+ }
+ }
+ at.colSpan = 0
+ at.rowSpan = 0
+ }
+ if (cells.length > columns) columns = cells.length
+ }
+ for (const row of rows) while (row.kids.length < columns) row.kids.push(node(TABLE_CELL))
+ while (align.length < columns) align.push(null)
+ inTable = false
+ const result = node(TABLE, rows)
+ result.align = align
+ return result
+}
+const inspect = (el: Element) => {
+ const align: (string | null)[] = [null]
+ let headless = true
+ let rowIndex = 0
+ let cellIndex = 0
+ const walk = (parent: Element) => {
+ for (const kid of kidsOf(parent)) {
+ if (typeof kid === 'string') continue
+ if (kid.tag === 'table') continue
+ if (kid.tag === 'th' || kid.tag === 'td') {
+ if (!align[cellIndex]) {
+ const value = (flags(kid) & ALIGN && read(kid, 'align')) || null
+ if (value === 'center' || value === 'left' || value === 'right' || value === null)
+ align[cellIndex] = value
+ }
+ if (headless && rowIndex < 2 && kid.tag === 'th') headless = false
+ cellIndex++
+ } else if (kid.tag === 'thead') headless = false
+ else if (kid.tag === 'tr') {
+ rowIndex++
+ cellIndex = 0
+ }
+ walk(kid)
+ }
+ }
+ walk(el)
+ return { align, headless }
+}
+
+// an element's text as a browser renders it (hast-util-to-text, MIT, Titus Wormer), over text the whitespace walk
+// has already collapsed: code, a code block, a table in a table
+const BLOCK_OR_CAPTION = new Set(
+ 'address article aside blockquote body caption center dd dialog dir dl dt div figure figcaption footer form h1 h2 h3 h4 h5 h6 header hgroup hr html legend li listing main menu nav ol p plaintext pre section ul xmp'.split(
+ ' ',
+ ),
+)
+const NOT_RENDERED = new Set([
+ 'datalist',
+ 'head',
+ 'noembed',
+ 'noframes',
+ 'noscript',
+ 'rp',
+ 'script',
+ 'style',
+ 'template',
+ 'title',
+])
+const TABLE_PARTS = new Set([
+ 'caption',
+ 'col',
+ 'colgroup',
+ 'tbody',
+ 'td',
+ 'tfoot',
+ 'th',
+ 'thead',
+ 'tr',
+])
+const ROW_GROUPS = new Set(['tbody', 'tfoot', 'thead'])
+type Info = {
+ breakBefore: boolean | number | string | undefined
+ breakAfter: boolean | number | string | undefined
+ rowAfter: boolean | undefined
+ normal: boolean
+}
+type Piece = string | number
+const isBr = (kid: Node | undefined) =>
+ kid !== undefined && typeof kid !== 'string' && kid.tag === 'br'
+const isRow = (kid: Node) => typeof kid !== 'string' && kid.tag === 'tr'
+const isCell = (kid: Node) => typeof kid !== 'string' && (kid.tag === 'td' || kid.tag === 'th')
+const rowOrGroupWithRow = (kid: Node) =>
+ typeof kid !== 'string' &&
+ (kid.tag === 'tr' || (ROW_GROUPS.has(kid.tag) && kidsOf(kid).some(isRow)))
+const afterIn = (kids: Node[], index: number, test: (kid: Node) => boolean) => {
+ while (++index < kids.length) if (test(kids[index]!)) return true
+ return false
+}
+const inTableTag = (tag: string) => tag === 'table' || ROW_GROUPS.has(tag)
+
+export const toText = (el: Element): string => {
+ const block = BLOCK_OR_CAPTION.has(el.tag)
+ const tableish = inTableTag(el.tag)
+ const normal = whitespaceOf(el, NORMAL) === NORMAL
+ const kids = kidsOf(el)
+ const results: Piece[] = []
+ for (let i = 0; i < kids.length; i++) {
+ const next = kids[i + 1]
+ collect(kids, i, el, results, {
+ breakAfter: next ? isBr(next) : block,
+ breakBefore: i ? undefined : block,
+ rowAfter: tableish && el.tag === 'table' ? afterIn(kids, i, rowOrGroupWithRow) : undefined,
+ normal,
+ })
+ }
+ return joinPieces(results)
+}
+const joinPieces = (results: Piece[]) => {
+ let result = ''
+ let count: number | undefined
+ for (const value of results) {
+ if (typeof value === 'number') {
+ if (count !== undefined && value > count) count = value
+ } else if (value) {
+ if (count !== undefined && count > -1) result += '\n'.repeat(count) || ' '
+ count = -1
+ result += value
+ }
+ }
+ return result
+}
+const collect = (kids: Node[], index: number, parent: Element, out: Piece[], info: Info) => {
+ const kid = kids[index]!
+ if (typeof kid === 'string') {
+ // preformatted text is as written, and what's beside it doesn't matter
+ const value = mode === PRE ? kid : minified(kid, kids, index)
+ if (value === undefined) return
+ if (
+ blank(value) &&
+ (parent.tag === 'table' || parent.tag === 'tr' || ROW_GROUPS.has(parent.tag))
+ ) {
+ const previous = kids[index - 1]
+ const following = kids[index + 1]
+ if (
+ (!previous || (typeof previous !== 'string' && TABLE_PARTS.has(previous.tag))) &&
+ (!following || (typeof following !== 'string' && TABLE_PARTS.has(following.tag)))
+ )
+ return
+ }
+ if (info.normal) collectText(value, info, out)
+ else out.push(value)
+ return
+ }
+ if (mode === PRE) {
+ collectElement(kid, index, kids, parent, info, out)
+ return
+ }
+ const saved = enterElement(kid, kids, index)
+ collectElement(kid, index, kids, parent, info, out)
+ exitElement(kid, saved)
+}
+const collectElement = (
+ el: Element,
+ position: number,
+ siblings: Node[],
+ _parent: Element,
+ info: Info,
+ out: Piece[],
+) => {
+ const normal = info.normal && whitespaceOf(el, NORMAL) === NORMAL
+ if (NOT_RENDERED.has(el.tag) || (el.tag === 'dialog' && read(el, 'open') === undefined)) {
+ walkOnly(el)
+ return
+ }
+ let prefix: number | undefined
+ let suffix: number | string | undefined
+ if (el.tag === 'br') suffix = '\n'
+ else if (el.tag === 'tr' && (info.rowAfter || afterIn(siblings, position, isRow))) suffix = '\n'
+ else if (el.tag === 'p') {
+ prefix = 2
+ suffix = 2
+ } else if (BLOCK_OR_CAPTION.has(el.tag)) {
+ prefix = 1
+ suffix = 1
+ }
+ const kids = kidsOf(el)
+ const tableish = inTableTag(el.tag)
+ const items: Piece[] = []
+ for (let i = 0; i < kids.length; i++) {
+ const next = kids[i + 1]
+ collect(kids, i, el, items, {
+ breakAfter: next ? isBr(next) : suffix,
+ breakBefore: i ? undefined : prefix,
+ rowAfter: tableish
+ ? el.tag === 'table'
+ ? afterIn(kids, i, rowOrGroupWithRow)
+ : info.rowAfter
+ : undefined,
+ normal,
+ })
+ }
+ if (isCell(el) && afterIn(siblings, position, isCell)) items.push('\t')
+ if (prefix) out.push(prefix)
+ out.push(...items)
+ if (suffix) out.push(suffix)
+}
+const BIDI = /[--]/g
+const collectText = (value: string, info: Info, out: Piece[]) => {
+ const lines: string[] = []
+ let start = 0
+ while (start <= value.length) {
+ const found = value.indexOf('\n', start)
+ const end = found < 0 ? value.length : found
+ lines.push(
+ trimAndCollapse(
+ value.slice(start, end).replace(BIDI, ''),
+ start === 0 ? info.breakBefore : true,
+ end === value.length ? info.breakAfter : true,
+ ),
+ )
+ start = end + 1
+ }
+ let join: number | undefined
+ for (let index = 0; index < lines.length; index++) {
+ const line = lines[index]!
+ if (
+ line.charCodeAt(line.length - 1) === 0x200b ||
+ (index < lines.length - 1 && lines[index + 1]!.charCodeAt(0) === 0x200b)
+ ) {
+ out.push(line)
+ join = undefined
+ } else if (line) {
+ if (typeof join === 'number') out.push(join)
+ out.push(line)
+ join = 0
+ } else if (index === 0 || index === lines.length - 1) out.push(0)
+ }
+}
+const trimAndCollapse = (value: string, breakBefore: unknown, breakAfter: unknown) => {
+ const result: string[] = []
+ const spaces = /[\t ]+/g
+ let start = 0
+ let end: number | undefined
+ while (start < value.length) {
+ spaces.lastIndex = start
+ const match = spaces.exec(value)
+ end = match ? match.index : value.length
+ if (!start && !end && match && !breakBefore) result.push('')
+ if (start !== end) result.push(value.slice(start, end))
+ start = match ? end + match[0].length : end
+ }
+ if (start !== end && !breakAfter) result.push('')
+ return result.join(' ')
+}
+
+// the walk over the content's root, as hast-util-to-mdast's root handler: wrapped when it holds blocks
+export const convertRoot = (root: Element): Md => {
+ before = true
+ after = true
+ mode = NORMAL
+ const result = node(ROOT, rootKids(all(root)))
+ tidy(result)
+ return result
+}
+
+// what hast-util-to-mdast does last: adjacent texts as one, the line ending's spaces, a paragraph's (heading's,
+// root's) outer spaces, and empty texts gone
+const TRIMMED = new Set([PARAGRAPH, HEADING, ROOT])
+const edgeSpace = (char: number) => char === 32 || char === 9
+
+const tidy = (parent: Md) => {
+ const kids = parent.kids
+ const trims = TRIMMED.has(parent.type)
+ for (let index = 0; index < kids.length; index++) {
+ const item = kids[index]!
+ if (item.type !== TEXT) {
+ if (item.kids.length) tidy(item)
+ continue
+ }
+ const previous = kids[index - 1]
+ if (previous?.type === TEXT) {
+ previous.value += item.value
+ previous.depth |= item.depth
+ kids.splice(index, 1)
+ index -= 2
+ continue
+ }
+ let value = item.value
+ if (item.depth !== 0 && (value.includes('\n') || value.includes('\r')))
+ value = value.replace(/[\t ]*(\r?\n|\r)[\t ]*/, '$1')
+ if (trims) {
+ if (index === 0 && edgeSpace(value.charCodeAt(0))) value = value.replace(/^[\t ]+/, '')
+ if (index === kids.length - 1 && edgeSpace(value.charCodeAt(value.length - 1)))
+ value = value.replace(/[\t ]+$/, '')
+ }
+ item.value = value
+ if (!value) {
+ kids.splice(index, 1)
+ index--
+ }
+ }
+}
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
new file mode 100644
index 0000000..63273bb
--- /dev/null
+++ b/packages/md-core/src/emit-markdown.ts
@@ -0,0 +1,1378 @@
+// markdown from the emitter's lean tree, written the way mdast-util-to-markdown (MIT, Titus Wormer) writes an mdast
+// tree with @affordances/md's options: bullet -, emphasis _, strong *, rule -, fenced code, and gfm (tables, task
+// lists, strikethrough, autolink literals with their escapes kept to headings). its rules are ported one for one, over
+// a construct bitmask instead of a stack of names, with a fast path for text that needs no escape
+
+// node types: the phrasing ones are TEXT and up, so phrasing is a comparison
+export const ROOT = 0
+export const PARAGRAPH = 1
+export const HEADING = 2
+export const THEMATIC_BREAK = 3
+export const BLOCKQUOTE = 4
+export const LIST = 5
+export const LIST_ITEM = 6
+export const CODE = 7
+export const TABLE = 8
+export const TABLE_ROW = 9
+export const TABLE_CELL = 10
+export const HTML = 11
+export const TEXT = 12
+export const EMPHASIS = 13
+export const STRONG = 14
+export const DELETE = 15
+export const INLINE_CODE = 16
+export const BREAK = 17
+export const LINK = 18
+export const IMAGE = 19
+
+// one shape for every node, so the walks over them stay monomorphic
+export class Md {
+ type: number
+ kids: Md[]
+ // text, code, inline code, html; an image's alt
+ value: string
+ url: string
+ title: string | null
+ lang: string | null
+ meta: string | null
+ // a heading's depth, an ordered list's start
+ depth: number
+ ordered: boolean
+ spread: boolean
+ checked: boolean | null
+ align: (string | null)[] | null
+ rowSpan: number
+ colSpan: number
+ constructor(type: number, kids: Md[] = [], value = '') {
+ this.type = type
+ this.kids = kids
+ this.value = value
+ this.url = ''
+ this.title = null
+ this.lang = null
+ this.meta = null
+ this.depth = 0
+ this.ordered = false
+ this.spread = false
+ this.checked = null
+ this.align = null
+ this.rowSpan = 0
+ this.colSpan = 0
+ }
+}
+
+export const isPhrasing = (node: Md) => node.type >= TEXT
+
+// constructs, as bits
+const PHRASING = 1
+const HEADING_ATX = 2
+const LABEL = 4
+const REFERENCE = 8
+const AUTOLINK = 16
+const DESTINATION_LITERAL = 32
+const DESTINATION_RAW = 64
+const TITLE_QUOTE = 128
+const TITLE_APOSTROPHE = 256
+const LANG_GRAVE = 512
+const LANG_TILDE = 1024
+const META_GRAVE = 2048
+const META_TILDE = 4096
+const TABLE_CELL_BIT = 8192
+const LINK_BIT = 16384
+const IMAGE_BIT = 32768
+const STRIKETHROUGH = 65536
+const BITS: Record = {
+ phrasing: PHRASING,
+ headingAtx: HEADING_ATX,
+ label: LABEL,
+ reference: REFERENCE,
+ autolink: AUTOLINK,
+ destinationLiteral: DESTINATION_LITERAL,
+ destinationRaw: DESTINATION_RAW,
+ titleQuote: TITLE_QUOTE,
+ titleApostrophe: TITLE_APOSTROPHE,
+ codeFencedLangGraveAccent: LANG_GRAVE,
+ codeFencedLangTilde: LANG_TILDE,
+ codeFencedMetaGraveAccent: META_GRAVE,
+ codeFencedMetaTilde: META_TILDE,
+ tableCell: TABLE_CELL_BIT,
+ link: LINK_BIT,
+ image: IMAGE_BIT,
+ strikethrough: STRIKETHROUGH,
+}
+const maskOf = (names: string[] | string | undefined) =>
+ [names ?? []].flat().reduce((mask, name) => mask | (BITS[name] ?? 0), 0)
+
+type Unsafe = {
+ character: string
+ inConstruct?: string | string[]
+ notInConstruct?: string[]
+ before?: string
+ after?: string
+ atBreak?: boolean
+}
+const FULL_PHRASING_SPANS = [
+ 'autolink',
+ 'destinationLiteral',
+ 'destinationRaw',
+ 'reference',
+ 'titleQuote',
+ 'titleApostrophe',
+]
+const LANG_META = [
+ 'codeFencedLangGraveAccent',
+ 'codeFencedLangTilde',
+ 'codeFencedMetaGraveAccent',
+ 'codeFencedMetaTilde',
+]
+// mdast-util-to-markdown's unsafe patterns, then gfm's: autolink literals (made heading-only, as @affordances/md
+// does), footnotes, strikethrough, tables and task lists
+const UNSAFE: Unsafe[] = [
+ { character: '\t', after: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: '\t', before: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: '\t', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] },
+ { character: '\r', inConstruct: [...LANG_META, 'destinationLiteral', 'headingAtx'] },
+ { character: '\n', inConstruct: [...LANG_META, 'destinationLiteral', 'headingAtx'] },
+ { character: '\r', before: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: '\r', after: '\\r', inConstruct: 'phrasing' },
+ { character: '\n', before: '\\n', inConstruct: 'phrasing' },
+ { character: '\n', after: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: ' ', after: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: ' ', before: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: ' ', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde'] },
+ { character: '!', after: '\\[', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { character: '"', inConstruct: 'titleQuote' },
+ { atBreak: true, character: '#' },
+ { character: '#', inConstruct: 'headingAtx', after: '(?:[\r\n]|$)' },
+ {
+ character: '&',
+ after: '[#A-Za-z]',
+ inConstruct: [
+ ...LANG_META,
+ 'destinationLiteral',
+ 'destinationRaw',
+ 'phrasing',
+ 'titleApostrophe',
+ 'titleQuote',
+ ],
+ },
+ { character: "'", inConstruct: 'titleApostrophe' },
+ { character: '(', inConstruct: 'destinationRaw' },
+ { before: '\\]', character: '(', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { atBreak: true, before: '\\d+', character: ')' },
+ { character: ')', inConstruct: 'destinationRaw' },
+ { atBreak: true, character: '*', after: '(?:[ \t\r\n*])' },
+ { character: '*', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { atBreak: true, character: '+', after: '(?:[ \t\r\n])' },
+ { atBreak: true, character: '-', after: '(?:[ \t\r\n-])' },
+ { atBreak: true, before: '\\d+', character: '.', after: '(?:[ \t\r\n]|$)' },
+ { atBreak: true, character: '<', after: '[!/?A-Za-z]' },
+ {
+ character: '<',
+ after: '[!/?A-Za-z]',
+ inConstruct: 'phrasing',
+ notInConstruct: FULL_PHRASING_SPANS,
+ },
+ { character: '<', inConstruct: 'destinationLiteral' },
+ { atBreak: true, character: '=' },
+ { atBreak: true, character: '>' },
+ { character: '>', inConstruct: 'destinationLiteral' },
+ { atBreak: true, character: '[' },
+ { character: '[', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { character: '[', inConstruct: ['label', 'reference'] },
+ { character: '\\', after: '[\\r\\n]', inConstruct: 'phrasing' },
+ { character: ']', inConstruct: ['label', 'reference'] },
+ { atBreak: true, character: '_' },
+ { character: '_', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { atBreak: true, character: '`' },
+ { character: '`', inConstruct: ['codeFencedLangGraveAccent', 'codeFencedMetaGraveAccent'] },
+ { character: '`', inConstruct: 'phrasing', notInConstruct: FULL_PHRASING_SPANS },
+ { atBreak: true, character: '~' },
+ { character: '<', inConstruct: 'autolink' },
+ { character: '>', inConstruct: 'autolink' },
+ { character: '\u007F', inConstruct: 'autolink' },
+ ...Array.from({ length: 33 }, (_, code) => ({
+ character: String.fromCharCode(code),
+ inConstruct: 'autolink',
+ })),
+ // gfm autolink literals, kept to headings
+ {
+ character: '@',
+ before: '[+\\-.\\w]',
+ after: '[\\-.\\w]',
+ inConstruct: 'headingAtx',
+ notInConstruct: ['autolink', 'link', 'image', 'label'],
+ },
+ {
+ character: '.',
+ before: '[Ww]',
+ after: '[\\-.\\w]',
+ inConstruct: 'headingAtx',
+ notInConstruct: ['autolink', 'link', 'image', 'label'],
+ },
+ {
+ character: ':',
+ before: '[ps]',
+ after: '\\/',
+ inConstruct: 'headingAtx',
+ notInConstruct: ['autolink', 'link', 'image', 'label'],
+ },
+ // footnotes
+ { character: '[', inConstruct: ['label', 'phrasing', 'reference'] },
+ // strikethrough
+ {
+ character: '~',
+ inConstruct: 'phrasing',
+ notInConstruct: [
+ 'autolink',
+ 'destinationLiteral',
+ 'destinationRaw',
+ 'reference',
+ 'titleQuote',
+ 'titleApostrophe',
+ ],
+ },
+ // tables
+ { character: '\r', inConstruct: 'tableCell' },
+ { character: '\n', inConstruct: 'tableCell' },
+ { atBreak: true, character: '|', after: '[\t :-]' },
+ { character: '|', inConstruct: 'tableCell' },
+ { atBreak: true, character: ':', after: '-' },
+ { atBreak: true, character: '-', after: '[:|-]' },
+ // task lists
+ { atBreak: true, character: '-', after: '[:|-]' },
+]
+
+type Pattern = {
+ character: string
+ in: number
+ notIn: number
+ // matches only next to a line ending: never in a value without one
+ newline: boolean
+ // whether it has a before (or is atBreak), or an after
+ before: boolean
+ after: boolean
+ regex: RegExp
+}
+const NEWLINE_ONLY = new Set(['[\\r\\n]', '\\n', '\\r'])
+const PATTERNS: Pattern[] = UNSAFE.map((pattern) => {
+ const before =
+ (pattern.atBreak ? '[\\r\\n][\\t ]*' : '') + (pattern.before ? `(?:${pattern.before})` : '')
+ return {
+ character: pattern.character,
+ // no inConstruct: always in scope
+ in: pattern.inConstruct === undefined ? -1 : maskOf(pattern.inConstruct),
+ notIn: maskOf(pattern.notInConstruct),
+ newline:
+ Boolean(pattern.atBreak) ||
+ NEWLINE_ONLY.has(pattern.before ?? '') ||
+ NEWLINE_ONLY.has(pattern.after ?? ''),
+ before: 'before' in pattern || Boolean(pattern.atBreak),
+ after: 'after' in pattern,
+ regex: new RegExp(
+ (before ? `(${before})` : '') +
+ (/[$()*+.?[\\\]^{|}]/.test(pattern.character) ? '\\' : '') +
+ pattern.character +
+ (pattern.after ? `(?:${pattern.after})` : ''),
+ 'g',
+ ),
+ }
+})
+
+// the patterns in scope for a set of constructs, and a test for text that none of them (or a backslash) can touch
+type Scope = { patterns: Pattern[]; special: RegExp; bareNewline: boolean }
+const scopes = new Map()
+const scopeOf = (mask: number): Scope => {
+ let scope = scopes.get(mask)
+ if (scope) return scope
+ const patterns = PATTERNS.filter(
+ (pattern) => (pattern.in === -1 || (pattern.in & mask) !== 0) && (pattern.notIn & mask) === 0,
+ )
+ const chars = new Set(['\\'])
+ for (const pattern of patterns) if (!pattern.newline) chars.add(pattern.character)
+ const set = [...chars]
+ .map((char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
+ .join('')
+ scope = {
+ patterns,
+ special: new RegExp(`[${set}\\r\\n]`),
+ bareNewline: patterns.some(
+ (pattern) => pattern.character === '\n' && !pattern.before && !pattern.after,
+ ),
+ }
+ scopes.set(mask, scope)
+ return scope
+}
+
+// the serializer's state: the constructs it's in, as names (the list handler reads them) and as a mask
+let stack: string[] = []
+let masks: number[] = []
+let mask = 0
+let indexStack: number[] = []
+let bulletCurrent: string | undefined
+let bulletLastUsed: string | undefined
+const enter = (name: string) => {
+ stack.push(name)
+ masks.push(mask)
+ mask |= BITS[name] ?? 0
+}
+const exit = () => {
+ stack.pop()
+ mask = masks.pop()!
+}
+
+// micromark's classes: 1 whitespace, 2 punctuation, 0 anything else (a letter, a digit, a lone surrogate)
+const PUNCTUATION = /[\p{P}\p{S}]/u
+const WHITESPACE = /\s/
+const classes = new Uint8Array(128)
+for (let code = 0; code < 128; code++) {
+ const char = String.fromCharCode(code)
+ classes[code] = code === 32 || WHITESPACE.test(char) ? 1 : PUNCTUATION.test(char) ? 2 : 0
+}
+const classify = (code: number): number => {
+ if (code !== code) return 0
+ if (code < 128) return classes[code]!
+ const char = String.fromCharCode(code)
+ return WHITESPACE.test(char) ? 1 : PUNCTUATION.test(char) ? 2 : 0
+}
+
+const ASCII_PUNCTUATION = /[!-/:-@[-`{-~]/
+const reference = (code: number) => `${code.toString(16).toUpperCase()};`
+// a string's first and last code points
+const high = (code: number) => code >= 0xd800 && code <= 0xdbff
+const low = (code: number) => code >= 0xdc00 && code <= 0xdfff
+const firstCharacter = (value: string) =>
+ high(value.charCodeAt(0)) && low(value.charCodeAt(1)) ? value.slice(0, 2) : value.charAt(0)
+const lastCharacter = (value: string) => {
+ const n = value.length
+ return n > 1 && low(value.charCodeAt(n - 1)) && high(value.charCodeAt(n - 2))
+ ? value.slice(-2)
+ : value.charAt(n - 1)
+}
+const isNewline = (code: number) => code === 10 || code === 13
+
+const escapeBackslashes = (value: string, after: string) => {
+ if (value.indexOf('\\') < 0 && after.indexOf('\\') < 0) return value
+ const expression = /\\(?=[!-/:-@[-`{-~])/g
+ const whole = value + after
+ const results: string[] = []
+ let start = 0
+ let match
+ while ((match = expression.exec(whole))) {
+ if (start !== match.index) results.push(value.slice(start, match.index))
+ results.push('\\')
+ start = match.index
+ }
+ results.push(value.slice(start))
+ return results.join('')
+}
+
+// text made safe to write between before and after in the current constructs: mdast-util-to-markdown's safe()
+const safe = (input: string, before: string, after: string, encode = ''): string => {
+ if (input === '') return escapeBackslashes(input, after)
+ const scope = scopeOf(mask)
+ // the fast path: nothing a pattern could match, and no line ending beside the text to start a construct
+ if (!scope.special.test(input)) {
+ const head = input.charCodeAt(0)
+ const tail = input.charCodeAt(input.length - 1)
+ const lineBefore = before !== '' && isNewline(before.charCodeAt(before.length - 1))
+ const lineAfter = after !== '' && isNewline(after.charCodeAt(0))
+ if (
+ !(lineBefore && atLineStart(input, head)) &&
+ !(lineAfter && (tail === 32 || tail === 9 || tail === 35)) &&
+ !(after === '' && tail === 46)
+ )
+ return input
+ }
+ return slowSafe(scope, input, before, after, encode)
+}
+// what can start a construct at the start of a line: an atBreak pattern's character, a digit (an ordered list), or
+// whitespace
+const LINE_START = new Uint8Array(128)
+for (const char of '#)*+-.<=>[_`~|: \t0123456789') LINE_START[char.charCodeAt(0)] = 1
+const atLineStart = (input: string, head: number) =>
+ head < 128 && LINE_START[head] === 1 && input !== ''
+
+const slowSafe = (scope: Scope, input: string, before: string, after: string, encode: string) => {
+ // what came before matters only from its last line ending (atBreak), or as one character
+ if (before.length > 1) {
+ const line = Math.max(before.lastIndexOf('\n'), before.lastIndexOf('\r'))
+ before = line >= 0 ? before.slice(line) : before.slice(-1)
+ }
+ const value = before + input + after
+ const offset = before.length
+ const end = value.length - after.length
+ const hasNewline = /[\r\n]/.test(value)
+ const positions: number[] = []
+ // per position matched: whether every pattern there had a before (1), an after (2)
+ const infos = new Map()
+ for (const pattern of scope.patterns) {
+ if (pattern.newline && !hasNewline) continue
+ if (input.indexOf(pattern.character) < 0) continue
+ const expression = pattern.regex
+ expression.lastIndex = 0
+ const sides = (pattern.before ? 1 : 0) | (pattern.after ? 2 : 0)
+ let match
+ while ((match = expression.exec(value))) {
+ const position = match.index + (pattern.before ? match[1]!.length : 0)
+ const info = infos.get(position)
+ if (info === undefined) {
+ positions.push(position)
+ infos.set(position, sides)
+ } else infos.set(position, info & sides)
+ }
+ }
+ if (!positions.length) return escapeBackslashes(input, after)
+ positions.sort((a, b) => a - b)
+ const result: string[] = []
+ let start = offset
+ for (let index = 0; index < positions.length; index++) {
+ const position = positions[index]!
+ if (position < start || position >= end) continue
+ // an intraword underscore run (snake_case) needs no escape
+ if (
+ value.charCodeAt(position) === 95 &&
+ position > 0 &&
+ classify(value.charCodeAt(position - 1)) === 0 &&
+ !infos.has(position - 1) &&
+ !(position - 1 === offset && /[*_]/.test(value.charAt(offset - 1)))
+ ) {
+ let sequenceEnd = position + 1
+ while (sequenceEnd < end && value.charCodeAt(sequenceEnd) === 95) sequenceEnd++
+ const skip = sequenceEnd - position - 1
+ if (
+ positions[index + skip] === sequenceEnd - 1 &&
+ sequenceEnd < value.length &&
+ classify(value.charCodeAt(sequenceEnd)) === 0 &&
+ !infos.has(sequenceEnd) &&
+ !(sequenceEnd === end - 1 && /[*_]/.test(value.charAt(end)))
+ ) {
+ index += skip
+ continue
+ }
+ }
+ const info = infos.get(position)!
+ // escaping what follows (or precedes) is enough
+ if (
+ (position + 1 < end &&
+ positions[index + 1] === position + 1 &&
+ info & 2 &&
+ infos.get(position + 1) === 0) ||
+ (position - 1 >= offset &&
+ positions[index - 1] === position - 1 &&
+ info & 1 &&
+ infos.get(position - 1) === 0)
+ )
+ continue
+ if (start !== position) result.push(escapeBackslashes(value.slice(start, position), '\\'))
+ start = position + 1
+ const char = value.charAt(position)
+ result.push(
+ ASCII_PUNCTUATION.test(char) && !encode.includes(char)
+ ? '\\' + char
+ : reference(value.charCodeAt(position)),
+ )
+ }
+ result.push(escapeBackslashes(value.slice(start, end), after))
+ return result.join('')
+}
+
+// emphasis, strong and strikethrough: attention whose markers are chosen once the run around them is known
+type Attention = { children: Item[]; sequences: string[] }
+type Item = string | Attention
+type Token = { value: string; attention: Attention | undefined }
+
+const attentionItem = (node: Md): Attention => {
+ const [construct, sequences] =
+ node.type === EMPHASIS
+ ? ['emphasis', EMPHASIS_SEQUENCES]
+ : node.type === STRONG
+ ? ['strong', STRONG_SEQUENCES]
+ : ['strikethrough', DELETE_SEQUENCES]
+ const sequence = sequences[0]!
+ enter(construct)
+ const children = phrasing(node, sequence, sequence)
+ exit()
+ return { children, sequences }
+}
+const EMPHASIS_SEQUENCES = ['_', '*']
+const STRONG_SEQUENCES = ['**', '__']
+const DELETE_SEQUENCES = ['~~', '~']
+const isAttention = (node: Md) =>
+ node.type === EMPHASIS || node.type === STRONG || node.type === DELETE
+
+const encodeEdge = (tokens: Token[], start: boolean) => {
+ const token = tokens[start ? 0 : tokens.length - 1]
+ if (!token || token.attention) return
+ const character = start ? firstCharacter(token.value) : lastCharacter(token.value)
+ const ref = reference(character.codePointAt(0)!)
+ if (start) token.value = ref + token.value.slice(character.length)
+ else {
+ let value = token.value.slice(0, token.value.length - character.length)
+ let escapes = 0
+ while (value.charCodeAt(value.length - 1 - escapes) === 92) escapes++
+ if (escapes % 2) value += '\\'
+ token.value = value + ref
+ }
+}
+
+const encodeInfo = (outside: number, inside: number, marker: string) => {
+ const outsideKind = classify(outside)
+ const insideKind = classify(inside)
+ if (outsideKind === 0)
+ return insideKind === 0 ? (marker === '_' ? BOTH : NEITHER) : insideKind === 1 ? BOTH : OUTSIDE
+ if (outsideKind === 1) return insideKind === 1 ? BOTH : NEITHER
+ return insideKind === 1 ? INSIDE : NEITHER
+}
+const BOTH = { inside: true, outside: true }
+const NEITHER = { inside: false, outside: false }
+const OUTSIDE = { inside: false, outside: true }
+const INSIDE = { inside: true, outside: false }
+
+const render = (
+ items: Item[],
+ chosen: Map,
+ before: string,
+ after: string,
+): Token[] => {
+ const tokens: Token[] = []
+ let encodeAfter: string | undefined
+ let previous = lastCharacter(before)
+ for (let index = 0; index < items.length; index++) {
+ const item = items[index]!
+ if (typeof item === 'string') {
+ const token: Token = { value: item, attention: undefined }
+ if (encodeAfter && encodeAfter === firstCharacter(item)) encodeEdge([token], true)
+ encodeAfter = undefined
+ tokens.push(token)
+ if (token.value) previous = lastCharacter(token.value)
+ continue
+ }
+ const sequence = chosen.get(item) || item.sequences[0]!
+ const marker = sequence.charAt(0)
+ const next = items[index + 1]
+ const outsideBefore = previous
+ const outsideAfter = firstCharacter(
+ next === undefined
+ ? after
+ : typeof next === 'string'
+ ? next
+ : chosen.get(next) || next.sequences[0]!,
+ )
+ const inside = render(item.children, chosen, sequence, sequence)
+ const head = inside.length > 0 ? inside[0]!.value : ''
+ const open = encodeInfo(
+ outsideBefore.charCodeAt(outsideBefore.length - 1),
+ head.charCodeAt(0),
+ marker,
+ )
+ if (open.inside) encodeEdge(inside, true)
+ const tail = inside.length > 0 ? lastCharacter(inside[inside.length - 1]!.value) : ''
+ const close = encodeInfo(outsideAfter.charCodeAt(0), tail.charCodeAt(tail.length - 1), marker)
+ if (close.inside) encodeEdge(inside, false)
+ if (open.outside && outsideBefore !== '\n' && outsideBefore !== '\r') encodeEdge(tokens, false)
+ if (close.outside) encodeAfter = outsideAfter
+ tokens.push({ value: sequence, attention: item }, ...inside, {
+ value: sequence,
+ attention: item,
+ })
+ previous = sequence.charAt(sequence.length - 1)
+ }
+ return tokens
+}
+
+type Run = {
+ tokens: Token[]
+ markers: Token[]
+ start: number
+ end: number
+ open: boolean
+ close: boolean
+ split: boolean
+}
+const STRICT = new Map([
+ ['*', false],
+ ['_', true],
+])
+const check = (tokens: Token[], before: string, after: string) => {
+ const runs: Run[] = []
+ const wrong = new Map()
+ const runOf = new Map()
+ let index = 0
+ while (index < tokens.length) {
+ if (!tokens[index]!.attention) {
+ index++
+ continue
+ }
+ const marker = tokens[index]!.value.charAt(0)
+ const strict = STRICT.get(marker)
+ let end = index + 1
+ while (end < tokens.length && tokens[end]!.attention && tokens[end]!.value.charAt(0) === marker)
+ end++
+ const head = index ? tokens[index - 1]!.value : before
+ const previous = classify(head.charCodeAt(head.length - 1))
+ const next = classify((end < tokens.length ? tokens[end]!.value : after).charCodeAt(0))
+ const open = !next || (next === 2 && Boolean(previous))
+ const close = !previous || (previous === 2 && Boolean(next))
+ const run: Run = {
+ tokens: tokens.slice(index, end),
+ markers: [],
+ start: 0,
+ end: 0,
+ open: strict ? open && (Boolean(previous) || !close) : open,
+ close: strict ? close && (Boolean(next) || !open) : close,
+ split: strict !== undefined,
+ }
+ for (const token of run.tokens) {
+ wrong.set(token, [...run.tokens])
+ runOf.set(token, run)
+ let size = token.value.length
+ while (size--) run.markers.push(token)
+ }
+ run.end = run.markers.length
+ runs.push(run)
+ index = end
+ }
+ pair(runs, wrong)
+ for (index = 0; index < tokens.length; index++) {
+ const involved = wrong.get(tokens[index]!)
+ if (involved) return { attention: candidates(tokens, involved, runOf), index }
+ }
+ return undefined
+}
+
+const candidates = (tokens: Token[], involved: Token[], runOf: Map) => {
+ const related = new Set()
+ for (const token of tokens) {
+ const siblings = runOf.get(token)
+ if (siblings && token.attention && involved.some((d) => d.attention === token.attention))
+ for (const sibling of siblings.tokens) related.add(sibling.attention!)
+ }
+ const ordered: Attention[] = []
+ for (const token of tokens)
+ if (token.attention && related.delete(token.attention)) ordered.push(token.attention)
+ ordered.reverse()
+ return ordered
+}
+
+const pair = (runs: Run[], wrong: Map) => {
+ const openersByMarker = new Map()
+ for (const closer of runs) {
+ const marker = closer.tokens[0]!.value.charAt(0)
+ let openers = openersByMarker.get(marker)
+ if (!openers) openersByMarker.set(marker, (openers = []))
+ let open = closer.close ? openers.length : 0
+ while (open-- && closer.start < closer.end) {
+ const opener = openers[open]!
+ const openerSize = opener.end - opener.start
+ const closerSize = closer.end - closer.start
+ if (
+ closer.split
+ ? (opener.close || closer.open) && closerSize % 3 && !((openerSize + closerSize) % 3)
+ : openerSize !== opener.markers.length || openerSize !== closerSize
+ )
+ continue
+ const size = closer.split ? (openerSize > 1 && closerSize > 1 ? 2 : 1) : closerSize
+ const opening = opener.markers.slice(opener.end - size, opener.end)
+ const closing = closer.markers.slice(closer.start, closer.start + size)
+ const openToken = opening[0]!
+ const closeToken = closing[0]!
+ if (
+ openToken === opening[size - 1] &&
+ openToken.value.length === size &&
+ closeToken === closing[size - 1] &&
+ closeToken.value.length === size &&
+ openToken.attention === closeToken.attention
+ ) {
+ wrong.delete(openToken)
+ wrong.delete(closeToken)
+ } else {
+ const involved = [...new Set([...opening, ...closing])]
+ for (const token of involved) {
+ const list = wrong.get(token)
+ if (list) list.push(...involved)
+ }
+ }
+ opener.end -= size
+ closer.start += size
+ if (opener.start === opener.end) openers.splice(open, 1)
+ open = openers.length
+ }
+ if (closer.open && closer.start < closer.end) openers.push(closer)
+ }
+}
+
+const improve = (
+ items: Item[],
+ chosen: Map,
+ mistake: { attention: Attention[]; index: number },
+ before: string,
+ after: string,
+) => {
+ for (const attention of mistake.attention) {
+ const current = chosen.get(attention) || attention.sequences[0]
+ for (const sequence of attention.sequences) {
+ if (sequence === current) continue
+ const trial = new Map(chosen)
+ trial.set(attention, sequence)
+ const tokens = render(items, trial, before, after)
+ const next = check(tokens, before, after)
+ if (!next || next.index > mistake.index) return { chosen: trial, mistake: next, tokens }
+ }
+ }
+ return undefined
+}
+
+const serialize = (items: Item[], before: string, after: string) => {
+ let plain = true
+ for (const item of items)
+ if (typeof item !== 'string') {
+ plain = false
+ break
+ }
+ if (plain) return items.join('')
+ let chosen = new Map()
+ const initial = render(items, chosen, before, after)
+ let tokens = initial
+ let mistake = check(tokens, before, after)
+ while (mistake) {
+ const next = improve(items, chosen, mistake, before, after)
+ if (!next) {
+ tokens = initial
+ break
+ }
+ chosen = next.chosen
+ tokens = next.tokens
+ mistake = next.mistake
+ }
+ let result = ''
+ for (const token of tokens) result += token.value
+ return result
+}
+
+// the first character a node writes, for the text before it
+const peek = (node: Md, parent: Md): string => {
+ switch (node.type) {
+ case EMPHASIS:
+ return '_'
+ case STRONG:
+ return '*'
+ case DELETE:
+ return '~'
+ case LINK:
+ return autolinked(node) ? '<' : '['
+ case IMAGE:
+ return '!'
+ case INLINE_CODE:
+ return '`'
+ case HTML:
+ return '<'
+ case TEXT: {
+ // a text's first character is written as it is unless a pattern can escape it there: only its own character
+ // and the one after it can say
+ const value = node.value
+ const head = value.charCodeAt(0)
+ if (
+ value !== '' &&
+ !scopeOf(mask).special.test(value.charAt(0)) &&
+ !((head === 32 || head === 9) && isNewline(value.charCodeAt(1)))
+ )
+ return firstCharacter(value)
+ return firstCharacter(handle(node, parent, '', ''))
+ }
+ default:
+ return firstCharacter(handle(node, parent, '', ''))
+ }
+}
+
+const phrasing = (parent: Md, before: string, after: string): Item[] => {
+ const kids = parent.kids
+ const results: Item[] = []
+ indexStack.push(-1)
+ for (let index = 0; index < kids.length; index++) {
+ const child = kids[index]!
+ indexStack[indexStack.length - 1] = index
+ const next = index + 1 < kids.length ? firstCharacter(peek(kids[index + 1]!, parent)) : after
+ if (isAttention(child)) {
+ const item = attentionItem(child)
+ results.push(item)
+ before = lastCharacter(item.sequences[0]!)
+ } else {
+ const value = handle(child, parent, before, next)
+ if (!value) continue
+ results.push(value)
+ // what a link, an image or inline code ends with is known, without reading what was written
+ before =
+ child.type === LINK
+ ? autolinked(child)
+ ? '>'
+ : ')'
+ : child.type === IMAGE
+ ? ')'
+ : child.type === INLINE_CODE
+ ? '`'
+ : lastCharacter(value)
+ }
+ }
+ indexStack.pop()
+ return results
+}
+const containerPhrasing = (parent: Md, before: string, after: string) =>
+ serialize(phrasing(parent, before, after), before, after)
+
+const containerFlow = (parent: Md): string => {
+ const kids = parent.kids
+ let result = ''
+ indexStack.push(-1)
+ for (let index = 0; index < kids.length; index++) {
+ const child = kids[index]!
+ indexStack[indexStack.length - 1] = index
+ result += handle(child, parent, '\n', '\n')
+ if (child.type !== LIST) bulletLastUsed = undefined
+ if (index < kids.length - 1) result += between(child, kids[index + 1]!, parent)
+ }
+ indexStack.pop()
+ return result
+}
+
+// the blank line between two blocks, or a single line ending in a tight list
+const between = (left: Md, right: Md, parent: Md) => {
+ if (parent.type !== LIST && parent.type !== LIST_ITEM) return '\n\n'
+ if (parent.spread) return '\n\n'
+ if (left.type === HTML) {
+ const kind = htmlKind(left.value)
+ if (kind === undefined || kind === 6 || kind === 7) return '\n\n'
+ }
+ if (left.type === BLOCKQUOTE && right.type === BLOCKQUOTE) return '\n\n'
+ if (
+ left.type === PARAGRAPH &&
+ right.type === LIST &&
+ ((right.ordered && right.depth !== 1) ||
+ (right.kids.length > 0 && right.kids[0]!.kids.length === 0))
+ )
+ return '\n\n'
+ if (left.type === PARAGRAPH && right.type === THEMATIC_BREAK) return '\n\n'
+ let tail = left
+ while (
+ (tail.type === BLOCKQUOTE || tail.type === LIST || tail.type === LIST_ITEM) &&
+ tail.kids.length > 0
+ )
+ tail = tail.kids[tail.kids.length - 1]!
+ if (tail.type !== PARAGRAPH) return '\n'
+ if (right.type === HTML) {
+ const kind = htmlKind(right.value)
+ if (kind === undefined || kind === 7) return '\n\n'
+ }
+ if (
+ (left.type === PARAGRAPH || left !== tail) &&
+ ((right.type === HEADING && setext(right)) || right.type === PARAGRAPH)
+ )
+ return '\n\n'
+ return '\n'
+}
+
+// micromark's html block kinds, as far as what the emitter writes needs: and are kind 7
+const htmlKind = (value: string): number | undefined => {
+ if (value.charCodeAt(0) !== 60) return undefined
+ const closing = value.charCodeAt(1) === 47
+ const name = /^[a-z][a-z0-9-]*/i.exec(value.slice(closing ? 2 : 1))?.[0]?.toLowerCase()
+ if (!name) return undefined
+ return HTML_BLOCK_NAMES.has(name) ? 6 : 7
+}
+const HTML_BLOCK_NAMES = new Set(
+ '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 h1 h2 h3 h4 h5 h6 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'.split(
+ ' ',
+ ),
+)
+
+// a node's text, as mdast-util-to-string reads it (image alts too)
+const toText = (node: Md): string => {
+ if (node.type === TEXT || node.type === INLINE_CODE || node.type === HTML || node.type === CODE)
+ return node.value
+ if (node.type === IMAGE) return node.value
+ let text = ''
+ for (const kid of node.kids) text += toText(kid)
+ return text
+}
+
+const hasBreak = (node: Md): boolean => {
+ for (const kid of node.kids) {
+ if (kid.type === BREAK) return true
+ if (
+ (kid.type === TEXT || kid.type === INLINE_CODE || kid.type === HTML) &&
+ /[\r\n]/.test(kid.value)
+ )
+ return true
+ if (hasBreak(kid)) return true
+ }
+ return false
+}
+// a heading written setext style: an h1 or h2 that holds a line break
+export const setext = (node: Md) => node.depth < 3 && toText(node) !== '' && hasBreak(node)
+
+// a link written : its text is its url. worked out once, kept in its depth (1 no, 2 yes)
+const autolinked = (node: Md) => {
+ if (node.depth === 0) node.depth = isAutolink(node) ? 2 : 1
+ return node.depth === 2
+}
+const isAutolink = (node: Md) => {
+ if (node.title || !node.url || node.kids.length !== 1 || node.kids[0]!.type !== TEXT) return false
+ const raw = node.kids[0]!.value
+ return (
+ (raw === node.url || 'mailto:' + raw === node.url) &&
+ /^[a-z][+\-.a-z]+:/i.test(node.url) &&
+ !/[\0- <>\u007F]/.test(node.url)
+ )
+}
+
+const indentLines = (
+ value: string,
+ map: (line: string, index: number, blank: boolean) => string,
+) => {
+ const eol = /\r?\n|\r/g
+ let result = ''
+ let start = 0
+ let line = 0
+ let match
+ while ((match = eol.exec(value))) {
+ const text = value.slice(start, match.index)
+ result += map(text, line, !text) + match[0]
+ start = match.index + match[0].length
+ line++
+ }
+ const text = value.slice(start)
+ return result + map(text, line, !text)
+}
+
+const ENCLOSE = /[\0- \u007F]/
+
+const handle = (node: Md, parent: Md | undefined, before: string, after: string): string => {
+ switch (node.type) {
+ case TEXT:
+ return safe(node.value, before, after)
+ case PARAGRAPH: {
+ enter('paragraph')
+ enter('phrasing')
+ const value = containerPhrasing(node, before, after)
+ exit()
+ exit()
+ return value
+ }
+ case HEADING:
+ return heading(node)
+ case ROOT: {
+ if (!node.kids.some(isPhrasing)) return containerFlow(node)
+ enter('phrasing')
+ const value = containerPhrasing(node, before, after)
+ exit()
+ return value
+ }
+ case THEMATIC_BREAK:
+ return '---'
+ case BLOCKQUOTE: {
+ enter('blockquote')
+ const value = indentLines(containerFlow(node), (line, _, blank) =>
+ blank ? '>' + line : '> ' + line,
+ )
+ exit()
+ return value
+ }
+ case LIST:
+ return list(node, parent)
+ case LIST_ITEM:
+ return listItem(node, parent)
+ case CODE:
+ return code(node)
+ case TABLE:
+ return table(node)
+ case TABLE_ROW: {
+ enter('table')
+ const row = rowData(node)
+ exit()
+ const value = markdownTable([row], node.align ?? [])
+ return value.slice(0, value.indexOf('\n'))
+ }
+ case TABLE_CELL:
+ return cell(node)
+ case HTML:
+ return node.value
+ case EMPHASIS:
+ case STRONG:
+ case DELETE: {
+ // outside phrasing (a peek, say): attention on its own
+ enter('phrasing')
+ const value = serialize([attentionItem(node)], before, after)
+ exit()
+ return value
+ }
+ case INLINE_CODE:
+ return inlineCode(node)
+ case BREAK:
+ return scopeOf(mask).bareNewline ? (/[\t ]/.test(before) ? '' : ' ') : '\\\n'
+ case LINK:
+ return link(node, before)
+ case IMAGE:
+ return image(node)
+ }
+ return ''
+}
+
+const heading = (node: Md) => {
+ const rank = Math.max(Math.min(6, node.depth || 1), 1)
+ if (setext(node)) {
+ enter('headingSetext')
+ enter('phrasing')
+ const value = containerPhrasing(node, '\n', '\n')
+ exit()
+ exit()
+ return (
+ value +
+ '\n' +
+ (rank === 1 ? '=' : '-').repeat(
+ value.length - (Math.max(value.lastIndexOf('\r'), value.lastIndexOf('\n')) + 1),
+ )
+ )
+ }
+ const sequence = '#'.repeat(rank)
+ enter('headingAtx')
+ enter('phrasing')
+ let value = containerPhrasing(node, '# ', '\n')
+ const head = value.charCodeAt(0)
+ if (head === 9 || head === 32) value = reference(head) + value.slice(1)
+ value = value ? sequence + ' ' + value : sequence
+ exit()
+ exit()
+ return value
+}
+
+const list = (node: Md, parent: Md | undefined) => {
+ enter('list')
+ const saved = bulletCurrent
+ let bullet = node.ordered ? '.' : '-'
+ const other = node.ordered ? ')' : '*'
+ let different = parent && bulletLastUsed ? bullet === bulletLastUsed : false
+ if (!node.ordered) {
+ const first = node.kids[0]
+ const n = stack.length
+ const at = indexStack.length
+ if (
+ first &&
+ !first.kids[0] &&
+ stack[n - 1] === 'list' &&
+ stack[n - 2] === 'listItem' &&
+ stack[n - 3] === 'list' &&
+ stack[n - 4] === 'listItem' &&
+ indexStack[at - 1] === 0 &&
+ indexStack[at - 2] === 0 &&
+ indexStack[at - 3] === 0
+ )
+ different = true
+ // the rule is - too, so an item that starts with a rule needs the other bullet
+ if (first)
+ for (const item of node.kids)
+ if (item.type === LIST_ITEM && item.kids[0]?.type === THEMATIC_BREAK) {
+ different = true
+ break
+ }
+ }
+ if (different) bullet = other
+ bulletCurrent = bullet
+ const value = containerFlow(node)
+ bulletLastUsed = bullet
+ bulletCurrent = saved
+ exit()
+ return value
+}
+
+const listItem = (node: Md, parent: Md | undefined) => {
+ let bullet = bulletCurrent || '-'
+ if (parent && parent.type === LIST && parent.ordered)
+ bullet = (parent.depth > -1 ? parent.depth : 1) + parent.kids.indexOf(node) + bullet
+ const size = bullet.length + 1
+ enter('listItem')
+ const pad = ' '.repeat(size)
+ let value = indentLines(containerFlow(node), (line, index, blank) =>
+ index ? (blank ? '' : pad) + line : (blank ? bullet : bullet + ' ') + line,
+ )
+ exit()
+ // a task list item
+ if (typeof node.checked === 'boolean' && node.kids[0]?.type === PARAGRAPH)
+ value = value.replace(
+ /^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,
+ (whole) => whole + (node.checked ? '[x] ' : '[ ] '),
+ )
+ return value
+}
+
+const longestStreak = (value: string, substring: string) => {
+ let index = value.indexOf(substring)
+ let expected = index
+ let count = 0
+ let max = 0
+ while (index !== -1) {
+ if (index === expected) {
+ if (++count > max) max = count
+ } else count = 1
+ expected = index + substring.length
+ index = value.indexOf(substring, expected)
+ }
+ return max
+}
+
+const code = (node: Md) => {
+ const raw = node.value
+ const sequence = '`'.repeat(Math.max(longestStreak(raw, '`') + 1, 3))
+ enter('codeFenced')
+ let value = sequence
+ if (node.lang) {
+ enter('codeFencedLangGraveAccent')
+ value += safe(node.lang, value, ' ', '`')
+ exit()
+ }
+ if (node.lang && node.meta) {
+ enter('codeFencedMetaGraveAccent')
+ value += ' '
+ value += safe(node.meta, value, '\n', '`')
+ exit()
+ }
+ value += '\n'
+ if (raw) value += raw + '\n'
+ value += sequence
+ exit()
+ return value
+}
+
+const inlineCode = (node: Md) => {
+ let value = node.value
+ let sequence = '`'
+ if (value.indexOf('`') >= 0)
+ while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) sequence += '`'
+ if (
+ /[^\n\r ]/.test(value) &&
+ ((/^[\n\r ]/.test(value) && /[\n\r ]$/.test(value)) || /^`|`$/.test(value))
+ )
+ value = ' ' + value + ' '
+ // a line ending that would start a construct is a space instead
+ if (/[\r\n]/.test(value))
+ for (const pattern of PATTERNS) {
+ if (!UNSAFE[PATTERNS.indexOf(pattern)]!.atBreak) continue
+ const expression = pattern.regex
+ expression.lastIndex = 0
+ let match
+ while ((match = expression.exec(value))) {
+ let position = match.index
+ if (value.charCodeAt(position) === 10 && value.charCodeAt(position - 1) === 13) position--
+ value = value.slice(0, position) + ' ' + value.slice(match.index + 1)
+ }
+ }
+ value = sequence + value + sequence
+ // in a table, a pipe would end the cell
+ if ((mask & TABLE_CELL_BIT) !== 0) value = value.replace(/\|/g, '\\$&')
+ return value
+}
+
+const destination = (url: string, value: string, title: string | undefined, enclose: boolean) => {
+ if ((!url && typeof title === 'string') || enclose) {
+ enter('destinationLiteral')
+ const out = '<' + safe(url, value + '<', '>') + '>'
+ exit()
+ return out
+ }
+ enter('destinationRaw')
+ const out = safe(url, value, typeof title === 'string' ? ' ' : ')')
+ exit()
+ return out
+}
+const titled = (title: string | undefined, value: string) => {
+ if (typeof title !== 'string') return ''
+ enter('titleQuote')
+ const out = ' "' + safe(title, value + ' "', '"') + '"'
+ exit()
+ return out
+}
+
+const link = (node: Md, before: string) => {
+ if (autolinked(node)) {
+ const savedStack = stack
+ const savedMask = mask
+ stack = stack.filter((name) => name !== 'phrasing')
+ mask &= ~PHRASING
+ enter('autolink')
+ const value = '<' + containerPhrasing(node, '<', '>') + '>'
+ exit()
+ stack = savedStack
+ mask = savedMask
+ return value
+ }
+ enter('link')
+ enter('label')
+ const text = containerPhrasing(node, '[', '](')
+ exit()
+ let value = '[' + text + ']('
+ const enclose = ENCLOSE.test(node.url)
+ const last = before.charAt(before.length - 1)
+ let title = node.title || undefined
+ // text that reads as a definition ([x]: …) at the start of a line gets an empty title, so it isn't one
+ if (!title && !enclose && (last === '\n' || last === '\r')) {
+ let index = 0
+ while (index < text.length && text.charCodeAt(index) !== 93)
+ index += text.charCodeAt(index) === 92 ? 2 : 1
+ if (text.charCodeAt(index + 1) === 58) title = ''
+ }
+ value += destination(node.url, value, title, enclose)
+ value += titled(title, value)
+ value += ')'
+ exit()
+ return value
+}
+
+const image = (node: Md) => {
+ enter('image')
+ enter('label')
+ let value = '![' + safe(node.value, '![', ']') + ']('
+ exit()
+ const title = node.title || undefined
+ if ((!node.url && title) || ENCLOSE.test(node.url)) {
+ enter('destinationLiteral')
+ value += '<' + safe(node.url, value + '<', '>') + '>'
+ exit()
+ } else {
+ enter('destinationRaw')
+ value += safe(node.url, value, title ? ' ' : ')')
+ exit()
+ }
+ value += titled(title, value)
+ value += ')'
+ exit()
+ return value
+}
+
+const cell = (node: Md) => {
+ enter('tableCell')
+ enter('phrasing')
+ const value = containerPhrasing(node, '|', '|')
+ exit()
+ exit()
+ return value
+}
+const rowData = (row: Md) => {
+ enter('tableRow')
+ const cells: string[] = []
+ for (const kid of row.kids) cells.push(cell(kid))
+ exit()
+ return cells
+}
+const table = (node: Md) => {
+ enter('table')
+ const matrix: string[][] = []
+ for (const row of node.kids) matrix.push(rowData(row))
+ exit()
+ return markdownTable(matrix, node.align ?? [])
+}
+
+// markdown-table (MIT, Titus Wormer) as gfm configures it: padded cells, delimiters aligned
+const markdownTable = (matrix: string[][], align: (string | null)[]) => {
+ const longest: number[] = []
+ let most = 0
+ for (const row of matrix) {
+ if (row.length > most) most = row.length
+ for (let column = 0; column < row.length; column++) {
+ const size = row[column]!.length
+ if (longest[column] === undefined || size > longest[column]!) longest[column] = size
+ }
+ }
+ const alignments: number[] = []
+ for (let column = 0; column < most; column++) {
+ const value = align[column]
+ const kind = typeof value === 'string' ? value.codePointAt(0) : 0
+ alignments[column] =
+ kind === 67 || kind === 99
+ ? 99
+ : kind === 76 || kind === 108
+ ? 108
+ : kind === 82 || kind === 114
+ ? 114
+ : 0
+ }
+ const delimiters: string[] = []
+ const delimiterSizes: number[] = []
+ for (let column = 0; column < most; column++) {
+ const kind = alignments[column]
+ const before = kind === 99 || kind === 108 ? ':' : ''
+ const after = kind === 99 || kind === 114 ? ':' : ''
+ let size = Math.max(1, longest[column]! - before.length - after.length)
+ const value = before + '-'.repeat(size) + after
+ size = before.length + size + after.length
+ if (size > longest[column]!) longest[column] = size
+ delimiterSizes[column] = size
+ delimiters[column] = value
+ }
+ const rows = matrix.length ? [matrix[0]!, delimiters, ...matrix.slice(1)] : [delimiters]
+ const lines: string[] = []
+ for (let index = 0; index < rows.length; index++) {
+ const row = rows[index]!
+ let line = ''
+ for (let column = 0; column < most; column++) {
+ const value = row[column] ?? ''
+ const own = index === 1 ? delimiterSizes[column]! : value.length
+ const size = longest[column]! - own
+ const kind = alignments[column]
+ let before = ''
+ let after = ''
+ if (kind === 114) before = ' '.repeat(size)
+ else if (kind === 99) {
+ if (size % 2) {
+ before = ' '.repeat(size / 2 + 0.5)
+ after = ' '.repeat(size / 2 - 0.5)
+ } else before = after = ' '.repeat(size / 2)
+ } else after = ' '.repeat(size)
+ if (!column) line += '|'
+ line += ' ' + before + value + after + ' |'
+ }
+ lines.push(line)
+ }
+ return lines.join('\n')
+}
+
+// the markdown for a root, as toMarkdown writes it
+export const toMarkdown = (root: Md): string => {
+ stack = []
+ masks = []
+ mask = 0
+ indexStack = []
+ bulletCurrent = undefined
+ bulletLastUsed = undefined
+ let result = handle(root, undefined, '\n', '\n')
+ const last = result.charCodeAt(result.length - 1)
+ if (result && last !== 10 && last !== 13) result += '\n'
+ return result
+}
+
+// a heading's text as a reader sees it (headingOf in @affordances/md): what it says, without images or a url shown as
+// itself, nor the brackets right around one
+export const headingText = (node: Md): string | undefined => {
+ const pieces: (string | null)[] = []
+ const walk = (parent: Md) => {
+ for (const kid of parent.kids) {
+ if (kid.type === TEXT || kid.type === INLINE_CODE || kid.type === HTML) pieces.push(kid.value)
+ else if (kid.type === BREAK) pieces.push(' ')
+ else if (kid.type === IMAGE) continue
+ else if (kid.type === LINK && autolinked(kid)) pieces.push(null)
+ else walk(kid)
+ }
+ }
+ walk(node)
+ pieces.forEach((piece, n) => {
+ if (piece !== null) return
+ const before = pieces[n - 1]
+ const after = pieces[n + 1]
+ const open = typeof before === 'string' ? /[([<]\s*$/.exec(before)?.[0] : undefined
+ const close = typeof after === 'string' ? /^\s*([)\]>])/.exec(after) : undefined
+ if (open && close && close[1] === BRACKETS[open.trim()]) {
+ pieces[n - 1] = before!.slice(0, -open.length)
+ pieces[n + 1] = after!.slice(close[0].length)
+ }
+ })
+ return pieces.join('').replace(/\s+/g, ' ').trim() || undefined
+}
+const BRACKETS: Record = { '(': ')', '[': ']', '<': '>' }
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md-core/src/emit-prune.ts
new file mode 100644
index 0000000..31d80d4
--- /dev/null
+++ b/packages/md-core/src/emit-prune.ts
@@ -0,0 +1,670 @@
+import { decode } from './entities.ts'
+import type { Element, Node } from './types.ts'
+
+// what @affordances/md's prune and extract leave of the page, read lazily: kidsOf(el) is an element's children as
+// prune leaves them (hidden things gone, empty links named or gone, inline boxes spaced, repeated links once), cached
+// on the element for the emit call that asked. nothing is copied unless it changes
+
+// the cache, on the element itself: the pruned children and the emit call they're for
+// pk, pe: the pruned children and the emit call they're for; lv, le: whether it's code, and for which call; pf: the
+// attribute names it has that anything here reads (-1 before they're read)
+type Pruned = Element & {
+ pk?: Node[] | undefined
+ pe?: number
+ lv?: boolean
+ le?: number
+ pf?: number
+}
+// the cache's fields, added at once and in one order, so every element the parser made has one shape after
+const touch = (el: Pruned) => {
+ if (el.pe === undefined) {
+ el.pk = undefined
+ el.pe = -1
+ el.lv = false
+ el.le = -1
+ el.pf = -1
+ }
+}
+let epoch = 0
+// chrome (nav, header, footer, …) is stripped too: the page has no
+let stripChrome = false
+export const begin = (strip: boolean) => {
+ epoch++
+ stripChrome = strip
+ byId = undefined
+}
+let page: Element | undefined
+export const setPage = (root: Element) => {
+ page = root
+ byId = undefined
+}
+
+// an element prune made, already pruned
+export const made = (from: Element, kids: Node[], tag = from.tag): Element => {
+ const el: Pruned = {
+ tag,
+ attrs: from.attrs,
+ kids,
+ up: from.up,
+ map: from.map,
+ pk: kids,
+ pe: epoch,
+ lv: false,
+ le: -1,
+ pf: (from as Pruned).pf ?? -1,
+ }
+ return el
+}
+
+const CHROME_TAGS = new Set(['nav', 'header', 'footer', 'aside', 'dialog'])
+const CHROME_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary'])
+
+// the attribute names an element has, of those read here: one scan of its attributes, ever. most elements have
+// none of them, and the scan is far cheaper than parsing every element's attributes
+const HIDDEN = 1
+const ARIA_HIDDEN = 2
+const STYLE = 4
+const ROLE = 8
+const EDITABLE = 16
+const MARKED = 32
+export const MDAST = 64
+export const DATA_TITLE = 128
+export const NOWRAP = 256
+export const TITLE = 512
+export const SPAN = 1024
+export const ALIGN = 2048
+const PRUNES = HIDDEN | ARIA_HIDDEN | STYLE | ROLE | EDITABLE | MARKED
+const space = (code: number) =>
+ code === 32 || code === 9 || code === 10 || code === 12 || code === 13
+// whether the name at start is this word: compared by hand, first character first (most names aren't ours)
+const is = (s: string, start: number, word: string) => {
+ for (let k = 0; k < word.length; k++)
+ if (s.charCodeAt(start + k) !== word.charCodeAt(k)) return false
+ return true
+}
+const named = (s: string, start: number, length: number) => {
+ const head = s.charCodeAt(start)
+ switch (length) {
+ case 4:
+ return head === 114 && is(s, start, 'role') ? ROLE : 0
+ case 5:
+ return head === 115 && is(s, start, 'style')
+ ? STYLE
+ : head === 116 && is(s, start, 'title')
+ ? TITLE
+ : head === 97 && is(s, start, 'align')
+ ? ALIGN
+ : 0
+ case 7:
+ return (head === 114 && is(s, start, 'rowspan')) || (head === 99 && is(s, start, 'colspan'))
+ ? SPAN
+ : 0
+ case 6:
+ return head === 104 && is(s, start, 'hidden')
+ ? HIDDEN
+ : head === 110 && is(s, start, 'nowrap')
+ ? NOWRAP
+ : 0
+ case 9:
+ return head === 100 && is(s, start, 'data-mode') ? MARKED : 0
+ case 10:
+ return head !== 100
+ ? 0
+ : is(s, start, 'data-mdast')
+ ? MDAST
+ : is(s, start, 'data-title')
+ ? DATA_TITLE
+ : 0
+ case 11:
+ return head === 97 && is(s, start, 'aria-hidden') ? ARIA_HIDDEN : 0
+ case 15:
+ return head === 99 && is(s, start, 'contenteditable') ? EDITABLE : 0
+ case 19:
+ return head === 100 && is(s, start, 'data-affordances-md') ? MARKED : 0
+ }
+ return 0
+}
+// the attribute names, as the tokenizer reads them, jumping over quoted values (most of the string); names as
+// written in lowercase, as pages write them
+const scan = (s: string) => {
+ const n = s.length
+ let found = 0
+ let i = 0
+ while (i < n) {
+ let c = s.charCodeAt(i)
+ while (space(c) || c === 47) c = s.charCodeAt(++i)
+ if (i >= n) break
+ const start = i
+ if (c === 61) i++
+ while (i < n) {
+ c = s.charCodeAt(i)
+ if (space(c) || c === 47 || c === 61) break
+ i++
+ }
+ found |= named(s, start, i - start)
+ while (space(c)) c = s.charCodeAt(++i)
+ if (c === 61) {
+ c = s.charCodeAt(++i)
+ while (space(c)) c = s.charCodeAt(++i)
+ if (c === 34 || c === 39) {
+ const end = s.indexOf(c === 34 ? '"' : "'", i + 1)
+ i = end < 0 ? n : end + 1
+ } else while (i < n && !space(s.charCodeAt(i))) i++
+ }
+ }
+ return found
+}
+// one attribute's value, as read() reads it (decoded; '' without a value; the first of a repeated name), without
+// parsing the rest: a scan to its name. names as written in lowercase, as with the scan above
+export const read = (el: Element, name: string): string | undefined => {
+ if (el.map !== undefined) return el.map.get(name)
+ const s = el.attrs
+ const n = s.length
+ let i = 0
+ while (i < n) {
+ let c = s.charCodeAt(i)
+ while (space(c) || c === 47) c = s.charCodeAt(++i)
+ if (i >= n) break
+ const start = i
+ if (c === 61) i++
+ while (i < n) {
+ c = s.charCodeAt(i)
+ if (space(c) || c === 47 || c === 61) break
+ i++
+ }
+ const match = i - start === name.length && is(s, start, name)
+ while (space(c)) c = s.charCodeAt(++i)
+ let value = ''
+ if (c === 61) {
+ c = s.charCodeAt(++i)
+ while (space(c)) c = s.charCodeAt(++i)
+ if (c === 34 || c === 39) {
+ const end = s.indexOf(c === 34 ? '"' : "'", i + 1)
+ if (match) value = s.slice(i + 1, end < 0 ? n : end)
+ i = end < 0 ? n : end + 1
+ } else {
+ const from = i
+ while (i < n && !space(s.charCodeAt(i))) i++
+ if (match) value = s.slice(from, i)
+ }
+ }
+ if (match) return decode(value, true)
+ }
+ return undefined
+}
+export const flags = (el: Element): number => {
+ if (el.attrs === '') return 0
+ const cached = el as Pruned
+ touch(cached)
+ if (cached.pf! < 0) cached.pf = scan(el.attrs)
+ return cached.pf!
+}
+const mentions = (el: Element) => (flags(el) & PRUNES) !== 0
+const marked = (el: Element) =>
+ el.tag === 'affordances-md' ? read(el, 'data-mode') : read(el, 'data-affordances-md')
+const unhidden = (el: Element) => {
+ const mode = flags(el) & MARKED ? marked(el) : undefined
+ return mode === 'only' || mode === 'show'
+}
+
+// a style attribute's declarations as [property, value], lowercased, without !important
+const codePoint = (hex: string) => {
+ const code = Number.parseInt(hex, 16)
+ return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)
+ ? '\ufffd'
+ : String.fromCodePoint(code)
+}
+const cssText = (style: string) =>
+ style
+ .replace(/\/\*[\s\S]*?(\*\/|$)/g, '')
+ .replace(/\\([0-9a-f]{1,6})[ \t\n\r\f]?|\\([^\n0-9a-f])/gi, (_, hex: string, char: string) =>
+ hex ? codePoint(hex) : char,
+ )
+type Declarations = [property: string, value: string][]
+const declarations = (style: string): Declarations =>
+ cssText(style)
+ .split(';')
+ .map((declaration) => {
+ const [property = '', value = ''] = declaration
+ .split(':')
+ .map((part) => part.trim().toLowerCase())
+ return [property, value.replace(/\s*!\s*important$/, '')]
+ })
+// display: none, visibility: hidden or content-visibility: hidden, however it's written; a style that can't say
+// any of it (no such keyword, no escape, no comment) isn't parsed
+const HIDING = /none|hidden|collapse|[\\/]/i
+const styleHidden = (style: string | undefined) =>
+ style !== undefined &&
+ HIDING.test(style) &&
+ declarations(style).some(
+ ([property, keyword]) =>
+ (property === 'display' && keyword === 'none') ||
+ (property === 'visibility' && (keyword === 'hidden' || keyword === 'collapse')) ||
+ (property === 'content-visibility' && keyword === 'hidden'),
+ )
+// whether a style's display is one of these
+const DISPLAY = /display|[\\/]/i
+const styleDisplays = (style: string | undefined, display: RegExp) =>
+ style !== undefined &&
+ DISPLAY.test(style) &&
+ declarations(style).some(([property, value]) => property === 'display' && display.test(value))
+export const role = (el: Element) => read(el, 'role') ?? ''
+const editor = (el: Element) => {
+ const r = role(el)
+ if (r === 'textbox' || r === 'searchbox') return true
+ const editable = read(el, 'contenteditable')
+ return editable !== undefined && editable !== 'false'
+}
+
+// what prune leaves out, with everything in it: what's hidden from people (unless marked for agents), what's marked
+// skip, and editors, whose text is what someone typed
+const dropped = (el: Element): boolean => {
+ const found = flags(el)
+ if ((found & PRUNES) === 0) return false
+ const mode = found & MARKED ? marked(el) : undefined
+ if (mode === 'skip') return true
+ if (found & (ROLE | EDITABLE) && editor(el)) return true
+ if (mode === 'only' || mode === 'show') return false
+ return (
+ (found & HIDDEN) !== 0 ||
+ ((found & ARIA_HIDDEN) !== 0 && read(el, 'aria-hidden') === 'true') ||
+ ((found & STYLE) !== 0 && styleHidden(read(el, 'style')))
+ )
+}
+const chrome = (el: Element) => {
+ const maybe = mentions(el)
+ return (
+ (CHROME_TAGS.has(el.tag) || (maybe && CHROME_ROLES.has(role(el)))) && !(maybe && unhidden(el))
+ )
+}
+
+// whether prune drops an element or what holds it
+const hiddenAbove = (el: Element) => {
+ for (let at: Element | null = el; at; at = at.up) if (dropped(at)) return true
+ return false
+}
+// the page's : the outermost, a real before a role=main, among what prune keeps. the walk reads tags
+// alone, and asks whether a landmark it finds is hidden only then
+export const findMain = (root: Element): Element | undefined => {
+ let byRole: Element | undefined
+ const walk = (parent: Element): Element | undefined => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string') continue
+ if (kid.tag === 'main') {
+ if (!hiddenAbove(kid)) return kid
+ continue
+ }
+ if (
+ kid.attrs !== '' &&
+ kid.attrs.indexOf('main') >= 0 &&
+ flags(kid) & ROLE &&
+ role(kid) === 'main'
+ ) {
+ if (!hiddenAbove(kid)) byRole ??= kid
+ continue
+ }
+ const found = walk(kid)
+ if (found) return found
+ }
+ return undefined
+ }
+ return walk(root) ?? byRole
+}
+
+// the page's ids, among what prune keeps, once a link's label needs them
+let byId: Map | undefined
+const ids = () => {
+ if (byId) return byId
+ byId = new Map()
+ const walk = (parent: Element) => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string' || dropped(kid)) continue
+ const id = read(kid, 'id')
+ if (id !== undefined && !byId!.has(id)) byId!.set(id, kid)
+ walk(kid)
+ }
+ }
+ if (page) walk(page)
+ return byId
+}
+
+const ASCII_SPACE = /[\t\n\f\r ]+/
+export const classes = (el: Element): string[] => {
+ const value = read(el, 'class')
+ return value ? value.split(ASCII_SPACE).filter(Boolean) : []
+}
+
+// an element's text, as hast-util-to-string reads it: every text in it, as written
+export const toString = (node: Node): string => {
+ if (typeof node === 'string') return node
+ let text = ''
+ for (const kid of kidsOf(node)) text += typeof kid === 'string' ? kid : toString(kid)
+ return text
+}
+export const text = (node: Node | undefined) =>
+ node === undefined ? '' : toString(node).replace(/\s+/g, ' ').trim()
+
+const VALUED = new Set([
+ 'input',
+ 'select',
+ 'option',
+ 'optgroup',
+ 'textarea',
+ 'datalist',
+ 'output',
+ 'meter',
+ 'progress',
+])
+const VALUE_ROLES = new Set(['spinbutton', 'slider'])
+// a control whose text is a value, not a name
+const valueBearing = (el: Element) =>
+ VALUED.has(el.tag) || (mentions(el) && (VALUE_ROLES.has(role(el)) || editor(el)))
+
+// children without the descendants drop picks, at any depth; the same array when nothing goes
+const without = (kids: Node[], drop: (el: Element) => boolean): Node[] => {
+ let out: Node[] | undefined
+ for (let i = 0; i < kids.length; i++) {
+ const kid = kids[i]!
+ if (typeof kid === 'string') {
+ out?.push(kid)
+ continue
+ }
+ if (drop(kid)) {
+ out ??= kids.slice(0, i)
+ continue
+ }
+ const inner = kidsOf(kid)
+ const kept = without(inner, drop)
+ if (kept !== inner) {
+ out ??= kids.slice(0, i)
+ out.push(made(kid, kept))
+ } else out?.push(kid)
+ }
+ return out ?? kids
+}
+// children with elements of one tag replaced by what's in them, at any depth
+const unwrap = (kids: Node[], tag: string): Node[] =>
+ kids.flatMap((kid): Node[] =>
+ typeof kid === 'string'
+ ? [kid]
+ : kid.tag === tag
+ ? unwrap(kidsOf(kid), tag)
+ : [made(kid, unwrap(kidsOf(kid), tag))],
+ )
+
+// a name's words: what an element says, without its controls or what's never content
+const words = (el: Element | undefined): string =>
+ el && !valueBearing(el)
+ ? text(
+ made(
+ el,
+ without(kidsOf(el), (inner) => valueBearing(inner) || inner.tag === 'button'),
+ ),
+ )
+ : ''
+// what an icon or avatar link is called without content: its aria-labelledby, aria-label or title
+export const linkLabel = (a: Element): string => {
+ if (a.attrs === '') return ''
+ const labelledBy = read(a, 'aria-labelledby')
+ if (labelledBy) {
+ const names = labelledBy
+ .split(/\s+/)
+ .filter(Boolean)
+ .flatMap((id) => ids().get(id) ?? [])
+ .map(words)
+ .filter(Boolean)
+ .join(' ')
+ if (names) return names
+ }
+ return (read(a, 'aria-label') ?? '').trim() || (read(a, 'title') ?? '').trim()
+}
+
+// images with a description, which an agent can read
+const described = (node: Node): Element[] => {
+ const found: Element[] = []
+ const walk = (el: Element) => {
+ for (const kid of kidsOf(el)) {
+ if (typeof kid === 'string') continue
+ if (kid.tag === 'img' && read(kid, 'alt')) found.push(kid)
+ walk(kid)
+ }
+ }
+ if (typeof node !== 'string') walk(node)
+ return found
+}
+const hasDescribed = (node: Node): boolean => {
+ if (typeof node === 'string') return false
+ for (const kid of kidsOf(node)) {
+ if (typeof kid === 'string') continue
+ if ((kid.tag === 'img' && read(kid, 'alt')) || hasDescribed(kid)) return true
+ }
+ return false
+}
+const nothingToRead = (node: Element) => !toString(node).trim() && !hasDescribed(node)
+
+const INLINE = new Set(['a', 'span', 'code', 'strong', 'em', 'b', 'i', 'small', 'time', 'abbr'])
+const isInline = (node: Node | undefined): node is Element =>
+ node !== undefined && typeof node !== 'string' && INLINE.has(node.tag)
+const isBlank = (node: Node | undefined) => typeof node === 'string' && !node.trim()
+const emptyBlock = (el: Element) =>
+ !INLINE.has(el.tag) && el.tag !== 'img' && el.tag !== 'br' && nothingToRead(el)
+const linkDrop = (el: Element) => valueBearing(el) || emptyBlock(el)
+
+// links and the text it renders as: its text, else its described images, else its label
+const linkText = (a: Element) =>
+ text(a) ||
+ described(a)
+ .map((img) => `${read(img, 'alt')} ${read(img, 'src')}`)
+ .join(' ') ||
+ linkLabel(a)
+
+// a skeleton table (placeholder cells waiting on data): nothing to read in any cell, or a header over empty rows
+const cellsOf = (row: Element, tags: Set) =>
+ kidsOf(row).filter((cell): cell is Element => typeof cell !== 'string' && tags.has(cell.tag))
+const CELLS = new Set(['td', 'th'])
+const TD = new Set(['td'])
+const emptyRow = (row: Element) =>
+ cellsOf(row, CELLS).every((cell) => !text(cell) && !hasDescribed(cell))
+const skeleton = (table: Element) => {
+ const rows: Element[] = []
+ const header = new Set()
+ const walk = (parent: Element, inHead: boolean) => {
+ for (const kid of kidsOf(parent)) {
+ if (typeof kid === 'string') continue
+ if (kid.tag === 'tr') {
+ rows.push(kid)
+ if (inHead) header.add(kid)
+ }
+ walk(kid, inHead || kid.tag === 'thead')
+ }
+ }
+ walk(table, false)
+ const first = rows[0]
+ if (!header.size && first && !cellsOf(first, TD).length) header.add(first)
+ const body = rows.filter((row) => !header.has(row))
+ return rows.every(emptyRow) || (body.length > 0 && body.every(emptyRow))
+}
+
+// headers and summaries whose text is a button's read as the button's text
+const LABEL_HOSTS = new Set(['th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'caption', 'summary', 'dt'])
+const hasTag = (el: Element, tag: string): boolean => {
+ for (const kid of kidsOf(el))
+ if (typeof kid !== 'string' && (kid.tag === tag || hasTag(kid, tag))) return true
+ return false
+}
+
+// what a child becomes: itself, something prune made of it, or nothing
+const pruned = (kid: Element): Element | undefined => {
+ if (dropped(kid) || (stripChrome && chrome(kid))) return undefined
+ if (kid.tag === 'a') {
+ const inner = kidsOf(kid)
+ const kept = without(inner, linkDrop)
+ let link = kept === inner ? kid : made(kid, kept)
+ if (nothingToRead(link)) {
+ const label = linkLabel(kid)
+ if (!label) return undefined
+ link = made(kid, [label])
+ }
+ return link
+ }
+ if (LABEL_HOSTS.has(kid.tag)) {
+ const inner = kidsOf(kid)
+ const buttons = hasTag(kid, 'button')
+ if (
+ buttons
+ ? text(
+ made(
+ kid,
+ without(inner, (el) => el.tag === 'button'),
+ ),
+ )
+ : text(kid)
+ )
+ return kid
+ // read as its name, so without what carries a value
+ const kept = without(inner, valueBearing)
+ if (buttons) return made(kid, unwrap(kept, 'button'))
+ return kept === inner ? kid : made(kid, kept)
+ }
+ if (kid.tag === 'table' && skeleton(kid)) return undefined
+ return kid
+}
+
+// whether text in an element is code, as written: no spacing there. cached with the children, 1 or 2
+const literal = (el: Element): boolean => {
+ const cached = el as Pruned
+ touch(cached)
+ if (cached.le === epoch) return cached.lv!
+ const value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up))
+ cached.le = epoch
+ cached.lv = value
+ return value
+}
+
+// display classes and styles: laid out side by side (flex, grid), or a box of its own
+const LAID_OUT = /^([\w-]+:)*(inline-)?(flex|grid)$/
+const BOXED = /^([\w-]+:)*(block|flex|grid)$/
+const displays = (el: Element, display: RegExp) =>
+ el.attrs !== '' &&
+ (classes(el).some((name) => display.test(name)) || styleDisplays(read(el, 'style'), display))
+const BOXISH = /block|flex|grid|display|\\/
+const boxed = (node: Node | undefined) =>
+ isInline(node) && BOXISH.test(node.attrs) && displays(node, BOXED)
+// a run of one-character elements is one word split for styling, so only longer words are spaced
+const word = (node: Node | undefined) => {
+ const said = isInline(node) ? toString(node).trim() : typeof node === 'string' ? node : ''
+ return longer(said) ? said : ''
+}
+// more than one character, counting code points
+const longer = (said: string) => {
+ const trimmed = said.trim()
+ if (trimmed.length !== 2) return trimmed.length > 2
+ const head = trimmed.charCodeAt(0)
+ const tail = trimmed.charCodeAt(1)
+ return !(head >= 0xd800 && head <= 0xdbff && tail >= 0xdc00 && tail <= 0xdfff)
+}
+const edgeLink = (node: Node | undefined, end: boolean): Element | undefined => {
+ if (!isInline(node)) return undefined
+ if (node.tag === 'a') return node
+ const inside = kidsOf(node).filter((kid) => !isBlank(kid))
+ return edgeLink(end ? inside.at(-1) : inside[0], end)
+}
+const soleLink = (node: Node | undefined): Element | undefined => {
+ if (!isInline(node)) return undefined
+ if (node.tag === 'a') return node
+ const inside = kidsOf(node).filter((kid) => !isBlank(kid))
+ return inside.length === 1 ? soleLink(inside[0]) : undefined
+}
+const LETTER_END = /[\p{L}\p{N}]$/u
+const LETTER_START = /^[\p{L}\p{N}]/u
+
+// inline boxes side by side with no text between get a space where a word meets a word (or a link a link, or a box
+// anything); then a run of the same link reads once
+const spaced = (parent: Element, kids: Node[]): Node[] => {
+ let out: Node[] | undefined
+ let items: boolean | undefined
+ const said: (string | undefined)[] = []
+ const boxes: (boolean | undefined)[] = []
+ const wordAt = (i: number) => (said[i] ??= word(kids[i]))
+ const boxedAt = (i: number) => (boxes[i] ??= boxed(kids[i]))
+ let inlines = 0
+ for (let i = 0; i < kids.length; i++) {
+ const left = kids[i]!
+ const right = kids[i + 1]
+ const leftInline = isInline(left)
+ if (leftInline) inlines++
+ out?.push(left)
+ if (right === undefined) break
+ const rightInline = isInline(right)
+ if (!leftInline && !rightInline) continue
+ if ((!leftInline && typeof left !== 'string') || (!rightInline && typeof right !== 'string'))
+ continue
+ let gap: boolean
+ if (leftInline && rightInline && edgeLink(left, true) && edgeLink(right, false)) gap = true
+ else {
+ const leftWord = wordAt(i)
+ const rightWord = wordAt(i + 1)
+ const letters = LETTER_END.test(leftWord) && LETTER_START.test(rightWord)
+ const both = leftWord !== '' && rightWord !== ''
+ if (!letters && !both) continue
+ const box = boxedAt(i) || boxedAt(i + 1)
+ gap = letters || (box && both)
+ // text beside an element is a box of its own only in a flex or grid container, or beside a box
+ if (gap && !(leftInline && rightInline)) gap = box || (items ??= displays(parent, LAID_OUT))
+ }
+ if (gap) {
+ out ??= kids.slice(0, i + 1)
+ out.push(' ')
+ }
+ }
+ let result = out ?? kids
+ if (inlines < 2) return result
+ // a run of the same link, only whitespace between, reads as one
+ let kept: Node[] | undefined
+ for (let i = 0; i < result.length; i++) {
+ const child = result[i]!
+ const current = soleLink(child)
+ if (current) {
+ const list = kept ?? result
+ let at = kept ? kept.length : i
+ while (at > 0 && isBlank(list[at - 1])) at--
+ const previous = soleLink(list[at - 1])
+ if (
+ previous &&
+ (read(previous, 'href') ?? '').trim() === (read(current, 'href') ?? '').trim() &&
+ linkText(previous) === linkText(current)
+ ) {
+ kept ??= result.slice(0, i)
+ kept.length = at
+ continue
+ }
+ }
+ kept?.push(child)
+ }
+ result = kept ?? result
+ return result
+}
+
+// an element's children as prune leaves them
+export const kidsOf = (el: Element): Node[] => {
+ const cached = el as Pruned
+ if (cached.pe === epoch) return cached.pk!
+ touch(cached)
+ const raw = el.kids
+ let out: Node[] | undefined
+ for (let i = 0; i < raw.length; i++) {
+ const kid = raw[i]!
+ if (typeof kid === 'string') {
+ out?.push(kid)
+ continue
+ }
+ const kept = pruned(kid)
+ if (kept !== kid) out ??= raw.slice(0, i)
+ if (out && kept) out.push(kept)
+ }
+ let kids = out ?? raw
+ if (kids.length > 1 && !literal(el)) kids = spaced(el, kids)
+ cached.pk = kids
+ cached.pe = epoch
+ return kids
+}
diff --git a/packages/md-core/src/emit.ts b/packages/md-core/src/emit.ts
new file mode 100644
index 0000000..8fcfcbd
--- /dev/null
+++ b/packages/md-core/src/emit.ts
@@ -0,0 +1,143 @@
+import { convertRoot, startConvert } from './emit-convert.ts'
+import { HEADING, headingText, IMAGE, Md, setext, TEXT, toMarkdown } from './emit-markdown.ts'
+import { begin, findMain, made, setPage } from './emit-prune.ts'
+import type { Document, Options, Result } from './types.ts'
+
+// markdown straight from the parser's tree: what @affordances/md's htmlToMarkdown writes for the same page. one walk
+// prunes, extracts, collapses whitespace and converts (emit-prune, emit-convert) into a lean tree that's written out
+// (emit-markdown); finish adds what the page's head says.
+// not here yet, where they'd hook in: markers and slots (prune's mode() and convert's one()), the form
+// summary (convert's form()), shown tab panels (prune), streamed suspense boundaries (the parser), custom handlers
+export const emit = (doc: Document, options: Options = {}): Result => {
+ const { head } = doc
+ const meta = (key: string) => (head.meta.get(key) ?? '').trim() || undefined
+ const canonical = canonicalOf(head.canonical, options.url)
+ const base = options.url ?? canonical
+ // extract: the page's , else the body without its chrome; or the whole body
+ const auto = (options.extract ?? 'auto') === 'auto'
+ begin(false)
+ setPage(doc.root)
+ const main = auto ? findMain(doc.root) : undefined
+ if (auto && !main) begin(true)
+ startConvert(options, base)
+ const root = convertRoot(main ? made(doc.root, [main], '#root') : doc.root)
+ return finish(
+ root,
+ {
+ title: head.title || meta('property og:title'),
+ description: meta('name description') ?? meta('property og:description'),
+ canonical,
+ image: meta('property og:image'),
+ lang: head.lang || undefined,
+ jsonLd: head.jsonLd,
+ },
+ canonical ?? options.url,
+ options,
+ )
+}
+
+// the page's canonical, if it's an http(s) url that fits in a Link header
+const canonicalOf = (href: string | undefined, base: string | undefined) => {
+ if (!href) return undefined
+ try {
+ const url = new URL(href, base)
+ return /^https?:$/.test(url.protocol) && !/[,;]/.test(url.href) ? url.href : undefined
+ } catch {
+ return undefined
+ }
+}
+
+type Meta = {
+ title: string | undefined
+ description: string | undefined
+ canonical: string | undefined
+ image: string | undefined
+ lang: string | undefined
+ jsonLd: string[]
+}
+
+// frontmatter, as @affordances/md writes it
+const yaml = (data: Record) => {
+ const lines = Object.entries(data).flatMap(([key, value]) =>
+ value ? [`${key}: ${JSON.stringify(value)}`] : [],
+ )
+ return lines.length ? `---\n${lines.join('\n')}\n---\n\n` : ''
+}
+const fenced = (lang: string, value: string) => {
+ const fence = '`'.repeat(Math.max(3, ...(value.match(/`+/g) ?? []).map((run) => run.length + 1)))
+ return `${fence}${lang}\n${value}\n${fence}`
+}
+const pretty = (raw: string) => {
+ try {
+ return JSON.stringify(JSON.parse(raw), null, 2)
+ } catch {
+ return raw
+ }
+}
+
+const TITLE_SEPARATORS = '·|–—-'
+const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+const collapsed = (value: string) => value.replace(/\s+/g, ' ').trim()
+// the page's title: its , or its h1 when the is the h1 and the site's name in a template
+const pageTitle = (title: string | undefined, h1: string | undefined) => {
+ const said = title === undefined ? undefined : collapsed(title)
+ if (!said || !h1) return title
+ const name = escapeRegExp(h1)
+ const separator = ` [${TITLE_SEPARATORS}] `
+ return new RegExp(`^${name}${separator}\\S|\\S${separator}${name}$`).test(said) ? h1 : title
+}
+
+// a node's text as written: its values, never an image's alt
+const valueText = (node: Md): string => {
+ if (node.type === IMAGE) return ''
+ if (node.kids.length === 0) return node.value
+ let text = ''
+ for (const kid of node.kids) text += valueText(kid)
+ return text
+}
+
+const isH1 = (node: Md) => node.type === HEADING && node.depth === 1
+
+const finish = (root: Md, meta: Meta, url: string | undefined, options: Options): Result => {
+ const { frontmatter = true, jsonLd = true } = options
+ // the page's own h1 is its title; without one, the stands in
+ const hasH1 = root.kids.some(isH1)
+ if (!hasH1 && meta.title) {
+ const heading = new Md(HEADING, [new Md(TEXT, undefined, meta.title)])
+ heading.depth = 1
+ root.kids.unshift(heading)
+ }
+ // the block right after the h1 goes when it says exactly the description
+ const h1 = root.kids.findIndex(isH1)
+ const next = root.kids[h1 + 1]
+ if (
+ frontmatter &&
+ meta.description &&
+ next &&
+ collapsed(valueText(next)) === collapsed(meta.description)
+ )
+ root.kids.splice(h1 + 1, 1)
+ let output = toMarkdown(root)
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+ const title = hasH1 ? pageTitle(meta.title, firstHeading(root)) : meta.title
+ if (jsonLd && meta.jsonLd.length)
+ output += `\n\n${meta.jsonLd.map((raw) => fenced('json', pretty(raw))).join('\n\n')}`
+ const markdown =
+ (frontmatter
+ ? yaml({
+ title,
+ description: meta.description,
+ url,
+ image: meta.image,
+ lang: meta.lang,
+ })
+ : '') + `${output}\n`
+ return { markdown, title, url, tokens: Math.ceil(markdown.length / 4) }
+}
+
+// the text of the markdown's first # heading: the first h1 written atx style at the top
+const firstHeading = (root: Md) => {
+ for (const node of root.kids) if (isH1(node) && !setext(node)) return headingText(node)
+ return undefined
+}
diff --git a/packages/md-core/src/entities-table.ts b/packages/md-core/src/entities-table.ts
new file mode 100644
index 0000000..b4819e2
--- /dev/null
+++ b/packages/md-core/src/entities-table.ts
@@ -0,0 +1,2235 @@
+// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
+// (decoded without a ';') also under their bare name. do not edit
+export const ENTITIES: Record = {
+ AElig: 'Æ',
+ 'AElig;': 'Æ',
+ AMP: '&',
+ 'AMP;': '&',
+ Aacute: 'Á',
+ 'Aacute;': 'Á',
+ 'Abreve;': 'Ă',
+ Acirc: 'Â',
+ 'Acirc;': 'Â',
+ 'Acy;': 'А',
+ 'Afr;': '𝔄',
+ Agrave: 'À',
+ 'Agrave;': 'À',
+ 'Alpha;': 'Α',
+ 'Amacr;': 'Ā',
+ 'And;': '⩓',
+ 'Aogon;': 'Ą',
+ 'Aopf;': '𝔸',
+ 'ApplyFunction;': '',
+ Aring: 'Å',
+ 'Aring;': 'Å',
+ 'Ascr;': '𝒜',
+ 'Assign;': '≔',
+ Atilde: 'Ã',
+ 'Atilde;': 'Ã',
+ Auml: 'Ä',
+ 'Auml;': 'Ä',
+ 'Backslash;': '∖',
+ 'Barv;': '⫧',
+ 'Barwed;': '⌆',
+ 'Bcy;': 'Б',
+ 'Because;': '∵',
+ 'Bernoullis;': 'ℬ',
+ 'Beta;': 'Β',
+ 'Bfr;': '𝔅',
+ 'Bopf;': '𝔹',
+ 'Breve;': '˘',
+ 'Bscr;': 'ℬ',
+ 'Bumpeq;': '≎',
+ 'CHcy;': 'Ч',
+ COPY: '©',
+ 'COPY;': '©',
+ 'Cacute;': 'Ć',
+ 'Cap;': '⋒',
+ 'CapitalDifferentialD;': 'ⅅ',
+ 'Cayleys;': 'ℭ',
+ 'Ccaron;': 'Č',
+ Ccedil: 'Ç',
+ 'Ccedil;': 'Ç',
+ 'Ccirc;': 'Ĉ',
+ 'Cconint;': '∰',
+ 'Cdot;': 'Ċ',
+ 'Cedilla;': '¸',
+ 'CenterDot;': '·',
+ 'Cfr;': 'ℭ',
+ 'Chi;': 'Χ',
+ 'CircleDot;': '⊙',
+ 'CircleMinus;': '⊖',
+ 'CirclePlus;': '⊕',
+ 'CircleTimes;': '⊗',
+ 'ClockwiseContourIntegral;': '∲',
+ 'CloseCurlyDoubleQuote;': '”',
+ 'CloseCurlyQuote;': '’',
+ 'Colon;': '∷',
+ 'Colone;': '⩴',
+ 'Congruent;': '≡',
+ 'Conint;': '∯',
+ 'ContourIntegral;': '∮',
+ 'Copf;': 'ℂ',
+ 'Coproduct;': '∐',
+ 'CounterClockwiseContourIntegral;': '∳',
+ 'Cross;': '⨯',
+ 'Cscr;': '𝒞',
+ 'Cup;': '⋓',
+ 'CupCap;': '≍',
+ 'DD;': 'ⅅ',
+ 'DDotrahd;': '⤑',
+ 'DJcy;': 'Ђ',
+ 'DScy;': 'Ѕ',
+ 'DZcy;': 'Џ',
+ 'Dagger;': '‡',
+ 'Darr;': '↡',
+ 'Dashv;': '⫤',
+ 'Dcaron;': 'Ď',
+ 'Dcy;': 'Д',
+ 'Del;': '∇',
+ 'Delta;': 'Δ',
+ 'Dfr;': '𝔇',
+ 'DiacriticalAcute;': '´',
+ 'DiacriticalDot;': '˙',
+ 'DiacriticalDoubleAcute;': '˝',
+ 'DiacriticalGrave;': '`',
+ 'DiacriticalTilde;': '˜',
+ 'Diamond;': '⋄',
+ 'DifferentialD;': 'ⅆ',
+ 'Dopf;': '𝔻',
+ 'Dot;': '¨',
+ 'DotDot;': '⃜',
+ 'DotEqual;': '≐',
+ 'DoubleContourIntegral;': '∯',
+ 'DoubleDot;': '¨',
+ 'DoubleDownArrow;': '⇓',
+ 'DoubleLeftArrow;': '⇐',
+ 'DoubleLeftRightArrow;': '⇔',
+ 'DoubleLeftTee;': '⫤',
+ 'DoubleLongLeftArrow;': '⟸',
+ 'DoubleLongLeftRightArrow;': '⟺',
+ 'DoubleLongRightArrow;': '⟹',
+ 'DoubleRightArrow;': '⇒',
+ 'DoubleRightTee;': '⊨',
+ 'DoubleUpArrow;': '⇑',
+ 'DoubleUpDownArrow;': '⇕',
+ 'DoubleVerticalBar;': '∥',
+ 'DownArrow;': '↓',
+ 'DownArrowBar;': '⤓',
+ 'DownArrowUpArrow;': '⇵',
+ 'DownBreve;': '̑',
+ 'DownLeftRightVector;': '⥐',
+ 'DownLeftTeeVector;': '⥞',
+ 'DownLeftVector;': '↽',
+ 'DownLeftVectorBar;': '⥖',
+ 'DownRightTeeVector;': '⥟',
+ 'DownRightVector;': '⇁',
+ 'DownRightVectorBar;': '⥗',
+ 'DownTee;': '⊤',
+ 'DownTeeArrow;': '↧',
+ 'Downarrow;': '⇓',
+ 'Dscr;': '𝒟',
+ 'Dstrok;': 'Đ',
+ 'ENG;': 'Ŋ',
+ ETH: 'Ð',
+ 'ETH;': 'Ð',
+ Eacute: 'É',
+ 'Eacute;': 'É',
+ 'Ecaron;': 'Ě',
+ Ecirc: 'Ê',
+ 'Ecirc;': 'Ê',
+ 'Ecy;': 'Э',
+ 'Edot;': 'Ė',
+ 'Efr;': '𝔈',
+ Egrave: 'È',
+ 'Egrave;': 'È',
+ 'Element;': '∈',
+ 'Emacr;': 'Ē',
+ 'EmptySmallSquare;': '◻',
+ 'EmptyVerySmallSquare;': '▫',
+ 'Eogon;': 'Ę',
+ 'Eopf;': '𝔼',
+ 'Epsilon;': 'Ε',
+ 'Equal;': '⩵',
+ 'EqualTilde;': '≂',
+ 'Equilibrium;': '⇌',
+ 'Escr;': 'ℰ',
+ 'Esim;': '⩳',
+ 'Eta;': 'Η',
+ Euml: 'Ë',
+ 'Euml;': 'Ë',
+ 'Exists;': '∃',
+ 'ExponentialE;': 'ⅇ',
+ 'Fcy;': 'Ф',
+ 'Ffr;': '𝔉',
+ 'FilledSmallSquare;': '◼',
+ 'FilledVerySmallSquare;': '▪',
+ 'Fopf;': '𝔽',
+ 'ForAll;': '∀',
+ 'Fouriertrf;': 'ℱ',
+ 'Fscr;': 'ℱ',
+ 'GJcy;': 'Ѓ',
+ GT: '>',
+ 'GT;': '>',
+ 'Gamma;': 'Γ',
+ 'Gammad;': 'Ϝ',
+ 'Gbreve;': 'Ğ',
+ 'Gcedil;': 'Ģ',
+ 'Gcirc;': 'Ĝ',
+ 'Gcy;': 'Г',
+ 'Gdot;': 'Ġ',
+ 'Gfr;': '𝔊',
+ 'Gg;': '⋙',
+ 'Gopf;': '𝔾',
+ 'GreaterEqual;': '≥',
+ 'GreaterEqualLess;': '⋛',
+ 'GreaterFullEqual;': '≧',
+ 'GreaterGreater;': '⪢',
+ 'GreaterLess;': '≷',
+ 'GreaterSlantEqual;': '⩾',
+ 'GreaterTilde;': '≳',
+ 'Gscr;': '𝒢',
+ 'Gt;': '≫',
+ 'HARDcy;': 'Ъ',
+ 'Hacek;': 'ˇ',
+ 'Hat;': '^',
+ 'Hcirc;': 'Ĥ',
+ 'Hfr;': 'ℌ',
+ 'HilbertSpace;': 'ℋ',
+ 'Hopf;': 'ℍ',
+ 'HorizontalLine;': '─',
+ 'Hscr;': 'ℋ',
+ 'Hstrok;': 'Ħ',
+ 'HumpDownHump;': '≎',
+ 'HumpEqual;': '≏',
+ 'IEcy;': 'Е',
+ 'IJlig;': 'IJ',
+ 'IOcy;': 'Ё',
+ Iacute: 'Í',
+ 'Iacute;': 'Í',
+ Icirc: 'Î',
+ 'Icirc;': 'Î',
+ 'Icy;': 'И',
+ 'Idot;': 'İ',
+ 'Ifr;': 'ℑ',
+ Igrave: 'Ì',
+ 'Igrave;': 'Ì',
+ 'Im;': 'ℑ',
+ 'Imacr;': 'Ī',
+ 'ImaginaryI;': 'ⅈ',
+ 'Implies;': '⇒',
+ 'Int;': '∬',
+ 'Integral;': '∫',
+ 'Intersection;': '⋂',
+ 'InvisibleComma;': '',
+ 'InvisibleTimes;': '',
+ 'Iogon;': 'Į',
+ 'Iopf;': '𝕀',
+ 'Iota;': 'Ι',
+ 'Iscr;': 'ℐ',
+ 'Itilde;': 'Ĩ',
+ 'Iukcy;': 'І',
+ Iuml: 'Ï',
+ 'Iuml;': 'Ï',
+ 'Jcirc;': 'Ĵ',
+ 'Jcy;': 'Й',
+ 'Jfr;': '𝔍',
+ 'Jopf;': '𝕁',
+ 'Jscr;': '𝒥',
+ 'Jsercy;': 'Ј',
+ 'Jukcy;': 'Є',
+ 'KHcy;': 'Х',
+ 'KJcy;': 'Ќ',
+ 'Kappa;': 'Κ',
+ 'Kcedil;': 'Ķ',
+ 'Kcy;': 'К',
+ 'Kfr;': '𝔎',
+ 'Kopf;': '𝕂',
+ 'Kscr;': '𝒦',
+ 'LJcy;': 'Љ',
+ LT: '<',
+ 'LT;': '<',
+ 'Lacute;': 'Ĺ',
+ 'Lambda;': 'Λ',
+ 'Lang;': '⟪',
+ 'Laplacetrf;': 'ℒ',
+ 'Larr;': '↞',
+ 'Lcaron;': 'Ľ',
+ 'Lcedil;': 'Ļ',
+ 'Lcy;': 'Л',
+ 'LeftAngleBracket;': '⟨',
+ 'LeftArrow;': '←',
+ 'LeftArrowBar;': '⇤',
+ 'LeftArrowRightArrow;': '⇆',
+ 'LeftCeiling;': '⌈',
+ 'LeftDoubleBracket;': '⟦',
+ 'LeftDownTeeVector;': '⥡',
+ 'LeftDownVector;': '⇃',
+ 'LeftDownVectorBar;': '⥙',
+ 'LeftFloor;': '⌊',
+ 'LeftRightArrow;': '↔',
+ 'LeftRightVector;': '⥎',
+ 'LeftTee;': '⊣',
+ 'LeftTeeArrow;': '↤',
+ 'LeftTeeVector;': '⥚',
+ 'LeftTriangle;': '⊲',
+ 'LeftTriangleBar;': '⧏',
+ 'LeftTriangleEqual;': '⊴',
+ 'LeftUpDownVector;': '⥑',
+ 'LeftUpTeeVector;': '⥠',
+ 'LeftUpVector;': '↿',
+ 'LeftUpVectorBar;': '⥘',
+ 'LeftVector;': '↼',
+ 'LeftVectorBar;': '⥒',
+ 'Leftarrow;': '⇐',
+ 'Leftrightarrow;': '⇔',
+ 'LessEqualGreater;': '⋚',
+ 'LessFullEqual;': '≦',
+ 'LessGreater;': '≶',
+ 'LessLess;': '⪡',
+ 'LessSlantEqual;': '⩽',
+ 'LessTilde;': '≲',
+ 'Lfr;': '𝔏',
+ 'Ll;': '⋘',
+ 'Lleftarrow;': '⇚',
+ 'Lmidot;': 'Ŀ',
+ 'LongLeftArrow;': '⟵',
+ 'LongLeftRightArrow;': '⟷',
+ 'LongRightArrow;': '⟶',
+ 'Longleftarrow;': '⟸',
+ 'Longleftrightarrow;': '⟺',
+ 'Longrightarrow;': '⟹',
+ 'Lopf;': '𝕃',
+ 'LowerLeftArrow;': '↙',
+ 'LowerRightArrow;': '↘',
+ 'Lscr;': 'ℒ',
+ 'Lsh;': '↰',
+ 'Lstrok;': 'Ł',
+ 'Lt;': '≪',
+ 'Map;': '⤅',
+ 'Mcy;': 'М',
+ 'MediumSpace;': ' ',
+ 'Mellintrf;': 'ℳ',
+ 'Mfr;': '𝔐',
+ 'MinusPlus;': '∓',
+ 'Mopf;': '𝕄',
+ 'Mscr;': 'ℳ',
+ 'Mu;': 'Μ',
+ 'NJcy;': 'Њ',
+ 'Nacute;': 'Ń',
+ 'Ncaron;': 'Ň',
+ 'Ncedil;': 'Ņ',
+ 'Ncy;': 'Н',
+ 'NegativeMediumSpace;': '',
+ 'NegativeThickSpace;': '',
+ 'NegativeThinSpace;': '',
+ 'NegativeVeryThinSpace;': '',
+ 'NestedGreaterGreater;': '≫',
+ 'NestedLessLess;': '≪',
+ 'NewLine;': '\n',
+ 'Nfr;': '𝔑',
+ 'NoBreak;': '',
+ 'NonBreakingSpace;': ' ',
+ 'Nopf;': 'ℕ',
+ 'Not;': '⫬',
+ 'NotCongruent;': '≢',
+ 'NotCupCap;': '≭',
+ 'NotDoubleVerticalBar;': '∦',
+ 'NotElement;': '∉',
+ 'NotEqual;': '≠',
+ 'NotEqualTilde;': '≂̸',
+ 'NotExists;': '∄',
+ 'NotGreater;': '≯',
+ 'NotGreaterEqual;': '≱',
+ 'NotGreaterFullEqual;': '≧̸',
+ 'NotGreaterGreater;': '≫̸',
+ 'NotGreaterLess;': '≹',
+ 'NotGreaterSlantEqual;': '⩾̸',
+ 'NotGreaterTilde;': '≵',
+ 'NotHumpDownHump;': '≎̸',
+ 'NotHumpEqual;': '≏̸',
+ 'NotLeftTriangle;': '⋪',
+ 'NotLeftTriangleBar;': '⧏̸',
+ 'NotLeftTriangleEqual;': '⋬',
+ 'NotLess;': '≮',
+ 'NotLessEqual;': '≰',
+ 'NotLessGreater;': '≸',
+ 'NotLessLess;': '≪̸',
+ 'NotLessSlantEqual;': '⩽̸',
+ 'NotLessTilde;': '≴',
+ 'NotNestedGreaterGreater;': '⪢̸',
+ 'NotNestedLessLess;': '⪡̸',
+ 'NotPrecedes;': '⊀',
+ 'NotPrecedesEqual;': '⪯̸',
+ 'NotPrecedesSlantEqual;': '⋠',
+ 'NotReverseElement;': '∌',
+ 'NotRightTriangle;': '⋫',
+ 'NotRightTriangleBar;': '⧐̸',
+ 'NotRightTriangleEqual;': '⋭',
+ 'NotSquareSubset;': '⊏̸',
+ 'NotSquareSubsetEqual;': '⋢',
+ 'NotSquareSuperset;': '⊐̸',
+ 'NotSquareSupersetEqual;': '⋣',
+ 'NotSubset;': '⊂⃒',
+ 'NotSubsetEqual;': '⊈',
+ 'NotSucceeds;': '⊁',
+ 'NotSucceedsEqual;': '⪰̸',
+ 'NotSucceedsSlantEqual;': '⋡',
+ 'NotSucceedsTilde;': '≿̸',
+ 'NotSuperset;': '⊃⃒',
+ 'NotSupersetEqual;': '⊉',
+ 'NotTilde;': '≁',
+ 'NotTildeEqual;': '≄',
+ 'NotTildeFullEqual;': '≇',
+ 'NotTildeTilde;': '≉',
+ 'NotVerticalBar;': '∤',
+ 'Nscr;': '𝒩',
+ Ntilde: 'Ñ',
+ 'Ntilde;': 'Ñ',
+ 'Nu;': 'Ν',
+ 'OElig;': 'Œ',
+ Oacute: 'Ó',
+ 'Oacute;': 'Ó',
+ Ocirc: 'Ô',
+ 'Ocirc;': 'Ô',
+ 'Ocy;': 'О',
+ 'Odblac;': 'Ő',
+ 'Ofr;': '𝔒',
+ Ograve: 'Ò',
+ 'Ograve;': 'Ò',
+ 'Omacr;': 'Ō',
+ 'Omega;': 'Ω',
+ 'Omicron;': 'Ο',
+ 'Oopf;': '𝕆',
+ 'OpenCurlyDoubleQuote;': '“',
+ 'OpenCurlyQuote;': '‘',
+ 'Or;': '⩔',
+ 'Oscr;': '𝒪',
+ Oslash: 'Ø',
+ 'Oslash;': 'Ø',
+ Otilde: 'Õ',
+ 'Otilde;': 'Õ',
+ 'Otimes;': '⨷',
+ Ouml: 'Ö',
+ 'Ouml;': 'Ö',
+ 'OverBar;': '‾',
+ 'OverBrace;': '⏞',
+ 'OverBracket;': '⎴',
+ 'OverParenthesis;': '⏜',
+ 'PartialD;': '∂',
+ 'Pcy;': 'П',
+ 'Pfr;': '𝔓',
+ 'Phi;': 'Φ',
+ 'Pi;': 'Π',
+ 'PlusMinus;': '±',
+ 'Poincareplane;': 'ℌ',
+ 'Popf;': 'ℙ',
+ 'Pr;': '⪻',
+ 'Precedes;': '≺',
+ 'PrecedesEqual;': '⪯',
+ 'PrecedesSlantEqual;': '≼',
+ 'PrecedesTilde;': '≾',
+ 'Prime;': '″',
+ 'Product;': '∏',
+ 'Proportion;': '∷',
+ 'Proportional;': '∝',
+ 'Pscr;': '𝒫',
+ 'Psi;': 'Ψ',
+ QUOT: '"',
+ 'QUOT;': '"',
+ 'Qfr;': '𝔔',
+ 'Qopf;': 'ℚ',
+ 'Qscr;': '𝒬',
+ 'RBarr;': '⤐',
+ REG: '®',
+ 'REG;': '®',
+ 'Racute;': 'Ŕ',
+ 'Rang;': '⟫',
+ 'Rarr;': '↠',
+ 'Rarrtl;': '⤖',
+ 'Rcaron;': 'Ř',
+ 'Rcedil;': 'Ŗ',
+ 'Rcy;': 'Р',
+ 'Re;': 'ℜ',
+ 'ReverseElement;': '∋',
+ 'ReverseEquilibrium;': '⇋',
+ 'ReverseUpEquilibrium;': '⥯',
+ 'Rfr;': 'ℜ',
+ 'Rho;': 'Ρ',
+ 'RightAngleBracket;': '⟩',
+ 'RightArrow;': '→',
+ 'RightArrowBar;': '⇥',
+ 'RightArrowLeftArrow;': '⇄',
+ 'RightCeiling;': '⌉',
+ 'RightDoubleBracket;': '⟧',
+ 'RightDownTeeVector;': '⥝',
+ 'RightDownVector;': '⇂',
+ 'RightDownVectorBar;': '⥕',
+ 'RightFloor;': '⌋',
+ 'RightTee;': '⊢',
+ 'RightTeeArrow;': '↦',
+ 'RightTeeVector;': '⥛',
+ 'RightTriangle;': '⊳',
+ 'RightTriangleBar;': '⧐',
+ 'RightTriangleEqual;': '⊵',
+ 'RightUpDownVector;': '⥏',
+ 'RightUpTeeVector;': '⥜',
+ 'RightUpVector;': '↾',
+ 'RightUpVectorBar;': '⥔',
+ 'RightVector;': '⇀',
+ 'RightVectorBar;': '⥓',
+ 'Rightarrow;': '⇒',
+ 'Ropf;': 'ℝ',
+ 'RoundImplies;': '⥰',
+ 'Rrightarrow;': '⇛',
+ 'Rscr;': 'ℛ',
+ 'Rsh;': '↱',
+ 'RuleDelayed;': '⧴',
+ 'SHCHcy;': 'Щ',
+ 'SHcy;': 'Ш',
+ 'SOFTcy;': 'Ь',
+ 'Sacute;': 'Ś',
+ 'Sc;': '⪼',
+ 'Scaron;': 'Š',
+ 'Scedil;': 'Ş',
+ 'Scirc;': 'Ŝ',
+ 'Scy;': 'С',
+ 'Sfr;': '𝔖',
+ 'ShortDownArrow;': '↓',
+ 'ShortLeftArrow;': '←',
+ 'ShortRightArrow;': '→',
+ 'ShortUpArrow;': '↑',
+ 'Sigma;': 'Σ',
+ 'SmallCircle;': '∘',
+ 'Sopf;': '𝕊',
+ 'Sqrt;': '√',
+ 'Square;': '□',
+ 'SquareIntersection;': '⊓',
+ 'SquareSubset;': '⊏',
+ 'SquareSubsetEqual;': '⊑',
+ 'SquareSuperset;': '⊐',
+ 'SquareSupersetEqual;': '⊒',
+ 'SquareUnion;': '⊔',
+ 'Sscr;': '𝒮',
+ 'Star;': '⋆',
+ 'Sub;': '⋐',
+ 'Subset;': '⋐',
+ 'SubsetEqual;': '⊆',
+ 'Succeeds;': '≻',
+ 'SucceedsEqual;': '⪰',
+ 'SucceedsSlantEqual;': '≽',
+ 'SucceedsTilde;': '≿',
+ 'SuchThat;': '∋',
+ 'Sum;': '∑',
+ 'Sup;': '⋑',
+ 'Superset;': '⊃',
+ 'SupersetEqual;': '⊇',
+ 'Supset;': '⋑',
+ THORN: 'Þ',
+ 'THORN;': 'Þ',
+ 'TRADE;': '™',
+ 'TSHcy;': 'Ћ',
+ 'TScy;': 'Ц',
+ 'Tab;': '\t',
+ 'Tau;': 'Τ',
+ 'Tcaron;': 'Ť',
+ 'Tcedil;': 'Ţ',
+ 'Tcy;': 'Т',
+ 'Tfr;': '𝔗',
+ 'Therefore;': '∴',
+ 'Theta;': 'Θ',
+ 'ThickSpace;': ' ',
+ 'ThinSpace;': ' ',
+ 'Tilde;': '∼',
+ 'TildeEqual;': '≃',
+ 'TildeFullEqual;': '≅',
+ 'TildeTilde;': '≈',
+ 'Topf;': '𝕋',
+ 'TripleDot;': '⃛',
+ 'Tscr;': '𝒯',
+ 'Tstrok;': 'Ŧ',
+ Uacute: 'Ú',
+ 'Uacute;': 'Ú',
+ 'Uarr;': '↟',
+ 'Uarrocir;': '⥉',
+ 'Ubrcy;': 'Ў',
+ 'Ubreve;': 'Ŭ',
+ Ucirc: 'Û',
+ 'Ucirc;': 'Û',
+ 'Ucy;': 'У',
+ 'Udblac;': 'Ű',
+ 'Ufr;': '𝔘',
+ Ugrave: 'Ù',
+ 'Ugrave;': 'Ù',
+ 'Umacr;': 'Ū',
+ 'UnderBar;': '_',
+ 'UnderBrace;': '⏟',
+ 'UnderBracket;': '⎵',
+ 'UnderParenthesis;': '⏝',
+ 'Union;': '⋃',
+ 'UnionPlus;': '⊎',
+ 'Uogon;': 'Ų',
+ 'Uopf;': '𝕌',
+ 'UpArrow;': '↑',
+ 'UpArrowBar;': '⤒',
+ 'UpArrowDownArrow;': '⇅',
+ 'UpDownArrow;': '↕',
+ 'UpEquilibrium;': '⥮',
+ 'UpTee;': '⊥',
+ 'UpTeeArrow;': '↥',
+ 'Uparrow;': '⇑',
+ 'Updownarrow;': '⇕',
+ 'UpperLeftArrow;': '↖',
+ 'UpperRightArrow;': '↗',
+ 'Upsi;': 'ϒ',
+ 'Upsilon;': 'Υ',
+ 'Uring;': 'Ů',
+ 'Uscr;': '𝒰',
+ 'Utilde;': 'Ũ',
+ Uuml: 'Ü',
+ 'Uuml;': 'Ü',
+ 'VDash;': '⊫',
+ 'Vbar;': '⫫',
+ 'Vcy;': 'В',
+ 'Vdash;': '⊩',
+ 'Vdashl;': '⫦',
+ 'Vee;': '⋁',
+ 'Verbar;': '‖',
+ 'Vert;': '‖',
+ 'VerticalBar;': '∣',
+ 'VerticalLine;': '|',
+ 'VerticalSeparator;': '❘',
+ 'VerticalTilde;': '≀',
+ 'VeryThinSpace;': ' ',
+ 'Vfr;': '𝔙',
+ 'Vopf;': '𝕍',
+ 'Vscr;': '𝒱',
+ 'Vvdash;': '⊪',
+ 'Wcirc;': 'Ŵ',
+ 'Wedge;': '⋀',
+ 'Wfr;': '𝔚',
+ 'Wopf;': '𝕎',
+ 'Wscr;': '𝒲',
+ 'Xfr;': '𝔛',
+ 'Xi;': 'Ξ',
+ 'Xopf;': '𝕏',
+ 'Xscr;': '𝒳',
+ 'YAcy;': 'Я',
+ 'YIcy;': 'Ї',
+ 'YUcy;': 'Ю',
+ Yacute: 'Ý',
+ 'Yacute;': 'Ý',
+ 'Ycirc;': 'Ŷ',
+ 'Ycy;': 'Ы',
+ 'Yfr;': '𝔜',
+ 'Yopf;': '𝕐',
+ 'Yscr;': '𝒴',
+ 'Yuml;': 'Ÿ',
+ 'ZHcy;': 'Ж',
+ 'Zacute;': 'Ź',
+ 'Zcaron;': 'Ž',
+ 'Zcy;': 'З',
+ 'Zdot;': 'Ż',
+ 'ZeroWidthSpace;': '',
+ 'Zeta;': 'Ζ',
+ 'Zfr;': 'ℨ',
+ 'Zopf;': 'ℤ',
+ 'Zscr;': '𝒵',
+ aacute: 'á',
+ 'aacute;': 'á',
+ 'abreve;': 'ă',
+ 'ac;': '∾',
+ 'acE;': '∾̳',
+ 'acd;': '∿',
+ acirc: 'â',
+ 'acirc;': 'â',
+ acute: '´',
+ 'acute;': '´',
+ 'acy;': 'а',
+ aelig: 'æ',
+ 'aelig;': 'æ',
+ 'af;': '',
+ 'afr;': '𝔞',
+ agrave: 'à',
+ 'agrave;': 'à',
+ 'alefsym;': 'ℵ',
+ 'aleph;': 'ℵ',
+ 'alpha;': 'α',
+ 'amacr;': 'ā',
+ 'amalg;': '⨿',
+ amp: '&',
+ 'amp;': '&',
+ 'and;': '∧',
+ 'andand;': '⩕',
+ 'andd;': '⩜',
+ 'andslope;': '⩘',
+ 'andv;': '⩚',
+ 'ang;': '∠',
+ 'ange;': '⦤',
+ 'angle;': '∠',
+ 'angmsd;': '∡',
+ 'angmsdaa;': '⦨',
+ 'angmsdab;': '⦩',
+ 'angmsdac;': '⦪',
+ 'angmsdad;': '⦫',
+ 'angmsdae;': '⦬',
+ 'angmsdaf;': '⦭',
+ 'angmsdag;': '⦮',
+ 'angmsdah;': '⦯',
+ 'angrt;': '∟',
+ 'angrtvb;': '⊾',
+ 'angrtvbd;': '⦝',
+ 'angsph;': '∢',
+ 'angst;': 'Å',
+ 'angzarr;': '⍼',
+ 'aogon;': 'ą',
+ 'aopf;': '𝕒',
+ 'ap;': '≈',
+ 'apE;': '⩰',
+ 'apacir;': '⩯',
+ 'ape;': '≊',
+ 'apid;': '≋',
+ 'apos;': "'",
+ 'approx;': '≈',
+ 'approxeq;': '≊',
+ aring: 'å',
+ 'aring;': 'å',
+ 'ascr;': '𝒶',
+ 'ast;': '*',
+ 'asymp;': '≈',
+ 'asympeq;': '≍',
+ atilde: 'ã',
+ 'atilde;': 'ã',
+ auml: 'ä',
+ 'auml;': 'ä',
+ 'awconint;': '∳',
+ 'awint;': '⨑',
+ 'bNot;': '⫭',
+ 'backcong;': '≌',
+ 'backepsilon;': '϶',
+ 'backprime;': '‵',
+ 'backsim;': '∽',
+ 'backsimeq;': '⋍',
+ 'barvee;': '⊽',
+ 'barwed;': '⌅',
+ 'barwedge;': '⌅',
+ 'bbrk;': '⎵',
+ 'bbrktbrk;': '⎶',
+ 'bcong;': '≌',
+ 'bcy;': 'б',
+ 'bdquo;': '„',
+ 'becaus;': '∵',
+ 'because;': '∵',
+ 'bemptyv;': '⦰',
+ 'bepsi;': '϶',
+ 'bernou;': 'ℬ',
+ 'beta;': 'β',
+ 'beth;': 'ℶ',
+ 'between;': '≬',
+ 'bfr;': '𝔟',
+ 'bigcap;': '⋂',
+ 'bigcirc;': '◯',
+ 'bigcup;': '⋃',
+ 'bigodot;': '⨀',
+ 'bigoplus;': '⨁',
+ 'bigotimes;': '⨂',
+ 'bigsqcup;': '⨆',
+ 'bigstar;': '★',
+ 'bigtriangledown;': '▽',
+ 'bigtriangleup;': '△',
+ 'biguplus;': '⨄',
+ 'bigvee;': '⋁',
+ 'bigwedge;': '⋀',
+ 'bkarow;': '⤍',
+ 'blacklozenge;': '⧫',
+ 'blacksquare;': '▪',
+ 'blacktriangle;': '▴',
+ 'blacktriangledown;': '▾',
+ 'blacktriangleleft;': '◂',
+ 'blacktriangleright;': '▸',
+ 'blank;': '␣',
+ 'blk12;': '▒',
+ 'blk14;': '░',
+ 'blk34;': '▓',
+ 'block;': '█',
+ 'bne;': '=⃥',
+ 'bnequiv;': '≡⃥',
+ 'bnot;': '⌐',
+ 'bopf;': '𝕓',
+ 'bot;': '⊥',
+ 'bottom;': '⊥',
+ 'bowtie;': '⋈',
+ 'boxDL;': '╗',
+ 'boxDR;': '╔',
+ 'boxDl;': '╖',
+ 'boxDr;': '╓',
+ 'boxH;': '═',
+ 'boxHD;': '╦',
+ 'boxHU;': '╩',
+ 'boxHd;': '╤',
+ 'boxHu;': '╧',
+ 'boxUL;': '╝',
+ 'boxUR;': '╚',
+ 'boxUl;': '╜',
+ 'boxUr;': '╙',
+ 'boxV;': '║',
+ 'boxVH;': '╬',
+ 'boxVL;': '╣',
+ 'boxVR;': '╠',
+ 'boxVh;': '╫',
+ 'boxVl;': '╢',
+ 'boxVr;': '╟',
+ 'boxbox;': '⧉',
+ 'boxdL;': '╕',
+ 'boxdR;': '╒',
+ 'boxdl;': '┐',
+ 'boxdr;': '┌',
+ 'boxh;': '─',
+ 'boxhD;': '╥',
+ 'boxhU;': '╨',
+ 'boxhd;': '┬',
+ 'boxhu;': '┴',
+ 'boxminus;': '⊟',
+ 'boxplus;': '⊞',
+ 'boxtimes;': '⊠',
+ 'boxuL;': '╛',
+ 'boxuR;': '╘',
+ 'boxul;': '┘',
+ 'boxur;': '└',
+ 'boxv;': '│',
+ 'boxvH;': '╪',
+ 'boxvL;': '╡',
+ 'boxvR;': '╞',
+ 'boxvh;': '┼',
+ 'boxvl;': '┤',
+ 'boxvr;': '├',
+ 'bprime;': '‵',
+ 'breve;': '˘',
+ brvbar: '¦',
+ 'brvbar;': '¦',
+ 'bscr;': '𝒷',
+ 'bsemi;': '⁏',
+ 'bsim;': '∽',
+ 'bsime;': '⋍',
+ 'bsol;': '\\',
+ 'bsolb;': '⧅',
+ 'bsolhsub;': '⟈',
+ 'bull;': '•',
+ 'bullet;': '•',
+ 'bump;': '≎',
+ 'bumpE;': '⪮',
+ 'bumpe;': '≏',
+ 'bumpeq;': '≏',
+ 'cacute;': 'ć',
+ 'cap;': '∩',
+ 'capand;': '⩄',
+ 'capbrcup;': '⩉',
+ 'capcap;': '⩋',
+ 'capcup;': '⩇',
+ 'capdot;': '⩀',
+ 'caps;': '∩︀',
+ 'caret;': '⁁',
+ 'caron;': 'ˇ',
+ 'ccaps;': '⩍',
+ 'ccaron;': 'č',
+ ccedil: 'ç',
+ 'ccedil;': 'ç',
+ 'ccirc;': 'ĉ',
+ 'ccups;': '⩌',
+ 'ccupssm;': '⩐',
+ 'cdot;': 'ċ',
+ cedil: '¸',
+ 'cedil;': '¸',
+ 'cemptyv;': '⦲',
+ cent: '¢',
+ 'cent;': '¢',
+ 'centerdot;': '·',
+ 'cfr;': '𝔠',
+ 'chcy;': 'ч',
+ 'check;': '✓',
+ 'checkmark;': '✓',
+ 'chi;': 'χ',
+ 'cir;': '○',
+ 'cirE;': '⧃',
+ 'circ;': 'ˆ',
+ 'circeq;': '≗',
+ 'circlearrowleft;': '↺',
+ 'circlearrowright;': '↻',
+ 'circledR;': '®',
+ 'circledS;': 'Ⓢ',
+ 'circledast;': '⊛',
+ 'circledcirc;': '⊚',
+ 'circleddash;': '⊝',
+ 'cire;': '≗',
+ 'cirfnint;': '⨐',
+ 'cirmid;': '⫯',
+ 'cirscir;': '⧂',
+ 'clubs;': '♣',
+ 'clubsuit;': '♣',
+ 'colon;': ':',
+ 'colone;': '≔',
+ 'coloneq;': '≔',
+ 'comma;': ',',
+ 'commat;': '@',
+ 'comp;': '∁',
+ 'compfn;': '∘',
+ 'complement;': '∁',
+ 'complexes;': 'ℂ',
+ 'cong;': '≅',
+ 'congdot;': '⩭',
+ 'conint;': '∮',
+ 'copf;': '𝕔',
+ 'coprod;': '∐',
+ copy: '©',
+ 'copy;': '©',
+ 'copysr;': '℗',
+ 'crarr;': '↵',
+ 'cross;': '✗',
+ 'cscr;': '𝒸',
+ 'csub;': '⫏',
+ 'csube;': '⫑',
+ 'csup;': '⫐',
+ 'csupe;': '⫒',
+ 'ctdot;': '⋯',
+ 'cudarrl;': '⤸',
+ 'cudarrr;': '⤵',
+ 'cuepr;': '⋞',
+ 'cuesc;': '⋟',
+ 'cularr;': '↶',
+ 'cularrp;': '⤽',
+ 'cup;': '∪',
+ 'cupbrcap;': '⩈',
+ 'cupcap;': '⩆',
+ 'cupcup;': '⩊',
+ 'cupdot;': '⊍',
+ 'cupor;': '⩅',
+ 'cups;': '∪︀',
+ 'curarr;': '↷',
+ 'curarrm;': '⤼',
+ 'curlyeqprec;': '⋞',
+ 'curlyeqsucc;': '⋟',
+ 'curlyvee;': '⋎',
+ 'curlywedge;': '⋏',
+ curren: '¤',
+ 'curren;': '¤',
+ 'curvearrowleft;': '↶',
+ 'curvearrowright;': '↷',
+ 'cuvee;': '⋎',
+ 'cuwed;': '⋏',
+ 'cwconint;': '∲',
+ 'cwint;': '∱',
+ 'cylcty;': '⌭',
+ 'dArr;': '⇓',
+ 'dHar;': '⥥',
+ 'dagger;': '†',
+ 'daleth;': 'ℸ',
+ 'darr;': '↓',
+ 'dash;': '‐',
+ 'dashv;': '⊣',
+ 'dbkarow;': '⤏',
+ 'dblac;': '˝',
+ 'dcaron;': 'ď',
+ 'dcy;': 'д',
+ 'dd;': 'ⅆ',
+ 'ddagger;': '‡',
+ 'ddarr;': '⇊',
+ 'ddotseq;': '⩷',
+ deg: '°',
+ 'deg;': '°',
+ 'delta;': 'δ',
+ 'demptyv;': '⦱',
+ 'dfisht;': '⥿',
+ 'dfr;': '𝔡',
+ 'dharl;': '⇃',
+ 'dharr;': '⇂',
+ 'diam;': '⋄',
+ 'diamond;': '⋄',
+ 'diamondsuit;': '♦',
+ 'diams;': '♦',
+ 'die;': '¨',
+ 'digamma;': 'ϝ',
+ 'disin;': '⋲',
+ 'div;': '÷',
+ divide: '÷',
+ 'divide;': '÷',
+ 'divideontimes;': '⋇',
+ 'divonx;': '⋇',
+ 'djcy;': 'ђ',
+ 'dlcorn;': '⌞',
+ 'dlcrop;': '⌍',
+ 'dollar;': '$',
+ 'dopf;': '𝕕',
+ 'dot;': '˙',
+ 'doteq;': '≐',
+ 'doteqdot;': '≑',
+ 'dotminus;': '∸',
+ 'dotplus;': '∔',
+ 'dotsquare;': '⊡',
+ 'doublebarwedge;': '⌆',
+ 'downarrow;': '↓',
+ 'downdownarrows;': '⇊',
+ 'downharpoonleft;': '⇃',
+ 'downharpoonright;': '⇂',
+ 'drbkarow;': '⤐',
+ 'drcorn;': '⌟',
+ 'drcrop;': '⌌',
+ 'dscr;': '𝒹',
+ 'dscy;': 'ѕ',
+ 'dsol;': '⧶',
+ 'dstrok;': 'đ',
+ 'dtdot;': '⋱',
+ 'dtri;': '▿',
+ 'dtrif;': '▾',
+ 'duarr;': '⇵',
+ 'duhar;': '⥯',
+ 'dwangle;': '⦦',
+ 'dzcy;': 'џ',
+ 'dzigrarr;': '⟿',
+ 'eDDot;': '⩷',
+ 'eDot;': '≑',
+ eacute: 'é',
+ 'eacute;': 'é',
+ 'easter;': '⩮',
+ 'ecaron;': 'ě',
+ 'ecir;': '≖',
+ ecirc: 'ê',
+ 'ecirc;': 'ê',
+ 'ecolon;': '≕',
+ 'ecy;': 'э',
+ 'edot;': 'ė',
+ 'ee;': 'ⅇ',
+ 'efDot;': '≒',
+ 'efr;': '𝔢',
+ 'eg;': '⪚',
+ egrave: 'è',
+ 'egrave;': 'è',
+ 'egs;': '⪖',
+ 'egsdot;': '⪘',
+ 'el;': '⪙',
+ 'elinters;': '⏧',
+ 'ell;': 'ℓ',
+ 'els;': '⪕',
+ 'elsdot;': '⪗',
+ 'emacr;': 'ē',
+ 'empty;': '∅',
+ 'emptyset;': '∅',
+ 'emptyv;': '∅',
+ 'emsp13;': ' ',
+ 'emsp14;': ' ',
+ 'emsp;': ' ',
+ 'eng;': 'ŋ',
+ 'ensp;': ' ',
+ 'eogon;': 'ę',
+ 'eopf;': '𝕖',
+ 'epar;': '⋕',
+ 'eparsl;': '⧣',
+ 'eplus;': '⩱',
+ 'epsi;': 'ε',
+ 'epsilon;': 'ε',
+ 'epsiv;': 'ϵ',
+ 'eqcirc;': '≖',
+ 'eqcolon;': '≕',
+ 'eqsim;': '≂',
+ 'eqslantgtr;': '⪖',
+ 'eqslantless;': '⪕',
+ 'equals;': '=',
+ 'equest;': '≟',
+ 'equiv;': '≡',
+ 'equivDD;': '⩸',
+ 'eqvparsl;': '⧥',
+ 'erDot;': '≓',
+ 'erarr;': '⥱',
+ 'escr;': 'ℯ',
+ 'esdot;': '≐',
+ 'esim;': '≂',
+ 'eta;': 'η',
+ eth: 'ð',
+ 'eth;': 'ð',
+ euml: 'ë',
+ 'euml;': 'ë',
+ 'euro;': '€',
+ 'excl;': '!',
+ 'exist;': '∃',
+ 'expectation;': 'ℰ',
+ 'exponentiale;': 'ⅇ',
+ 'fallingdotseq;': '≒',
+ 'fcy;': 'ф',
+ 'female;': '♀',
+ 'ffilig;': 'ffi',
+ 'fflig;': 'ff',
+ 'ffllig;': 'ffl',
+ 'ffr;': '𝔣',
+ 'filig;': 'fi',
+ 'fjlig;': 'fj',
+ 'flat;': '♭',
+ 'fllig;': 'fl',
+ 'fltns;': '▱',
+ 'fnof;': 'ƒ',
+ 'fopf;': '𝕗',
+ 'forall;': '∀',
+ 'fork;': '⋔',
+ 'forkv;': '⫙',
+ 'fpartint;': '⨍',
+ frac12: '½',
+ 'frac12;': '½',
+ 'frac13;': '⅓',
+ frac14: '¼',
+ 'frac14;': '¼',
+ 'frac15;': '⅕',
+ 'frac16;': '⅙',
+ 'frac18;': '⅛',
+ 'frac23;': '⅔',
+ 'frac25;': '⅖',
+ frac34: '¾',
+ 'frac34;': '¾',
+ 'frac35;': '⅗',
+ 'frac38;': '⅜',
+ 'frac45;': '⅘',
+ 'frac56;': '⅚',
+ 'frac58;': '⅝',
+ 'frac78;': '⅞',
+ 'frasl;': '⁄',
+ 'frown;': '⌢',
+ 'fscr;': '𝒻',
+ 'gE;': '≧',
+ 'gEl;': '⪌',
+ 'gacute;': 'ǵ',
+ 'gamma;': 'γ',
+ 'gammad;': 'ϝ',
+ 'gap;': '⪆',
+ 'gbreve;': 'ğ',
+ 'gcirc;': 'ĝ',
+ 'gcy;': 'г',
+ 'gdot;': 'ġ',
+ 'ge;': '≥',
+ 'gel;': '⋛',
+ 'geq;': '≥',
+ 'geqq;': '≧',
+ 'geqslant;': '⩾',
+ 'ges;': '⩾',
+ 'gescc;': '⪩',
+ 'gesdot;': '⪀',
+ 'gesdoto;': '⪂',
+ 'gesdotol;': '⪄',
+ 'gesl;': '⋛︀',
+ 'gesles;': '⪔',
+ 'gfr;': '𝔤',
+ 'gg;': '≫',
+ 'ggg;': '⋙',
+ 'gimel;': 'ℷ',
+ 'gjcy;': 'ѓ',
+ 'gl;': '≷',
+ 'glE;': '⪒',
+ 'gla;': '⪥',
+ 'glj;': '⪤',
+ 'gnE;': '≩',
+ 'gnap;': '⪊',
+ 'gnapprox;': '⪊',
+ 'gne;': '⪈',
+ 'gneq;': '⪈',
+ 'gneqq;': '≩',
+ 'gnsim;': '⋧',
+ 'gopf;': '𝕘',
+ 'grave;': '`',
+ 'gscr;': 'ℊ',
+ 'gsim;': '≳',
+ 'gsime;': '⪎',
+ 'gsiml;': '⪐',
+ gt: '>',
+ 'gt;': '>',
+ 'gtcc;': '⪧',
+ 'gtcir;': '⩺',
+ 'gtdot;': '⋗',
+ 'gtlPar;': '⦕',
+ 'gtquest;': '⩼',
+ 'gtrapprox;': '⪆',
+ 'gtrarr;': '⥸',
+ 'gtrdot;': '⋗',
+ 'gtreqless;': '⋛',
+ 'gtreqqless;': '⪌',
+ 'gtrless;': '≷',
+ 'gtrsim;': '≳',
+ 'gvertneqq;': '≩︀',
+ 'gvnE;': '≩︀',
+ 'hArr;': '⇔',
+ 'hairsp;': ' ',
+ 'half;': '½',
+ 'hamilt;': 'ℋ',
+ 'hardcy;': 'ъ',
+ 'harr;': '↔',
+ 'harrcir;': '⥈',
+ 'harrw;': '↭',
+ 'hbar;': 'ℏ',
+ 'hcirc;': 'ĥ',
+ 'hearts;': '♥',
+ 'heartsuit;': '♥',
+ 'hellip;': '…',
+ 'hercon;': '⊹',
+ 'hfr;': '𝔥',
+ 'hksearow;': '⤥',
+ 'hkswarow;': '⤦',
+ 'hoarr;': '⇿',
+ 'homtht;': '∻',
+ 'hookleftarrow;': '↩',
+ 'hookrightarrow;': '↪',
+ 'hopf;': '𝕙',
+ 'horbar;': '―',
+ 'hscr;': '𝒽',
+ 'hslash;': 'ℏ',
+ 'hstrok;': 'ħ',
+ 'hybull;': '⁃',
+ 'hyphen;': '‐',
+ iacute: 'í',
+ 'iacute;': 'í',
+ 'ic;': '',
+ icirc: 'î',
+ 'icirc;': 'î',
+ 'icy;': 'и',
+ 'iecy;': 'е',
+ iexcl: '¡',
+ 'iexcl;': '¡',
+ 'iff;': '⇔',
+ 'ifr;': '𝔦',
+ igrave: 'ì',
+ 'igrave;': 'ì',
+ 'ii;': 'ⅈ',
+ 'iiiint;': '⨌',
+ 'iiint;': '∭',
+ 'iinfin;': '⧜',
+ 'iiota;': '℩',
+ 'ijlig;': 'ij',
+ 'imacr;': 'ī',
+ 'image;': 'ℑ',
+ 'imagline;': 'ℐ',
+ 'imagpart;': 'ℑ',
+ 'imath;': 'ı',
+ 'imof;': '⊷',
+ 'imped;': 'Ƶ',
+ 'in;': '∈',
+ 'incare;': '℅',
+ 'infin;': '∞',
+ 'infintie;': '⧝',
+ 'inodot;': 'ı',
+ 'int;': '∫',
+ 'intcal;': '⊺',
+ 'integers;': 'ℤ',
+ 'intercal;': '⊺',
+ 'intlarhk;': '⨗',
+ 'intprod;': '⨼',
+ 'iocy;': 'ё',
+ 'iogon;': 'į',
+ 'iopf;': '𝕚',
+ 'iota;': 'ι',
+ 'iprod;': '⨼',
+ iquest: '¿',
+ 'iquest;': '¿',
+ 'iscr;': '𝒾',
+ 'isin;': '∈',
+ 'isinE;': '⋹',
+ 'isindot;': '⋵',
+ 'isins;': '⋴',
+ 'isinsv;': '⋳',
+ 'isinv;': '∈',
+ 'it;': '',
+ 'itilde;': 'ĩ',
+ 'iukcy;': 'і',
+ iuml: 'ï',
+ 'iuml;': 'ï',
+ 'jcirc;': 'ĵ',
+ 'jcy;': 'й',
+ 'jfr;': '𝔧',
+ 'jmath;': 'ȷ',
+ 'jopf;': '𝕛',
+ 'jscr;': '𝒿',
+ 'jsercy;': 'ј',
+ 'jukcy;': 'є',
+ 'kappa;': 'κ',
+ 'kappav;': 'ϰ',
+ 'kcedil;': 'ķ',
+ 'kcy;': 'к',
+ 'kfr;': '𝔨',
+ 'kgreen;': 'ĸ',
+ 'khcy;': 'х',
+ 'kjcy;': 'ќ',
+ 'kopf;': '𝕜',
+ 'kscr;': '𝓀',
+ 'lAarr;': '⇚',
+ 'lArr;': '⇐',
+ 'lAtail;': '⤛',
+ 'lBarr;': '⤎',
+ 'lE;': '≦',
+ 'lEg;': '⪋',
+ 'lHar;': '⥢',
+ 'lacute;': 'ĺ',
+ 'laemptyv;': '⦴',
+ 'lagran;': 'ℒ',
+ 'lambda;': 'λ',
+ 'lang;': '⟨',
+ 'langd;': '⦑',
+ 'langle;': '⟨',
+ 'lap;': '⪅',
+ laquo: '«',
+ 'laquo;': '«',
+ 'larr;': '←',
+ 'larrb;': '⇤',
+ 'larrbfs;': '⤟',
+ 'larrfs;': '⤝',
+ 'larrhk;': '↩',
+ 'larrlp;': '↫',
+ 'larrpl;': '⤹',
+ 'larrsim;': '⥳',
+ 'larrtl;': '↢',
+ 'lat;': '⪫',
+ 'latail;': '⤙',
+ 'late;': '⪭',
+ 'lates;': '⪭︀',
+ 'lbarr;': '⤌',
+ 'lbbrk;': '❲',
+ 'lbrace;': '{',
+ 'lbrack;': '[',
+ 'lbrke;': '⦋',
+ 'lbrksld;': '⦏',
+ 'lbrkslu;': '⦍',
+ 'lcaron;': 'ľ',
+ 'lcedil;': 'ļ',
+ 'lceil;': '⌈',
+ 'lcub;': '{',
+ 'lcy;': 'л',
+ 'ldca;': '⤶',
+ 'ldquo;': '“',
+ 'ldquor;': '„',
+ 'ldrdhar;': '⥧',
+ 'ldrushar;': '⥋',
+ 'ldsh;': '↲',
+ 'le;': '≤',
+ 'leftarrow;': '←',
+ 'leftarrowtail;': '↢',
+ 'leftharpoondown;': '↽',
+ 'leftharpoonup;': '↼',
+ 'leftleftarrows;': '⇇',
+ 'leftrightarrow;': '↔',
+ 'leftrightarrows;': '⇆',
+ 'leftrightharpoons;': '⇋',
+ 'leftrightsquigarrow;': '↭',
+ 'leftthreetimes;': '⋋',
+ 'leg;': '⋚',
+ 'leq;': '≤',
+ 'leqq;': '≦',
+ 'leqslant;': '⩽',
+ 'les;': '⩽',
+ 'lescc;': '⪨',
+ 'lesdot;': '⩿',
+ 'lesdoto;': '⪁',
+ 'lesdotor;': '⪃',
+ 'lesg;': '⋚︀',
+ 'lesges;': '⪓',
+ 'lessapprox;': '⪅',
+ 'lessdot;': '⋖',
+ 'lesseqgtr;': '⋚',
+ 'lesseqqgtr;': '⪋',
+ 'lessgtr;': '≶',
+ 'lesssim;': '≲',
+ 'lfisht;': '⥼',
+ 'lfloor;': '⌊',
+ 'lfr;': '𝔩',
+ 'lg;': '≶',
+ 'lgE;': '⪑',
+ 'lhard;': '↽',
+ 'lharu;': '↼',
+ 'lharul;': '⥪',
+ 'lhblk;': '▄',
+ 'ljcy;': 'љ',
+ 'll;': '≪',
+ 'llarr;': '⇇',
+ 'llcorner;': '⌞',
+ 'llhard;': '⥫',
+ 'lltri;': '◺',
+ 'lmidot;': 'ŀ',
+ 'lmoust;': '⎰',
+ 'lmoustache;': '⎰',
+ 'lnE;': '≨',
+ 'lnap;': '⪉',
+ 'lnapprox;': '⪉',
+ 'lne;': '⪇',
+ 'lneq;': '⪇',
+ 'lneqq;': '≨',
+ 'lnsim;': '⋦',
+ 'loang;': '⟬',
+ 'loarr;': '⇽',
+ 'lobrk;': '⟦',
+ 'longleftarrow;': '⟵',
+ 'longleftrightarrow;': '⟷',
+ 'longmapsto;': '⟼',
+ 'longrightarrow;': '⟶',
+ 'looparrowleft;': '↫',
+ 'looparrowright;': '↬',
+ 'lopar;': '⦅',
+ 'lopf;': '𝕝',
+ 'loplus;': '⨭',
+ 'lotimes;': '⨴',
+ 'lowast;': '∗',
+ 'lowbar;': '_',
+ 'loz;': '◊',
+ 'lozenge;': '◊',
+ 'lozf;': '⧫',
+ 'lpar;': '(',
+ 'lparlt;': '⦓',
+ 'lrarr;': '⇆',
+ 'lrcorner;': '⌟',
+ 'lrhar;': '⇋',
+ 'lrhard;': '⥭',
+ 'lrm;': '',
+ 'lrtri;': '⊿',
+ 'lsaquo;': '‹',
+ 'lscr;': '𝓁',
+ 'lsh;': '↰',
+ 'lsim;': '≲',
+ 'lsime;': '⪍',
+ 'lsimg;': '⪏',
+ 'lsqb;': '[',
+ 'lsquo;': '‘',
+ 'lsquor;': '‚',
+ 'lstrok;': 'ł',
+ lt: '<',
+ 'lt;': '<',
+ 'ltcc;': '⪦',
+ 'ltcir;': '⩹',
+ 'ltdot;': '⋖',
+ 'lthree;': '⋋',
+ 'ltimes;': '⋉',
+ 'ltlarr;': '⥶',
+ 'ltquest;': '⩻',
+ 'ltrPar;': '⦖',
+ 'ltri;': '◃',
+ 'ltrie;': '⊴',
+ 'ltrif;': '◂',
+ 'lurdshar;': '⥊',
+ 'luruhar;': '⥦',
+ 'lvertneqq;': '≨︀',
+ 'lvnE;': '≨︀',
+ 'mDDot;': '∺',
+ macr: '¯',
+ 'macr;': '¯',
+ 'male;': '♂',
+ 'malt;': '✠',
+ 'maltese;': '✠',
+ 'map;': '↦',
+ 'mapsto;': '↦',
+ 'mapstodown;': '↧',
+ 'mapstoleft;': '↤',
+ 'mapstoup;': '↥',
+ 'marker;': '▮',
+ 'mcomma;': '⨩',
+ 'mcy;': 'м',
+ 'mdash;': '—',
+ 'measuredangle;': '∡',
+ 'mfr;': '𝔪',
+ 'mho;': '℧',
+ micro: 'µ',
+ 'micro;': 'µ',
+ 'mid;': '∣',
+ 'midast;': '*',
+ 'midcir;': '⫰',
+ middot: '·',
+ 'middot;': '·',
+ 'minus;': '−',
+ 'minusb;': '⊟',
+ 'minusd;': '∸',
+ 'minusdu;': '⨪',
+ 'mlcp;': '⫛',
+ 'mldr;': '…',
+ 'mnplus;': '∓',
+ 'models;': '⊧',
+ 'mopf;': '𝕞',
+ 'mp;': '∓',
+ 'mscr;': '𝓂',
+ 'mstpos;': '∾',
+ 'mu;': 'μ',
+ 'multimap;': '⊸',
+ 'mumap;': '⊸',
+ 'nGg;': '⋙̸',
+ 'nGt;': '≫⃒',
+ 'nGtv;': '≫̸',
+ 'nLeftarrow;': '⇍',
+ 'nLeftrightarrow;': '⇎',
+ 'nLl;': '⋘̸',
+ 'nLt;': '≪⃒',
+ 'nLtv;': '≪̸',
+ 'nRightarrow;': '⇏',
+ 'nVDash;': '⊯',
+ 'nVdash;': '⊮',
+ 'nabla;': '∇',
+ 'nacute;': 'ń',
+ 'nang;': '∠⃒',
+ 'nap;': '≉',
+ 'napE;': '⩰̸',
+ 'napid;': '≋̸',
+ 'napos;': 'ʼn',
+ 'napprox;': '≉',
+ 'natur;': '♮',
+ 'natural;': '♮',
+ 'naturals;': 'ℕ',
+ nbsp: ' ',
+ 'nbsp;': ' ',
+ 'nbump;': '≎̸',
+ 'nbumpe;': '≏̸',
+ 'ncap;': '⩃',
+ 'ncaron;': 'ň',
+ 'ncedil;': 'ņ',
+ 'ncong;': '≇',
+ 'ncongdot;': '⩭̸',
+ 'ncup;': '⩂',
+ 'ncy;': 'н',
+ 'ndash;': '–',
+ 'ne;': '≠',
+ 'neArr;': '⇗',
+ 'nearhk;': '⤤',
+ 'nearr;': '↗',
+ 'nearrow;': '↗',
+ 'nedot;': '≐̸',
+ 'nequiv;': '≢',
+ 'nesear;': '⤨',
+ 'nesim;': '≂̸',
+ 'nexist;': '∄',
+ 'nexists;': '∄',
+ 'nfr;': '𝔫',
+ 'ngE;': '≧̸',
+ 'nge;': '≱',
+ 'ngeq;': '≱',
+ 'ngeqq;': '≧̸',
+ 'ngeqslant;': '⩾̸',
+ 'nges;': '⩾̸',
+ 'ngsim;': '≵',
+ 'ngt;': '≯',
+ 'ngtr;': '≯',
+ 'nhArr;': '⇎',
+ 'nharr;': '↮',
+ 'nhpar;': '⫲',
+ 'ni;': '∋',
+ 'nis;': '⋼',
+ 'nisd;': '⋺',
+ 'niv;': '∋',
+ 'njcy;': 'њ',
+ 'nlArr;': '⇍',
+ 'nlE;': '≦̸',
+ 'nlarr;': '↚',
+ 'nldr;': '‥',
+ 'nle;': '≰',
+ 'nleftarrow;': '↚',
+ 'nleftrightarrow;': '↮',
+ 'nleq;': '≰',
+ 'nleqq;': '≦̸',
+ 'nleqslant;': '⩽̸',
+ 'nles;': '⩽̸',
+ 'nless;': '≮',
+ 'nlsim;': '≴',
+ 'nlt;': '≮',
+ 'nltri;': '⋪',
+ 'nltrie;': '⋬',
+ 'nmid;': '∤',
+ 'nopf;': '𝕟',
+ not: '¬',
+ 'not;': '¬',
+ 'notin;': '∉',
+ 'notinE;': '⋹̸',
+ 'notindot;': '⋵̸',
+ 'notinva;': '∉',
+ 'notinvb;': '⋷',
+ 'notinvc;': '⋶',
+ 'notni;': '∌',
+ 'notniva;': '∌',
+ 'notnivb;': '⋾',
+ 'notnivc;': '⋽',
+ 'npar;': '∦',
+ 'nparallel;': '∦',
+ 'nparsl;': '⫽⃥',
+ 'npart;': '∂̸',
+ 'npolint;': '⨔',
+ 'npr;': '⊀',
+ 'nprcue;': '⋠',
+ 'npre;': '⪯̸',
+ 'nprec;': '⊀',
+ 'npreceq;': '⪯̸',
+ 'nrArr;': '⇏',
+ 'nrarr;': '↛',
+ 'nrarrc;': '⤳̸',
+ 'nrarrw;': '↝̸',
+ 'nrightarrow;': '↛',
+ 'nrtri;': '⋫',
+ 'nrtrie;': '⋭',
+ 'nsc;': '⊁',
+ 'nsccue;': '⋡',
+ 'nsce;': '⪰̸',
+ 'nscr;': '𝓃',
+ 'nshortmid;': '∤',
+ 'nshortparallel;': '∦',
+ 'nsim;': '≁',
+ 'nsime;': '≄',
+ 'nsimeq;': '≄',
+ 'nsmid;': '∤',
+ 'nspar;': '∦',
+ 'nsqsube;': '⋢',
+ 'nsqsupe;': '⋣',
+ 'nsub;': '⊄',
+ 'nsubE;': '⫅̸',
+ 'nsube;': '⊈',
+ 'nsubset;': '⊂⃒',
+ 'nsubseteq;': '⊈',
+ 'nsubseteqq;': '⫅̸',
+ 'nsucc;': '⊁',
+ 'nsucceq;': '⪰̸',
+ 'nsup;': '⊅',
+ 'nsupE;': '⫆̸',
+ 'nsupe;': '⊉',
+ 'nsupset;': '⊃⃒',
+ 'nsupseteq;': '⊉',
+ 'nsupseteqq;': '⫆̸',
+ 'ntgl;': '≹',
+ ntilde: 'ñ',
+ 'ntilde;': 'ñ',
+ 'ntlg;': '≸',
+ 'ntriangleleft;': '⋪',
+ 'ntrianglelefteq;': '⋬',
+ 'ntriangleright;': '⋫',
+ 'ntrianglerighteq;': '⋭',
+ 'nu;': 'ν',
+ 'num;': '#',
+ 'numero;': '№',
+ 'numsp;': ' ',
+ 'nvDash;': '⊭',
+ 'nvHarr;': '⤄',
+ 'nvap;': '≍⃒',
+ 'nvdash;': '⊬',
+ 'nvge;': '≥⃒',
+ 'nvgt;': '>⃒',
+ 'nvinfin;': '⧞',
+ 'nvlArr;': '⤂',
+ 'nvle;': '≤⃒',
+ 'nvlt;': '<⃒',
+ 'nvltrie;': '⊴⃒',
+ 'nvrArr;': '⤃',
+ 'nvrtrie;': '⊵⃒',
+ 'nvsim;': '∼⃒',
+ 'nwArr;': '⇖',
+ 'nwarhk;': '⤣',
+ 'nwarr;': '↖',
+ 'nwarrow;': '↖',
+ 'nwnear;': '⤧',
+ 'oS;': 'Ⓢ',
+ oacute: 'ó',
+ 'oacute;': 'ó',
+ 'oast;': '⊛',
+ 'ocir;': '⊚',
+ ocirc: 'ô',
+ 'ocirc;': 'ô',
+ 'ocy;': 'о',
+ 'odash;': '⊝',
+ 'odblac;': 'ő',
+ 'odiv;': '⨸',
+ 'odot;': '⊙',
+ 'odsold;': '⦼',
+ 'oelig;': 'œ',
+ 'ofcir;': '⦿',
+ 'ofr;': '𝔬',
+ 'ogon;': '˛',
+ ograve: 'ò',
+ 'ograve;': 'ò',
+ 'ogt;': '⧁',
+ 'ohbar;': '⦵',
+ 'ohm;': 'Ω',
+ 'oint;': '∮',
+ 'olarr;': '↺',
+ 'olcir;': '⦾',
+ 'olcross;': '⦻',
+ 'oline;': '‾',
+ 'olt;': '⧀',
+ 'omacr;': 'ō',
+ 'omega;': 'ω',
+ 'omicron;': 'ο',
+ 'omid;': '⦶',
+ 'ominus;': '⊖',
+ 'oopf;': '𝕠',
+ 'opar;': '⦷',
+ 'operp;': '⦹',
+ 'oplus;': '⊕',
+ 'or;': '∨',
+ 'orarr;': '↻',
+ 'ord;': '⩝',
+ 'order;': 'ℴ',
+ 'orderof;': 'ℴ',
+ ordf: 'ª',
+ 'ordf;': 'ª',
+ ordm: 'º',
+ 'ordm;': 'º',
+ 'origof;': '⊶',
+ 'oror;': '⩖',
+ 'orslope;': '⩗',
+ 'orv;': '⩛',
+ 'oscr;': 'ℴ',
+ oslash: 'ø',
+ 'oslash;': 'ø',
+ 'osol;': '⊘',
+ otilde: 'õ',
+ 'otilde;': 'õ',
+ 'otimes;': '⊗',
+ 'otimesas;': '⨶',
+ ouml: 'ö',
+ 'ouml;': 'ö',
+ 'ovbar;': '⌽',
+ 'par;': '∥',
+ para: '¶',
+ 'para;': '¶',
+ 'parallel;': '∥',
+ 'parsim;': '⫳',
+ 'parsl;': '⫽',
+ 'part;': '∂',
+ 'pcy;': 'п',
+ 'percnt;': '%',
+ 'period;': '.',
+ 'permil;': '‰',
+ 'perp;': '⊥',
+ 'pertenk;': '‱',
+ 'pfr;': '𝔭',
+ 'phi;': 'φ',
+ 'phiv;': 'ϕ',
+ 'phmmat;': 'ℳ',
+ 'phone;': '☎',
+ 'pi;': 'π',
+ 'pitchfork;': '⋔',
+ 'piv;': 'ϖ',
+ 'planck;': 'ℏ',
+ 'planckh;': 'ℎ',
+ 'plankv;': 'ℏ',
+ 'plus;': '+',
+ 'plusacir;': '⨣',
+ 'plusb;': '⊞',
+ 'pluscir;': '⨢',
+ 'plusdo;': '∔',
+ 'plusdu;': '⨥',
+ 'pluse;': '⩲',
+ plusmn: '±',
+ 'plusmn;': '±',
+ 'plussim;': '⨦',
+ 'plustwo;': '⨧',
+ 'pm;': '±',
+ 'pointint;': '⨕',
+ 'popf;': '𝕡',
+ pound: '£',
+ 'pound;': '£',
+ 'pr;': '≺',
+ 'prE;': '⪳',
+ 'prap;': '⪷',
+ 'prcue;': '≼',
+ 'pre;': '⪯',
+ 'prec;': '≺',
+ 'precapprox;': '⪷',
+ 'preccurlyeq;': '≼',
+ 'preceq;': '⪯',
+ 'precnapprox;': '⪹',
+ 'precneqq;': '⪵',
+ 'precnsim;': '⋨',
+ 'precsim;': '≾',
+ 'prime;': '′',
+ 'primes;': 'ℙ',
+ 'prnE;': '⪵',
+ 'prnap;': '⪹',
+ 'prnsim;': '⋨',
+ 'prod;': '∏',
+ 'profalar;': '⌮',
+ 'profline;': '⌒',
+ 'profsurf;': '⌓',
+ 'prop;': '∝',
+ 'propto;': '∝',
+ 'prsim;': '≾',
+ 'prurel;': '⊰',
+ 'pscr;': '𝓅',
+ 'psi;': 'ψ',
+ 'puncsp;': ' ',
+ 'qfr;': '𝔮',
+ 'qint;': '⨌',
+ 'qopf;': '𝕢',
+ 'qprime;': '⁗',
+ 'qscr;': '𝓆',
+ 'quaternions;': 'ℍ',
+ 'quatint;': '⨖',
+ 'quest;': '?',
+ 'questeq;': '≟',
+ quot: '"',
+ 'quot;': '"',
+ 'rAarr;': '⇛',
+ 'rArr;': '⇒',
+ 'rAtail;': '⤜',
+ 'rBarr;': '⤏',
+ 'rHar;': '⥤',
+ 'race;': '∽̱',
+ 'racute;': 'ŕ',
+ 'radic;': '√',
+ 'raemptyv;': '⦳',
+ 'rang;': '⟩',
+ 'rangd;': '⦒',
+ 'range;': '⦥',
+ 'rangle;': '⟩',
+ raquo: '»',
+ 'raquo;': '»',
+ 'rarr;': '→',
+ 'rarrap;': '⥵',
+ 'rarrb;': '⇥',
+ 'rarrbfs;': '⤠',
+ 'rarrc;': '⤳',
+ 'rarrfs;': '⤞',
+ 'rarrhk;': '↪',
+ 'rarrlp;': '↬',
+ 'rarrpl;': '⥅',
+ 'rarrsim;': '⥴',
+ 'rarrtl;': '↣',
+ 'rarrw;': '↝',
+ 'ratail;': '⤚',
+ 'ratio;': '∶',
+ 'rationals;': 'ℚ',
+ 'rbarr;': '⤍',
+ 'rbbrk;': '❳',
+ 'rbrace;': '}',
+ 'rbrack;': ']',
+ 'rbrke;': '⦌',
+ 'rbrksld;': '⦎',
+ 'rbrkslu;': '⦐',
+ 'rcaron;': 'ř',
+ 'rcedil;': 'ŗ',
+ 'rceil;': '⌉',
+ 'rcub;': '}',
+ 'rcy;': 'р',
+ 'rdca;': '⤷',
+ 'rdldhar;': '⥩',
+ 'rdquo;': '”',
+ 'rdquor;': '”',
+ 'rdsh;': '↳',
+ 'real;': 'ℜ',
+ 'realine;': 'ℛ',
+ 'realpart;': 'ℜ',
+ 'reals;': 'ℝ',
+ 'rect;': '▭',
+ reg: '®',
+ 'reg;': '®',
+ 'rfisht;': '⥽',
+ 'rfloor;': '⌋',
+ 'rfr;': '𝔯',
+ 'rhard;': '⇁',
+ 'rharu;': '⇀',
+ 'rharul;': '⥬',
+ 'rho;': 'ρ',
+ 'rhov;': 'ϱ',
+ 'rightarrow;': '→',
+ 'rightarrowtail;': '↣',
+ 'rightharpoondown;': '⇁',
+ 'rightharpoonup;': '⇀',
+ 'rightleftarrows;': '⇄',
+ 'rightleftharpoons;': '⇌',
+ 'rightrightarrows;': '⇉',
+ 'rightsquigarrow;': '↝',
+ 'rightthreetimes;': '⋌',
+ 'ring;': '˚',
+ 'risingdotseq;': '≓',
+ 'rlarr;': '⇄',
+ 'rlhar;': '⇌',
+ 'rlm;': '',
+ 'rmoust;': '⎱',
+ 'rmoustache;': '⎱',
+ 'rnmid;': '⫮',
+ 'roang;': '⟭',
+ 'roarr;': '⇾',
+ 'robrk;': '⟧',
+ 'ropar;': '⦆',
+ 'ropf;': '𝕣',
+ 'roplus;': '⨮',
+ 'rotimes;': '⨵',
+ 'rpar;': ')',
+ 'rpargt;': '⦔',
+ 'rppolint;': '⨒',
+ 'rrarr;': '⇉',
+ 'rsaquo;': '›',
+ 'rscr;': '𝓇',
+ 'rsh;': '↱',
+ 'rsqb;': ']',
+ 'rsquo;': '’',
+ 'rsquor;': '’',
+ 'rthree;': '⋌',
+ 'rtimes;': '⋊',
+ 'rtri;': '▹',
+ 'rtrie;': '⊵',
+ 'rtrif;': '▸',
+ 'rtriltri;': '⧎',
+ 'ruluhar;': '⥨',
+ 'rx;': '℞',
+ 'sacute;': 'ś',
+ 'sbquo;': '‚',
+ 'sc;': '≻',
+ 'scE;': '⪴',
+ 'scap;': '⪸',
+ 'scaron;': 'š',
+ 'sccue;': '≽',
+ 'sce;': '⪰',
+ 'scedil;': 'ş',
+ 'scirc;': 'ŝ',
+ 'scnE;': '⪶',
+ 'scnap;': '⪺',
+ 'scnsim;': '⋩',
+ 'scpolint;': '⨓',
+ 'scsim;': '≿',
+ 'scy;': 'с',
+ 'sdot;': '⋅',
+ 'sdotb;': '⊡',
+ 'sdote;': '⩦',
+ 'seArr;': '⇘',
+ 'searhk;': '⤥',
+ 'searr;': '↘',
+ 'searrow;': '↘',
+ sect: '§',
+ 'sect;': '§',
+ 'semi;': ';',
+ 'seswar;': '⤩',
+ 'setminus;': '∖',
+ 'setmn;': '∖',
+ 'sext;': '✶',
+ 'sfr;': '𝔰',
+ 'sfrown;': '⌢',
+ 'sharp;': '♯',
+ 'shchcy;': 'щ',
+ 'shcy;': 'ш',
+ 'shortmid;': '∣',
+ 'shortparallel;': '∥',
+ shy: '',
+ 'shy;': '',
+ 'sigma;': 'σ',
+ 'sigmaf;': 'ς',
+ 'sigmav;': 'ς',
+ 'sim;': '∼',
+ 'simdot;': '⩪',
+ 'sime;': '≃',
+ 'simeq;': '≃',
+ 'simg;': '⪞',
+ 'simgE;': '⪠',
+ 'siml;': '⪝',
+ 'simlE;': '⪟',
+ 'simne;': '≆',
+ 'simplus;': '⨤',
+ 'simrarr;': '⥲',
+ 'slarr;': '←',
+ 'smallsetminus;': '∖',
+ 'smashp;': '⨳',
+ 'smeparsl;': '⧤',
+ 'smid;': '∣',
+ 'smile;': '⌣',
+ 'smt;': '⪪',
+ 'smte;': '⪬',
+ 'smtes;': '⪬︀',
+ 'softcy;': 'ь',
+ 'sol;': '/',
+ 'solb;': '⧄',
+ 'solbar;': '⌿',
+ 'sopf;': '𝕤',
+ 'spades;': '♠',
+ 'spadesuit;': '♠',
+ 'spar;': '∥',
+ 'sqcap;': '⊓',
+ 'sqcaps;': '⊓︀',
+ 'sqcup;': '⊔',
+ 'sqcups;': '⊔︀',
+ 'sqsub;': '⊏',
+ 'sqsube;': '⊑',
+ 'sqsubset;': '⊏',
+ 'sqsubseteq;': '⊑',
+ 'sqsup;': '⊐',
+ 'sqsupe;': '⊒',
+ 'sqsupset;': '⊐',
+ 'sqsupseteq;': '⊒',
+ 'squ;': '□',
+ 'square;': '□',
+ 'squarf;': '▪',
+ 'squf;': '▪',
+ 'srarr;': '→',
+ 'sscr;': '𝓈',
+ 'ssetmn;': '∖',
+ 'ssmile;': '⌣',
+ 'sstarf;': '⋆',
+ 'star;': '☆',
+ 'starf;': '★',
+ 'straightepsilon;': 'ϵ',
+ 'straightphi;': 'ϕ',
+ 'strns;': '¯',
+ 'sub;': '⊂',
+ 'subE;': '⫅',
+ 'subdot;': '⪽',
+ 'sube;': '⊆',
+ 'subedot;': '⫃',
+ 'submult;': '⫁',
+ 'subnE;': '⫋',
+ 'subne;': '⊊',
+ 'subplus;': '⪿',
+ 'subrarr;': '⥹',
+ 'subset;': '⊂',
+ 'subseteq;': '⊆',
+ 'subseteqq;': '⫅',
+ 'subsetneq;': '⊊',
+ 'subsetneqq;': '⫋',
+ 'subsim;': '⫇',
+ 'subsub;': '⫕',
+ 'subsup;': '⫓',
+ 'succ;': '≻',
+ 'succapprox;': '⪸',
+ 'succcurlyeq;': '≽',
+ 'succeq;': '⪰',
+ 'succnapprox;': '⪺',
+ 'succneqq;': '⪶',
+ 'succnsim;': '⋩',
+ 'succsim;': '≿',
+ 'sum;': '∑',
+ 'sung;': '♪',
+ sup1: '¹',
+ 'sup1;': '¹',
+ sup2: '²',
+ 'sup2;': '²',
+ sup3: '³',
+ 'sup3;': '³',
+ 'sup;': '⊃',
+ 'supE;': '⫆',
+ 'supdot;': '⪾',
+ 'supdsub;': '⫘',
+ 'supe;': '⊇',
+ 'supedot;': '⫄',
+ 'suphsol;': '⟉',
+ 'suphsub;': '⫗',
+ 'suplarr;': '⥻',
+ 'supmult;': '⫂',
+ 'supnE;': '⫌',
+ 'supne;': '⊋',
+ 'supplus;': '⫀',
+ 'supset;': '⊃',
+ 'supseteq;': '⊇',
+ 'supseteqq;': '⫆',
+ 'supsetneq;': '⊋',
+ 'supsetneqq;': '⫌',
+ 'supsim;': '⫈',
+ 'supsub;': '⫔',
+ 'supsup;': '⫖',
+ 'swArr;': '⇙',
+ 'swarhk;': '⤦',
+ 'swarr;': '↙',
+ 'swarrow;': '↙',
+ 'swnwar;': '⤪',
+ szlig: 'ß',
+ 'szlig;': 'ß',
+ 'target;': '⌖',
+ 'tau;': 'τ',
+ 'tbrk;': '⎴',
+ 'tcaron;': 'ť',
+ 'tcedil;': 'ţ',
+ 'tcy;': 'т',
+ 'tdot;': '⃛',
+ 'telrec;': '⌕',
+ 'tfr;': '𝔱',
+ 'there4;': '∴',
+ 'therefore;': '∴',
+ 'theta;': 'θ',
+ 'thetasym;': 'ϑ',
+ 'thetav;': 'ϑ',
+ 'thickapprox;': '≈',
+ 'thicksim;': '∼',
+ 'thinsp;': ' ',
+ 'thkap;': '≈',
+ 'thksim;': '∼',
+ thorn: 'þ',
+ 'thorn;': 'þ',
+ 'tilde;': '˜',
+ times: '×',
+ 'times;': '×',
+ 'timesb;': '⊠',
+ 'timesbar;': '⨱',
+ 'timesd;': '⨰',
+ 'tint;': '∭',
+ 'toea;': '⤨',
+ 'top;': '⊤',
+ 'topbot;': '⌶',
+ 'topcir;': '⫱',
+ 'topf;': '𝕥',
+ 'topfork;': '⫚',
+ 'tosa;': '⤩',
+ 'tprime;': '‴',
+ 'trade;': '™',
+ 'triangle;': '▵',
+ 'triangledown;': '▿',
+ 'triangleleft;': '◃',
+ 'trianglelefteq;': '⊴',
+ 'triangleq;': '≜',
+ 'triangleright;': '▹',
+ 'trianglerighteq;': '⊵',
+ 'tridot;': '◬',
+ 'trie;': '≜',
+ 'triminus;': '⨺',
+ 'triplus;': '⨹',
+ 'trisb;': '⧍',
+ 'tritime;': '⨻',
+ 'trpezium;': '⏢',
+ 'tscr;': '𝓉',
+ 'tscy;': 'ц',
+ 'tshcy;': 'ћ',
+ 'tstrok;': 'ŧ',
+ 'twixt;': '≬',
+ 'twoheadleftarrow;': '↞',
+ 'twoheadrightarrow;': '↠',
+ 'uArr;': '⇑',
+ 'uHar;': '⥣',
+ uacute: 'ú',
+ 'uacute;': 'ú',
+ 'uarr;': '↑',
+ 'ubrcy;': 'ў',
+ 'ubreve;': 'ŭ',
+ ucirc: 'û',
+ 'ucirc;': 'û',
+ 'ucy;': 'у',
+ 'udarr;': '⇅',
+ 'udblac;': 'ű',
+ 'udhar;': '⥮',
+ 'ufisht;': '⥾',
+ 'ufr;': '𝔲',
+ ugrave: 'ù',
+ 'ugrave;': 'ù',
+ 'uharl;': '↿',
+ 'uharr;': '↾',
+ 'uhblk;': '▀',
+ 'ulcorn;': '⌜',
+ 'ulcorner;': '⌜',
+ 'ulcrop;': '⌏',
+ 'ultri;': '◸',
+ 'umacr;': 'ū',
+ uml: '¨',
+ 'uml;': '¨',
+ 'uogon;': 'ų',
+ 'uopf;': '𝕦',
+ 'uparrow;': '↑',
+ 'updownarrow;': '↕',
+ 'upharpoonleft;': '↿',
+ 'upharpoonright;': '↾',
+ 'uplus;': '⊎',
+ 'upsi;': 'υ',
+ 'upsih;': 'ϒ',
+ 'upsilon;': 'υ',
+ 'upuparrows;': '⇈',
+ 'urcorn;': '⌝',
+ 'urcorner;': '⌝',
+ 'urcrop;': '⌎',
+ 'uring;': 'ů',
+ 'urtri;': '◹',
+ 'uscr;': '𝓊',
+ 'utdot;': '⋰',
+ 'utilde;': 'ũ',
+ 'utri;': '▵',
+ 'utrif;': '▴',
+ 'uuarr;': '⇈',
+ uuml: 'ü',
+ 'uuml;': 'ü',
+ 'uwangle;': '⦧',
+ 'vArr;': '⇕',
+ 'vBar;': '⫨',
+ 'vBarv;': '⫩',
+ 'vDash;': '⊨',
+ 'vangrt;': '⦜',
+ 'varepsilon;': 'ϵ',
+ 'varkappa;': 'ϰ',
+ 'varnothing;': '∅',
+ 'varphi;': 'ϕ',
+ 'varpi;': 'ϖ',
+ 'varpropto;': '∝',
+ 'varr;': '↕',
+ 'varrho;': 'ϱ',
+ 'varsigma;': 'ς',
+ 'varsubsetneq;': '⊊︀',
+ 'varsubsetneqq;': '⫋︀',
+ 'varsupsetneq;': '⊋︀',
+ 'varsupsetneqq;': '⫌︀',
+ 'vartheta;': 'ϑ',
+ 'vartriangleleft;': '⊲',
+ 'vartriangleright;': '⊳',
+ 'vcy;': 'в',
+ 'vdash;': '⊢',
+ 'vee;': '∨',
+ 'veebar;': '⊻',
+ 'veeeq;': '≚',
+ 'vellip;': '⋮',
+ 'verbar;': '|',
+ 'vert;': '|',
+ 'vfr;': '𝔳',
+ 'vltri;': '⊲',
+ 'vnsub;': '⊂⃒',
+ 'vnsup;': '⊃⃒',
+ 'vopf;': '𝕧',
+ 'vprop;': '∝',
+ 'vrtri;': '⊳',
+ 'vscr;': '𝓋',
+ 'vsubnE;': '⫋︀',
+ 'vsubne;': '⊊︀',
+ 'vsupnE;': '⫌︀',
+ 'vsupne;': '⊋︀',
+ 'vzigzag;': '⦚',
+ 'wcirc;': 'ŵ',
+ 'wedbar;': '⩟',
+ 'wedge;': '∧',
+ 'wedgeq;': '≙',
+ 'weierp;': '℘',
+ 'wfr;': '𝔴',
+ 'wopf;': '𝕨',
+ 'wp;': '℘',
+ 'wr;': '≀',
+ 'wreath;': '≀',
+ 'wscr;': '𝓌',
+ 'xcap;': '⋂',
+ 'xcirc;': '◯',
+ 'xcup;': '⋃',
+ 'xdtri;': '▽',
+ 'xfr;': '𝔵',
+ 'xhArr;': '⟺',
+ 'xharr;': '⟷',
+ 'xi;': 'ξ',
+ 'xlArr;': '⟸',
+ 'xlarr;': '⟵',
+ 'xmap;': '⟼',
+ 'xnis;': '⋻',
+ 'xodot;': '⨀',
+ 'xopf;': '𝕩',
+ 'xoplus;': '⨁',
+ 'xotime;': '⨂',
+ 'xrArr;': '⟹',
+ 'xrarr;': '⟶',
+ 'xscr;': '𝓍',
+ 'xsqcup;': '⨆',
+ 'xuplus;': '⨄',
+ 'xutri;': '△',
+ 'xvee;': '⋁',
+ 'xwedge;': '⋀',
+ yacute: 'ý',
+ 'yacute;': 'ý',
+ 'yacy;': 'я',
+ 'ycirc;': 'ŷ',
+ 'ycy;': 'ы',
+ yen: '¥',
+ 'yen;': '¥',
+ 'yfr;': '𝔶',
+ 'yicy;': 'ї',
+ 'yopf;': '𝕪',
+ 'yscr;': '𝓎',
+ 'yucy;': 'ю',
+ yuml: 'ÿ',
+ 'yuml;': 'ÿ',
+ 'zacute;': 'ź',
+ 'zcaron;': 'ž',
+ 'zcy;': 'з',
+ 'zdot;': 'ż',
+ 'zeetrf;': 'ℨ',
+ 'zeta;': 'ζ',
+ 'zfr;': '𝔷',
+ 'zhcy;': 'ж',
+ 'zigrarr;': '⇝',
+ 'zopf;': '𝕫',
+ 'zscr;': '𝓏',
+ 'zwj;': '',
+ 'zwnj;': '',
+}
diff --git a/packages/md-core/src/entities.ts b/packages/md-core/src/entities.ts
new file mode 100644
index 0000000..3dd7be4
--- /dev/null
+++ b/packages/md-core/src/entities.ts
@@ -0,0 +1,84 @@
+import { ENTITIES } from './entities-table.ts'
+
+// character references, decoded as the html tokenizer does: the full named table (legacy names also without ';', the
+// longest one that matches), the attribute exception, and numeric references with the spec's replacements
+const NAMED = new Map(Object.entries(ENTITIES))
+// the longest name the table has without a ';'
+let LEGACY_MAX = 0
+for (const name of NAMED.keys())
+ if (!name.endsWith(';')) LEGACY_MAX = Math.max(LEGACY_MAX, name.length)
+// the longest name with its ';', so a run of letters past it can't be one
+const NAME_MAX = 32
+
+// - are read as windows-1252, as browsers always have; 0 keeps the code point
+const C1 = [
+ 0x20ac, 0, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152,
+ 0, 0x017d, 0, 0, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161,
+ 0x203a, 0x0153, 0, 0x017e, 0x0178,
+]
+
+const numeric = (code: number) => {
+ if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return '\uFFFD'
+ if (code >= 0x80 && code <= 0x9f && C1[code - 0x80]) return String.fromCharCode(C1[code - 0x80]!)
+ return String.fromCodePoint(code)
+}
+
+const alnum = (c: number) => (c >= 48 && c <= 57) || ((c | 32) >= 97 && (c | 32) <= 122)
+
+// attribute: decoding an attribute's value, where a legacy name followed by '=' or an alphanumeric isn't a reference
+export const decode = (text: string, attribute = false): string => {
+ let amp = text.indexOf('&')
+ if (amp < 0) return text
+ const n = text.length
+ let out = ''
+ let from = 0
+ while (amp >= 0) {
+ const i = amp + 1
+ let value: string | undefined
+ let end = i
+ if (text.charCodeAt(i) === 35) {
+ // { or {, the ';' optional; with no digits it is only text
+ let j = i + 1
+ const hex = (text.charCodeAt(j) | 32) === 120
+ if (hex) j++
+ const digits = j
+ let code = 0
+ for (; j < n; j++) {
+ const c = text.charCodeAt(j)
+ let digit: number
+ if (c >= 48 && c <= 57) digit = c - 48
+ else if (hex && (c | 32) >= 97 && (c | 32) <= 102) digit = (c | 32) - 87
+ else break
+ // past the last code point it stays past it, without growing toward a float
+ if (code <= 0x10ffff) code = code * (hex ? 16 : 10) + digit
+ }
+ if (j > digits) {
+ value = numeric(code)
+ end = text.charCodeAt(j) === 59 ? j + 1 : j
+ }
+ } else {
+ let j = i
+ while (j < n && j - i <= NAME_MAX && alnum(text.charCodeAt(j))) j++
+ if (j > i) {
+ if (text.charCodeAt(j) === 59) value = NAMED.get(text.slice(i, j + 1))
+ if (value !== undefined) end = j + 1
+ else
+ // without its ';', the longest legacy name the letters start with
+ for (let k = Math.min(j, i + LEGACY_MAX); k > i; k--) {
+ value = NAMED.get(text.slice(i, k))
+ if (value === undefined) continue
+ const next = text.charCodeAt(k)
+ if (attribute && (next === 61 || alnum(next))) value = undefined
+ else end = k
+ break
+ }
+ }
+ }
+ if (value !== undefined) {
+ out += text.slice(from, amp) + value
+ from = end
+ }
+ amp = text.indexOf('&', end)
+ }
+ return from === 0 ? text : from >= n ? out : out + text.slice(from)
+}
diff --git a/packages/md-core/src/index.ts b/packages/md-core/src/index.ts
new file mode 100644
index 0000000..8c4489a
--- /dev/null
+++ b/packages/md-core/src/index.ts
@@ -0,0 +1,13 @@
+import { emit } from './emit.ts'
+import { parse } from './parse.ts'
+import type { Options, Result } from './types.ts'
+
+export type { Document, Element, Head, Node, Options, Result } from './types.ts'
+export { emit } from './emit.ts'
+export { parse } from './parse.ts'
+
+// html to markdown in two passes over the page and none over a generic tree: a skip-scanning parser that builds only
+// what can be content, and an emitter that writes markdown straight from that. the output aims to be
+// @affordances/md's, byte for byte
+export const htmlToMarkdown = (html: string, options: Options = {}): Result =>
+ emit(parse(html), options)
diff --git a/packages/md-core/src/parse.ts b/packages/md-core/src/parse.ts
new file mode 100644
index 0000000..142bc3c
--- /dev/null
+++ b/packages/md-core/src/parse.ts
@@ -0,0 +1,2886 @@
+import { attr, parseAttrs } from './attr.ts'
+import { decode } from './entities.ts'
+import { NEVER, type Document, type Element, type Head, type Node } from './types.ts'
+
+// html to a Document in one scan, as a browser with scripting off reads it. the tokenizer jumps between '<' with
+// indexOf, takes raw text (script, style) and attribute values whole, and never builds comments or the doctype. the
+// tree builder is the html spec's, as parse5 implements it (the oracle the tests hold this to): insertion modes,
+// implied end tags, the adoption agency, foster parenting, foreign content. what NEVER names is still put on the stack
+// (the algorithm needs it to know where things end) but never into its parent's kids, its text is never kept, and
+// inside svg nothing is kept at all
+
+// what the parser knows of an element beyond the contract: its tag's number, its namespace, and what it keeps
+interface El extends Element {
+ up: El | null
+ id: number
+ ns: number
+ // what it keeps while the page is parsed: 3 all text, even a dropped element's (inside what the Head reads whole: a
+ // foreign title, or json-ld); 2 text; 1 no text (a dropped element); 0 nothing at all (inside svg, where nothing can
+ // ever leave). every element but inside svg keeps its children, dropped ones too, until the parse ends: the
+ // adoption agency and foster parenting place nodes by them, and the Head is read in their order
+ rec: number
+ // whether a dropped child is among its kids, to take out at the end
+ drops: boolean
+}
+
+const HTML = 0
+const SVG = 1
+const MATH = 2
+
+// tag numbers: what the tree builder switches on. unknown tags are 0, and compare by name
+const NAMES = (
+ 'a address annotation-xml applet area article aside audio b base basefont bgsound big blockquote body br button ' +
+ 'canvas caption center code col colgroup dd desc details dialog dir div dl dt em embed fieldset figcaption figure ' +
+ 'font footer foreignObject form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe image img ' +
+ 'input keygen label li link listing main malignmark marquee math menu meta mglyph mi mn mo ms mtext nav nobr ' +
+ 'noembed noframes noscript object ol optgroup option p param plaintext pre rb rp rt rtc ruby s script search ' +
+ 'section select small source span strike strong style sub summary sup svg table tbody td template textarea tfoot ' +
+ 'th thead title tr track tt u ul var video wbr xmp'
+).split(' ')
+const IDS = new Map(NAMES.map((name, i) => [name, i + 1]))
+const T = (name: string) => {
+ const id = IDS.get(name)
+ if (id === undefined) throw new Error(`no tag ${name}`)
+ return id
+}
+const set = (names: string) => {
+ const ids = new Uint8Array(NAMES.length + 1)
+ for (const name of names.split(' ')) ids[T(name)] = 1
+ return ids
+}
+
+const A = T('a')
+const ADDRESS = T('address')
+const ANNOTATION_XML = T('annotation-xml')
+const APPLET = T('applet')
+const AREA = T('area')
+const ARTICLE = T('article')
+const ASIDE = T('aside')
+const B = T('b')
+const BASE = T('base')
+const BASEFONT = T('basefont')
+const BGSOUND = T('bgsound')
+const BIG = T('big')
+const BLOCKQUOTE = T('blockquote')
+const BODY = T('body')
+const BR = T('br')
+const BUTTON = T('button')
+const CAPTION = T('caption')
+const CENTER = T('center')
+const CODE = T('code')
+const T_DESC = T('desc')
+const COL = T('col')
+const COLGROUP = T('colgroup')
+const DD = T('dd')
+const DETAILS = T('details')
+const DIALOG = T('dialog')
+const DIR = T('dir')
+const DIV = T('div')
+const DL = T('dl')
+const DT = T('dt')
+const EM = T('em')
+const EMBED = T('embed')
+const FIELDSET = T('fieldset')
+const FIGCAPTION = T('figcaption')
+const FIGURE = T('figure')
+const FONT = T('font')
+const FOOTER = T('footer')
+const FOREIGN_OBJECT = T('foreignObject')
+const FORM = T('form')
+const FRAME = T('frame')
+const FRAMESET = T('frameset')
+const H1 = T('h1')
+const H2 = T('h2')
+const H3 = T('h3')
+const H4 = T('h4')
+const H5 = T('h5')
+const H6 = T('h6')
+const HEAD = T('head')
+const HEADER = T('header')
+const HGROUP = T('hgroup')
+const HR = T('hr')
+const HTML_TAG = T('html')
+const I = T('i')
+const IFRAME = T('iframe')
+const IMAGE = T('image')
+const IMG = T('img')
+const INPUT = T('input')
+const KEYGEN = T('keygen')
+const LI = T('li')
+const LINK = T('link')
+const LISTING = T('listing')
+const MAIN = T('main')
+const MALIGNMARK = T('malignmark')
+const MARQUEE = T('marquee')
+const MATH_TAG = T('math')
+const MENU = T('menu')
+const META = T('meta')
+const MGLYPH = T('mglyph')
+const NAV = T('nav')
+const NOBR = T('nobr')
+const NOEMBED = T('noembed')
+const NOFRAMES = T('noframes')
+const NOSCRIPT = T('noscript')
+const OBJECT = T('object')
+const OL = T('ol')
+const OPTGROUP = T('optgroup')
+const OPTION = T('option')
+const P = T('p')
+const PARAM = T('param')
+const PLAINTEXT = T('plaintext')
+const PRE = T('pre')
+const RB = T('rb')
+const RP = T('rp')
+const RT = T('rt')
+const RTC = T('rtc')
+const RUBY = T('ruby')
+const S = T('s')
+const SCRIPT = T('script')
+const SEARCH = T('search')
+const SECTION = T('section')
+const SELECT = T('select')
+const SMALL = T('small')
+const SOURCE = T('source')
+const STRIKE = T('strike')
+const STRONG = T('strong')
+const STYLE = T('style')
+const SUMMARY = T('summary')
+const SVG_TAG = T('svg')
+const TABLE = T('table')
+const TBODY = T('tbody')
+const TD = T('td')
+const TEMPLATE = T('template')
+const TEXTAREA = T('textarea')
+const TFOOT = T('tfoot')
+const TH = T('th')
+const THEAD = T('thead')
+const TITLE = T('title')
+const TR = T('tr')
+const TRACK = T('track')
+const TT = T('tt')
+const U = T('u')
+const UL = T('ul')
+const WBR = T('wbr')
+const XMP = T('xmp')
+
+const DROP = set([...NEVER].join(' '))
+// elements the Head is read from
+const WATCH = set('html title meta link script')
+const SPECIAL_HTML = set(
+ 'address applet area article aside base basefont bgsound blockquote body br button caption center col colgroup dd ' +
+ 'details dir div dl dt embed fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header ' +
+ 'hgroup hr html iframe img input li link listing main marquee menu meta nav noembed noframes noscript object ol p ' +
+ 'param plaintext pre script section select source style summary table tbody td template textarea tfoot th thead ' +
+ 'title tr track ul wbr xmp',
+)
+const SPECIAL_MATH = set('mi mo mn ms mtext annotation-xml')
+const SPECIAL_SVG = set('title foreignObject desc')
+const HEADINGS = set('h1 h2 h3 h4 h5 h6')
+const IMPLIED = set('dd dt li optgroup option p rb rp rt rtc')
+const IMPLIED_ALL = set(
+ 'dd dt li optgroup option p rb rp rt rtc caption colgroup tbody td tfoot th thead tr',
+)
+const SCOPE = set('applet caption html marquee object table td template th')
+const LIST_SCOPE = set('applet caption html marquee object table td template th ol ul')
+const BUTTON_SCOPE = set('applet caption html marquee object table td template th button')
+const TABLE_CONTEXT = set('table template html')
+const TABLE_BODY_CONTEXT = set('tbody tfoot thead template html')
+const TABLE_ROW_CONTEXT = set('tr template html')
+const CELLS = set('td th')
+const FOSTERING = set('table tbody tfoot thead tr')
+const TABLE_VOID = set('caption col colgroup tbody td tfoot th thead tr')
+const MATH_TEXT = set('mi mo mn ms mtext')
+const EXITS_FOREIGN = set(
+ 'b big blockquote body br center code dd div dl dt em embed h1 h2 h3 h4 h5 h6 head hr i img li listing menu meta ' +
+ 'nobr ol p pre ruby s small span strong strike sub sup table tt u ul var',
+)
+const SVG_TAGS = new Map(
+ (
+ 'altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix ' +
+ 'feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feFlood ' +
+ 'feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight ' +
+ 'feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath'
+ )
+ .split(' ')
+ .map((name) => [name.toLowerCase(), name]),
+)
+// foreign attributes parse5 renames to their local name (the oracle writes that name)
+const XML_ATTRS = new Map([
+ ['xlink:actuate', 'actuate'],
+ ['xlink:arcrole', 'arcrole'],
+ ['xlink:href', 'href'],
+ ['xlink:role', 'role'],
+ ['xlink:show', 'show'],
+ ['xlink:title', 'title'],
+ ['xlink:type', 'type'],
+ ['xml:lang', 'lang'],
+ ['xml:space', 'space'],
+ ['xmlns', 'xmlns'],
+ ['xmlns:xlink', 'xlink'],
+])
+
+// insertion modes
+const INITIAL = 0
+const BEFORE_HTML = 1
+const BEFORE_HEAD = 2
+const IN_HEAD = 3
+const IN_HEAD_NOSCRIPT = 4
+const AFTER_HEAD = 5
+const IN_BODY = 6
+const TEXT = 7
+const IN_TABLE = 8
+const IN_TABLE_TEXT = 9
+const IN_CAPTION = 10
+const IN_COLUMN_GROUP = 11
+const IN_TABLE_BODY = 12
+const IN_ROW = 13
+const IN_CELL = 14
+const IN_SELECT = 15
+const IN_SELECT_IN_TABLE = 16
+const IN_TEMPLATE = 17
+const AFTER_BODY = 18
+const IN_FRAMESET = 19
+const AFTER_FRAMESET = 20
+const AFTER_AFTER_BODY = 21
+const AFTER_AFTER_FRAMESET = 22
+
+// tokenizer states the tree builder switches to; the rest live inside the scanning functions
+const DATA = 0
+const RCDATA = 1
+const RAWTEXT = 2
+const SCRIPT_DATA = 3
+const PLAIN = 4
+
+// the token being processed, for the modes that hand it on
+const START = 1
+const END = 2
+const CHARS = 3
+const SPACE = 4
+const NUL = 5
+const COMMENT = 6
+const DOCTYPE = 7
+const EOF = 8
+
+// the parse's state: module-level, since a parse runs to completion and the hot paths read it constantly
+let html = ''
+let n = 0
+// the next '&' and ' and end at once, then the first --> or --!>
+const commentEnd = (i: number) => {
+ if (html.charCodeAt(i) === 62) return i + 1
+ if (html.charCodeAt(i) === 45 && html.charCodeAt(i + 1) === 62) return i + 2
+ for (let at = html.indexOf('--', i); at >= 0; at = html.indexOf('--', at + 1)) {
+ const c = html.charCodeAt(at + 2)
+ if (c === 62) return at + 3
+ if (c === 33 && html.charCodeAt(at + 3) === 62) return at + 4
+ }
+ return n
+}
+
+const tokenize = () => {
+ const h = html
+ const length = n
+ let pos = 0
+ // where the text not yet handed on starts: a '<' that starts nothing is text, and joins it
+ let from = 0
+ while (pos < length) {
+ if (tstate !== DATA) {
+ if (tstate === PLAIN) {
+ rawText(pos, length, false)
+ return
+ }
+ const at = tstate === SCRIPT_DATA ? scriptEnd(pos) : rawEnd(pos)
+ rawText(pos, at < 0 ? length : at, tstate === RCDATA)
+ if (at < 0) return
+ const end = tagEnd(at + 2 + rawTag.length)
+ if (end < 0) return
+ tstate = DATA
+ tag = rawTag
+ tid = IDS.get(rawTag) ?? 0
+ emitEnd()
+ pos = from = end
+ continue
+ }
+ // the next '<' is often a few characters on: by hand that far, then indexOf
+ let lt = pos
+ const stop = pos + 8 < length ? pos + 8 : length
+ while (lt < stop && h.charCodeAt(lt) !== 60) lt++
+ if (lt === stop) lt = h.indexOf('<', lt)
+ if (lt < 0) break
+ const c = h.charCodeAt(lt + 1)
+ if (alpha(c)) {
+ const to = readName(lt + 1)
+ const end = tagEnd(to)
+ dataText(from, lt)
+ if (end < 0) return
+ emitStart(to, attrsEnd)
+ pos = from = end
+ } else if (c === 47) {
+ const next = h.charCodeAt(lt + 2)
+ if (alpha(next)) {
+ // an end tag mostly closes the current node: its name read against that one, without a scan
+ const open = current.tag
+ let to = lt + 2 + open.length
+ const after = h.charCodeAt(to)
+ if (
+ current.ns !== SVG &&
+ (after === 62 ||
+ after === 32 ||
+ after === 47 ||
+ after === 10 ||
+ after === 9 ||
+ after === 12) &&
+ h.startsWith(open, lt + 2)
+ ) {
+ tag = open
+ tid = current.id
+ } else to = readName(lt + 2)
+ const end = tagEnd(to)
+ dataText(from, lt)
+ if (end < 0) return
+ emitEnd()
+ pos = from = end
+ } else if (next === 62) {
+ // > is nothing at all
+ dataText(from, lt)
+ pos = from = lt + 3
+ } else if (lt + 2 >= length) pos = length
+ else {
+ dataText(from, lt)
+ onComment()
+ pos = from = bogusEnd(lt + 2)
+ }
+ } else if (c === 33) {
+ dataText(from, lt)
+ pos = from = markup(lt + 2)
+ } else if (c === 63) {
+ dataText(from, lt)
+ onComment()
+ pos = from = bogusEnd(lt + 1)
+ } else pos = lt + 1
+ }
+ if (tstate === DATA) dataText(from, length)
+}
+
+// the Head, read from the elements watched as they were made: where each ended up, by the oracle's rules
+// an html template's content is a fragment of its own, outside the element's text
+const textOf = (el: El): string => {
+ let out = ''
+ for (const kid of el.kids)
+ if (typeof kid === 'string') out += kid
+ else if ((kid as El).id !== TEMPLATE || (kid as El).ns !== HTML) out += textOf(kid as El)
+ return out
+}
+// where an element is in tree order: its child indexes from the root. inside svg nothing is kept, so an element there
+// is where its nearest kept ancestor is (and after it, in the order made, which inside svg is tree order)
+const position = (el: El) => {
+ const path: number[] = []
+ for (let x = el, up = el.up; up; x = up, up = up.up) {
+ const at = up.kids.lastIndexOf(x)
+ if (at < 0) path.length = 0
+ else path.push(at)
+ }
+ return path.toReversed()
+}
+const treeOrder = (a: number[], b: number[]) => {
+ for (let i = 0; i < a.length && i < b.length; i++) if (a[i] !== b[i]) return a[i]! - b[i]!
+ return a.length - b.length
+}
+const readHead = (): Head => {
+ const head: Head = { meta: new Map(), jsonLd: [] }
+ let headTitle: string | undefined
+ let anyTitle: string | undefined
+ // made in tree order, unless something was inserted before or moved
+ let order = watched
+ if (reordered) {
+ const places = new Map(watched.map((el) => [el, position(el)]))
+ order = watched.toSorted((a, b) => treeOrder(places.get(a)!, places.get(b)!))
+ }
+ for (const el of order) {
+ // in the document (not in a template's content, or a body a frameset threw out), and in what
+ let inHead = false
+ let inSvg = false
+ let top: El = el
+ let inside = true
+ for (let up = el.up; up; top = up, up = up.up) {
+ if (up.id === TEMPLATE && up.ns === HTML) inside = false
+ if (up.tag === 'head') inHead = true
+ else if (up.tag === 'svg') inSvg = true
+ }
+ if (!inside || top !== doc) continue
+ if (el.tag === 'title') {
+ if (inSvg) continue
+ if (inHead) headTitle ??= textOf(el)
+ anyTitle ??= textOf(el)
+ } else if (el.tag === 'link') {
+ if (inHead && attr(el, 'rel') === 'canonical') head.canonical ??= attr(el, 'href')
+ } else if (el.tag === 'html') head.lang ??= attr(el, 'lang') || undefined
+ else if (el.tag === 'meta') {
+ for (const kind of ['name', 'property']) {
+ const value = attr(el, kind)
+ const key = `${kind} ${value}`
+ if (value !== undefined && !head.meta.has(key))
+ head.meta.set(key, attr(el, 'content') ?? '')
+ }
+ } else if (el.tag === 'script') {
+ const value = textOf(el).trim()
+ if (value) head.jsonLd.push(value)
+ }
+ }
+ head.title = (headTitle ?? anyTitle)?.trim() || undefined
+ return head
+}
+
+export const parse = (input: string): Document => {
+ html = input.indexOf('\r') < 0 ? input : input.replace(/\r\n?/g, '\n')
+ n = html.length
+ tstate = DATA
+ rawTag = ''
+ doc = make('#root', 0, HTML, '')
+ stack = []
+ current = doc
+ pCount = 0
+ tmplCount = 0
+ afe = []
+ tmplModes = []
+ mode = INITIAL
+ origMode = INITIAL
+ quirks = false
+ framesetOk = true
+ foster = false
+ skipNL = false
+ headEl = formEl = htmlEl = bodyEl = null
+ bodyGone = false
+ pending = []
+ pendingText = false
+ watched = []
+ pruned = []
+ reordered = false
+ tok = 0
+ // found when first needed
+ amp = -1
+ commentOpen = -1
+ tokenize()
+ onEof()
+ const head = readHead()
+ // the dropped elements leave the tree, and the text either side of one is one text
+ for (const el of pruned) {
+ const kids: Node[] = []
+ for (const kid of el.kids)
+ if (typeof kid === 'string') {
+ if (typeof kids[kids.length - 1] === 'string') kids[kids.length - 1] += kid
+ else kids.push(kid)
+ } else if (!DROP[(kid as El).id]) kids.push(kid)
+ el.kids = kids
+ }
+ const root = bodyEl && !bodyGone ? bodyEl : doc
+ root.tag = '#root'
+ root.up = null
+ const document: Document = { root, head }
+ // let the page go: the tree holds slices of it, not the parse's state
+ html = tag = tattrs = ttext = ''
+ NAME_CACHE.fill('')
+ stack = []
+ afe = []
+ watched = []
+ pruned = []
+ pending = []
+ current = doc = headEl = formEl = htmlEl = bodyEl = null as unknown as El
+ return document
+}
diff --git a/packages/md-core/src/types.ts b/packages/md-core/src/types.ts
new file mode 100644
index 0000000..ae183a0
--- /dev/null
+++ b/packages/md-core/src/types.ts
@@ -0,0 +1,71 @@
+// the contract between the parser (parse.ts) and the emitter (emit.ts). both sides are written against this file, so
+// change it only with the other side in hand
+
+// a text node is its string, already entity-decoded, whitespace as written (the emitter collapses it; keeps it)
+export type Node = Element | string
+
+export interface Element {
+ // lowercase tag name; the root is '#root'
+ tag: string
+ // the tag's attributes exactly as written, from after the tag name to before the closing '>' ('' when none). read
+ // them with attr(), which parses on first use: most elements' attributes are never read
+ attrs: string
+ kids: Node[]
+ up: Element | null
+ // attr()'s cache
+ map?: Map | undefined
+}
+
+// what the page's says, read during the one scan; the head's elements are not in the tree
+export interface Head {
+ // the first in the head, else the first anywhere outside an ; trimmed
+ title?: string | undefined
+ //
+ lang?: string | undefined
+ // in the head: its href as written
+ canonical?: string | undefined
+ // anywhere, first one wins: keyed 'name ' and 'property ' for each of the two it has, value
+ // its content (decoded; '' without one)
+ meta: Map
+ // each non-empty ',
+ 'x
',
+ ),
+ whole('', 'x
'),
+ whole(' Spaced title ', 'a b '),
+ ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+
+ test('without frontmatter or json-ld', () => {
+ const html = whole(
+ 'T ',
+ 'd
',
+ )
+ expect(ours(html, { frontmatter: false })).toEqual(theirs(html, { frontmatter: false }))
+ expect(ours(html, { jsonLd: false })).toEqual(theirs(html, { jsonLd: false }))
+ })
+})
+
+// a link hook: every page's twin, but one
+const link = (target: URL) => (target.pathname === '/skip' ? undefined : `${target.href}.md`)
+describe('options', () => {
+ test('extract none keeps the chrome', () => {
+ const html = 'nav main
'
+ expect(ours(html, { extract: 'none' })).toEqual(theirs(html, { extract: 'none' }))
+ })
+ test('the link hook relinks links, never images or fragments', () => {
+ const html =
+ 'a f s
'
+ expect(ours(html, { link })).toEqual(theirs(html, { link }))
+ })
+ test('without a url, links stay as written', () => {
+ const html = 'a
'
+ expect(ours(html, { url: undefined })).toEqual(theirs(html, { url: undefined }))
+ })
+})
+
+// @affordances/md's own fixtures, each against its output (not the .md beside it, which the working tree may change
+// before the package is built again)
+const fixtures = fixturePages()
+// known differences, all from what emit doesn't do yet, each with the share of its reference lines emit reproduces in
+// order: markers and slots (: main, text), the form summary, shown tab panels, streamed suspense
+// boundaries. a page that gets closer should raise its floor; one that gets exact moves out of the list
+const KNOWN = new Map([
+ ['disclosure-fumadocs-tabs', 0.76],
+ ['disclosure-radix-tabs', 0.76],
+ ['form', 0.58],
+ ['form-labels', 0.53],
+ ['form-values', 0.33],
+ ['main-markers', 0.99],
+ ['markers', 0.66],
+ ['package-page', 0.93],
+ ['settings-form', 0.56],
+ ['streamed-instructions', 0.68],
+ ['streamed-next16.3', 0.46],
+ ['streamed-product', 0.86],
+ ['streamed-react19', 0.46],
+])
+const markdownOf = (page: Page) => ({
+ ours: emit(oracle(page.html), { url: page.url }).markdown,
+ reference: htmlToMarkdown(page.html, { url: page.url }).markdown,
+})
+describe('fixtures', () => {
+ test.each(
+ fixtures.filter((page) => !KNOWN.has(page.name)).map((page) => [page.name, page] as const),
+ )('%s', (_, page) => {
+ const { ours: written, reference } = markdownOf(page)
+ expect(written).toBe(reference)
+ })
+ test.each(
+ fixtures.filter((page) => KNOWN.has(page.name)).map((page) => [page.name, page] as const),
+ )('%s, a known difference', (_, page) => {
+ const { ours: written, reference } = markdownOf(page)
+ expect(written).not.toBe(reference)
+ expect(similarity(reference, written)).toBeGreaterThanOrEqual(KNOWN.get(page.name)!)
+ })
+})
+
+// the benchmark corpus, when it's been fetched: byte for byte, every page
+const corpus = corpusPages()
+describe.skipIf(!corpus.length)('corpus parity', () => {
+ test.each(corpus.map((page) => [page.name, page] as const))('%s', (_, page) => {
+ const { ours: written, reference } = markdownOf(page)
+ expect(written).toBe(reference)
+ })
+})
diff --git a/packages/md-core/test/parse-entities-gen.ts b/packages/md-core/test/parse-entities-gen.ts
new file mode 100644
index 0000000..045f5b3
--- /dev/null
+++ b/packages/md-core/test/parse-entities-gen.ts
@@ -0,0 +1,62 @@
+// writes src/entities-table.ts: every named character reference html knows, read out of the decode tree that parse5
+// itself decodes with (the entities package, parse5's dependency), so the table is the oracle's by construction. run
+// with `node test/parse-entities-gen.ts` from the package, then `oxfmt src/entities-table.ts`
+import { writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+
+const require = createRequire(import.meta.resolve('parse5'))
+const entities = (await import(require.resolve('entities/decode'))) as {
+ EntityDecoder: new (
+ tree: Uint16Array,
+ emit: (cp: number) => void,
+ ) => {
+ startEntity(mode: number): void
+ write(input: string, offset: number): number
+ end(): number
+ }
+ htmlDecodeTree: Uint16Array
+}
+const LEGACY = 0
+const STRICT = 1
+
+let out = ''
+const decoder = new entities.EntityDecoder(entities.htmlDecodeTree, (cp) => {
+ out += String.fromCodePoint(cp)
+})
+// -1: the name so far could still become a reference; >0: it is one (the count includes the '&')
+const run = (mode: number, text: string, end: boolean) => {
+ out = ''
+ decoder.startEntity(mode)
+ let consumed = decoder.write(text, 0)
+ if (consumed < 0 && end) consumed = decoder.end()
+ return { consumed, value: out }
+}
+
+const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+const table: [string, string][] = []
+const walk = (prefix: string) => {
+ for (const char of ALNUM) {
+ const name = prefix + char
+ if (run(STRICT, name, false).consumed !== -1) continue
+ const full = run(STRICT, `${name};`, false)
+ if (full.consumed === name.length + 2) table.push([`${name};`, full.value])
+ const legacy = run(LEGACY, name, true)
+ if (legacy.consumed === name.length + 1) table.push([name, legacy.value])
+ walk(name)
+ }
+}
+walk('')
+table.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+const strict = table.filter(([name]) => name.endsWith(';')).length
+// the html spec's table: 2125 names with ';' and 106 legacy ones without
+if (strict !== 2125 || table.length - strict !== 106)
+ throw new Error(`unexpected table: ${strict} with ';', ${table.length - strict} without`)
+
+const body = table.map(([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`)
+writeFileSync(
+ new URL('../src/entities-table.ts', import.meta.url),
+ `// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
+// (decoded without a ';') also under their bare name. do not edit
+export const ENTITIES: Record = {\n${body.join('\n')}\n}\n`,
+)
+console.log(`wrote ${table.length} names`)
diff --git a/packages/md-core/test/parse-fuzz.ts b/packages/md-core/test/parse-fuzz.ts
new file mode 100644
index 0000000..ce5c46d
--- /dev/null
+++ b/packages/md-core/test/parse-fuzz.ts
@@ -0,0 +1,224 @@
+// generated html for the differential fuzz: small pages that pile up the constructs a parser gets wrong (raw text and
+// its end tags, comments and their odd endings, quotes and '>' in attributes, references, misnesting, tables, foreign
+// content, implied tags), seeded so a failure can be replayed
+
+// where this parser knowingly differs from the oracle, on what the generator can make: a generated page one of these
+// matches is left out of the fuzz, and the reason stays here to be seen. none at present: the differences known (see
+// the report) are on pages this generator doesn't make
+export const KNOWN: { why: string; matches: (html: string) => boolean }[] = []
+
+// pages parse5 7.3 throws on: an end tag that empties its stack of open elements (popUntilTagNamePopped pops
+// everything when the tag isn't there, then text goes into nothing). browsers don't, so the oracle can't speak to
+// them; the fuzz counts and skips them, and checks this parser still parses them
+export const ORACLE_THROWS = ['>']
+
+// mulberry32: small, fast, and the same everywhere
+export const random = (seed: number) => {
+ let state = seed >>> 0
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0
+ let t = state
+ t = Math.imul(t ^ (t >>> 15), t | 1)
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+const TAGS = (
+ 'p div span b i u s em strong code a font nobr big small tt strike li ul ol dl dt dd h1 h2 h3 pre listing ' +
+ 'table caption colgroup col tbody thead tfoot tr td th select option optgroup form button label input textarea ' +
+ 'title script style xmp iframe noembed noframes noscript template svg math mi mo mtext annotation-xml desc ' +
+ 'foreignObject path g html head body br img hr wbr image keygen object applet marquee canvas video audio source ' +
+ 'meta link base rt rp rb rtc ruby section article header footer nav main aside blockquote figure figcaption ' +
+ 'details summary dialog address center fieldset menu dir search hgroup frameset frame param track embed area ' +
+ 'sub sup var my-element x'
+).split(' ')
+const RARE_TAGS = ['plaintext']
+const ATTRS = [
+ 'class',
+ 'id',
+ 'href',
+ 'type',
+ 'color',
+ 'face',
+ 'size',
+ 'encoding',
+ 'lang',
+ 'rel',
+ 'name',
+ 'content',
+ 'property',
+ 'xlink:href',
+ 'XLINK:href',
+ 'definitionurl',
+ 'title',
+ 'data-x',
+ 'CLASS',
+]
+const VALUES = [
+ 'x',
+ 'hidden',
+ 'HIDDEN',
+ 'canonical',
+ 'text/html',
+ 'application/ld+json',
+ 'a b',
+ '>',
+ 'a>b',
+ '"',
+ "'",
+ '&',
+ '¬it;',
+ '¬',
+ '&=',
+ '&x',
+ '&',
+ '',
+ '',
+ '',
+ '/',
+ 'red',
+ 'en',
+ 'og:title',
+]
+const WORDS = [
+ 'a',
+ 'text',
+ ' ',
+ '\n',
+ ' \n ',
+ '\t',
+ '&',
+ '<b>',
+ '¬it;',
+ '¬',
+ '©',
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'A',
+ '
',
+ '
',
+ '',
+ '',
+ '&',
+ '&;',
+ '&zz;',
+ '<',
+ '< b',
+ '>',
+ '"',
+ "'",
+ '=',
+ '\r\n',
+ '\r',
+ '\0',
+ ' ',
+ '©',
+ '',
+ ' >',
+ '>',
+]
+const COMMENTS = [
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ ''",
+ '\0',
+]
+
+// a few tags that interact a lot, for the denser half of the pages: formatting misnested across blocks, tables and
+// what gets fostered out of them, select, and foreign content with its integration points and breakouts
+const DENSE = (
+ 'a b i nobr font p div li dd table caption tr td th tbody colgroup col select option optgroup svg math mi ' +
+ 'annotation-xml desc foreignObject title template button form h1 pre textarea script style noscript object br'
+).split(' ')
+
+export const generate = (seed: number) => {
+ const next = random(seed)
+ const dense = next() < 0.5
+ const pick = (list: readonly T[]) => list[Math.floor(next() * list.length)]!
+ const chance = (p: number) => next() < p
+ const attrs = () => {
+ let out = ''
+ const count = chance(0.5) ? 0 : Math.floor(next() * 4)
+ for (let i = 0; i < count; i++) {
+ out += pick([' ', '\n', ' ', '/', ' /'])
+ out += pick(ATTRS)
+ if (chance(0.8)) {
+ out += pick(['=', ' = ', '='])
+ const value = pick(VALUES)
+ const q = next()
+ if (q < 0.45) out += `"${value.replaceAll('"', '"')}"`
+ else if (q < 0.8) out += `'${value.replaceAll("'", ''')}'`
+ else out += value.replace(/[\s"'>]/g, '') || 'v'
+ }
+ }
+ if (chance(0.1)) out += '/'
+ return out
+ }
+ const parts: string[] = chance(0.3) ? [''] : []
+ const length = 1 + Math.floor(next() * (dense ? 80 : 40))
+ for (let i = 0; i < length; i++) {
+ const r = next()
+ if (r < 0.3) parts.push(pick(WORDS))
+ else if (r < 0.62) {
+ const tag = chance(0.003) ? pick(RARE_TAGS) : pick(dense && chance(0.8) ? DENSE : TAGS)
+ const name = chance(0.1) ? tag.toUpperCase() : tag
+ parts.push(`<${name}${attrs()}>`)
+ // raw text content right after its element
+ if (/^(script|style|title|textarea|xmp|iframe|noembed|noframes)$/.test(tag) && chance(0.7)) {
+ const bits = 1 + Math.floor(next() * 5)
+ for (let b = 0; b < bits; b++) parts.push(pick(RAW_BITS))
+ if (chance(0.8)) parts.push(`${tag}>`)
+ }
+ } else if (r < 0.9)
+ parts.push(`${pick(dense && chance(0.8) ? DENSE : TAGS)}${chance(0.1) ? attrs() : ''}>`)
+ else parts.push(pick(COMMENTS))
+ }
+ // sometimes a page ends inside a tag or an attribute
+ if (chance(0.03))
+ parts.push(pick(['">y',
+ 'a never closed ',
+ '',
+ '',
+ '',
+ '',
+ '
',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('rawtext: style, xmp, iframe, noembed, noframes', () => {
+ test.each([
+ 'after',
+ '
& ',
+ 'a
b ',
+ 'after',
+ 'x after',
+ 'x after',
+ 'x',
+ '',
+ // noscript isn't raw text with scripting off: its content is parsed
+ 'x after',
+ 'y ',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('script data and its escapes', () => {
+ test.each([
+ 'after',
+ 'after',
+ 'b',
+ 'b',
+ 'b',
+ ' still -->after',
+ 'after',
+ 'after',
+ 'after',
+ 'after',
+ ' --> after',
+ ' -- > -->after',
+ 'after',
+ 'after',
+ '',
+ '{"a": "
"}',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('plaintext', () => {
+ test.each(['x &', 'ab'])('%j', (html) =>
+ expect(difference(html)).toBeUndefined(),
+ )
+})
+
+describe('comments and bogus comments', () => {
+ test.each([
+ 'ab',
+ 'ab',
+ 'ab',
+ 'ab',
+ 'ab',
+ 'ab',
+ 'ab',
+ 'a -->b',
+ 'ab',
+ 'a\nx',
+ '',
+ 'a
b
',
+ 'a b c d ',
+ 'a b c d ',
+ 'ab c ',
+ '
b',
+ 'x',
+ 'x',
+ 'x',
+ 'ab
',
+ 'x
y',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('misnested formatting: the adoption agency', () => {
+ test.each([
+ '1 23
',
+ '12 34',
+ '12
3',
+ 'x ',
+ '1 23
45',
+ 'x',
+ ' xy',
+ 'ad',
+ 'x
y',
+ 'x
y',
+ '
xy',
+ 'x
y',
+ 'a b',
+ 'x
yz',
+ 'ab
c',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('tables and foster parenting', () => {
+ test.each([
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'b',
+ '',
+ '',
+ '',
+ '',
+ 'outside ',
+ 'y',
+ '',
+ 'a
',
+ '',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('select', () => {
+ test.each([
+ 'a bold? text ',
+ ' x',
+ '',
+ 'x',
+ 'b ',
+ 'a ',
+ 'a b ',
+ '\0x ',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('html, head and body', () => {
+ test.each([
+ '',
+ ' ',
+ 'x',
+ '',
+ '',
+ '',
+ 't b',
+ 'beforexafter',
+ ' x ',
+ 't body text',
+ 'x',
+ '
betweenx',
+ ' after head x',
+ 'x',
+ 'x
',
+ 'abc',
+ 'ab',
+ '
a b',
+ 'a \n',
+ '
x',
+ '
x
',
+ 'x ',
+ 'x',
+ 't
x',
+ 'x',
+ '\0x',
+ '\0x',
+ '\0x',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('templates', () => {
+ test.each([
+ 'x
after',
+ 'a b',
+ 'ab',
+ ' b',
+ 'c b',
+ 'x y z',
+ 'a
bc',
+ ' ',
+ 'never closed',
+ '',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('frameset', () => {
+ test.each([
+ ' ',
+ 'x after',
+ ' ',
+ 'x ',
+ ' ',
+ ' ',
+ 'x',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('foreign content: svg skipped where the browser ends it', () => {
+ test.each([
+ ' after',
+ 'adropped b
',
+ 'breaks out
',
+ 'breaks out
',
+ 'x y ',
+ 'x ',
+ 'stays inside y z',
+ 'in desc x y',
+ 'in foreign object
after',
+ 'x
after',
+ 't after',
+ ' after',
+ ' after',
+ ' still svg after',
+ ' x y',
+ ' after',
+ 'never closed x',
+ '
x',
+ 'x',
+ '',
+ '',
+ 'a\0b c',
+ '\0 ',
+ '
x',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('foreign content: math', () => {
+ test.each([
+ 'x + 1 ',
+ 'bold ',
+ 'x
',
+ ' ',
+ 'x
',
+ 'x
',
+ 'x
',
+ 'breaks out
',
+ 'x ',
+ 'math svg ',
+ 'x ',
+ ' after',
+ ' x ',
+ 'math title ',
+ ' ',
+ ' ',
+ ' ',
+ 'x ',
+ 'a\0\0b ',
+ '\0 ',
+ ' ',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('the head', () => {
+ test.each([
+ ' spaced ',
+ 'second ',
+ 'body title ',
+ 'head body ',
+ 'svg title real ',
+ '',
+ 'x',
+ 'x',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ ' ',
+ '
',
+ 't ',
+ '',
+ '',
+ '',
+ '',
+ ' ',
+ ' ',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
+describe('the contract', () => {
+ const walk = (node: Element, visit: (el: Element) => void) => {
+ visit(node)
+ for (const kid of node.kids) if (typeof kid !== 'string') walk(kid, visit)
+ }
+ test('nothing NEVER names is in the tree, text is never split, and parents are right', () => {
+ const page =
+ 't ab c' +
+ 'n dt ef go h'
+ const { root } = parse(page)
+ expect(root.tag).toBe('#root')
+ expect(root.up).toBeNull()
+ expect(root.kids).toEqual(['abcdefgh'])
+ const problems: string[] = []
+ for (let seed = 1; seed <= 300; seed++)
+ walk(parse(generate(seed)).root, (el) => {
+ if (NEVER.has(el.tag)) problems.push(`${seed}: a ${el.tag}`)
+ el.kids.forEach((kid: Node, i: number) => {
+ if (kid === '') problems.push(`${seed}: empty text in ${el.tag}`)
+ if (typeof kid === 'string' && typeof el.kids[i + 1] === 'string')
+ problems.push(`${seed}: split text in ${el.tag}`)
+ if (typeof kid !== 'string' && kid.up !== el)
+ problems.push(`${seed}: ${kid.tag}'s parent`)
+ })
+ })
+ expect(problems).toEqual([])
+ })
+ test('attrs is the source after the name, and empty without attributes', () => {
+ const { root } = parse('x
y
z ')
+ const [div, p, br, span] = root.kids as Element[]
+ expect(div!.attrs).toBe(' class="a" ')
+ expect(p!.attrs).toBe('')
+ expect(br!.attrs).toBe('')
+ expect(span!.attrs).toBe('')
+ })
+ test('the body is the root, with its attributes', () => {
+ const { root } = parse('a')
+ expect(root.attrs).toBe(' class=x')
+ expect((root.kids[0] as Element).up).toBe(root)
+ })
+})
+
+describe('character references, the whole table', () => {
+ const names = Object.keys(ENTITIES)
+ test('in text, each with and without its ";", and followed by more letters', () => {
+ const page = names.map((name) => `&${name}|&${name}x|&${name.replace(';', '')}=`).join(' ')
+ expect(difference(page)).toBeUndefined()
+ })
+ test('in attribute values, where a legacy name before = or a letter stays text', () => {
+ const page = names
+ .map((name, i) => `${i} `)
+ .join('')
+ expect(difference(page)).toBeUndefined()
+ })
+ test('every numeric reference up to U+FFFF and the edges past it', () => {
+ let page = ''
+ for (let code = 0; code <= 0xffff; code++) page += `${code};${code.toString(16)}`
+ for (const code of [0x10000, 0x1f600, 0x10ffff, 0x110000, 0xffffffff, 2 ** 53])
+ page += `${code};${code.toString(16)};`
+ expect(difference(page)).toBeUndefined()
+ })
+})
+
+describe('the corpus pages', () => {
+ const dir = new URL('../bench/corpus/.cache/', import.meta.url)
+ const pages = existsSync(dir) ? readdirSync(dir).filter((file) => file.endsWith('.html')) : []
+ test.skipIf(pages.length === 0).each(pages)('%s', (file) => {
+ const html = readFileSync(new URL(file, dir), 'utf8')
+ expect(difference(html)).toBeUndefined()
+ })
+})
+
+describe('differential fuzz against the oracle', () => {
+ const RUNS = 6000
+ test(`${RUNS} generated pages`, () => {
+ const failures: string[] = []
+ const oracleThrew: number[] = []
+ for (let seed = 1; seed <= RUNS; seed++) {
+ const html = generate(seed)
+ if (KNOWN.some(({ matches }) => matches(html))) continue
+ let found: string | undefined
+ try {
+ found = difference(html)
+ } catch {
+ // parse5 itself throws on a few inputs (see ORACLE_THROWS); this parser must not
+ parse(html)
+ oracleThrew.push(seed)
+ continue
+ }
+ if (found) failures.push(`seed ${seed} ${JSON.stringify(html)}\n ${found}`)
+ }
+ expect(failures.slice(0, 5)).toEqual([])
+ expect(oracleThrew.length).toBeLessThan(RUNS / 100)
+ })
+ test('pages parse5 throws on still parse', () => {
+ for (const html of ORACLE_THROWS) expect(parse(html).root.tag).toBe('#root')
+ })
+})
diff --git a/packages/md-core/test/support/oracle.ts b/packages/md-core/test/support/oracle.ts
new file mode 100644
index 0000000..4130a50
--- /dev/null
+++ b/packages/md-core/test/support/oracle.ts
@@ -0,0 +1,85 @@
+import { parse } from 'parse5'
+import { NEVER, type Document, type Element, type Head, type Node } from '../../src/types.ts'
+
+// the Document parse.ts must build, made the slow way: parse5 reads the page as a browser does, and this walks its
+// tree into the contract's shape. the parser is tested against it, and the emitter can be written against it before
+// the parser exists
+type P5 = {
+ nodeName: string
+ tagName?: string
+ value?: string
+ attrs?: { name: string; value: string }[]
+ childNodes?: P5[]
+ namespaceURI?: string
+}
+
+const source = (attrs: P5['attrs'] = []) =>
+ attrs
+ .map(
+ ({ name, value }) => ` ${name}="${value.replaceAll('&', '&').replaceAll('"', '"')}"`,
+ )
+ .join('')
+const textOf = (node: P5): string =>
+ node.nodeName === '#text' ? (node.value ?? '') : (node.childNodes ?? []).map(textOf).join('')
+const get = (node: P5, name: string) => node.attrs?.find((a) => a.name === name)?.value
+
+export const oracle = (html: string): Document => {
+ const document = parse(html, { scriptingEnabled: false }) as unknown as P5
+ const head: Head = { meta: new Map(), jsonLd: [] }
+ let headTitle: string | undefined
+ let anyTitle: string | undefined
+ let body: P5 | undefined
+ const scan = (parent: P5, inHead: boolean, inSvg: boolean) => {
+ for (const child of parent.childNodes ?? []) {
+ const tag = child.tagName
+ if (!tag) continue
+ if (tag === 'title' && !inSvg) {
+ if (inHead) headTitle ??= textOf(child)
+ anyTitle ??= textOf(child)
+ } else if (tag === 'link' && inHead && get(child, 'rel') === 'canonical')
+ head.canonical ??= get(child, 'href')
+ else if (tag === 'html') head.lang ??= get(child, 'lang') || undefined
+ else if (tag === 'body') body ??= child
+ else if (tag === 'meta') {
+ for (const kind of ['name', 'property']) {
+ const value = get(child, kind)
+ const key = `${kind} ${value}`
+ if (value !== undefined && !head.meta.has(key))
+ head.meta.set(key, get(child, 'content') ?? '')
+ }
+ } else if (tag === 'script' && get(child, 'type') === 'application/ld+json') {
+ const value = textOf(child).trim()
+ if (value) head.jsonLd.push(value)
+ }
+ scan(child, inHead || tag === 'head', inSvg || tag === 'svg')
+ }
+ }
+ scan(document, false, false)
+ head.title = (headTitle ?? anyTitle)?.trim() || undefined
+ const build = (from: P5, up: Element | null, tag: string): Element => {
+ const el: Element = { tag, attrs: source(from.attrs), kids: [], up }
+ for (const child of from.childNodes ?? []) {
+ let kid: Node | undefined
+ if (child.nodeName === '#text') kid = child.value ?? ''
+ else if (child.tagName && !NEVER.has(child.tagName)) kid = build(child, el, child.tagName)
+ if (kid === undefined) continue
+ // text on both sides of something dropped is one text
+ const last = el.kids.at(-1)
+ if (typeof kid === 'string' && typeof last === 'string')
+ el.kids[el.kids.length - 1] = last + kid
+ else el.kids.push(kid)
+ }
+ return el
+ }
+ return { root: build(body ?? document, null, '#root'), head }
+}
+
+// a Document as plain data, for comparing two of them: attributes parsed, parents left out
+export const plain = (doc: Document, attrs: (el: Element) => Record) => {
+ const node = (n: Node): unknown =>
+ typeof n === 'string' ? n : { tag: n.tag, attrs: attrs(n), kids: n.kids.map(node) }
+ return {
+ root: node(doc.root),
+ head: { ...doc.head, meta: Object.fromEntries(doc.head.meta) },
+ }
+}
diff --git a/packages/md-core/tsconfig.json b/packages/md-core/tsconfig.json
new file mode 100644
index 0000000..739f18b
--- /dev/null
+++ b/packages/md-core/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "include": ["src", "test", "bench"]
+}
diff --git a/vlt-lock.json b/vlt-lock.json
index e8a04a8..a4f6ef4 100644
--- a/vlt-lock.json
+++ b/vlt-lock.json
@@ -147,8 +147,22 @@
"~npm~@manypkg+find-root@3.1.0": [2,"@manypkg/find-root","sha512-BcSqCyKhBVZ5YkSzOiheMCV41kqAFptW6xGqYSTjkVTl9XQpr+pqHhwgGCOHQtjDCv7Is6EFyA14Sm5GVbVABA=="],
"~npm~@manypkg+get-packages@3.1.0": [2,"@manypkg/get-packages","sha512-0TbBVyvPrP7xGYBI/cP8UP+yl/z+HtbTttAD7FMAJgn/kXOTwh5/60TsqP9ZYY710forNfyV0N8P/IE/ujGZJg=="],
"~npm~@manypkg+tools@2.1.2": [2,"@manypkg/tools","sha512-6QEf6yqFbETdwGITKq57aYoPfX/3K8XFNwsAlx0C1M7o8cb79sv1M3w+tWuWvIcSbNqrLF7OD7YpZMVVz335hQ=="],
+ "~npm~@mdream+rust-android-arm-eabi@2.1.0": [3,"@mdream/rust-android-arm-eabi","sha512-ZS0Ql9OqVe6smwDNvhvSFW9MCuvMfjpylS7YwyT3e7f82qxYMaH/iRUrUwB2ztffoyQIOC8zqgO1OsgiOr1xmw==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "android" ], "cpu": [ "arm" ]}],
+ "~npm~@mdream+rust-android-arm64@2.1.0": [3,"@mdream/rust-android-arm64","sha512-K5XQSoDZ/pIdIYcYDVK1G6zc8ipwi8vyAr/dL0nuDtzovOP0aWWpg0ImyHAKA3UC/MLsGMuupPPvMu6eInM2pg==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "android" ], "cpu": [ "arm64" ]}],
+ "~npm~@mdream+rust-darwin-arm64@2.1.0": [3,"@mdream/rust-darwin-arm64","sha512-jkCqALTpNoC8pdj3MrLVxvtB2ZtWQhD/G3E2FTJtDd+KD17pD4HMNEeJ+yc/7uT5HJqWu8/f7QOLwG4eiBz5qQ==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "darwin" ], "cpu": [ "arm64" ]}],
+ "~npm~@mdream+rust-darwin-x64@2.1.0": [3,"@mdream/rust-darwin-x64","sha512-dVTfJHk6rUvXZMliwiovyScfe5Vgle4v+4fzFq2JtFL2rOU4852A/0sMV56RTsIMfzuhXm7qiASE4Gj0d/3E3A==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "darwin" ], "cpu": [ "x64" ]}],
+ "~npm~@mdream+rust-freebsd-x64@2.1.0": [3,"@mdream/rust-freebsd-x64","sha512-My0qtUm06Yuv8gJi0kKVV8mPLvZ3NUkv5F1+lNqqEV3D8W2/JDfAbusBwMBsXKKEeqdA8n/627IjEgqh54iNEg==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "freebsd" ], "cpu": [ "x64" ]}],
+ "~npm~@mdream+rust-linux-arm-gnueabihf@2.1.0": [3,"@mdream/rust-linux-arm-gnueabihf","sha512-Nk99/mC9USjyDvNH93yP+7cZZcIc55esGTt1JkiK5K0+nFJdJM8fNQozcGxeZG01qptFdPeVPcqdw3fkgj2CoA==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "linux" ], "cpu": [ "arm" ]}],
+ "~npm~@mdream+rust-linux-arm64-gnu@2.1.0": [3,"@mdream/rust-linux-arm64-gnu","sha512-8kmWBb8xTBAETRpwulQmxu0AnSptj7oTFqWhFRGFgbkKVHAxR7dXKuvFvC9qllXAfII1A2ZuyHpBHt9w5lGMcg==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "linux" ], "cpu": [ "arm64" ], "libc": [ "glibc" ]}],
+ "~npm~@mdream+rust-linux-arm64-musl@2.1.0": [3,"@mdream/rust-linux-arm64-musl","sha512-pN4oXZMOwAGSEpRbELOjPh+hV8NXIfCQJcQkQQrtrZ+3anxtnXaV9bL8m0noZwEcZ15fj/6IESSR7d+2D77usA==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "linux" ], "cpu": [ "arm64" ], "libc": [ "musl" ]}],
+ "~npm~@mdream+rust-linux-x64-gnu@2.1.0": [3,"@mdream/rust-linux-x64-gnu","sha512-yB9goh1wzk7R5fz1yCZ3oCqPRh58EvWUPiEEDYnUfmv9wiC77PA21vkwWCvE+J93avLiwYdnUDTwX9IWEchb8g==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "linux" ], "cpu": [ "x64" ], "libc": [ "glibc" ]}],
+ "~npm~@mdream+rust-linux-x64-musl@2.1.0": [3,"@mdream/rust-linux-x64-musl","sha512-3cNNLYlFIEWJyRfXoHZQUd1IM/Hk/1LQKAGoQgS0nB1u8EXn1f+jfM+wPWtqLNN5gQkdVqUxNIybYvq7z7d7KQ==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "linux" ], "cpu": [ "x64" ], "libc": [ "musl" ]}],
+ "~npm~@mdream+rust-wasm32-wasi@2.1.0": [3,"@mdream/rust-wasm32-wasi","sha512-0qaSWQKZmeYufr67ymAJ8NrBgJM/z5rx73013a9Qo/jIUiiaHvk12UAy3rMTyFA6FpfktdQP7h5+qewYyrGPSA==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "cpu": [ "wasm32" ]}],
+ "~npm~@mdream+rust-win32-arm64-msvc@2.1.0": [3,"@mdream/rust-win32-arm64-msvc","sha512-/fQfVPN3SohP2SqpXoA+9YA/uJHgl5MppcgJ1ud6oum132tZ5Iv68s9E3taZa+1i31OmBdJIAPnyZS9IDlytsA==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "win32" ], "cpu": [ "arm64" ]}],
+ "~npm~@mdream+rust-win32-x64-msvc@2.1.0": [3,"@mdream/rust-win32-x64-msvc","sha512-HqH0Uh/OZJo+zHnHep3CobefIBk7pEapRN1l1v6Qv44wuBOrPSzA3rhjx79wzSnpXvZj3TC6ET3CM9MVK1Jirw==",null,null,null,null,{ "engines": { "node": ">= 22.0.0" }, "os": [ "win32" ], "cpu": [ "x64" ]}],
"~npm~@mdx-js+mdx@3.1.1": [0,"@mdx-js/mdx","sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="],
"~npm~@mdx-js+react@3.1.1~peer.bcf16a95f0dfe866": [0,"@mdx-js/react","sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw=="],
+ "~npm~@mixmark-io+domino@2.2.0": [2,"@mixmark-io/domino","sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="],
"~npm~@modelcontextprotocol+core@2.4.0": [0,"@modelcontextprotocol/core","sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q=="],
"~npm~@modelcontextprotocol+sdk@1.32.2~peer.b1cb2f6de5198dea": [0,"@modelcontextprotocol/sdk","sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="],
"~npm~@modelcontextprotocol+server@2.4.0": [0,"@modelcontextprotocol/server","sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q=="],
@@ -431,7 +445,9 @@
"~npm~cookie@0.7.2": [0,"cookie","sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"~npm~cors@2.8.6": [0,"cors","sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"~npm~cross-spawn@7.0.6": [0,"cross-spawn","sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
+ "~npm~css-select@5.2.2": [2,"css-select","sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw=="],
"~npm~css-selector-parser@3.3.0": [0,"css-selector-parser","sha512-Y2asgMGFqJKF4fq4xHDSlFYIkeVfRsm69lQC1q9kbEsH5XtnINTMrweLkjYMeaUgiXBy/uvKeO/a1JHTNnmB2g=="],
+ "~npm~css-what@6.2.2": [2,"css-what","sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="],
"~npm~cssesc@3.0.0": [0,"cssesc","sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",null,null,null,null,null,{ "cssesc": "bin/cssesc"}],
"~npm~csstype@3.2.3": [0,"csstype","sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"~npm~d3-array@3.2.4": [0,"d3-array","sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
@@ -464,6 +480,10 @@
"~npm~devlop@1.1.0": [0,"devlop","sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"~npm~diff@8.0.4": [0,"diff","sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
"~npm~direction@2.0.1": [0,"direction","sha512-9S6m9Sukh1cZNknO1CWAr2QAWsbKLafQiyM5gZ7VgXHeuaoUwffKN4q6NC4A/Mf9iiPlOXQEKW/Mv/mh9/3YFA==",null,null,null,null,null,{ "direction": "cli.js"}],
+ "~npm~dom-serializer@2.0.0": [2,"dom-serializer","sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
+ "~npm~domelementtype@2.3.0": [2,"domelementtype","sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
+ "~npm~domhandler@5.0.3": [2,"domhandler","sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],
+ "~npm~domutils@3.2.2": [2,"domutils","sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
"~npm~dot-prop@6.0.1": [0,"dot-prop","sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="],
"~npm~dotenv@17.4.2": [0,"dotenv","sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="],
"~npm~dts-resolver@3.0.0~peer.41cbad1f63c80ef1": [2,"dts-resolver","sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q=="],
@@ -585,6 +605,7 @@
"~npm~hast-util-to-text@4.0.3": [0,"hast-util-to-text","sha512-5yrlWOvGFs6CqHriUpSsNrjzT/Tdo+IOQudbznxOn8K5qblp18MJyzOg8IgDOKQ8MYgQcJA7SusuCjSpDr8mSA=="],
"~npm~hast-util-whitespace@3.0.0": [0,"hast-util-whitespace","sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"~npm~hastscript@9.0.1": [0,"hastscript","sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w=="],
+ "~npm~he@1.2.0": [2,"he","sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",null,null,null,null,null,{ "he": "bin/he"}],
"~npm~hono@4.13.14": [0,"hono","sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ=="],
"~npm~hookable@6.1.2": [2,"hookable","sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg=="],
"~npm~hookified@1.15.1": [2,"hookified","sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
@@ -703,6 +724,7 @@
"~npm~mdast-util-to-hast@13.2.1": [0,"mdast-util-to-hast","sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="],
"~npm~mdast-util-to-markdown@2.2.1": [0,"mdast-util-to-markdown","sha512-ThatlCBxG2GE+mljhNSfZPv56d3QrGiRh97jjYgIk80IzS4uU6d7cHAaexCYSAmUCCcOs3grJ07kX3oTGsFUOw=="],
"~npm~mdast-util-to-string@4.0.0": [0,"mdast-util-to-string","sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="],
+ "~npm~mdream@2.1.0": [2,"mdream","sha512-iYqnp2TjcwLslqrvwoObS0sc4gesbL+CDtc0Zqxo1ceg83ZammD3XFJ9xYlRNaMkbqtRkMmy4VSo/ZKckPv9fg==",null,null,null,null,null,{ "mdream": "bin/mdream.mjs"}],
"~npm~mdurl@2.1.0": [2,"mdurl","sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="],
"~npm~media-typer@1.1.1": [0,"media-typer","sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="],
"~npm~merge-descriptors@2.0.0": [0,"merge-descriptors","sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
@@ -762,6 +784,8 @@
"~npm~next-themes@0.4.6~peer.2d54d32842304f52": [0,"next-themes","sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
"~npm~next@16.4.3~peer.5dc2eee7e5c0226b": [0,"next","sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",null,null,null,null,null,{ "next": "dist/bin/next"}],
"~npm~next@16.4.3~peer.945c44dd448424f8": [0,"next","sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",null,null,null,null,null,{ "next": "dist/bin/next"}],
+ "~npm~node-html-markdown@2.0.0": [2,"node-html-markdown","sha512-DqUC3GGP7pwSYxS93SwHoP+qCw78xcMP6C6H2DuC8rPD2AweJRjBzQb5SdXpKtDlqAQ7hVotJcfhgU7hU5Gthw=="],
+ "~npm~node-html-parser@6.1.13": [2,"node-html-parser","sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg=="],
"~npm~node-releases@2.0.60": [0,"node-releases","sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ=="],
"~npm~npm-run-path@4.0.1": [0,"npm-run-path","sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="],
"~npm~npm-run-path@6.0.0": [0,"npm-run-path","sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
@@ -925,6 +949,8 @@
"~npm~tsconfig-paths@4.2.0": [0,"tsconfig-paths","sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg=="],
"~npm~tsdown@0.23.3~peer.05f46aaa1fc4cc7a": [2,"tsdown","sha512-yAju1F5b7GDEPCLl4ewM3g54lq0NyyYpFnK2lh/ax7/uznmsn4wBOS9/49pI3cGvxtj2LoOjBUtzaT17UEQkhQ==",null,null,null,null,null,{ "tsdown": "dist/run.mjs"}],
"~npm~tslib@2.8.1": [0,"tslib","sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "~npm~turndown-plugin-gfm@1.0.2": [2,"turndown-plugin-gfm","sha512-vwz9tfvF7XN/jE0dGoBei3FXWuvll78ohzCZQuOb+ZjWrs3a0XhQVomJEb2Qh4VHTPNRO4GPZh0V7VRbiWwkRg=="],
+ "~npm~turndown@7.2.5": [2,"turndown","sha512-EKZvCCFHh8sWttpAMs10U6niZFJ2cpz8LkCPlylxoG4JcHF50J7EHnnBW3AY1qXtUMu7kDjCp7dnggB1sIbqEQ=="],
"~npm~tw-animate-css@1.4.0": [0,"tw-animate-css","sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
"~npm~type-check@0.4.0": [2,"type-check","sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
"~npm~type-fest@4.41.0": [0,"type-fest","sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
@@ -1093,6 +1119,13 @@
"workspace~packages+md micromark": "prod ^4.0.3 ~npm~micromark@4.0.3",
"workspace~packages+md parse5": "prod ^7.3.0 ~npm~parse5@7.3.0",
"workspace~packages+md unist-util-visit": "prod ^5.2.0 ~npm~unist-util-visit@5.2.0",
+ "workspace~packages+md-core hast-util-from-parse5": "dev ^8.0.3 ~npm~hast-util-from-parse5@8.0.3",
+ "workspace~packages+md-core mdream": "dev ^2.1.0 ~npm~mdream@2.1.0",
+ "workspace~packages+md-core node-html-markdown": "dev ^2.0.0 ~npm~node-html-markdown@2.0.0",
+ "workspace~packages+md-core parse5": "dev ^7.3.0 ~npm~parse5@7.3.0",
+ "workspace~packages+md-core turndown-plugin-gfm": "dev ^1.0.2 ~npm~turndown-plugin-gfm@1.0.2",
+ "workspace~packages+md-core turndown": "dev ^7.2.5 ~npm~turndown@7.2.5",
+ "workspace~packages+md-core @affordances/md": "dev workspace:* workspace~packages+md",
"workspace~packages+next next": "dev ^16.4.3 ~npm~next@16.4.3~peer.945c44dd448424f8",
"workspace~packages+next react-dom": "dev ^19.3.1 ~npm~react-dom@19.3.1~peer.ac52619a787f06cf",
"workspace~packages+next react": "dev ^19.3.1 ~npm~react@19.3.1",
@@ -1697,6 +1730,11 @@
"~npm~cross-spawn@7.0.6 path-key": "prod ^3.1.0 ~npm~path-key@3.1.1",
"~npm~cross-spawn@7.0.6 shebang-command": "prod ^2.0.0 ~npm~shebang-command@2.0.0",
"~npm~cross-spawn@7.0.6 which": "prod ^2.0.1 ~npm~which@2.0.2",
+ "~npm~css-select@5.2.2 boolbase": "prod ^1.0.0 ~npm~boolbase@1.0.0",
+ "~npm~css-select@5.2.2 css-what": "prod ^6.1.0 ~npm~css-what@6.2.2",
+ "~npm~css-select@5.2.2 domhandler": "prod ^5.0.2 ~npm~domhandler@5.0.3",
+ "~npm~css-select@5.2.2 domutils": "prod ^3.0.1 ~npm~domutils@3.2.2",
+ "~npm~css-select@5.2.2 nth-check": "prod ^2.0.1 ~npm~nth-check@2.1.1",
"~npm~d3-array@3.2.4 internmap": "prod 1 - 2 ~npm~internmap@2.0.3",
"~npm~d3-interpolate@3.0.1 d3-color": "prod 1 - 3 ~npm~d3-color@3.1.0",
"~npm~d3-scale@4.0.2 d3-array": "prod 2.10.0 - 3 ~npm~d3-array@3.2.4",
@@ -1714,6 +1752,13 @@
"~npm~default-browser@5.5.1 bundle-name": "prod ^4.1.0 ~npm~bundle-name@4.1.1",
"~npm~default-browser@5.5.1 default-browser-id": "prod ^5.0.0 ~npm~default-browser-id@5.0.1",
"~npm~devlop@1.1.0 dequal": "prod ^2.0.0 ~npm~dequal@2.0.3",
+ "~npm~dom-serializer@2.0.0 domelementtype": "prod ^2.3.0 ~npm~domelementtype@2.3.0",
+ "~npm~dom-serializer@2.0.0 domhandler": "prod ^5.0.2 ~npm~domhandler@5.0.3",
+ "~npm~dom-serializer@2.0.0 entities": "prod ^4.2.0 ~npm~entities@4.5.0",
+ "~npm~domhandler@5.0.3 domelementtype": "prod ^2.3.0 ~npm~domelementtype@2.3.0",
+ "~npm~domutils@3.2.2 dom-serializer": "prod ^2.0.0 ~npm~dom-serializer@2.0.0",
+ "~npm~domutils@3.2.2 domelementtype": "prod ^2.3.0 ~npm~domelementtype@2.3.0",
+ "~npm~domutils@3.2.2 domhandler": "prod ^5.0.3 ~npm~domhandler@5.0.3",
"~npm~dot-prop@6.0.1 is-obj": "prod ^2.0.0 ~npm~is-obj@2.0.0",
"~npm~dts-resolver@3.0.0~peer.41cbad1f63c80ef1 oxc-resolver": "peerOptional >=11.0.0 MISSING",
"~npm~dunder-proto@1.0.1 call-bind-apply-helpers": "prod ^1.0.1 ~npm~call-bind-apply-helpers@1.0.2",
@@ -2263,6 +2308,19 @@
"~npm~mdast-util-to-markdown@2.2.1 unist-util-visit": "prod ^5.0.0 ~npm~unist-util-visit@5.2.0",
"~npm~mdast-util-to-markdown@2.2.1 zwitch": "prod ^2.0.0 ~npm~zwitch@2.0.4",
"~npm~mdast-util-to-string@4.0.0 @types/mdast": "prod ^4.0.0 ~npm~@types+mdast@4.0.4",
+ "~npm~mdream@2.1.0 @mdream/rust-android-arm-eabi": "optional 2.1.0 ~npm~@mdream+rust-android-arm-eabi@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-android-arm64": "optional 2.1.0 ~npm~@mdream+rust-android-arm64@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-darwin-arm64": "optional 2.1.0 ~npm~@mdream+rust-darwin-arm64@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-darwin-x64": "optional 2.1.0 ~npm~@mdream+rust-darwin-x64@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-freebsd-x64": "optional 2.1.0 ~npm~@mdream+rust-freebsd-x64@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-linux-arm-gnueabihf": "optional 2.1.0 ~npm~@mdream+rust-linux-arm-gnueabihf@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-linux-arm64-gnu": "optional 2.1.0 ~npm~@mdream+rust-linux-arm64-gnu@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-linux-arm64-musl": "optional 2.1.0 ~npm~@mdream+rust-linux-arm64-musl@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-linux-x64-gnu": "optional 2.1.0 ~npm~@mdream+rust-linux-x64-gnu@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-linux-x64-musl": "optional 2.1.0 ~npm~@mdream+rust-linux-x64-musl@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-wasm32-wasi": "optional 2.1.0 ~npm~@mdream+rust-wasm32-wasi@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-win32-arm64-msvc": "optional 2.1.0 ~npm~@mdream+rust-win32-arm64-msvc@2.1.0",
+ "~npm~mdream@2.1.0 @mdream/rust-win32-x64-msvc": "optional 2.1.0 ~npm~@mdream+rust-win32-x64-msvc@2.1.0",
"~npm~micromark-core-commonmark@2.0.4 decode-named-character-reference": "prod ^1.0.0 ~npm~decode-named-character-reference@1.3.0",
"~npm~micromark-core-commonmark@2.0.4 devlop": "prod ^1.0.0 ~npm~devlop@1.1.0",
"~npm~micromark-core-commonmark@2.0.4 micromark-factory-destination": "prod ^2.0.0 ~npm~micromark-factory-destination@2.0.1",
@@ -2481,6 +2539,9 @@
"~npm~next@16.4.3~peer.945c44dd448424f8 caniuse-lite": "prod ^1.0.30001579 ~npm~caniuse-lite@1.0.30001819",
"~npm~next@16.4.3~peer.945c44dd448424f8 postcss": "prod 8.5.23 ~npm~postcss@8.5.23",
"~npm~next@16.4.3~peer.945c44dd448424f8 styled-jsx": "prod 5.1.6 ~npm~styled-jsx@5.1.6~peer.a2bb08ab544944b3",
+ "~npm~node-html-markdown@2.0.0 node-html-parser": "prod ^6.1.13 ~npm~node-html-parser@6.1.13",
+ "~npm~node-html-parser@6.1.13 css-select": "prod ^5.1.0 ~npm~css-select@5.2.2",
+ "~npm~node-html-parser@6.1.13 he": "prod 1.2.0 ~npm~he@1.2.0",
"~npm~npm-run-path@4.0.1 path-key": "prod ^3.0.0 ~npm~path-key@3.1.1",
"~npm~npm-run-path@6.0.0 path-key": "prod ^4.0.0 ~npm~path-key@4.0.0",
"~npm~npm-run-path@6.0.0 unicorn-magic": "prod ^0.3.0 ~npm~unicorn-magic@0.3.0",
@@ -2899,6 +2960,7 @@
"~npm~tsdown@0.23.3~peer.05f46aaa1fc4cc7a tree-kill": "prod ^1.2.2 ~npm~tree-kill@1.2.2",
"~npm~tsdown@0.23.3~peer.05f46aaa1fc4cc7a unconfig-core": "prod ^7.5.0 ~npm~unconfig-core@7.5.0",
"~npm~tsdown@0.23.3~peer.05f46aaa1fc4cc7a verkit": "prod ^0.5.0 ~npm~verkit@0.5.0",
+ "~npm~turndown@7.2.5 @mixmark-io/domino": "prod ^2.2.0 ~npm~@mixmark-io+domino@2.2.0",
"~npm~type-check@0.4.0 prelude-ls": "prod ^1.2.1 ~npm~prelude-ls@1.2.1",
"~npm~type-is@2.1.0 content-type": "prod ^2.0.0 ~npm~content-type@2.1.0",
"~npm~type-is@2.1.0 media-typer": "prod ^1.1.0 ~npm~media-typer@1.1.1",
From 4efe4d8e7e27236384186e9cef7da99fed0f3dc0 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Thu, 12 Nov 2026 04:14:32 +0000
Subject: [PATCH 03/74] feat(md-core): the parser flags attributes and finds
main; the emitter reads only through it
The emitter scanned attribute source by hand and matched names
case-sensitively, so a table written with React's colSpan lost its span.
Presence now comes from Element.flags, set as the parser reads each tag,
values from attr(), and the main landmark from Document.mains. Every
emitter case is re-run in five attribute spellings through the real
parser.
Parity is 8 of 10 benchmark pages byte for byte; the two synthetic pages
differ only by the form summary. Speed is unchanged in total: 128 ms
against mdream's 35 ms.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_018hJ9SEkCX16tDcRNj1QfjV
---
packages/md-core/src/emit-convert.ts | 78 ++--
packages/md-core/src/emit-markdown.ts | 174 ++++++++-
packages/md-core/src/emit-prune.ts | 281 +++-----------
packages/md-core/src/emit.ts | 2 +-
packages/md-core/src/parse.ts | 250 ++++++++++---
packages/md-core/src/types.ts | 35 +-
packages/md-core/test/emit-phases.ts | 2 +-
packages/md-core/test/emit.test.ts | 469 ++++++++++++++++--------
packages/md-core/test/parse-fuzz.ts | 30 +-
packages/md-core/test/parse.test.ts | 23 ++
packages/md-core/test/support/oracle.ts | 23 +-
11 files changed, 888 insertions(+), 479 deletions(-)
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts
index 3ebc41d..4e1c22d 100644
--- a/packages/md-core/src/emit-convert.ts
+++ b/packages/md-core/src/emit-convert.ts
@@ -22,21 +22,9 @@ import {
THEMATIC_BREAK,
BLOCKQUOTE,
} from './emit-markdown.ts'
-import {
- classes,
- DATA_TITLE,
- flags,
- kidsOf,
- linkLabel,
- MDAST,
- NOWRAP as NOWRAP_ATTR,
- read,
- SPAN,
- ALIGN,
- text,
- TITLE,
-} from './emit-prune.ts'
-import type { Element, Node, Options } from './types.ts'
+import { attr } from './attr.ts'
+import { classes, kidsOf, linkLabel, text } from './emit-prune.ts'
+import { FLAG, type Element, type Node, type Options } from './types.ts'
// the page's content as the emitter's tree, as hast-util-to-mdast (MIT, Titus Wormer) converts it with
// @affordances/md's handlers. whitespace is collapsed on the way, as hast-util-minify-whitespace would before: the
@@ -81,7 +69,7 @@ const whitespaceOf = (el: Element, current: number) => {
return PRE
case 'td':
case 'th':
- return flags(el) & NOWRAP_ATTR ? NOWRAP : current
+ return el.flags & FLAG.nowrap ? NOWRAP : current
case 'textarea':
return PRE
}
@@ -251,7 +239,7 @@ export const all = (parent: Element, out: Md[] = []): Md[] => {
if (info & IS_SPACED) mode = whitespaceOf(kid, mode)
let result: Md | Md[] | undefined
if (controls !== 0 && CONTROL_TAGS.has(kid.tag)) result = walkOnly(kid)
- else if (kind === PASS && !(flags(kid) & MDAST)) all(kid, out)
+ else if (kind === PASS && !(kid.flags & FLAG['data-mdast'])) all(kid, out)
else result = one(kid, kind, parent)
const strip = before || end
after = savedAfter
@@ -362,8 +350,7 @@ for (const tag of new Set([...KIND.keys(), ...BLOCKS, ...CONTENT, 'nobr', 'texta
)
const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined => {
- if (el.attrs !== '' && flags(el) & MDAST && read(el, 'data-mdast') === 'ignore')
- return walkOnly(el)
+ if (el.flags & FLAG['data-mdast'] && attr(el, 'data-mdast') === 'ignore') return walkOnly(el)
switch (kind) {
case PASS:
return all(el)
@@ -643,14 +630,14 @@ const resolve = (url: string, image: boolean) => {
const HEADINGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
const link = (el: Element, parent: Element) => {
- const href = (read(el, 'href') ?? '').trim()
+ const href = (attr(el, 'href') ?? '').trim()
const children = all(el)
if (!href || href === '#' || !allowed(href, LINK_SCHEMES)) return children
// a heading's link to its own anchor is the heading
if (href.startsWith('#') && HEADINGS.has(parent.tag)) return children
const result = node(LINK, children)
result.url = resolve(href, false)
- result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null
+ result.title = el.flags & FLAG.title ? (attr(el, 'title') ?? null) : null
// an icon or avatar link reads as its label
if (!children.some((child) => child.type !== TEXT || child.value.trim())) {
const name = linkLabel(el)
@@ -661,12 +648,12 @@ const link = (el: Element, parent: Element) => {
}
const image = (el: Element) => {
- const alt = (read(el, 'alt') ?? '').trim()
- const src = read(el, 'src')
+ const alt = (attr(el, 'alt') ?? '').trim()
+ const src = attr(el, 'src')
if (!alt || !src || !allowed(src, IMAGE_SCHEMES)) return undefined
const result = node(IMAGE, undefined, alt)
result.url = resolve(src, true)
- result.title = flags(el) & TITLE ? (read(el, 'title') ?? null) : null
+ result.title = el.flags & FLAG.title ? (attr(el, 'title') ?? null) : null
return result
}
@@ -679,7 +666,7 @@ const firstKid = (el: Element): Node | undefined => {
const checkbox = (kid: Node | undefined): Element | undefined => {
if (kid === undefined || typeof kid === 'string') return undefined
if (kid.tag === 'input') {
- const type = read(kid, 'type')
+ const type = attr(kid, 'type')
return type === 'checkbox' || type === 'radio' ? kid : undefined
}
return kid.tag === 'p' ? checkbox(firstKid(kid)) : undefined
@@ -703,7 +690,7 @@ const spreadOut = (el: Element): boolean => {
const listItem = (el: Element) => {
const box = checkbox(firstKid(el))
const item = node(LIST_ITEM)
- item.checked = box ? read(box, 'checked') !== undefined : null
+ item.checked = box ? attr(box, 'checked') !== undefined : null
item.spread = spreadOut(el)
item.kids = toFlow(all(el))
return item
@@ -712,7 +699,7 @@ const list = (el: Element) => {
const result = node(LIST, specific(all(el), LIST_ITEM))
result.ordered = el.tag === 'ol'
if (result.ordered) {
- const start = read(el, 'start')
+ const start = attr(el, 'start')
// as hast reads it: a number when it is one, and 0 is no start
const value =
start !== undefined && start !== '' && !Number.isNaN(Number(start)) ? Number(start) : start
@@ -805,7 +792,7 @@ const codeOf = (pre: Element) =>
kidsOf(pre).find((kid): kid is Element => typeof kid !== 'string' && kid.tag === 'code')
const languageOf = (pre: Element) => {
const inner = codeOf(pre)
- const said = [inner && read(inner, 'data-language'), read(pre, 'data-language')]
+ const said = [inner && attr(inner, 'data-language'), attr(pre, 'data-language')]
.map((language) => (language ?? '').trim())
.find(Boolean)
return (classLanguage(inner) ?? said ?? classLanguage(pre))?.split(/\s/)[0] || null
@@ -814,7 +801,7 @@ const code = (el: Element) => {
const result = node(CODE, undefined, toText(el).replace(/[\r\n]+$/, ''))
if (el.tag !== 'pre') return result
result.lang = languageOf(el)
- const title = el === titledCode ? titledAs : read(el, 'data-title')
+ const title = el === titledCode ? titledAs : attr(el, 'data-title')
if (title) result.meta = `title=${JSON.stringify(title)}`
return result
}
@@ -831,16 +818,17 @@ const PRE_TAGS = new Set(['pre'])
const CAPTION_OR_PRE = new Set(['figcaption', 'pre'])
const titled = (el: Element) => {
const flow = () => toFlow(all(el))
- if (el.tag !== 'figure' && !(flags(el) & DATA_TITLE)) return flow()
- const [pre, ...more] = descendants(el, [], PRE_TAGS)
- if (!pre || more.length || read(pre, 'data-title') || pre === titledCode || !languageOf(pre))
+ if (el.tag !== 'figure' && !(el.flags & FLAG['data-title'])) return flow()
+ // one walk: the code blocks, and the captions among them in order
+ const order = descendants(el, [], el.tag === 'figure' ? CAPTION_OR_PRE : PRE_TAGS)
+ const [pre, ...more] = order.filter((at) => at.tag === 'pre')
+ if (!pre || more.length || attr(pre, 'data-title') || pre === titledCode || !languageOf(pre))
return flow()
- let caption: Element | undefined
- if (el.tag === 'figure') {
- const order = descendants(el, [], CAPTION_OR_PRE)
- caption = order.slice(0, order.indexOf(pre)).find((at) => at.tag === 'figcaption')
- }
- const title = text(caption) || (read(el, 'data-title') ?? '').trim()
+ const caption =
+ el.tag === 'figure'
+ ? order.slice(0, order.indexOf(pre)).find((at) => at.tag === 'figcaption')
+ : undefined
+ const title = text(caption) || (attr(el, 'data-title') ?? '').trim()
if (!title) return flow()
const saved = titledCode
const savedAs = titledAs
@@ -857,9 +845,9 @@ const titled = (el: Element) => {
// a cell is one line: blocks in it are separated by a space
const cell = (el: Element) => {
const result = node(TABLE_CELL, all(el))
- if (flags(el) & SPAN) {
- const rowSpan = read(el, 'rowspan')
- const colSpan = read(el, 'colspan')
+ if (el.flags & (FLAG.rowspan | FLAG.colspan)) {
+ const rowSpan = attr(el, 'rowspan')
+ const colSpan = attr(el, 'colspan')
if (rowSpan) result.rowSpan = Number.parseInt(rowSpan, 10) || 1
if (colSpan) result.colSpan = Number.parseInt(colSpan, 10) || 1
}
@@ -932,7 +920,7 @@ const inspect = (el: Element) => {
if (kid.tag === 'table') continue
if (kid.tag === 'th' || kid.tag === 'td') {
if (!align[cellIndex]) {
- const value = (flags(kid) & ALIGN && read(kid, 'align')) || null
+ const value = (kid.flags & FLAG.align && attr(kid, 'align')) || null
if (value === 'center' || value === 'left' || value === 'right' || value === null)
align[cellIndex] = value
}
@@ -1071,7 +1059,7 @@ const collectElement = (
out: Piece[],
) => {
const normal = info.normal && whitespaceOf(el, NORMAL) === NORMAL
- if (NOT_RENDERED.has(el.tag) || (el.tag === 'dialog' && read(el, 'open') === undefined)) {
+ if (NOT_RENDERED.has(el.tag) || (el.tag === 'dialog' && attr(el, 'open') === undefined)) {
walkOnly(el)
return
}
@@ -1168,12 +1156,12 @@ export const convertRoot = (root: Element): Md => {
// what hast-util-to-mdast does last: adjacent texts as one, the line ending's spaces, a paragraph's (heading's,
// root's) outer spaces, and empty texts gone
-const TRIMMED = new Set([PARAGRAPH, HEADING, ROOT])
const edgeSpace = (char: number) => char === 32 || char === 9
const tidy = (parent: Md) => {
const kids = parent.kids
- const trims = TRIMMED.has(parent.type)
+ const type = parent.type
+ const trims = type === PARAGRAPH || type === HEADING || type === ROOT
for (let index = 0; index < kids.length; index++) {
const item = kids[index]!
if (item.type !== TEXT) {
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
index 63273bb..36a7440 100644
--- a/packages/md-core/src/emit-markdown.ts
+++ b/packages/md-core/src/emit-markdown.ts
@@ -25,6 +25,10 @@ export const BREAK = 17
export const LINK = 18
export const IMAGE = 19
+// what never has children shares one empty list (never pushed to), so a text costs no array
+const NO_KIDS: Md[] = []
+const LEAF: boolean[] = []
+for (const type of [TEXT, INLINE_CODE, BREAK, IMAGE, HTML, CODE, THEMATIC_BREAK]) LEAF[type] = true
// one shape for every node, so the walks over them stay monomorphic
export class Md {
type: number
@@ -43,7 +47,7 @@ export class Md {
align: (string | null)[] | null
rowSpan: number
colSpan: number
- constructor(type: number, kids: Md[] = [], value = '') {
+ constructor(type: number, kids: Md[] = LEAF[type] ? NO_KIDS : [], value = '') {
this.type = type
this.kids = kids
this.value = value
@@ -253,6 +257,21 @@ type Pattern = {
before: boolean
after: boolean
regex: RegExp
+ // the before and after as sets of ascii codes, when each is one character of a class (null: none, or not that)
+ beforeSet: Uint8Array | null
+ afterSet: Uint8Array | null
+ simple: boolean
+}
+// a pattern's one-character class as a set of ascii codes; undefined when it isn't one (\d+, $, …). nothing past
+// ascii is in any of them, as the regexes have no u flag and name ascii classes only
+const charSet = (source: string | undefined): Uint8Array | null | undefined => {
+ if (source === undefined) return null
+ if (/[+*$|]/.test(source.replace(/\\./g, ''))) return undefined
+ const regex = new RegExp(`^(?:${source})$`)
+ if (regex.test('é') || regex.test('ab')) return undefined
+ const set = new Uint8Array(128)
+ for (let code = 0; code < 128; code++) if (regex.test(String.fromCharCode(code))) set[code] = 1
+ return set
}
const NEWLINE_ONLY = new Set(['[\\r\\n]', '\\n', '\\r'])
const PATTERNS: Pattern[] = UNSAFE.map((pattern) => {
@@ -269,6 +288,12 @@ const PATTERNS: Pattern[] = UNSAFE.map((pattern) => {
NEWLINE_ONLY.has(pattern.after ?? ''),
before: 'before' in pattern || Boolean(pattern.atBreak),
after: 'after' in pattern,
+ beforeSet: charSet(pattern.before) ?? null,
+ afterSet: charSet(pattern.after) ?? null,
+ simple:
+ !pattern.atBreak &&
+ charSet(pattern.before) !== undefined &&
+ charSet(pattern.after) !== undefined,
regex: new RegExp(
(before ? `(${before})` : '') +
(/[$()*+.?[\\\]^{|}]/.test(pattern.character) ? '\\' : '') +
@@ -280,7 +305,14 @@ const PATTERNS: Pattern[] = UNSAFE.map((pattern) => {
})
// the patterns in scope for a set of constructs, and a test for text that none of them (or a backslash) can touch
-type Scope = { patterns: Pattern[]; special: RegExp; bareNewline: boolean }
+type Scope = {
+ patterns: Pattern[]
+ special: RegExp
+ bareNewline: boolean
+ // for the scan: each ascii character's patterns (those that need no line ending), when all are one character on
+ // either side; undefined where a pattern's regex could swallow a neighbour another match needs (headings)
+ byChar: (Pattern[] | undefined)[] | undefined
+}
const scopes = new Map()
const scopeOf = (mask: number): Scope => {
let scope = scopes.get(mask)
@@ -293,8 +325,17 @@ const scopeOf = (mask: number): Scope => {
const set = [...chars]
.map((char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)
.join('')
+ let byChar: (Pattern[] | undefined)[] | undefined = []
+ if ((mask & HEADING_ATX) !== 0) byChar = undefined
+ for (const pattern of patterns) {
+ if (pattern.newline || !byChar) continue
+ const code = pattern.character.charCodeAt(0)
+ if (!pattern.simple || code >= 128) byChar = undefined
+ else (byChar[code] ??= []).push(pattern)
+ }
scope = {
patterns,
+ byChar,
special: new RegExp(`[${set}\\r\\n]`),
bareNewline: patterns.some(
(pattern) => pattern.character === '\n' && !pattern.before && !pattern.after,
@@ -384,7 +425,134 @@ const safe = (input: string, before: string, after: string, encode = ''): string
)
return input
}
- return slowSafe(scope, input, before, after, encode)
+ return scope.byChar && scannable(input, before, after)
+ ? scanSafe(scope.byChar, input, before, after, encode)
+ : slowSafe(scope, input, before, after, encode)
+}
+// whether no pattern that needs a line ending can match: none in the text, and none beside it that the text's
+// edges could use
+const scannable = (input: string, before: string, after: string) => {
+ if (/[\r\n]/.test(input)) return false
+ if (
+ before !== '' &&
+ isNewline(before.charCodeAt(before.length - 1)) &&
+ atLineStart(input, input.charCodeAt(0))
+ )
+ return false
+ if (after !== '' && isNewline(after.charCodeAt(0))) {
+ const tail = input.charCodeAt(input.length - 1)
+ if (tail === 32 || tail === 9 || tail === 92) return false
+ }
+ return true
+}
+const sidesOf = (pattern: Pattern) => (pattern.before ? 1 : 0) | (pattern.after ? 2 : 0)
+// safe() as one pass over the text: each character's patterns asked of its neighbours, then the same rules as
+// slowSafe. only for text no line ending can reach (scannable), in a scope with one-character patterns
+export const scanSafe = (
+ byChar: (Pattern[] | undefined)[],
+ input: string,
+ before: string,
+ after: string,
+ encode: string,
+) => {
+ const n = input.length
+ const previous = before === '' ? -1 : before.charCodeAt(before.length - 1)
+ const next = after === '' ? -1 : after.charCodeAt(0)
+ const positions: number[] = []
+ const infos: number[] = []
+ for (let i = 0; i < n; i++) {
+ const code = input.charCodeAt(i)
+ if (code >= 128) continue
+ const list = byChar[code]
+ if (list === undefined) continue
+ let bits = -1
+ for (const pattern of list) {
+ if (pattern.beforeSet) {
+ const b = i ? input.charCodeAt(i - 1) : previous
+ if (b < 0 || b >= 128 || pattern.beforeSet[b] !== 1) continue
+ }
+ if (pattern.afterSet) {
+ const a = i + 1 < n ? input.charCodeAt(i + 1) : next
+ if (a < 0 || a >= 128 || pattern.afterSet[a] !== 1) continue
+ }
+ bits = bits < 0 ? sidesOf(pattern) : bits & sidesOf(pattern)
+ }
+ if (bits >= 0) {
+ positions.push(i)
+ infos.push(bits)
+ }
+ }
+ if (!positions.length) return escapeBackslashes(input, after)
+ const at = (i: number) => (i < 0 ? previous : i < n ? input.charCodeAt(i) : next)
+ const result: string[] = []
+ let start = 0
+ for (let index = 0; index < positions.length; index++) {
+ const position = positions[index]!
+ if (position < start) continue
+ // an intraword underscore run (snake_case) needs no escape
+ if (
+ input.charCodeAt(position) === 95 &&
+ (position > 0 || before !== '') &&
+ classify(at(position - 1)) === 0 &&
+ !(position === 1 && (previous === 42 || previous === 95))
+ ) {
+ let sequenceEnd = position + 1
+ while (sequenceEnd < n && input.charCodeAt(sequenceEnd) === 95) sequenceEnd++
+ const skip = sequenceEnd - position - 1
+ if (
+ positions[index + skip] === sequenceEnd - 1 &&
+ (sequenceEnd < n || after !== '') &&
+ classify(at(sequenceEnd)) === 0 &&
+ !(sequenceEnd === n - 1 && (next === 42 || next === 95))
+ ) {
+ index += skip
+ continue
+ }
+ }
+ const info = infos[index]!
+ // escaping what follows (or precedes) is enough
+ if (
+ (position + 1 < n &&
+ positions[index + 1] === position + 1 &&
+ info & 2 &&
+ infos[index + 1] === 0) ||
+ (position - 1 >= 0 &&
+ positions[index - 1] === position - 1 &&
+ info & 1 &&
+ infos[index - 1] === 0)
+ )
+ continue
+ if (start !== position) result.push(escapeBackslashes(input.slice(start, position), '\\'))
+ start = position + 1
+ const char = input.charAt(position)
+ result.push(
+ ASCII_PUNCTUATION.test(char) && !encode.includes(char)
+ ? '\\' + char
+ : reference(input.charCodeAt(position)),
+ )
+ }
+ result.push(escapeBackslashes(input.slice(start), after))
+ return result.join('')
+}
+// the slow path, for tests: safe() by the regexes, whatever the text
+export const regexSafe = (
+ names: string[],
+ input: string,
+ before: string,
+ after: string,
+ encode = '',
+) => slowSafe(scopeOf(maskOf(names)), input, before, after, encode)
+export const scannedSafe = (
+ names: string[],
+ input: string,
+ before: string,
+ after: string,
+ encode = '',
+) => {
+ const scope = scopeOf(maskOf(names))
+ return scope.byChar && scannable(input, before, after)
+ ? scanSafe(scope.byChar, input, before, after, encode)
+ : undefined
}
// what can start a construct at the start of a line: an atBreak pattern's character, a digit (an ordered list), or
// whitespace
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md-core/src/emit-prune.ts
index 31d80d4..00e7bb1 100644
--- a/packages/md-core/src/emit-prune.ts
+++ b/packages/md-core/src/emit-prune.ts
@@ -1,36 +1,20 @@
-import { decode } from './entities.ts'
-import type { Element, Node } from './types.ts'
+import { attr } from './attr.ts'
+import { FLAG, type Element, type Node } from './types.ts'
// what @affordances/md's prune and extract leave of the page, read lazily: kidsOf(el) is an element's children as
-// prune leaves them (hidden things gone, empty links named or gone, inline boxes spaced, repeated links once), cached
-// on the element for the emit call that asked. nothing is copied unless it changes
+// prune leaves them (hidden things gone, empty links named or gone, inline boxes spaced, repeated links once), kept
+// for the emit call that asked. nothing is copied unless it changes; an element of text alone isn't kept at all
-// the cache, on the element itself: the pruned children and the emit call they're for
-// pk, pe: the pruned children and the emit call they're for; lv, le: whether it's code, and for which call; pf: the
-// attribute names it has that anything here reads (-1 before they're read)
-type Pruned = Element & {
- pk?: Node[] | undefined
- pe?: number
- lv?: boolean
- le?: number
- pf?: number
-}
-// the cache's fields, added at once and in one order, so every element the parser made has one shape after
-const touch = (el: Pruned) => {
- if (el.pe === undefined) {
- el.pk = undefined
- el.pe = -1
- el.lv = false
- el.le = -1
- el.pf = -1
- }
-}
-let epoch = 0
+// the emitter's state for one emit call, kept off the parser's elements: each element's pruned children, and
+// whether it's code (no spacing there)
+let cache = new Map()
+let literals = new Map()
// chrome (nav, header, footer, …) is stripped too: the page has no
let stripChrome = false
export const begin = (strip: boolean) => {
- epoch++
stripChrome = strip
+ cache = new Map()
+ literals = new Map()
byId = undefined
}
let page: Element | undefined
@@ -41,167 +25,33 @@ export const setPage = (root: Element) => {
// an element prune made, already pruned
export const made = (from: Element, kids: Node[], tag = from.tag): Element => {
- const el: Pruned = {
+ const el: Element = {
tag,
attrs: from.attrs,
+ flags: from.flags,
kids,
up: from.up,
map: from.map,
- pk: kids,
- pe: epoch,
- lv: false,
- le: -1,
- pf: (from as Pruned).pf ?? -1,
}
+ cache.set(el, kids)
return el
}
const CHROME_TAGS = new Set(['nav', 'header', 'footer', 'aside', 'dialog'])
const CHROME_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary'])
-// the attribute names an element has, of those read here: one scan of its attributes, ever. most elements have
-// none of them, and the scan is far cheaper than parsing every element's attributes
-const HIDDEN = 1
-const ARIA_HIDDEN = 2
-const STYLE = 4
-const ROLE = 8
-const EDITABLE = 16
-const MARKED = 32
-export const MDAST = 64
-export const DATA_TITLE = 128
-export const NOWRAP = 256
-export const TITLE = 512
-export const SPAN = 1024
-export const ALIGN = 2048
+// the attributes prune reads, by their flags
+const HIDDEN = FLAG.hidden
+const ARIA_HIDDEN = FLAG['aria-hidden']
+const STYLE = FLAG.style
+const ROLE = FLAG.role
+const EDITABLE = FLAG.contenteditable
+const MARKED = FLAG['data-affordances-md'] | FLAG['data-mode']
const PRUNES = HIDDEN | ARIA_HIDDEN | STYLE | ROLE | EDITABLE | MARKED
-const space = (code: number) =>
- code === 32 || code === 9 || code === 10 || code === 12 || code === 13
-// whether the name at start is this word: compared by hand, first character first (most names aren't ours)
-const is = (s: string, start: number, word: string) => {
- for (let k = 0; k < word.length; k++)
- if (s.charCodeAt(start + k) !== word.charCodeAt(k)) return false
- return true
-}
-const named = (s: string, start: number, length: number) => {
- const head = s.charCodeAt(start)
- switch (length) {
- case 4:
- return head === 114 && is(s, start, 'role') ? ROLE : 0
- case 5:
- return head === 115 && is(s, start, 'style')
- ? STYLE
- : head === 116 && is(s, start, 'title')
- ? TITLE
- : head === 97 && is(s, start, 'align')
- ? ALIGN
- : 0
- case 7:
- return (head === 114 && is(s, start, 'rowspan')) || (head === 99 && is(s, start, 'colspan'))
- ? SPAN
- : 0
- case 6:
- return head === 104 && is(s, start, 'hidden')
- ? HIDDEN
- : head === 110 && is(s, start, 'nowrap')
- ? NOWRAP
- : 0
- case 9:
- return head === 100 && is(s, start, 'data-mode') ? MARKED : 0
- case 10:
- return head !== 100
- ? 0
- : is(s, start, 'data-mdast')
- ? MDAST
- : is(s, start, 'data-title')
- ? DATA_TITLE
- : 0
- case 11:
- return head === 97 && is(s, start, 'aria-hidden') ? ARIA_HIDDEN : 0
- case 15:
- return head === 99 && is(s, start, 'contenteditable') ? EDITABLE : 0
- case 19:
- return head === 100 && is(s, start, 'data-affordances-md') ? MARKED : 0
- }
- return 0
-}
-// the attribute names, as the tokenizer reads them, jumping over quoted values (most of the string); names as
-// written in lowercase, as pages write them
-const scan = (s: string) => {
- const n = s.length
- let found = 0
- let i = 0
- while (i < n) {
- let c = s.charCodeAt(i)
- while (space(c) || c === 47) c = s.charCodeAt(++i)
- if (i >= n) break
- const start = i
- if (c === 61) i++
- while (i < n) {
- c = s.charCodeAt(i)
- if (space(c) || c === 47 || c === 61) break
- i++
- }
- found |= named(s, start, i - start)
- while (space(c)) c = s.charCodeAt(++i)
- if (c === 61) {
- c = s.charCodeAt(++i)
- while (space(c)) c = s.charCodeAt(++i)
- if (c === 34 || c === 39) {
- const end = s.indexOf(c === 34 ? '"' : "'", i + 1)
- i = end < 0 ? n : end + 1
- } else while (i < n && !space(s.charCodeAt(i))) i++
- }
- }
- return found
-}
-// one attribute's value, as read() reads it (decoded; '' without a value; the first of a repeated name), without
-// parsing the rest: a scan to its name. names as written in lowercase, as with the scan above
-export const read = (el: Element, name: string): string | undefined => {
- if (el.map !== undefined) return el.map.get(name)
- const s = el.attrs
- const n = s.length
- let i = 0
- while (i < n) {
- let c = s.charCodeAt(i)
- while (space(c) || c === 47) c = s.charCodeAt(++i)
- if (i >= n) break
- const start = i
- if (c === 61) i++
- while (i < n) {
- c = s.charCodeAt(i)
- if (space(c) || c === 47 || c === 61) break
- i++
- }
- const match = i - start === name.length && is(s, start, name)
- while (space(c)) c = s.charCodeAt(++i)
- let value = ''
- if (c === 61) {
- c = s.charCodeAt(++i)
- while (space(c)) c = s.charCodeAt(++i)
- if (c === 34 || c === 39) {
- const end = s.indexOf(c === 34 ? '"' : "'", i + 1)
- if (match) value = s.slice(i + 1, end < 0 ? n : end)
- i = end < 0 ? n : end + 1
- } else {
- const from = i
- while (i < n && !space(s.charCodeAt(i))) i++
- if (match) value = s.slice(from, i)
- }
- }
- if (match) return decode(value, true)
- }
- return undefined
-}
-export const flags = (el: Element): number => {
- if (el.attrs === '') return 0
- const cached = el as Pruned
- touch(cached)
- if (cached.pf! < 0) cached.pf = scan(el.attrs)
- return cached.pf!
-}
-const mentions = (el: Element) => (flags(el) & PRUNES) !== 0
+const flags = (el: Element): number => el.flags
+const mentions = (el: Element) => (el.flags & PRUNES) !== 0
const marked = (el: Element) =>
- el.tag === 'affordances-md' ? read(el, 'data-mode') : read(el, 'data-affordances-md')
+ el.tag === 'affordances-md' ? attr(el, 'data-mode') : attr(el, 'data-affordances-md')
const unhidden = (el: Element) => {
const mode = flags(el) & MARKED ? marked(el) : undefined
return mode === 'only' || mode === 'show'
@@ -248,11 +98,11 @@ const styleDisplays = (style: string | undefined, display: RegExp) =>
style !== undefined &&
DISPLAY.test(style) &&
declarations(style).some(([property, value]) => property === 'display' && display.test(value))
-export const role = (el: Element) => read(el, 'role') ?? ''
+export const role = (el: Element) => attr(el, 'role') ?? ''
const editor = (el: Element) => {
const r = role(el)
if (r === 'textbox' || r === 'searchbox') return true
- const editable = read(el, 'contenteditable')
+ const editable = attr(el, 'contenteditable')
return editable !== undefined && editable !== 'false'
}
@@ -267,8 +117,8 @@ const dropped = (el: Element): boolean => {
if (mode === 'only' || mode === 'show') return false
return (
(found & HIDDEN) !== 0 ||
- ((found & ARIA_HIDDEN) !== 0 && read(el, 'aria-hidden') === 'true') ||
- ((found & STYLE) !== 0 && styleHidden(read(el, 'style')))
+ ((found & ARIA_HIDDEN) !== 0 && attr(el, 'aria-hidden') === 'true') ||
+ ((found & STYLE) !== 0 && styleHidden(attr(el, 'style')))
)
}
const chrome = (el: Element) => {
@@ -283,32 +133,16 @@ const hiddenAbove = (el: Element) => {
for (let at: Element | null = el; at; at = at.up) if (dropped(at)) return true
return false
}
-// the page's : the outermost, a real before a role=main, among what prune keeps. the walk reads tags
-// alone, and asks whether a landmark it finds is hidden only then
-export const findMain = (root: Element): Element | undefined => {
- let byRole: Element | undefined
- const walk = (parent: Element): Element | undefined => {
- for (const kid of parent.kids) {
- if (typeof kid === 'string') continue
- if (kid.tag === 'main') {
- if (!hiddenAbove(kid)) return kid
- continue
- }
- if (
- kid.attrs !== '' &&
- kid.attrs.indexOf('main') >= 0 &&
- flags(kid) & ROLE &&
- role(kid) === 'main'
- ) {
- if (!hiddenAbove(kid)) byRole ??= kid
- continue
- }
- const found = walk(kid)
- if (found) return found
- }
- return undefined
- }
- return walk(root) ?? byRole
+// the page's : of the landmarks the parser found, the outermost among what prune keeps, a real before a
+// role=main
+export const findMain = (mains: Element[]): Element | undefined => {
+ const kept = mains.filter((el) => !hiddenAbove(el))
+ const inside = new Set(kept)
+ const outermost = kept.filter((el) => {
+ for (let at = el.up; at; at = at.up) if (inside.has(at)) return false
+ return true
+ })
+ return outermost.find((el) => el.tag === 'main') ?? outermost[0]
}
// the page's ids, among what prune keeps, once a link's label needs them
@@ -319,7 +153,7 @@ const ids = () => {
const walk = (parent: Element) => {
for (const kid of parent.kids) {
if (typeof kid === 'string' || dropped(kid)) continue
- const id = read(kid, 'id')
+ const id = attr(kid, 'id')
if (id !== undefined && !byId!.has(id)) byId!.set(id, kid)
walk(kid)
}
@@ -330,7 +164,7 @@ const ids = () => {
const ASCII_SPACE = /[\t\n\f\r ]+/
export const classes = (el: Element): string[] => {
- const value = read(el, 'class')
+ const value = attr(el, 'class')
return value ? value.split(ASCII_SPACE).filter(Boolean) : []
}
@@ -405,7 +239,7 @@ const words = (el: Element | undefined): string =>
// what an icon or avatar link is called without content: its aria-labelledby, aria-label or title
export const linkLabel = (a: Element): string => {
if (a.attrs === '') return ''
- const labelledBy = read(a, 'aria-labelledby')
+ const labelledBy = attr(a, 'aria-labelledby')
if (labelledBy) {
const names = labelledBy
.split(/\s+/)
@@ -416,7 +250,7 @@ export const linkLabel = (a: Element): string => {
.join(' ')
if (names) return names
}
- return (read(a, 'aria-label') ?? '').trim() || (read(a, 'title') ?? '').trim()
+ return (attr(a, 'aria-label') ?? '').trim() || (attr(a, 'title') ?? '').trim()
}
// images with a description, which an agent can read
@@ -425,7 +259,7 @@ const described = (node: Node): Element[] => {
const walk = (el: Element) => {
for (const kid of kidsOf(el)) {
if (typeof kid === 'string') continue
- if (kid.tag === 'img' && read(kid, 'alt')) found.push(kid)
+ if (kid.tag === 'img' && attr(kid, 'alt')) found.push(kid)
walk(kid)
}
}
@@ -436,7 +270,7 @@ const hasDescribed = (node: Node): boolean => {
if (typeof node === 'string') return false
for (const kid of kidsOf(node)) {
if (typeof kid === 'string') continue
- if ((kid.tag === 'img' && read(kid, 'alt')) || hasDescribed(kid)) return true
+ if ((kid.tag === 'img' && attr(kid, 'alt')) || hasDescribed(kid)) return true
}
return false
}
@@ -454,7 +288,7 @@ const linkDrop = (el: Element) => valueBearing(el) || emptyBlock(el)
const linkText = (a: Element) =>
text(a) ||
described(a)
- .map((img) => `${read(img, 'alt')} ${read(img, 'src')}`)
+ .map((img) => `${attr(img, 'alt')} ${attr(img, 'src')}`)
.join(' ') ||
linkLabel(a)
@@ -530,14 +364,13 @@ const pruned = (kid: Element): Element | undefined => {
return kid
}
-// whether text in an element is code, as written: no spacing there. cached with the children, 1 or 2
+// whether text in an element is code, as written: no spacing there
const literal = (el: Element): boolean => {
- const cached = el as Pruned
- touch(cached)
- if (cached.le === epoch) return cached.lv!
- const value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up))
- cached.le = epoch
- cached.lv = value
+ let value = literals.get(el)
+ if (value === undefined) {
+ value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up))
+ literals.set(el, value)
+ }
return value
}
@@ -546,7 +379,7 @@ const LAID_OUT = /^([\w-]+:)*(inline-)?(flex|grid)$/
const BOXED = /^([\w-]+:)*(block|flex|grid)$/
const displays = (el: Element, display: RegExp) =>
el.attrs !== '' &&
- (classes(el).some((name) => display.test(name)) || styleDisplays(read(el, 'style'), display))
+ (classes(el).some((name) => display.test(name)) || styleDisplays(attr(el, 'style'), display))
const BOXISH = /block|flex|grid|display|\\/
const boxed = (node: Node | undefined) =>
isInline(node) && BOXISH.test(node.attrs) && displays(node, BOXED)
@@ -631,7 +464,7 @@ const spaced = (parent: Element, kids: Node[]): Node[] => {
const previous = soleLink(list[at - 1])
if (
previous &&
- (read(previous, 'href') ?? '').trim() === (read(current, 'href') ?? '').trim() &&
+ (attr(previous, 'href') ?? '').trim() === (attr(current, 'href') ?? '').trim() &&
linkText(previous) === linkText(current)
) {
kept ??= result.slice(0, i)
@@ -647,10 +480,11 @@ const spaced = (parent: Element, kids: Node[]): Node[] => {
// an element's children as prune leaves them
export const kidsOf = (el: Element): Node[] => {
- const cached = el as Pruned
- if (cached.pe === epoch) return cached.pk!
- touch(cached)
const raw = el.kids
+ // only text in it (most elements: a span of code, a link's words): nothing for prune to do, nothing to keep
+ if (raw.length === 0 || (raw.length === 1 && typeof raw[0] === 'string')) return raw
+ const cached = cache.get(el)
+ if (cached !== undefined) return cached
let out: Node[] | undefined
for (let i = 0; i < raw.length; i++) {
const kid = raw[i]!
@@ -664,7 +498,6 @@ export const kidsOf = (el: Element): Node[] => {
}
let kids = out ?? raw
if (kids.length > 1 && !literal(el)) kids = spaced(el, kids)
- cached.pk = kids
- cached.pe = epoch
+ cache.set(el, kids)
return kids
}
diff --git a/packages/md-core/src/emit.ts b/packages/md-core/src/emit.ts
index 8fcfcbd..9bd322b 100644
--- a/packages/md-core/src/emit.ts
+++ b/packages/md-core/src/emit.ts
@@ -17,7 +17,7 @@ export const emit = (doc: Document, options: Options = {}): Result => {
const auto = (options.extract ?? 'auto') === 'auto'
begin(false)
setPage(doc.root)
- const main = auto ? findMain(doc.root) : undefined
+ const main = auto ? findMain(doc.mains) : undefined
if (auto && !main) begin(true)
startConvert(options, base)
const root = convertRoot(main ? made(doc.root, [main], '#root') : doc.root)
diff --git a/packages/md-core/src/parse.ts b/packages/md-core/src/parse.ts
index 142bc3c..04e3a6a 100644
--- a/packages/md-core/src/parse.ts
+++ b/packages/md-core/src/parse.ts
@@ -1,6 +1,6 @@
import { attr, parseAttrs } from './attr.ts'
import { decode } from './entities.ts'
-import { NEVER, type Document, type Element, type Head, type Node } from './types.ts'
+import { FLAG, flagOf, NEVER, type Document, type Element, type Head, type Node } from './types.ts'
// html to a Document in one scan, as a browser with scripting off reads it. the tokenizer jumps between '<' with
// indexOf, takes raw text (script, style) and attribute values whole, and never builds comments or the doctype. the
@@ -19,8 +19,6 @@ interface El extends Element {
// ever leave). every element but inside svg keeps its children, dropped ones too, until the parse ends: the
// adoption agency and foster parenting place nodes by them, and the Head is read in their order
rec: number
- // whether a dropped child is among its kids, to take out at the end
- drops: boolean
}
const HTML = 0
@@ -291,7 +289,9 @@ let bodyGone = false
let pending: string[] = []
let pendingText = false
let watched: El[] = []
-let pruned: El[] = []
+let mains: El[] = []
+// the elements with a dropped child among their kids, to take out at the end
+let pruned = new Set()
// whether a node was put anywhere but after everything before it: then the Head's elements are sorted into tree order
let reordered = false
@@ -300,6 +300,8 @@ let tag = ''
let tid = 0
let tattrs = ''
let tself = false
+// the start tag's FLAG bits, read with its attribute names
+let tflags = 0
let ttext = ''
interface Entry {
@@ -307,6 +309,7 @@ interface Entry {
tag: string
id: number
attrs: string
+ flags: number
}
const lowerAscii = (text: string) =>
@@ -329,18 +332,21 @@ const serialize = (map: Map) => {
// tree
-const make = (name: string, id: number, ns: number, attrs: string): El => {
+const make = (name: string, id: number, ns: number, attrs: string, flags: number): El => {
const el: El = {
tag: name,
attrs,
+ flags,
kids: [],
up: null,
map: undefined,
id,
ns,
rec: ns === SVG ? 0 : DROP[id] ? 1 : 2,
- drops: false,
}
+ // a main, by tag or by role; which of them end up in the tree is settled at the end
+ if (id === MAIN || (flags & FLAG.role && maybe(attrs, 'main') && attr(el, 'role') === 'main'))
+ mains.push(el)
// the Head's elements; of the scripts and links, only those that could be json-ld or the canonical link
if (WATCH[id]) {
if (id === SCRIPT) {
@@ -370,24 +376,31 @@ const settle = () => {
const adopted = (parent: El, el: El) => {
if (parent.rec === 3 && el.rec !== 3) keepAll(el)
- if (DROP[el.id] && !parent.drops) dropsIn(parent)
+ if (DROP[el.id]) pruned.add(parent)
}
-const dropsIn = (parent: El) => {
- parent.drops = true
- pruned.push(parent)
+// a node's first few children go in arrays made to their size: an empty array grown by push takes room for 16
+const addKid = (parent: El, kid: Node) => {
+ const kids = parent.kids
+ switch (kids.length) {
+ case 0:
+ parent.kids = [kid]
+ return
+ default:
+ kids.push(kid)
+ }
}
const appendChild = (parent: El, el: El) => {
el.up = parent
if (parent.rec === 0) return
adopted(parent, el)
- parent.kids.push(el)
+ addKid(parent, el)
}
const appendText = (parent: El, text: string) => {
if (parent.rec < 2) return
const kids = parent.kids
const last = kids.length - 1
if (last >= 0 && typeof kids[last] === 'string') kids[last] += text
- else kids.push(text)
+ else addKid(parent, text)
}
const insertBefore = (parent: El, el: El, ref: El) => {
el.up = parent
@@ -395,7 +408,7 @@ const insertBefore = (parent: El, el: El, ref: El) => {
adopted(parent, el)
reordered = true
const at = parent.kids.lastIndexOf(ref)
- if (at < 0) parent.kids.push(el)
+ if (at < 0) addKid(parent, el)
else parent.kids.splice(at, 0, el)
}
const insertTextBefore = (parent: El, text: string, ref: El) => {
@@ -479,15 +492,15 @@ const removeEl = (el: El) => {
settle()
}
-const insert = (name: string, id: number, ns: number, attrs: string) => {
- const el = make(name, id, ns, attrs)
+const insert = (name: string, id: number, ns: number, attrs: string, flags: number) => {
+ const el = make(name, id, ns, attrs, flags)
attach(el)
push(el)
return el
}
-const insertTok = () => insert(tag, tid, HTML, tattrs)
-const appendTok = () => attach(make(tag, tid, HTML, tattrs))
-const insertFake = (name: string, id: number) => insert(name, id, HTML, '')
+const insertTok = () => insert(tag, tid, HTML, tattrs, tflags)
+const appendTok = () => attach(make(tag, tid, HTML, tattrs, tflags))
+const insertFake = (name: string, id: number) => insert(name, id, HTML, '', 0)
const special = (el: El) =>
(el.ns === HTML ? SPECIAL_HTML : el.ns === MATH ? SPECIAL_MATH : SPECIAL_SVG)[el.id] === 1
@@ -600,6 +613,13 @@ const EMPTY = new Map()
// recent first, removing by indexes taken before any removal), since that is the oracle
const noah = (el: El) => {
if (afe.length < 3) return
+ let same = 0
+ for (let i = afe.length - 1; i >= 0 && same < 3; i--) {
+ const entry = afe[i]!
+ if (entry === null) break
+ if (entry.el.tag === el.tag && entry.el.ns === el.ns) same++
+ }
+ if (same < 3) return
const own = attrsOf(el)
const list = afe.toReversed()
const candidates: number[] = []
@@ -613,32 +633,42 @@ const noah = (el: El) => {
const lists = candidates.map((i) => attrsOf(list[i]!.el))
let valid = 0
for (let c = 0; c < candidates.length; c++) {
- let same = true
- for (const [name, value] of lists[c]!) if (own.get(name) !== value) same = false
- if (same && ++valid >= 3) list.splice(candidates[c]!, 1)
+ let equal = true
+ for (const [name, value] of lists[c]!) if (own.get(name) !== value) equal = false
+ if (equal && ++valid >= 3) list.splice(candidates[c]!, 1)
}
afe = list.toReversed()
}
const afePush = (el: El) => {
noah(el)
- afe.push({ el, tag: el.tag, id: el.id, attrs: el.attrs })
+ afe.push({ el, tag: el.tag, id: el.id, attrs: el.attrs, flags: el.flags })
}
const reconstruct = () => {
if (afe.length !== 0) rebuild()
}
+// whether an element is open: nearly always one of the top few, so those first
+const isOpen = (el: El) => {
+ const top = stack.length - 1
+ return (
+ stack[top] === el ||
+ stack[top - 1] === el ||
+ stack[top - 2] === el ||
+ stack.lastIndexOf(el) >= 0
+ )
+}
const rebuild = () => {
const length = afe.length
let i = length - 1
const last = afe[i]!
- if (last === null || stack.lastIndexOf(last.el) >= 0) return
+ if (last === null || isOpen(last.el)) return
while (i > 0) {
const entry = afe[i - 1]!
- if (entry === null || stack.lastIndexOf(entry.el) >= 0) break
+ if (entry === null || isOpen(entry.el)) break
i--
}
for (; i < length; i++) {
const entry = afe[i]!
- entry.el = insert(entry.tag, entry.id, entry.el.ns, entry.attrs)
+ entry.el = insert(entry.tag, entry.id, entry.el.ns, entry.attrs, entry.flags)
}
}
@@ -679,7 +709,13 @@ const adoption = () => {
if (overflow) afeRemove(nodeEntry)
removeEl(node!)
} else {
- const clone = make(nodeEntry.tag, nodeEntry.id, nodeEntry.el.ns, nodeEntry.attrs)
+ const clone = make(
+ nodeEntry.tag,
+ nodeEntry.id,
+ nodeEntry.el.ns,
+ nodeEntry.attrs,
+ nodeEntry.flags,
+ )
stack[stack.lastIndexOf(node!)] = clone
settle()
nodeEntry.el = clone
@@ -695,16 +731,22 @@ const adoption = () => {
if (FOSTERING[common.id]) fosterElement(last)
else appendChild(common, last)
}
- const clone = make(entry.tag, entry.id, formatting.ns, entry.attrs)
+ const clone = make(entry.tag, entry.id, formatting.ns, entry.attrs, entry.flags)
// the furthest block's children move into the new formatting element
reordered = true
clone.kids = furthest.kids
for (const kid of clone.kids) if (typeof kid !== 'string') kid.up = clone
- if (furthest.drops) dropsIn(clone)
+ if (pruned.has(furthest)) pruned.add(clone)
furthest.kids = []
appendChild(furthest, clone)
const mark = afe.lastIndexOf(bookmark)
- afe.splice(mark + 1, 0, { el: clone, tag: entry.tag, id: entry.id, attrs: entry.attrs })
+ afe.splice(mark + 1, 0, {
+ el: clone,
+ tag: entry.tag,
+ id: entry.id,
+ attrs: entry.attrs,
+ flags: entry.flags,
+ })
afeRemove(entry)
removeEl(formatting)
stack.splice(stack.lastIndexOf(furthest) + 1, 0, clone)
@@ -803,6 +845,13 @@ const mathAttrs = (source: string) => {
for (const [name, value] of map) out += ` ${XML_ATTRS.get(name) ?? name}="${quote(value)}"`
return out
}
+// the token's flags, or a renamed source's (xlink:title is title)
+const flagsOf = (attrs: string) => {
+ if (attrs === tattrs) return tflags
+ let flags = 0
+ for (const name of parseAttrs(attrs).keys()) flags |= flagOf(name)
+ return flags
+}
const startInForeign = () => {
if (
EXITS_FOREIGN[tid] ||
@@ -820,9 +869,10 @@ const startInForeign = () => {
name = SVG_TAGS.get(tag) ?? tag
if (name === 'foreignObject') id = FOREIGN_OBJECT
} else if (attrs !== '') attrs = mathAttrs(attrs)
- if (!tself) insert(name, id, ns, attrs)
+ if (!tself) insert(name, id, ns, attrs, flagsOf(attrs))
// a self-closed svg child is nothing anyone will read, unless the Head reads it
- else if (ns !== SVG || WATCH[id] || cur().rec !== 0) attach(make(name, id, ns, attrs))
+ else if (ns !== SVG || WATCH[id] || cur().rec !== 0)
+ attach(make(name, id, ns, attrs, flagsOf(attrs)))
}
const fontExits = () => {
const map = parseAttrs(tattrs)
@@ -1257,7 +1307,7 @@ const initialAnything = () => {
dispatch()
}
const beforeHtmlAnything = () => {
- htmlEl = make('html', HTML_TAG, HTML, '')
+ htmlEl = make('html', HTML_TAG, HTML, '', 0)
appendChild(doc, htmlEl)
push(htmlEl)
mode = BEFORE_HEAD
@@ -1412,6 +1462,7 @@ const adopt = (el: El) => {
if (!added) return
el.attrs = serialize(own)
el.map = own
+ el.flags |= tflags
}
const hiddenInput = () =>
tattrs !== '' && parseAttrs(tattrs).get('type')?.toLowerCase() === 'hidden'
@@ -1433,6 +1484,10 @@ const SWITCH_END = set(
'a b i s u em tt big code font nobr small strike strong p li dd dt h1 h2 h3 h4 h5 h6 br body html form applet ' +
'object marquee template',
)
+// end tags in body that do more than pop the current node, even when they name it
+const POP_SPECIAL = set(
+ 'a b i s u em tt big code font nobr small strike strong br body html form applet object marquee template',
+)
const startInBody = (): void => {
if (tid === 0 || PLAIN_START[tid]) {
reconstruct()
@@ -1565,8 +1620,8 @@ const startInBody = (): void => {
return textParsing(RAWTEXT)
case SVG_TAG:
reconstruct()
- if (tself) attach(make(tag, tid, SVG, tattrs))
- else insert(tag, tid, SVG, tattrs)
+ if (tself) attach(make(tag, tid, SVG, tattrs, tflags))
+ else insert(tag, tid, SVG, tattrs, tflags)
return
case HTML_TAG:
if (tmplCount === 0) adopt(stack[0]!)
@@ -1609,8 +1664,8 @@ const startInBody = (): void => {
case MATH_TAG: {
reconstruct()
const attrs = tattrs === '' ? '' : mathAttrs(tattrs)
- if (tself) attach(make(tag, tid, MATH, attrs))
- else insert(tag, tid, MATH, attrs)
+ if (tself) attach(make(tag, tid, MATH, attrs, flagsOf(attrs)))
+ else insert(tag, tid, MATH, attrs, flagsOf(attrs))
return
}
case TABLE:
@@ -2359,7 +2414,9 @@ const readName = (from: number) => {
const size = i - from
const key = (first * 7 + size * 31 + h.charCodeAt(i - 1)) & 255
const cached = NAME_CACHE[key]!
- if (cached.length === size && h.startsWith(cached, from)) {
+ let k = cached.length === size ? 1 : size
+ while (k < size && h.charCodeAt(from + k) === cached.charCodeAt(k)) k++
+ if (k === size && cached.length === size && cached.charCodeAt(0) === first) {
tag = cached
tid = ID_CACHE[key]!
return i
@@ -2376,11 +2433,35 @@ const readName = (from: number) => {
// whether any attribute started
let attrsEnd = 0
let named = false
+// FLAG's names by a hash the attribute loop keeps as it reads a name (each character lowered with |32, which leaves
+// '-'; a cr, which it would also make '-', is gone by now): 10 is a multiplier that gives each of them its own slot
+// of 64, and a hit is then checked letter by letter, so any name can land anywhere without a false flag
+const FLAG_NAMES: string[] = []
+const FLAG_BITS: number[] = []
+const FLAG_SLOT = new Int8Array(64).fill(-1)
+for (const [name, bit] of Object.entries(FLAG)) {
+ let hash = 0
+ for (let k = 0; k < name.length; k++) hash = (hash * 10 + name.charCodeAt(k)) | 0
+ const slot = (hash ^ name.length) & 63
+ if (FLAG_SLOT[slot] !== -1) throw new Error(`flag hash collides: ${name}`)
+ FLAG_SLOT[slot] = FLAG_NAMES.length
+ FLAG_NAMES.push(name)
+ FLAG_BITS.push(bit)
+}
+const flagMatch = (at: number, from: number, to: number) => {
+ const name = FLAG_NAMES[at]!
+ if (name.length !== to - from) return 0
+ const h = html
+ for (let k = 0; k < name.length; k++)
+ if ((h.charCodeAt(from + k) | 32) !== name.charCodeAt(k)) return 0
+ return FLAG_BITS[at]!
+}
const tagEnd = (from: number): number => {
const h = html
const length = n
const stops = STOPS
named = false
+ tflags = 0
let i = from
let c = h.charCodeAt(i)
for (;;) {
@@ -2404,9 +2485,16 @@ const tagEnd = (from: number): number => {
if (i >= length) return -1
// a name, whose first character may be '='
named = true
+ const name = i
+ let hash = c | 32
c = h.charCodeAt(++i)
- while (i < length && (stops[c]! & 15) === 0) c = h.charCodeAt(++i)
+ while (i < length && (stops[c]! & 15) === 0) {
+ hash = (hash * 10 + (c | 32)) | 0
+ c = h.charCodeAt(++i)
+ }
if (i >= length) return -1
+ const flag = FLAG_SLOT[(hash ^ (i - name)) & 63]!
+ if (flag >= 0) tflags |= flagMatch(flag, name, i)
while (stops[c] === 1) c = h.charCodeAt(++i)
// no '=': what follows reads the same as before a name
if (c !== 61) continue
@@ -2435,7 +2523,21 @@ const hasNul = (from: number, to: number) => {
return false
}
// text in the data state: references decoded, and nuls (rare) handed on one by one
+// whether the page has this name at `at` (short names: by hand beats a startsWith call)
+const same = (name: string, at: number) => {
+ const h = html
+ for (let k = 0; k < name.length; k++)
+ if (h.charCodeAt(at + k) !== name.charCodeAt(k)) return false
+ return true
+}
+// the range of the page the tokenizer just read whole on its way to a '<', finding no nul
+let cleanFrom = -1
+let clean = -1
+// whether the text before the last > ended in a nul, whose run goes on into the next text
+let nulJoin = false
const dataText = (from: number, to: number) => {
+ const join = nulJoin
+ nulJoin = false
if (to <= from) return
// inside svg text goes nowhere, and only could say the page has content (framesetOk)
if (current.rec === 0 && !framesetOk && !integration(current)) return
@@ -2443,6 +2545,7 @@ const dataText = (from: number, to: number) => {
if (amp < from) amp = html.indexOf('&', from) >>> 0
if (amp < to) text = decode(text)
if (
+ !(clean === to && cleanFrom === from) &&
(to - from > 24 ? text.indexOf('\0') >= 0 : hasNul(from, to)) &&
!(current.rec === 0 && !framesetOk)
) {
@@ -2451,7 +2554,7 @@ const dataText = (from: number, to: number) => {
let j = i
if (text.charCodeAt(i) === 0) {
while (text.charCodeAt(j) === 0) j++
- onNul()
+ if (i > 0 || !join) onNul()
} else {
while (j < text.length && text.charCodeAt(j) !== 0) j++
chars(text.slice(i, j))
@@ -2473,15 +2576,41 @@ const rawText = (from: number, to: number, refs: boolean) => {
chars(text)
}
+// the common case first: in body, with an html current node, an ordinary element is reconstructed into and inserted,
+// and an end tag that names the current node (and isn't one in body treats specially) pops it. both are what the
+// general dispatch would do, minus the dispatch
const emitStart = (from: number, to: number) => {
tattrs = named ? html.slice(from, to) : ''
tok = START
skipNL = false
+ if (mode === IN_BODY && current.ns === HTML) {
+ if (tid === 0 || PLAIN_START[tid]) {
+ if (afe.length !== 0) rebuild()
+ insertTok()
+ return
+ }
+ if (BLOCK_START[tid]) {
+ if (pInButtonScope()) closeP()
+ insertTok()
+ return
+ }
+ }
processStart()
}
const emitEnd = () => {
tok = END
skipNL = false
+ const open = current
+ if (
+ mode === IN_BODY &&
+ open.ns === HTML &&
+ open.id === tid &&
+ open.tag === tag &&
+ !POP_SPECIAL[tid]
+ ) {
+ pop()
+ return
+ }
processEnd()
}
@@ -2698,12 +2827,20 @@ const tokenize = () => {
continue
}
// the next '<' is often a few characters on: by hand that far, then indexOf
+ // (a text read whole on the way, with no nul, needn't be read for one again)
let lt = pos
+ let c = 0
const stop = pos + 8 < length ? pos + 8 : length
- while (lt < stop && h.charCodeAt(lt) !== 60) lt++
- if (lt === stop) lt = h.indexOf('<', lt)
+ while (lt < stop && (c = h.charCodeAt(lt)) !== 60 && c !== 0) lt++
+ if (lt < stop && c === 60) {
+ cleanFrom = pos
+ clean = lt
+ } else {
+ clean = -1
+ lt = h.indexOf('<', lt)
+ }
if (lt < 0) break
- const c = h.charCodeAt(lt + 1)
+ c = h.charCodeAt(lt + 1)
if (alpha(c)) {
const to = readName(lt + 1)
const end = tagEnd(to)
@@ -2726,7 +2863,7 @@ const tokenize = () => {
after === 10 ||
after === 9 ||
after === 12) &&
- h.startsWith(open, lt + 2)
+ same(open, lt + 2)
) {
tag = open
tid = current.id
@@ -2737,8 +2874,10 @@ const tokenize = () => {
emitEnd()
pos = from = end
} else if (next === 62) {
- // > is nothing at all
+ // > is nothing at all: not even the end of a run of nuls either side of it
+ const join = lt > from ? h.charCodeAt(lt - 1) === 0 : nulJoin
dataText(from, lt)
+ nulJoin = join
pos = from = lt + 3
} else if (lt + 2 >= length) pos = length
else {
@@ -2827,12 +2966,25 @@ const readHead = (): Head => {
return head
}
+// the mains in the root's tree (under it, and in nothing dropped), in tree order
+const readMains = (root: El) => {
+ const found: El[] = []
+ for (const el of mains) {
+ let up: El | null = el
+ while (up && up !== root && !DROP[up.id]) up = up.up
+ if (up === root && el !== root) found.push(el)
+ }
+ if (!reordered || found.length < 2) return found
+ const places = new Map(found.map((el) => [el, position(el)]))
+ return found.toSorted((a, b) => treeOrder(places.get(a)!, places.get(b)!))
+}
+
export const parse = (input: string): Document => {
html = input.indexOf('\r') < 0 ? input : input.replace(/\r\n?/g, '\n')
n = html.length
tstate = DATA
rawTag = ''
- doc = make('#root', 0, HTML, '')
+ doc = make('#root', 0, HTML, '', 0)
stack = []
current = doc
pCount = 0
@@ -2850,7 +3002,8 @@ export const parse = (input: string): Document => {
pending = []
pendingText = false
watched = []
- pruned = []
+ mains = []
+ pruned.clear()
reordered = false
tok = 0
// found when first needed
@@ -2870,16 +3023,17 @@ export const parse = (input: string): Document => {
el.kids = kids
}
const root = bodyEl && !bodyGone ? bodyEl : doc
+ const document: Document = { root, head, mains: readMains(root) }
root.tag = '#root'
root.up = null
- const document: Document = { root, head }
// let the page go: the tree holds slices of it, not the parse's state
html = tag = tattrs = ttext = ''
NAME_CACHE.fill('')
stack = []
afe = []
watched = []
- pruned = []
+ mains = []
+ pruned.clear()
pending = []
current = doc = headEl = formEl = htmlEl = bodyEl = null as unknown as El
return document
diff --git a/packages/md-core/src/types.ts b/packages/md-core/src/types.ts
index ae183a0..4df746c 100644
--- a/packages/md-core/src/types.ts
+++ b/packages/md-core/src/types.ts
@@ -7,15 +7,43 @@ export type Node = Element | string
export interface Element {
// lowercase tag name; the root is '#root'
tag: string
- // the tag's attributes exactly as written, from after the tag name to before the closing '>' ('' when none). read
- // them with attr(), which parses on first use: most elements' attributes are never read
+ // the tag's attributes as written, from after the tag name to before the closing '>' ('' when none), in any syntax
+ // html allows (unquoted, single-quoted, any case, repeated names); re-serialised only where the parser had to merge
+ // or rename them. never scan it by hand: read values with attr(), which parses on first use, and presence with flags
attrs: string
+ // which of the attributes in FLAG the tag has, whatever their values: one bit each, set by the parser as it reads
+ // the tag, so asking "could this be hidden?" of every element never touches its source
+ flags: number
kids: Node[]
up: Element | null
// attr()'s cache
map?: Map | undefined
}
+// the attributes an element's flags record, by name (ascii case-insensitive, as html matches them)
+export const FLAG = {
+ hidden: 1 << 0,
+ 'aria-hidden': 1 << 1,
+ style: 1 << 2,
+ role: 1 << 3,
+ contenteditable: 1 << 4,
+ 'data-affordances-md': 1 << 5,
+ 'data-mode': 1 << 6,
+ 'data-mdast': 1 << 7,
+ 'data-title': 1 << 8,
+ title: 1 << 9,
+ nowrap: 1 << 10,
+ rowspan: 1 << 11,
+ colspan: 1 << 12,
+ align: 1 << 13,
+ class: 1 << 14,
+ id: 1 << 15,
+ 'aria-label': 1 << 16,
+ 'aria-labelledby': 1 << 17,
+ 'data-language': 1 << 18,
+} as const
+export const flagOf = (name: string): number => (FLAG as Record)[name] ?? 0
+
// what the page's says, read during the one scan; the head's elements are not in the tree
export interface Head {
// the first in the head, else the first anywhere outside an ; trimmed
@@ -35,6 +63,9 @@ export interface Document {
// children are the 's children (or, without a body, the page's own)
root: Element
head: Head
+ // every and every element whose role attribute is exactly 'main', in tree order, wherever it is in the
+ // root's tree (hidden or not: the emitter decides which one counts)
+ mains: Element[]
}
// what the parser never builds, with everything inside: never content, whatever the page says. the same set as
diff --git a/packages/md-core/test/emit-phases.ts b/packages/md-core/test/emit-phases.ts
index 61854d4..65dc861 100644
--- a/packages/md-core/test/emit-phases.ts
+++ b/packages/md-core/test/emit-phases.ts
@@ -20,7 +20,7 @@ for (let run = 0; run < runs; run++) {
let at = performance.now()
begin(false)
setPage(doc.root)
- const main = findMain(doc.root)
+ const main = findMain(doc.mains)
if (!main) begin(true)
totals.main += performance.now() - at
at = performance.now()
diff --git a/packages/md-core/test/emit.test.ts b/packages/md-core/test/emit.test.ts
index e7852f6..0f1693e 100644
--- a/packages/md-core/test/emit.test.ts
+++ b/packages/md-core/test/emit.test.ts
@@ -1,8 +1,10 @@
import { htmlToMarkdown } from '@affordances/md'
import { describe, expect, test } from 'vitest'
import { emit } from '../src/emit.ts'
+import { regexSafe, scannedSafe } from '../src/emit-markdown.ts'
import type { Options, Result } from '../src/types.ts'
import { corpusPages, fixturePages, type Page, similarity } from './emit-pages.ts'
+import { parse } from '../src/parse.ts'
import { oracle } from './support/oracle.ts'
// emit's result for a page, and @affordances/md's for the same page: the target is the same bytes (and title, url
@@ -20,189 +22,220 @@ const ours = (html: string, options: Options = {}) =>
const theirs = (html: string, options: Options = {}) =>
result(htmlToMarkdown(document(html), { url, ...options }))
+// every case above, for the parser's tree below
+const collected: string[] = []
+const collect = (pages: string[]) => {
+ collected.push(...pages)
+ return pages
+}
+
describe('blocks', () => {
- test.each([
- 'Title Two Three Six ',
- 'one
two
three
',
- 'a b c d e f ',
- '
x
',
- 'quoted
nested
',
- 'loose text ',
- '',
- '',
- 'E = mc2 and H2 O
x1 y
',
- 'a quoted b em
',
- 'longword
',
- 'old font big ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'Title Two Three Six ',
+ 'one
two
three
',
+ 'a b c d e f ',
+ '
x
',
+ 'quoted
nested
',
+ 'loose text ',
+ '',
+ '',
+ 'E = mc2 and H2 O
x1 y
',
+ 'a quoted b em
',
+ 'longword
',
+ 'old font big ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('lists', () => {
- test.each([
- '',
- 'one two three z ',
- 'a ten eleven ',
- '',
- '',
- '',
- '',
- '',
- 'lead
third ',
- '',
- '',
- '',
- ' ',
- 'stray term stray definition ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ '',
+ 'one two three z ',
+ 'a ten eleven ',
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'lead
third ',
+ '',
+ '',
+ '',
+ ' ',
+ 'stray term stray definition ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('inline', () => {
- test.each([
- 'Orders ship in two to three days , free x flat.
',
- 'foobar baz a b spaced
',
- '* ** _ both both
',
- 'ab c abc x y z
',
- 'am u i s Ctrl out v t
',
- 'code with `ticks` and ``double`` and spaced and a|b
',
- 'a b c
line after
',
- 'ab noon c d s
',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'Orders ship in two to three days , free x flat.
',
+ 'foobar baz a b spaced
',
+ '* ** _ both both
',
+ 'ab c abc x y z
',
+ 'am u i s Ctrl out v t
',
+ 'code with `ticks` and ``double`` and spaced and a|b
',
+ 'a b c
line after
',
+ 'ab noon c d s
',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('escapes', () => {
- test.each([
- '*star* _under_ snake_case_name __dunder__ 2*3*4
',
- '[brackets] and ![bang] and (parens) and a](b
',
- '1. not a list
2) nor this
- dash
+ plus
* star
# hash
> quote
',
- '= equals
~ tilde ~~strike~~
| pipe | x
`tick
<div> and <3
',
- '& © & A & B
',
- 'back\\slash \\* \\_ and a\\
',
- 'www.example.com and https://example.com and me@example.com
',
- 'www.example.com https://example.com me@example.com ',
- 'Ends with # # starts ',
- 'tab\there
lead and trail
',
- 'emoji 😀 and ünïcödé and 中文
',
- '100% sure: 3 < 4 > 2, a_b_c, *a*b
',
- 'text link ! and ![img
',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ '*star* _under_ snake_case_name __dunder__ 2*3*4
',
+ '[brackets] and ![bang] and (parens) and a](b
',
+ '1. not a list
2) nor this
- dash
+ plus
* star
# hash
> quote
',
+ '= equals
~ tilde ~~strike~~
| pipe | x
`tick
<div> and <3
',
+ '& © & A & B
',
+ 'back\\slash \\* \\_ and a\\
',
+ 'www.example.com and https://example.com and me@example.com
',
+ 'www.example.com https://example.com me@example.com ',
+ 'Ends with # # starts ',
+ 'tab\there
lead and trail
',
+ 'emoji 😀 and ünïcödé and 中文
',
+ '100% sure: 3 < 4 > 2, a_b_c, *a*b
',
+ 'text link ! and ![img
',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('links and images', () => {
- test.each([
- 'relative up query frag
',
- 'https://example.com me@x.test
',
- 'space paren p2
',
- 'titled js top none
',
- 'call ftp proto upper
',
- '',
- '
',
- ' x x y
',
- '',
- '
',
- '
',
- '[x]: y
',
- 'tilde port dots
',
- 'hash bare q ip
',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'relative up query frag
',
+ 'https://example.com me@x.test
',
+ 'space paren p2
',
+ 'titled js top none
',
+ 'call ftp proto upper
',
+ '',
+ '
',
+ ' x x y
',
+ '',
+ '
',
+ '
',
+ '[x]: y
',
+ 'tilde port dots
',
+ 'hash bare q ip
',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('code', () => {
- test.each([
- 'const a = 1\n ',
- 'no language\n\n\n ',
- 'print(1)puts 1 ',
- 'a ``` b ',
- 'line one
line two
',
- 'a b indented \nnext ',
- 'route.ts x ',
- 'xafter ',
- '',
- 'z ',
- 'old\n code raw x ',
- 'two classes ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'const a = 1\n ',
+ 'no language\n\n\n ',
+ 'print(1)puts 1 ',
+ 'a ``` b ',
+ 'line one
line two
',
+ 'a b indented \nnext ',
+ 'route.ts x ',
+ 'xafter ',
+ '',
+ 'z ',
+ 'old\n code raw x ',
+ 'two classes ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('tables', () => {
- test.each([
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- 'after skeleton
',
- '',
- '',
- '',
- '',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'after skeleton
',
+ '',
+ '',
+ '',
+ '',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('details and definitions', () => {
- test.each([
- 'Returns Within 30 days.
',
- 'no summary
bold sum text ',
- 'Carrier Post Insured Yes ',
- 'A B both
C wrapped
',
- 'T para
tailno term ',
- 'empty term ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'Returns Within 30 days.
',
+ 'no summary
bold sum text ',
+ 'Carrier Post Insured Yes ',
+ 'A B both
C wrapped ',
+ 'T para
tailno term ',
+ 'empty term ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('whitespace', () => {
- test.each([
- ' many spaces\n\nand\tlines
',
- 'a b c
x y
',
- '',
- 'nbsp kept
',
- 'before after
x y
',
- 'un believ able
',
- 'ab c o d
',
- 'stray cell no wrap ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ ' many spaces\n\nand\tlines
',
+ 'a b c
x y
',
+ '',
+ 'nbsp kept
',
+ 'before after
x y
',
+ 'un believ able
',
+ 'ab c o d
',
+ 'stray cell no wrap ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('spacing', () => {
- test.each([
- 'express 5.3.0 $ 48
',
- 'a b c d
',
- 'configurevlt
xy
',
- 'yarn (zpm) 6.0.0 5/6 fixtures
',
- 'H e l l o
',
- ' x
',
- 'no space a b
',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'express 5.3.0 $ 48
',
+ 'a b c d
',
+ 'configurevlt
xy
',
+ 'yarn (zpm) 6.0.0 5/6 fixtures
',
+ 'H e l l o
',
+ ' x
',
+ 'no space a b
',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('hidden', () => {
- test.each([
- 'shown
hidden
aria
kept
',
- 'none
vis
cv
kept
',
- 'caps
comment
escape
',
- 'collapse
red kept
',
- 'typed
kept
box
',
- 'a
skipped
shown for agents
',
- 'xgone y
',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'shown
hidden
aria
kept
',
+ 'none
vis
cv
kept
',
+ 'caps
comment
escape
',
+ 'collapse
red kept
',
+ 'typed
kept
box
',
+ 'a
skipped
shown for agents
',
+ 'xgone y
',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
describe('extract', () => {
- test.each([
- 'Main content
',
- 'nav ',
- 'real main wins
',
- 'first
second
',
- 'body
',
- 'nav role
body only
',
- 'x
c
',
- 'just text, no blocks at all ',
- ])('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
+ test.each(
+ collect([
+ 'Main content
',
+ 'nav ',
+ 'real main wins
',
+ 'first
second
',
+ 'body
',
+ 'nav role
body only
',
+ 'x
c
',
+ 'just text, no blocks at all ',
+ ]),
+ )('%s', (html) => expect(ours(html)).toEqual(theirs(html)))
})
const whole = (head: string, body: string) =>
@@ -311,3 +344,141 @@ describe.skipIf(!corpus.length)('corpus parity', () => {
expect(written).toBe(reference)
})
})
+
+// the parser's tree must make the same markdown as the oracle's, whatever syntax the attributes are written in: the
+// oracle always writes name="value", pages don't. each case again with its attributes uppercase, single-quoted,
+// unquoted where they can be, spaced out, and repeated (the first one counts)
+const ATTRIBUTE = /([\s])([a-z][a-z-]*)="([^"]*)"/g
+const variants = (html: string) => [
+ html.replace(ATTRIBUTE, (_, space, name, value) => `${space}${name.toUpperCase()}="${value}"`),
+ html.replace(ATTRIBUTE, (_, space, name, value) =>
+ value.includes("'") ? `${space}${name}="${value}"` : `${space}${name}='${value}'`,
+ ),
+ html.replace(ATTRIBUTE, (_, space, name, value) =>
+ /^[^\s"'=<>`]+$/.test(value) ? `${space}${name}=${value}` : `${space}${name}="${value}"`,
+ ),
+ html.replace(ATTRIBUTE, (_, space, name, value) => `${space} ${name} =\t"${value}" `),
+ html.replace(ATTRIBUTE, (_, space, name, value) => `${space}${name}="${value}" ${name}="x"`),
+]
+// whether the parser gives the contract's flags and mains yet (it's being written alongside)
+const parsed = parse(' ')
+const ready =
+ parsed.mains !== undefined &&
+ parsed.root.kids.some((kid) => typeof kid !== 'string' && kid.flags === 1)
+const viaParser = (html: string) => emit(parse(document(html)), { url }).markdown
+const viaOracle = (html: string) => emit(oracle(document(html)), { url }).markdown
+describe.skipIf(!ready)("the parser's tree", () => {
+ test.each(collected.flatMap(variants))('%s', (html) =>
+ expect(viaParser(html)).toBe(viaOracle(html)),
+ )
+ test.each(corpus.map((page) => [page.name, page] as const))('%s', (_, page) =>
+ expect(emit(parse(page.html), { url: page.url }).markdown).toBe(
+ emit(oracle(page.html), { url: page.url }).markdown,
+ ),
+ )
+})
+
+// escaping by one scan over the text must say what the regexes say, in every construct it's used in
+describe('escaping by scan', () => {
+ const SCOPES = [
+ ['phrasing'],
+ ['phrasing', 'label', 'link'],
+ ['phrasing', 'tableCell'],
+ ['phrasing', 'strikethrough', 'emphasis'],
+ ['phrasing', 'link', 'destinationRaw'],
+ ['phrasing', 'link', 'destinationLiteral'],
+ ['phrasing', 'link', 'titleQuote'],
+ ['phrasing', 'image', 'label'],
+ ['codeFencedLangGraveAccent'],
+ ['codeFencedMetaGraveAccent'],
+ ['phrasing', 'tableCell', 'link', 'label'],
+ ]
+ const ALPHABET = [
+ 'a',
+ 'b',
+ '1',
+ ' ',
+ '\t',
+ '_',
+ '*',
+ '[',
+ ']',
+ '(',
+ ')',
+ '!',
+ '&',
+ '#',
+ '<',
+ '>',
+ '`',
+ ]
+ const MORE = [
+ '~',
+ '|',
+ '\\',
+ '-',
+ '+',
+ '.',
+ '=',
+ ':',
+ '@',
+ '"',
+ "'",
+ '/',
+ '?',
+ 'é',
+ '😀',
+ 'w',
+ 'p',
+ 's',
+ ]
+ const EDGES = [
+ '',
+ '\n',
+ '[',
+ ']',
+ '_',
+ '*',
+ '**',
+ '](',
+ '|',
+ ' ',
+ 'a',
+ '!',
+ '&',
+ '<',
+ '~',
+ '\\',
+ '(',
+ ]
+ // a fixed sequence of pseudo-random strings, so a failure repeats
+ let seed = 7
+ const random = (n: number) => {
+ seed = (seed * 1103515245 + 12345) % 2147483648
+ return seed % n
+ }
+ const chars = [...ALPHABET, ...MORE]
+ test('random texts, every scope and edge', () => {
+ let checked = 0
+ for (let round = 0; round < 20000; round++) {
+ const scope = SCOPES[random(SCOPES.length)]!
+ const length = 1 + random(8)
+ let input = ''
+ for (let i = 0; i < length; i++) input += chars[random(chars.length)]
+ const before = EDGES[random(EDGES.length)]!
+ const after = EDGES[random(EDGES.length)]!
+ const encode = scope[0]!.startsWith('codeFenced') ? '`' : ''
+ const scanned = scannedSafe(scope, input, before, after, encode)
+ if (scanned === undefined) continue
+ checked++
+ expect([scope, input, before, after, scanned]).toEqual([
+ scope,
+ input,
+ before,
+ after,
+ regexSafe(scope, input, before, after, encode),
+ ])
+ }
+ expect(checked).toBeGreaterThan(10000)
+ })
+})
diff --git a/packages/md-core/test/parse-fuzz.ts b/packages/md-core/test/parse-fuzz.ts
index ce5c46d..ee2d0a2 100644
--- a/packages/md-core/test/parse-fuzz.ts
+++ b/packages/md-core/test/parse-fuzz.ts
@@ -31,7 +31,7 @@ const TAGS = (
'foreignObject path g html head body br img hr wbr image keygen object applet marquee canvas video audio source ' +
'meta link base rt rp rb rtc ruby section article header footer nav main aside blockquote figure figcaption ' +
'details summary dialog address center fieldset menu dir search hgroup frameset frame param track embed area ' +
- 'sub sup var my-element x'
+ 'sub sup var my-element x main'
).split(' ')
const RARE_TAGS = ['plaintext']
const ATTRS = [
@@ -54,6 +54,28 @@ const ATTRS = [
'title',
'data-x',
'CLASS',
+ 'hidden',
+ 'HIDDEN',
+ 'aria-hidden',
+ 'Aria-Hidden',
+ 'style',
+ 'role',
+ 'ROLE',
+ 'contenteditable',
+ 'data-affordances-md',
+ 'data-mode',
+ 'data-mdast',
+ 'data-title',
+ 'nowrap',
+ 'rowspan',
+ 'colspan',
+ 'align',
+ 'aria-label',
+ 'aria-labelledby',
+ 'data-language',
+ 'xlink:title',
+ 'hiddenx',
+ 'rol',
]
const VALUES = [
'x',
@@ -80,6 +102,10 @@ const VALUES = [
'red',
'en',
'og:title',
+ 'main',
+ 'Main',
+ 'main ',
+ 'main',
]
const WORDS = [
'a',
@@ -172,7 +198,7 @@ const RAW_BITS = [
// what gets fostered out of them, select, and foreign content with its integration points and breakouts
const DENSE = (
'a b i nobr font p div li dd table caption tr td th tbody colgroup col select option optgroup svg math mi ' +
- 'annotation-xml desc foreignObject title template button form h1 pre textarea script style noscript object br'
+ 'annotation-xml desc foreignObject title template button form h1 pre textarea script style noscript object br main'
).split(' ')
export const generate = (seed: number) => {
diff --git a/packages/md-core/test/parse.test.ts b/packages/md-core/test/parse.test.ts
index 31b2e27..8317579 100644
--- a/packages/md-core/test/parse.test.ts
+++ b/packages/md-core/test/parse.test.ts
@@ -28,6 +28,8 @@ describe('text and character references', () => {
'<3',
'a\r\nb\rc\n',
'a\0b\0\0c',
+ '\0>\0>\0 >\0 ',
+ '\0>\0x',
'\0',
'tab\there',
])('%j', (html) => expect(difference(html)).toBeUndefined())
@@ -401,6 +403,27 @@ describe('foreign content: math', () => {
])('%j', (html) => expect(difference(html)).toBeUndefined())
})
+describe('flags and mains', () => {
+ test.each([
+ 'x
',
+ 'x
y',
+ 'x
',
+ 'x
',
+ 'x
',
+ 'x
',
+ '
xy
z
',
+ 'x ',
+ 'x',
+ 'a b
c
d
',
+ 'x
nested ',
+ 'a bc',
+ '
',
+ 'in svg n after',
+ 't h',
+ 'math main ',
+ ])('%j', (html) => expect(difference(html)).toBeUndefined())
+})
+
describe('the head', () => {
test.each([
' spaced ',
diff --git a/packages/md-core/test/support/oracle.ts b/packages/md-core/test/support/oracle.ts
index 4130a50..56e2153 100644
--- a/packages/md-core/test/support/oracle.ts
+++ b/packages/md-core/test/support/oracle.ts
@@ -1,5 +1,12 @@
import { parse } from 'parse5'
-import { NEVER, type Document, type Element, type Head, type Node } from '../../src/types.ts'
+import {
+ flagOf,
+ NEVER,
+ type Document,
+ type Element,
+ type Head,
+ type Node,
+} from '../../src/types.ts'
// the Document parse.ts must build, made the slow way: parse5 reads the page as a browser does, and this walks its
// tree into the contract's shape. the parser is tested against it, and the emitter can be written against it before
@@ -56,8 +63,11 @@ export const oracle = (html: string): Document => {
}
scan(document, false, false)
head.title = (headTitle ?? anyTitle)?.trim() || undefined
+ const mains: Element[] = []
const build = (from: P5, up: Element | null, tag: string): Element => {
- const el: Element = { tag, attrs: source(from.attrs), kids: [], up }
+ const flags = (from.attrs ?? []).reduce((bits, { name }) => bits | flagOf(name), 0)
+ const el: Element = { tag, attrs: source(from.attrs), flags, kids: [], up }
+ if (up && (tag === 'main' || get(from, 'role') === 'main')) mains.push(el)
for (const child of from.childNodes ?? []) {
let kid: Node | undefined
if (child.nodeName === '#text') kid = child.value ?? ''
@@ -71,15 +81,20 @@ export const oracle = (html: string): Document => {
}
return el
}
- return { root: build(body ?? document, null, '#root'), head }
+ return { root: build(body ?? document, null, '#root'), head, mains }
}
// a Document as plain data, for comparing two of them: attributes parsed, parents left out
export const plain = (doc: Document, attrs: (el: Element) => Record) => {
const node = (n: Node): unknown =>
- typeof n === 'string' ? n : { tag: n.tag, attrs: attrs(n), kids: n.kids.map(node) }
+ typeof n === 'string'
+ ? n
+ : { tag: n.tag, attrs: attrs(n), flags: n.flags, kids: n.kids.map(node) }
+ const path = (el: Element): number[] => (el.up ? [...path(el.up), el.up.kids.indexOf(el)] : [])
return {
root: node(doc.root),
+ // each main by where it is in the tree
+ mains: doc.mains.map(path),
head: { ...doc.head, meta: Object.fromEntries(doc.head.meta) },
}
}
From 443969bccfe48132962b8c2d91861107a6f2d757 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Thu, 12 Nov 2026 04:42:10 +0000
Subject: [PATCH 04/74] perf(md-core): prune in place, scan single attribute
reads, time emit on fresh trees
- emit owns the Document it is given and prunes it in place: the per-emit
side tables and copied child lists are gone, and the separate tidy pass
is folded into first use.
- attr() reads the first two attributes asked of an element straight from
the tag's source and builds a map only on the third.
- The parser gives every element the emitter's fields from the start, so
elements keep one shape.
- The benchmark gives each timed emit a freshly parsed tree; it used to
re-emit one tree with warm caches, which read about 25% low.
- Fix: a later in a frameset document is now a main.
120 ms for the 10-page corpus against mdream's 37 ms; parity unchanged.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_018hJ9SEkCX16tDcRNj1QfjV
---
packages/md-core/bench/run.ts | 10 +-
packages/md-core/src/attr.ts | 63 ++++++++-
packages/md-core/src/emit-convert.ts | 190 +++++++++++---------------
packages/md-core/src/emit-markdown.ts | 71 +++++++++-
packages/md-core/src/emit-prune.ts | 63 ++++-----
packages/md-core/src/entities.ts | 20 ++-
packages/md-core/src/parse.ts | 14 +-
packages/md-core/src/types.ts | 5 +
packages/md-core/test/emit-fresh.ts | 25 ++++
packages/md-core/test/parse.test.ts | 56 ++++++++
10 files changed, 361 insertions(+), 156 deletions(-)
create mode 100644 packages/md-core/test/emit-fresh.ts
diff --git a/packages/md-core/bench/run.ts b/packages/md-core/bench/run.ts
index 8fc46b2..37a9538 100644
--- a/packages/md-core/bench/run.ts
+++ b/packages/md-core/bench/run.ts
@@ -80,13 +80,15 @@ const emit =
: undefined
if (parse) add({ name: 'md-core parse', setup: (html) => () => parse(html) })
if (parse && emit) {
- // the tree is parsed once, outside the clock. emit runs on the same tree each time, so anything it caches on the
- // tree (attr maps) is warm after the first run
+ // emit owns the tree it's given and may change it, so every call gets a tree of its own, parsed outside the clock.
+ // a pool rather than one per call, to bound memory; a call past the pool parses on the clock, which shows as an
+ // outlier the median ignores
+ const POOL = 40
add({
name: 'md-core emit',
setup: (html) => {
- const doc = parse(html)
- return () => emit(doc, { url })
+ const docs = Array.from({ length: POOL }, () => parse(html))
+ return () => emit(docs.pop() ?? parse(html), { url })
},
})
}
diff --git a/packages/md-core/src/attr.ts b/packages/md-core/src/attr.ts
index b5a44f9..ce3d4ab 100644
--- a/packages/md-core/src/attr.ts
+++ b/packages/md-core/src/attr.ts
@@ -2,9 +2,20 @@ import { decode } from './entities.ts'
import type { Element } from './types.ts'
// an element's attribute by lowercase name: its decoded value, '' for one without a value, undefined when absent.
-// the first of a repeated name wins, as in html. parsed from the tag's source on first use
-export const attr = (el: Element, name: string): string | undefined =>
- el.attrs === '' ? undefined : (el.map ??= parseAttrs(el.attrs)).get(name)
+// the first of a repeated name wins, as in html. the first two questions each read just that name out of the tag's
+// source (a link's href and title, a span's style); an element asked a third time straight after gets its map built
+export const attr = (el: Element, name: string): string | undefined => {
+ if (el.map) return el.map.get(name)
+ if (el.attrs === '') return undefined
+ if (el !== last) {
+ last = el
+ asked = 0
+ } else if (++asked > 1) return (el.map = parseAttrs(el.attrs)).get(name)
+ return scanAttr(el.attrs, name)
+}
+// the element the last questions without a map were about, and how many more there were after the first
+let last: Element | undefined
+let asked = 0
export const hasAttrs = (el: Element) => el.attrs !== ''
@@ -60,3 +71,49 @@ export const parseAttrs = (source: string): Map => {
}
return map
}
+
+// one attribute out of a start tag's source, read by the same states as parseAttrs, with no map: the value of the
+// first attribute whose name is `name` (ascii lowered, a nul read as U+FFFD), decoded, or undefined
+export const scanAttr = (source: string, name: string): string | undefined => {
+ const n = source.length
+ const size = name.length
+ let i = 0
+ while (i < n) {
+ let c = source.charCodeAt(i)
+ if (space(c) || c === 47) {
+ i++
+ continue
+ }
+ // a name runs to whitespace, '/' or '='; an '=' first is part of it
+ const start = i++
+ while (i < n && !space((c = source.charCodeAt(i))) && c !== 47 && c !== 61) i++
+ let match = i - start === size
+ for (let k = 0; match && k < size; k++) {
+ const d = source.charCodeAt(start + k)
+ match = (d >= 65 && d <= 90 ? d | 32 : d === 0 ? 0xfffd : d) === name.charCodeAt(k)
+ }
+ while (i < n && space(source.charCodeAt(i))) i++
+ let from = i
+ let to = i
+ if (source.charCodeAt(i) === 61) {
+ i++
+ while (i < n && space(source.charCodeAt(i))) i++
+ const quote = source.charCodeAt(i)
+ if (quote === 34 || quote === 39) {
+ const end = source.indexOf(quote === 34 ? '"' : "'", i + 1)
+ from = i + 1
+ to = end < 0 ? n : end
+ i = end < 0 ? n : end + 1
+ } else {
+ from = i
+ while (i < n && !space(source.charCodeAt(i))) i++
+ to = i
+ }
+ }
+ if (!match) continue
+ let value = source.slice(from, to)
+ if (value.indexOf('\0') >= 0) value = value.replaceAll('\0', '\uFFFD')
+ return decode(value, true)
+ }
+ return undefined
+}
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts
index 4e1c22d..c0c8a3a 100644
--- a/packages/md-core/src/emit-convert.ts
+++ b/packages/md-core/src/emit-convert.ts
@@ -200,7 +200,7 @@ const pushOne = (out: Md[], result: Md) => {
} else out.push(result)
}
const push = (out: Md[], results: Md[]) => {
- for (const result of results) pushOne(out, result)
+ for (let i = 0; i < results.length; i++) pushOne(out, results[i]!)
}
// an element's children, converted, appended to out
@@ -490,18 +490,23 @@ const split = (parent: Md): Md[] =>
const runs = (nodes: Md[], onPhrasing: (run: Md[]) => Md[], onOther: (item: Md) => Md): Md[] => {
const flat = flatten(nodes)
const result: Md[] = []
- let queue: Md[] = []
- for (const item of flat) {
- if (isPhrasing(item)) queue.push(item)
- else {
- if (queue.length) {
- result.push(...onPhrasing(queue))
- queue = []
- }
+ // a run of phrasing is a slice of what's given, from start to the block after it
+ let start = -1
+ const close = (end: number) => {
+ const made = onPhrasing(start === 0 && end === flat.length ? flat : flat.slice(start, end))
+ for (let k = 0; k < made.length; k++) result.push(made[k]!)
+ start = -1
+ }
+ for (let i = 0; i < flat.length; i++) {
+ const item = flat[i]!
+ if (isPhrasing(item)) {
+ if (start < 0) start = i
+ } else {
+ if (start >= 0) close(i)
result.push(onOther(item))
}
}
- if (queue.length) result.push(...onPhrasing(queue))
+ if (start >= 0) close(flat.length)
return result
}
const whitespaceOnly = (value: string) => /^[ \t\n\f\r]*$/.test(value)
@@ -969,12 +974,6 @@ const TABLE_PARTS = new Set([
'tr',
])
const ROW_GROUPS = new Set(['tbody', 'tfoot', 'thead'])
-type Info = {
- breakBefore: boolean | number | string | undefined
- breakAfter: boolean | number | string | undefined
- rowAfter: boolean | undefined
- normal: boolean
-}
type Piece = string | number
const isBr = (kid: Node | undefined) =>
kid !== undefined && typeof kid !== 'string' && kid.tag === 'br'
@@ -990,37 +989,55 @@ const afterIn = (kids: Node[], index: number, test: (kid: Node) => boolean) => {
const inTableTag = (tag: string) => tag === 'table' || ROW_GROUPS.has(tag)
export const toText = (el: Element): string => {
+ // the pieces are joined as they come (hast-util-to-text joins them after): what's joined so far, and the most line
+ // endings asked for since the last text (-1: none yet since one; undefined: no text yet)
+ const savedJoined = joined
+ const savedCount = count
+ joined = ''
+ count = undefined
const block = BLOCK_OR_CAPTION.has(el.tag)
- const tableish = inTableTag(el.tag)
const normal = whitespaceOf(el, NORMAL) === NORMAL
const kids = kidsOf(el)
- const results: Piece[] = []
+ const isTable = el.tag === 'table'
for (let i = 0; i < kids.length; i++) {
const next = kids[i + 1]
- collect(kids, i, el, results, {
- breakAfter: next ? isBr(next) : block,
- breakBefore: i ? undefined : block,
- rowAfter: tableish && el.tag === 'table' ? afterIn(kids, i, rowOrGroupWithRow) : undefined,
+ collect(
+ kids,
+ i,
+ el,
+ i ? undefined : block,
+ next ? isBr(next) : block,
+ isTable ? afterIn(kids, i, rowOrGroupWithRow) : undefined,
normal,
- })
+ )
}
- return joinPieces(results)
+ const result = joined
+ joined = savedJoined
+ count = savedCount
+ return result
}
-const joinPieces = (results: Piece[]) => {
- let result = ''
- let count: number | undefined
- for (const value of results) {
- if (typeof value === 'number') {
- if (count !== undefined && value > count) count = value
- } else if (value) {
- if (count !== undefined && count > -1) result += '\n'.repeat(count) || ' '
- count = -1
- result += value
- }
+let joined = ''
+let count: number | undefined
+// one piece of the text: a number asks for that many line endings before the next text
+const piece = (value: Piece) => {
+ if (typeof value === 'number') {
+ if (count !== undefined && value > count) count = value
+ } else if (value) {
+ if (count !== undefined && count > -1) joined += '\n'.repeat(count) || ' '
+ count = -1
+ joined += value
}
- return result
}
-const collect = (kids: Node[], index: number, parent: Element, out: Piece[], info: Info) => {
+type Break = boolean | number | string | undefined
+const collect = (
+ kids: Node[],
+ index: number,
+ parent: Element,
+ breakBefore: Break,
+ breakAfter: Break,
+ rowAfter: boolean | undefined,
+ normal: boolean,
+) => {
const kid = kids[index]!
if (typeof kid === 'string') {
// preformatted text is as written, and what's beside it doesn't matter
@@ -1038,27 +1055,26 @@ const collect = (kids: Node[], index: number, parent: Element, out: Piece[], inf
)
return
}
- if (info.normal) collectText(value, info, out)
- else out.push(value)
+ if (normal) collectText(value, breakBefore, breakAfter)
+ else piece(value)
return
}
if (mode === PRE) {
- collectElement(kid, index, kids, parent, info, out)
+ collectElement(kid, index, kids, rowAfter, normal)
return
}
const saved = enterElement(kid, kids, index)
- collectElement(kid, index, kids, parent, info, out)
+ collectElement(kid, index, kids, rowAfter, normal)
exitElement(kid, saved)
}
const collectElement = (
el: Element,
position: number,
siblings: Node[],
- _parent: Element,
- info: Info,
- out: Piece[],
+ rowAfter: boolean | undefined,
+ inherited: boolean,
) => {
- const normal = info.normal && whitespaceOf(el, NORMAL) === NORMAL
+ const normal = inherited && whitespaceOf(el, NORMAL) === NORMAL
if (NOT_RENDERED.has(el.tag) || (el.tag === 'dialog' && attr(el, 'open') === undefined)) {
walkOnly(el)
return
@@ -1066,7 +1082,7 @@ const collectElement = (
let prefix: number | undefined
let suffix: number | string | undefined
if (el.tag === 'br') suffix = '\n'
- else if (el.tag === 'tr' && (info.rowAfter || afterIn(siblings, position, isRow))) suffix = '\n'
+ else if (el.tag === 'tr' && (rowAfter || afterIn(siblings, position, isRow))) suffix = '\n'
else if (el.tag === 'p') {
prefix = 2
suffix = 2
@@ -1074,29 +1090,27 @@ const collectElement = (
prefix = 1
suffix = 1
}
+ if (prefix) piece(prefix)
const kids = kidsOf(el)
const tableish = inTableTag(el.tag)
- const items: Piece[] = []
+ const isTable = el.tag === 'table'
for (let i = 0; i < kids.length; i++) {
const next = kids[i + 1]
- collect(kids, i, el, items, {
- breakAfter: next ? isBr(next) : suffix,
- breakBefore: i ? undefined : prefix,
- rowAfter: tableish
- ? el.tag === 'table'
- ? afterIn(kids, i, rowOrGroupWithRow)
- : info.rowAfter
- : undefined,
+ collect(
+ kids,
+ i,
+ el,
+ i ? undefined : prefix,
+ next ? isBr(next) : suffix,
+ tableish ? (isTable ? afterIn(kids, i, rowOrGroupWithRow) : rowAfter) : undefined,
normal,
- })
+ )
}
- if (isCell(el) && afterIn(siblings, position, isCell)) items.push('\t')
- if (prefix) out.push(prefix)
- out.push(...items)
- if (suffix) out.push(suffix)
+ if (isCell(el) && afterIn(siblings, position, isCell)) piece('\t')
+ if (suffix) piece(suffix)
}
const BIDI = /[--]/g
-const collectText = (value: string, info: Info, out: Piece[]) => {
+const collectText = (value: string, breakBefore: Break, breakAfter: Break) => {
const lines: string[] = []
let start = 0
while (start <= value.length) {
@@ -1105,8 +1119,8 @@ const collectText = (value: string, info: Info, out: Piece[]) => {
lines.push(
trimAndCollapse(
value.slice(start, end).replace(BIDI, ''),
- start === 0 ? info.breakBefore : true,
- end === value.length ? info.breakAfter : true,
+ start === 0 ? breakBefore : true,
+ end === value.length ? breakAfter : true,
),
)
start = end + 1
@@ -1118,13 +1132,13 @@ const collectText = (value: string, info: Info, out: Piece[]) => {
line.charCodeAt(line.length - 1) === 0x200b ||
(index < lines.length - 1 && lines[index + 1]!.charCodeAt(0) === 0x200b)
) {
- out.push(line)
+ piece(line)
join = undefined
} else if (line) {
- if (typeof join === 'number') out.push(join)
- out.push(line)
+ if (typeof join === 'number') piece(join)
+ piece(line)
join = 0
- } else if (index === 0 || index === lines.length - 1) out.push(0)
+ } else if (index === 0 || index === lines.length - 1) piece(0)
}
}
const trimAndCollapse = (value: string, breakBefore: unknown, breakAfter: unknown) => {
@@ -1149,45 +1163,5 @@ export const convertRoot = (root: Element): Md => {
before = true
after = true
mode = NORMAL
- const result = node(ROOT, rootKids(all(root)))
- tidy(result)
- return result
-}
-
-// what hast-util-to-mdast does last: adjacent texts as one, the line ending's spaces, a paragraph's (heading's,
-// root's) outer spaces, and empty texts gone
-const edgeSpace = (char: number) => char === 32 || char === 9
-
-const tidy = (parent: Md) => {
- const kids = parent.kids
- const type = parent.type
- const trims = type === PARAGRAPH || type === HEADING || type === ROOT
- for (let index = 0; index < kids.length; index++) {
- const item = kids[index]!
- if (item.type !== TEXT) {
- if (item.kids.length) tidy(item)
- continue
- }
- const previous = kids[index - 1]
- if (previous?.type === TEXT) {
- previous.value += item.value
- previous.depth |= item.depth
- kids.splice(index, 1)
- index -= 2
- continue
- }
- let value = item.value
- if (item.depth !== 0 && (value.includes('\n') || value.includes('\r')))
- value = value.replace(/[\t ]*(\r?\n|\r)[\t ]*/, '$1')
- if (trims) {
- if (index === 0 && edgeSpace(value.charCodeAt(0))) value = value.replace(/^[\t ]+/, '')
- if (index === kids.length - 1 && edgeSpace(value.charCodeAt(value.length - 1)))
- value = value.replace(/[\t ]+$/, '')
- }
- item.value = value
- if (!value) {
- kids.splice(index, 1)
- index--
- }
- }
+ return node(ROOT, rootKids(all(root)))
}
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
index 36a7440..a956377 100644
--- a/packages/md-core/src/emit-markdown.ts
+++ b/packages/md-core/src/emit-markdown.ts
@@ -47,6 +47,8 @@ export class Md {
align: (string | null)[] | null
rowSpan: number
colSpan: number
+ // its kids have been tidied (tidy below), which happens once, just before anything reads them
+ clean: boolean
constructor(type: number, kids: Md[] = LEAF[type] ? NO_KIDS : [], value = '') {
this.type = type
this.kids = kids
@@ -62,11 +64,54 @@ export class Md {
this.align = null
this.rowSpan = 0
this.colSpan = 0
+ this.clean = false
}
}
export const isPhrasing = (node: Md) => node.type >= TEXT
+// what hast-util-to-mdast does last, to each node's children: adjacent texts as one, the line ending's spaces, a
+// paragraph's (heading's, root's) outer spaces, and empty texts gone. it depends on nothing but the node's own
+// children, so it's done to each node when its children are first read, while they're at hand, not in a pass of its own
+const edgeSpace = (char: number) => char === 32 || char === 9
+export const tidy = (parent: Md): Md[] => {
+ const kids = parent.kids
+ if (parent.clean) return kids
+ parent.clean = true
+ const type = parent.type
+ const trims = type === PARAGRAPH || type === HEADING || type === ROOT
+ for (let index = 0; index < kids.length; index++) {
+ const item = kids[index]!
+ if (item.type !== TEXT) continue
+ const previous = kids[index - 1]
+ if (previous?.type === TEXT) {
+ previous.value += item.value
+ previous.depth |= item.depth
+ kids.splice(index, 1)
+ index -= 2
+ continue
+ }
+ let value = item.value
+ if (item.depth !== 0 && (value.includes('\n') || value.includes('\r')))
+ value = value.replace(/[\t ]*(\r?\n|\r)[\t ]*/, '$1')
+ if (trims) {
+ if (index === 0 && edgeSpace(value.charCodeAt(0))) value = value.replace(/^[\t ]+/, '')
+ if (index === kids.length - 1 && edgeSpace(value.charCodeAt(value.length - 1)))
+ value = value.replace(/[\t ]+$/, '')
+ }
+ item.value = value
+ if (!value) {
+ kids.splice(index, 1)
+ index--
+ }
+ }
+ return kids
+}
+// a node tidied all the way down, for what reads a whole subtree before it's written (a heading's setext test)
+const tidyDeep = (node: Md) => {
+ for (const kid of tidy(node)) if (kid.kids.length) tidyDeep(kid)
+}
+
// constructs, as bits
const PHRASING = 1
const HEADING_ATX = 2
@@ -314,9 +359,17 @@ type Scope = {
byChar: (Pattern[] | undefined)[] | undefined
}
const scopes = new Map()
+// the last scope asked for: text after text is usually in the same constructs
+let lastMask = -1
+let lastScope: Scope | undefined
const scopeOf = (mask: number): Scope => {
+ if (mask === lastMask) return lastScope!
let scope = scopes.get(mask)
- if (scope) return scope
+ if (scope) {
+ lastMask = mask
+ lastScope = scope
+ return scope
+ }
const patterns = PATTERNS.filter(
(pattern) => (pattern.in === -1 || (pattern.in & mask) !== 0) && (pattern.notIn & mask) === 0,
)
@@ -954,7 +1007,7 @@ const peek = (node: Md, parent: Md): string => {
}
const phrasing = (parent: Md, before: string, after: string): Item[] => {
- const kids = parent.kids
+ const kids = tidy(parent)
const results: Item[] = []
indexStack.push(-1)
for (let index = 0; index < kids.length; index++) {
@@ -989,7 +1042,7 @@ const containerPhrasing = (parent: Md, before: string, after: string) =>
serialize(phrasing(parent, before, after), before, after)
const containerFlow = (parent: Md): string => {
- const kids = parent.kids
+ const kids = tidy(parent)
let result = ''
indexStack.push(-1)
for (let index = 0; index < kids.length; index++) {
@@ -1016,7 +1069,7 @@ const between = (left: Md, right: Md, parent: Md) => {
left.type === PARAGRAPH &&
right.type === LIST &&
((right.ordered && right.depth !== 1) ||
- (right.kids.length > 0 && right.kids[0]!.kids.length === 0))
+ (tidy(right).length > 0 && tidy(right.kids[0]!).length === 0))
)
return '\n\n'
if (left.type === PARAGRAPH && right.type === THEMATIC_BREAK) return '\n\n'
@@ -1076,7 +1129,11 @@ const hasBreak = (node: Md): boolean => {
return false
}
// a heading written setext style: an h1 or h2 that holds a line break
-export const setext = (node: Md) => node.depth < 3 && toText(node) !== '' && hasBreak(node)
+export const setext = (node: Md) => {
+ if (node.depth >= 3) return false
+ tidyDeep(node)
+ return toText(node) !== '' && hasBreak(node)
+}
// a link written : its text is its url. worked out once, kept in its depth (1 no, 2 yes)
const autolinked = (node: Md) => {
@@ -1084,6 +1141,7 @@ const autolinked = (node: Md) => {
return node.depth === 2
}
const isAutolink = (node: Md) => {
+ tidy(node)
if (node.title || !node.url || node.kids.length !== 1 || node.kids[0]!.type !== TEXT) return false
const raw = node.kids[0]!.value
return (
@@ -1129,7 +1187,7 @@ const handle = (node: Md, parent: Md | undefined, before: string, after: string)
case HEADING:
return heading(node)
case ROOT: {
- if (!node.kids.some(isPhrasing)) return containerFlow(node)
+ if (!tidy(node).some(isPhrasing)) return containerFlow(node)
enter('phrasing')
const value = containerPhrasing(node, before, after)
exit()
@@ -1214,6 +1272,7 @@ const heading = (node: Md) => {
}
const list = (node: Md, parent: Md | undefined) => {
+ for (const item of tidy(node)) tidy(item)
enter('list')
const saved = bulletCurrent
let bullet = node.ordered ? '.' : '-'
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md-core/src/emit-prune.ts
index 00e7bb1..0a17aaa 100644
--- a/packages/md-core/src/emit-prune.ts
+++ b/packages/md-core/src/emit-prune.ts
@@ -5,16 +5,11 @@ import { FLAG, type Element, type Node } from './types.ts'
// prune leaves them (hidden things gone, empty links named or gone, inline boxes spaced, repeated links once), kept
// for the emit call that asked. nothing is copied unless it changes; an element of text alone isn't kept at all
-// the emitter's state for one emit call, kept off the parser's elements: each element's pruned children, and
-// whether it's code (no spacing there)
-let cache = new Map()
-let literals = new Map()
+// emit owns its document and prunes it in place: an element's kids become what prune leaves, once, and pruned says so
// chrome (nav, header, footer, …) is stripped too: the page has no
let stripChrome = false
export const begin = (strip: boolean) => {
stripChrome = strip
- cache = new Map()
- literals = new Map()
byId = undefined
}
let page: Element | undefined
@@ -32,8 +27,9 @@ export const made = (from: Element, kids: Node[], tag = from.tag): Element => {
kids,
up: from.up,
map: from.map,
+ pruned: true,
+ code: from.code,
}
- cache.set(el, kids)
return el
}
@@ -366,11 +362,9 @@ const pruned = (kid: Element): Element | undefined => {
// whether text in an element is code, as written: no spacing there
const literal = (el: Element): boolean => {
- let value = literals.get(el)
- if (value === undefined) {
- value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up))
- literals.set(el, value)
- }
+ let value = el.code
+ if (value === undefined)
+ el.code = value = el.tag === 'pre' || el.tag === 'code' || (el.up !== null && literal(el.up))
return value
}
@@ -416,10 +410,13 @@ const LETTER_START = /^[\p{L}\p{N}]/u
const spaced = (parent: Element, kids: Node[]): Node[] => {
let out: Node[] | undefined
let items: boolean | undefined
- const said: (string | undefined)[] = []
- const boxes: (boolean | undefined)[] = []
- const wordAt = (i: number) => (said[i] ??= word(kids[i]))
- const boxedAt = (i: number) => (boxes[i] ??= boxed(kids[i]))
+ // each child's word and box, worked out at most once (one pair's right is the next one's left)
+ let lastWord = -1
+ let leftSaid = ''
+ let rightSaid = ''
+ let lastBox = -1
+ let leftBox = false
+ let rightBox = false
let inlines = 0
for (let i = 0; i < kids.length; i++) {
const left = kids[i]!
@@ -435,12 +432,18 @@ const spaced = (parent: Element, kids: Node[]): Node[] => {
let gap: boolean
if (leftInline && rightInline && edgeLink(left, true) && edgeLink(right, false)) gap = true
else {
- const leftWord = wordAt(i)
- const rightWord = wordAt(i + 1)
+ leftSaid = i > 0 && lastWord === i - 1 ? rightSaid : word(left)
+ rightSaid = word(right)
+ lastWord = i
+ const leftWord = leftSaid
+ const rightWord = rightSaid
const letters = LETTER_END.test(leftWord) && LETTER_START.test(rightWord)
const both = leftWord !== '' && rightWord !== ''
if (!letters && !both) continue
- const box = boxedAt(i) || boxedAt(i + 1)
+ leftBox = i > 0 && lastBox === i - 1 ? rightBox : boxed(left)
+ rightBox = boxed(right)
+ lastBox = i
+ const box = leftBox || rightBox
gap = letters || (box && both)
// text beside an element is a box of its own only in a flex or grid container, or beside a box
if (gap && !(leftInline && rightInline)) gap = box || (items ??= displays(parent, LAID_OUT))
@@ -483,21 +486,15 @@ export const kidsOf = (el: Element): Node[] => {
const raw = el.kids
// only text in it (most elements: a span of code, a link's words): nothing for prune to do, nothing to keep
if (raw.length === 0 || (raw.length === 1 && typeof raw[0] === 'string')) return raw
- const cached = cache.get(el)
- if (cached !== undefined) return cached
- let out: Node[] | undefined
+ if (el.pruned) return raw
+ el.pruned = true
+ // in place: what's kept moves down over what's dropped
+ let at = 0
for (let i = 0; i < raw.length; i++) {
const kid = raw[i]!
- if (typeof kid === 'string') {
- out?.push(kid)
- continue
- }
- const kept = pruned(kid)
- if (kept !== kid) out ??= raw.slice(0, i)
- if (out && kept) out.push(kept)
+ const kept = typeof kid === 'string' ? kid : pruned(kid)
+ if (kept !== undefined) raw[at++] = kept
}
- let kids = out ?? raw
- if (kids.length > 1 && !literal(el)) kids = spaced(el, kids)
- cache.set(el, kids)
- return kids
+ raw.length = at
+ return at > 1 && !literal(el) ? (el.kids = spaced(el, raw)) : raw
}
diff --git a/packages/md-core/src/entities.ts b/packages/md-core/src/entities.ts
index 3dd7be4..8b6c210 100644
--- a/packages/md-core/src/entities.ts
+++ b/packages/md-core/src/entities.ts
@@ -23,6 +23,24 @@ const numeric = (code: number) => {
return String.fromCodePoint(code)
}
+// the few references most pages are made of, matched without a slice and a lookup: the letters from..to, before a ';'
+const common = (text: string, from: number, to: number) => {
+ const c = text.charCodeAt(from)
+ switch (to - from) {
+ case 2:
+ if (text.charCodeAt(from + 1) !== 116) return undefined
+ return c === 108 ? '<' : c === 103 ? '>' : undefined
+ case 3:
+ return c === 97 && text.charCodeAt(from + 1) === 109 && text.charCodeAt(from + 2) === 112
+ ? '&'
+ : undefined
+ case 4:
+ if (c === 113 && text.startsWith('uot', from + 1)) return '"'
+ if (c === 110 && text.startsWith('bsp', from + 1)) return '\u00a0'
+ if (c === 97 && text.startsWith('pos', from + 1)) return "'"
+ }
+ return undefined
+}
const alnum = (c: number) => (c >= 48 && c <= 57) || ((c | 32) >= 97 && (c | 32) <= 122)
// attribute: decoding an attribute's value, where a legacy name followed by '=' or an alphanumeric isn't a reference
@@ -60,7 +78,7 @@ export const decode = (text: string, attribute = false): string => {
let j = i
while (j < n && j - i <= NAME_MAX && alnum(text.charCodeAt(j))) j++
if (j > i) {
- if (text.charCodeAt(j) === 59) value = NAMED.get(text.slice(i, j + 1))
+ if (text.charCodeAt(j) === 59) value = common(text, i, j) ?? NAMED.get(text.slice(i, j + 1))
if (value !== undefined) end = j + 1
else
// without its ';', the longest legacy name the letters start with
diff --git a/packages/md-core/src/parse.ts b/packages/md-core/src/parse.ts
index 04e3a6a..0e2a2e2 100644
--- a/packages/md-core/src/parse.ts
+++ b/packages/md-core/src/parse.ts
@@ -340,6 +340,9 @@ const make = (name: string, id: number, ns: number, attrs: string, flags: number
kids: [],
up: null,
map: undefined,
+ // the emitter's fields, here so every element has one shape from the start
+ pruned: false,
+ code: undefined,
id,
ns,
rec: ns === SVG ? 0 : DROP[id] ? 1 : 2,
@@ -1463,6 +1466,8 @@ const adopt = (el: El) => {
el.attrs = serialize(own)
el.map = own
el.flags |= tflags
+ // a role it gains can make it a main (an html element is in the tree when a frameset put the page's own in it)
+ if (own.get('role') === 'main' && !mains.includes(el)) mains.push(el)
}
const hiddenInput = () =>
tattrs !== '' && parseAttrs(tattrs).get('type')?.toLowerCase() === 'hidden'
@@ -2563,6 +2568,13 @@ const dataText = (from: number, to: number) => {
}
return
}
+ // the common case: text in body, into an html element (what chars would do, minus its dispatch)
+ if (mode === IN_BODY && current.ns === HTML && !skipNL && !foster) {
+ if (afe.length !== 0) rebuild()
+ appendText(current, text)
+ if (framesetOk && !allSpace(text)) framesetOk = false
+ return
+ }
chars(text)
}
// text in raw text, rcdata, script data and plaintext: nuls are U+FFFD
@@ -2974,7 +2986,7 @@ const readMains = (root: El) => {
while (up && up !== root && !DROP[up.id]) up = up.up
if (up === root && el !== root) found.push(el)
}
- if (!reordered || found.length < 2) return found
+ if (found.length < 2) return found
const places = new Map(found.map((el) => [el, position(el)]))
return found.toSorted((a, b) => treeOrder(places.get(a)!, places.get(b)!))
}
diff --git a/packages/md-core/src/types.ts b/packages/md-core/src/types.ts
index 4df746c..2478c0a 100644
--- a/packages/md-core/src/types.ts
+++ b/packages/md-core/src/types.ts
@@ -18,6 +18,10 @@ export interface Element {
up: Element | null
// attr()'s cache
map?: Map | undefined
+ // the emitter's own, on a document it owns (it emits each once and prunes it in place): kids are already as prune
+ // leaves them; and whether the element is code or inside it (undefined until asked)
+ pruned?: boolean | undefined
+ code?: boolean | undefined
}
// the attributes an element's flags record, by name (ascii case-insensitive, as html matches them)
@@ -59,6 +63,7 @@ export interface Head {
jsonLd: string[]
}
+// a Document is emitted once: emit owns the tree it's given and may prune or annotate it in place
export interface Document {
// children are the 's children (or, without a body, the page's own)
root: Element
diff --git a/packages/md-core/test/emit-fresh.ts b/packages/md-core/test/emit-fresh.ts
new file mode 100644
index 0000000..560b81f
--- /dev/null
+++ b/packages/md-core/test/emit-fresh.ts
@@ -0,0 +1,25 @@
+// emit on fresh trees, as bench/run.ts times it: a pool of parsed documents, each emitted once. prints, per page,
+// the best of several pool medians (other work on the machine only ever adds time): node test/emit-fresh.ts [page]
+import { loadCorpus } from '../bench/corpus.ts'
+import { emit } from '../src/emit.ts'
+import { parse } from '../src/parse.ts'
+
+const want = process.argv[2]
+const gc = (globalThis as { gc?: () => void }).gc
+let total = 0
+for (const page of loadCorpus().filter((p) => !want || p.name.includes(want))) {
+ let best = Infinity
+ for (let round = 0; round < 3; round++) {
+ const docs = Array.from({ length: 15 }, () => parse(page.html))
+ gc?.()
+ const times = docs.map((doc) => {
+ const start = performance.now()
+ emit(doc, { url: 'https://site.test/a' })
+ return performance.now() - start
+ })
+ best = Math.min(best, times.toSorted((a, b) => a - b)[times.length >> 1]!)
+ }
+ total += best
+ console.log(`${best.toFixed(2).padStart(7)} ms ${page.name}`)
+}
+console.log(`${total.toFixed(2).padStart(7)} ms total`)
diff --git a/packages/md-core/test/parse.test.ts b/packages/md-core/test/parse.test.ts
index 8317579..835b1f0 100644
--- a/packages/md-core/test/parse.test.ts
+++ b/packages/md-core/test/parse.test.ts
@@ -1,5 +1,6 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { describe, expect, test } from 'vitest'
+import { attr, parseAttrs, scanAttr } from '../src/attr.ts'
import { ENTITIES } from '../src/entities-table.ts'
import { parse } from '../src/parse.ts'
import { NEVER, type Element, type Node } from '../src/types.ts'
@@ -403,6 +404,59 @@ describe('foreign content: math', () => {
])('%j', (html) => expect(difference(html)).toBeUndefined())
})
+describe('one attribute read alone agrees with them all parsed', () => {
+ const NAMES = [
+ 'class',
+ 'id',
+ 'href',
+ 'style',
+ 'role',
+ 'hidden',
+ 'title',
+ 'type',
+ 'xlink:href',
+ 'x',
+ '=',
+ '\uFFFD',
+ ]
+ const agree = (source: string) => {
+ const map = parseAttrs(source)
+ const problems: string[] = []
+ for (const name of new Set([...map.keys(), ...NAMES]))
+ if (scanAttr(source, name) !== map.get(name))
+ problems.push(`${JSON.stringify(source)} ${name}`)
+ return problems
+ }
+ test.each([
+ ' a=1 A=2 a=3',
+ ' STYLE="color:red" style=x',
+ ' a b=c d = "e" f=\'g\' h=i/ j',
+ '/a/b=c//d',
+ ' =x ==y',
+ ' a="&¬it;¬=&=x&x" b=<',
+ ' a="\0" \0b=c',
+ ' a="never closed',
+ ' a=',
+ ' a"b=c \'d=e',
+ '',
+ ])('%j', (source) => expect(agree(source)).toEqual([]))
+ test('on every element of generated pages, and attr() in any order of questions', () => {
+ const problems: string[] = []
+ const walk = (el: Element) => {
+ problems.push(...agree(el.attrs))
+ const map = parseAttrs(el.attrs)
+ for (const name of [...NAMES, ...map.keys()]) {
+ const fresh = { ...el, map: undefined } as Element
+ if (attr(fresh, name) !== map.get(name) || attr(fresh, name) !== map.get(name))
+ problems.push(`attr ${JSON.stringify(el.attrs)} ${name}`)
+ }
+ for (const kid of el.kids) if (typeof kid !== 'string') walk(kid)
+ }
+ for (let seed = 1; seed <= 1500; seed++) walk(parse(generate(seed)).root)
+ expect(problems.slice(0, 5)).toEqual([])
+ })
+})
+
describe('flags and mains', () => {
test.each([
'x
',
@@ -421,6 +475,8 @@ describe('flags and mains', () => {
'in svg n after',
't h',
'math main ',
+ '> ',
+ 'a ',
])('%j', (html) => expect(difference(html)).toBeUndefined())
})
From 83c30a39049756a642e9660bc1f04fe006ad76cd Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Thu, 12 Nov 2026 12:44:01 +0000
Subject: [PATCH 05/74] perf(md-core): write paragraphs and headings directly,
with the full emitter as fallback
Top-level paragraphs and headings of plain inline content (text, strong,
em, code, links, breaks, spans) are written as soon as they are
converted, without building their children. Anything else declines
before a byte is written and goes through the existing emitter, which
stays the definition of correct: output with the fast path on must equal
output with it off, across every case, the corpus, the fixtures and a
fuzz of the accepted shapes and their near misses.
Also: one-pass escape scan, an emphasis shortcut when markers pair as
written, and the hidden-style check remembered per attribute string.
109 ms for the 10-page corpus against mdream's 37.5 ms; parity unchanged.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_018hJ9SEkCX16tDcRNj1QfjV
---
packages/md-core/src/emit-convert.ts | 198 +++++++++++++++-
packages/md-core/src/emit-markdown.ts | 302 +++++++++++++++++++------
packages/md-core/src/emit-prune.ts | 31 ++-
packages/md-core/src/emit.ts | 7 +-
packages/md-core/test/emit-coverage.ts | 20 ++
packages/md-core/test/emit-fuzz.ts | 166 ++++++++++++++
packages/md-core/test/emit.test.ts | 79 ++++++-
7 files changed, 726 insertions(+), 77 deletions(-)
create mode 100644 packages/md-core/test/emit-coverage.ts
create mode 100644 packages/md-core/test/emit-fuzz.ts
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts
index c0c8a3a..6703e96 100644
--- a/packages/md-core/src/emit-convert.ts
+++ b/packages/md-core/src/emit-convert.ts
@@ -8,6 +8,8 @@ import {
IMAGE,
INLINE_CODE,
isPhrasing,
+ renderBlock,
+ setext,
LINK,
LIST,
LIST_ITEM,
@@ -171,6 +173,7 @@ let controls = 0
let titledCode: Element | undefined
let titledAs = ''
export const startConvert = (options: Options, page: string | undefined) => {
+ fast = (options as { fast?: boolean }).fast !== false
base = page
relink = options.link
inTable = false
@@ -206,6 +209,11 @@ const push = (out: Md[], results: Md[]) => {
// an element's children, converted, appended to out
export const all = (parent: Element, out: Md[] = []): Md[] => {
const kids = kidsOf(parent)
+ // whether what's converted here lands in a flow (root, blockquote, list item) as it is: every element between here
+ // and the nearest one is a flow element, or one whose children are its parent's (a span, a custom element). only
+ // there is a block written as a flow writes it
+ const savedFlow = flow
+ flow = flow && (FLOWS.has(parent.tag) || ((INFO.get(parent.tag) ?? 0) & KIND_MASK) === PASS)
for (let i = 0; i < kids.length; i++) {
const kid = kids[i]!
if (typeof kid === 'string') {
@@ -240,7 +248,22 @@ export const all = (parent: Element, out: Md[] = []): Md[] => {
let result: Md | Md[] | undefined
if (controls !== 0 && CONTROL_TAGS.has(kid.tag)) result = walkOnly(kid)
else if (kind === PASS && !(kid.flags & FLAG['data-mdast'])) all(kid, out)
- else result = one(kid, kind, parent)
+ else if (
+ flow &&
+ fast &&
+ (kind === PARAGRAPH_TAG || kind === HEADING_TAG) &&
+ controls === 0 &&
+ !inTable &&
+ skips.size === 0 &&
+ mode === NORMAL &&
+ (result = fastBlock(kid, kind)) !== DECLINED
+ ) {
+ // written by the fast path (or nothing, for a paragraph with nothing in it)
+ } else {
+ // a block the fast path declined starts again where it started: at a block's edge
+ if (block) before = true
+ result = one(kid, kind, parent)
+ }
const strip = before || end
after = savedAfter
mode = savedMode
@@ -249,6 +272,7 @@ export const all = (parent: Element, out: Md[] = []): Md[] => {
if (result instanceof Md) pushOne(out, result)
else push(out, result)
}
+ flow = savedFlow
return out
}
// the whitespace an element leaves, without what it says
@@ -563,7 +587,17 @@ const DOT_SEGMENT = /\/\.|%2e/i
const HTTP = /^(https?):\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?=[/?#]|$)/
const NUMERIC_LABEL = /(?:^|\.)(?:0x[0-9a-f]*|\d+)\.?$/
// the shape an href is, when it's one of those: 'fragment', 'path', or an http url's length up to its path
+// the last url shaped: a link's url is shaped twice in a row (its scheme, then its resolution)
+let shapedUrl = ''
+let shaped: 'fragment' | 'path' | number | undefined
const shape = (url: string): 'fragment' | 'path' | number | undefined => {
+ if (url !== shapedUrl) {
+ shapedUrl = url
+ shaped = shapeOf(url)
+ }
+ return shaped
+}
+const shapeOf = (url: string): 'fragment' | 'path' | number | undefined => {
const head = url.charCodeAt(0)
if (head === 35) return PLAIN.test(url) && url.indexOf('#', 1) < 0 ? 'fragment' : undefined
if (head === 47) {
@@ -1109,6 +1143,19 @@ const collectElement = (
if (isCell(el) && afterIn(siblings, position, isCell)) piece('\t')
if (suffix) piece(suffix)
}
+const BIDI_TEST = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/
+// toText of an inline element holding one text, already collapsed
+const toTextOfOne = (value: string) => {
+ const savedJoined = joined
+ const savedCount = count
+ joined = ''
+ count = undefined
+ collectText(value, false, false)
+ const result = joined
+ joined = savedJoined
+ count = savedCount
+ return result
+}
const BIDI = /[--]/g
const collectText = (value: string, breakBefore: Break, breakAfter: Break) => {
const lines: string[] = []
@@ -1160,8 +1207,157 @@ const trimAndCollapse = (value: string, breakBefore: unknown, breakAfter: unknow
// the walk over the content's root, as hast-util-to-mdast's root handler: wrapped when it holds blocks
export const convertRoot = (root: Element): Md => {
+ flow = true
before = true
after = true
mode = NORMAL
return node(ROOT, rootKids(all(root)))
}
+
+// the fast path: a paragraph or heading of plain inline content (text, strong, emphasis, code, links, breaks, spans)
+// is converted by a walk that knows only those, and written straight away. anything else declines it, and it's
+// converted as before. it makes the same tree one() would (finish and the joins read it), so the gate is simply
+// that the markdown is the same with it and without it (emit's second argument takes fast: false)
+let fast = true
+let flow = false
+const FLOWS = new Set([
+ '#root',
+ ...'address article aside body center fieldset figcaption footer header hgroup html legend main multicol nav picture section div figure blockquote li details form'.split(
+ ' ',
+ ),
+])
+const DECLINED = null as unknown as Md
+// how the fast path fared, for the reports: blocks written, and declined by the tag that stopped them
+export const fastStats = { taken: 0, declined: new Map() }
+const decline = (why: string) => {
+ fastStats.declined.set(why, (fastStats.declined.get(why) ?? 0) + 1)
+ return false
+}
+const fastBlock = (el: Element, kind: number): Md | undefined => {
+ const out: Md[] = []
+ const savedAfter = after
+ if (!fastInline(el, el, out)) {
+ // what a declined block leaves is set back, so it's converted as if it had never been tried
+ after = savedAfter
+ return DECLINED
+ }
+ const kids = dropBreaks(out)
+ let block: Md
+ if (kind === PARAGRAPH_TAG) {
+ if (!kids.length) return undefined
+ block = node(PARAGRAPH, kids)
+ } else {
+ block = node(HEADING, kids)
+ block.depth = el.tag.charCodeAt(1) - 48
+ // a heading with a line break is written setext style, which joins read from its children: the slow way
+ if (setext(block)) {
+ decline('setext heading')
+ return DECLINED
+ }
+ }
+ block.raw = renderBlock(block)
+ fastStats.taken++
+ // only its markdown is kept: what's built for it goes now, and the element stands in for it if it's ever read
+ block.kids = []
+ block.el = el
+ return block
+}
+// a block the fast path wrote, converted the slow way, for what reads its children (finish: the description and
+// the title read the blocks at the top)
+export const materialize = (block: Md): Md => {
+ if (block.raw === null || block.el === null) return block
+ const savedFast = fast
+ fast = false
+ before = true
+ after = true
+ mode = NORMAL
+ const el = block.el
+ const made = one(el, el.tag === 'p' ? PARAGRAPH_TAG : HEADING_TAG, el.up ?? el)
+ fast = savedFast
+ return made instanceof Md ? made : block
+}
+// an element's inline children into out, as all() converts them, or false at the first thing it doesn't know
+const fastInline = (parent: Element, heading: Element, out: Md[]): boolean => {
+ const kids = kidsOf(parent)
+ for (let i = 0; i < kids.length; i++) {
+ const kid = kids[i]!
+ if (typeof kid === 'string') {
+ const value = minified(kid, kids, i)
+ if (value === undefined) continue
+ const last = out[out.length - 1]
+ if (last !== undefined && last.type === TEXT) last.value += value
+ else out.push(new Md(TEXT, undefined, value))
+ continue
+ }
+ const tag = kid.tag
+ if (kid.flags & FLAG['data-mdast']) return decline('data-mdast')
+ const isBreak = tag === 'br'
+ const savedAfter = after
+ const end = isBreak ? true : collapsableAfter(kids, i, after)
+ if (isBreak) before = true
+ after = end
+ let ok = true
+ switch (tag) {
+ case 'span':
+ ok = fastInline(kid, heading, out)
+ break
+ case 'strong':
+ case 'b':
+ case 'em':
+ case 'i': {
+ const inner: Md[] = []
+ ok = fastInline(kid, heading, inner)
+ if (ok) out.push(node(tag === 'strong' || tag === 'b' ? STRONG : EMPHASIS, inner))
+ break
+ }
+ case 'code': {
+ // code of one text is that text as whitespace leaves it (toText's trims are already done), unless it has
+ // bidi controls, which toText strips
+ const inner = kidsOf(kid)
+ let value: string
+ if (inner.length === 1 && typeof inner[0] === 'string') {
+ value = minified(inner[0], inner, 0) ?? ''
+ if (BIDI_TEST.test(value)) value = toTextOfOne(value)
+ } else value = toText(kid)
+ out.push(node(INLINE_CODE, undefined, value))
+ break
+ }
+ case 'br':
+ out.push(node(BREAK))
+ break
+ case 'a':
+ ok = fastLink(kid, parent === heading && HEADINGS.has(heading.tag), out)
+ break
+ default:
+ ok = decline(`<${tag}>`)
+ }
+ if (!ok) return false
+ const strip = before || end
+ after = savedAfter
+ before = Boolean(strip)
+ }
+ return true
+}
+// a link as link() converts it: unwrapped when it goes nowhere (or to its heading's own anchor)
+const fastLink = (el: Element, inHeading: boolean, out: Md[]): boolean => {
+ const href = (attr(el, 'href') ?? '').trim()
+ const children: Md[] = []
+ if (!fastInline(el, el, children)) return false
+ if (
+ !href ||
+ href === '#' ||
+ !allowed(href, LINK_SCHEMES) ||
+ (href.startsWith('#') && inHeading)
+ ) {
+ push(out, children)
+ return true
+ }
+ // a link with nothing to read is named by its label: the slow way
+ if (!children.some((child) => child.type !== TEXT || child.value.trim()))
+ return decline('link named by its label')
+ const result = node(LINK, children)
+ result.url = resolve(href, false)
+ result.title = el.flags & FLAG.title ? (attr(el, 'title') ?? null) : null
+ out.push(result)
+ return true
+}
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
index a956377..e178fa6 100644
--- a/packages/md-core/src/emit-markdown.ts
+++ b/packages/md-core/src/emit-markdown.ts
@@ -1,3 +1,4 @@
+import type { Element } from './types.ts'
// markdown from the emitter's lean tree, written the way mdast-util-to-markdown (MIT, Titus Wormer) writes an mdast
// tree with @affordances/md's options: bullet -, emphasis _, strong *, rule -, fenced code, and gfm (tables, task
// lists, strikethrough, autolink literals with their escapes kept to headings). its rules are ported one for one, over
@@ -49,6 +50,10 @@ export class Md {
colSpan: number
// its kids have been tidied (tidy below), which happens once, just before anything reads them
clean: boolean
+ // a block the fast path wrote already (emit-convert's fast): its markdown, as handle() would write it in a flow
+ raw: string | null
+ // and the element it was written from, to convert again the slow way if its children are ever asked for
+ el: Element | null
constructor(type: number, kids: Md[] = LEAF[type] ? NO_KIDS : [], value = '') {
this.type = type
this.kids = kids
@@ -65,6 +70,8 @@ export class Md {
this.rowSpan = 0
this.colSpan = 0
this.clean = false
+ this.raw = null
+ this.el = null
}
}
@@ -462,7 +469,11 @@ const escapeBackslashes = (value: string, after: string) => {
}
// text made safe to write between before and after in the current constructs: mdast-util-to-markdown's safe()
+// whether what safe() last wrote ends with its input's last character (so that's what follows it), when it isn't
+// the input itself
+let endsAsInput = false
const safe = (input: string, before: string, after: string, encode = ''): string => {
+ endsAsInput = false
if (input === '') return escapeBackslashes(input, after)
const scope = scopeOf(mask)
// the fast path: nothing a pattern could match, and no line ending beside the text to start a construct
@@ -501,6 +512,34 @@ const scannable = (input: string, before: string, after: string) => {
const sidesOf = (pattern: Pattern) => (pattern.before ? 1 : 0) | (pattern.after ? 2 : 0)
// safe() as one pass over the text: each character's patterns asked of its neighbours, then the same rules as
// slowSafe. only for text no line ending can reach (scannable), in a scope with one-character patterns
+// what the patterns say of the character at i: -1 nothing matches; else 1 if every match there had a before, | 2 if
+// every one had an after
+const matchAt = (
+ byChar: (Pattern[] | undefined)[],
+ input: string,
+ i: number,
+ previous: number,
+ next: number,
+) => {
+ const code = input.charCodeAt(i)
+ if (code >= 128) return -1
+ const list = byChar[code]
+ if (list === undefined) return -1
+ let bits = -1
+ for (let k = 0; k < list.length; k++) {
+ const pattern = list[k]!
+ if (pattern.beforeSet) {
+ const b = i ? input.charCodeAt(i - 1) : previous
+ if (b < 0 || b >= 128 || pattern.beforeSet[b] !== 1) continue
+ }
+ if (pattern.afterSet) {
+ const a = i + 1 < input.length ? input.charCodeAt(i + 1) : next
+ if (a < 0 || a >= 128 || pattern.afterSet[a] !== 1) continue
+ }
+ bits = bits < 0 ? sidesOf(pattern) : bits & sidesOf(pattern)
+ }
+ return bits
+}
export const scanSafe = (
byChar: (Pattern[] | undefined)[],
input: string,
@@ -511,81 +550,54 @@ export const scanSafe = (
const n = input.length
const previous = before === '' ? -1 : before.charCodeAt(before.length - 1)
const next = after === '' ? -1 : after.charCodeAt(0)
- const positions: number[] = []
- const infos: number[] = []
- for (let i = 0; i < n; i++) {
- const code = input.charCodeAt(i)
- if (code >= 128) continue
- const list = byChar[code]
- if (list === undefined) continue
- let bits = -1
- for (const pattern of list) {
- if (pattern.beforeSet) {
- const b = i ? input.charCodeAt(i - 1) : previous
- if (b < 0 || b >= 128 || pattern.beforeSet[b] !== 1) continue
- }
- if (pattern.afterSet) {
- const a = i + 1 < n ? input.charCodeAt(i + 1) : next
- if (a < 0 || a >= 128 || pattern.afterSet[a] !== 1) continue
- }
- bits = bits < 0 ? sidesOf(pattern) : bits & sidesOf(pattern)
- }
- if (bits >= 0) {
- positions.push(i)
- infos.push(bits)
- }
- }
- if (!positions.length) return escapeBackslashes(input, after)
- const at = (i: number) => (i < 0 ? previous : i < n ? input.charCodeAt(i) : next)
- const result: string[] = []
+ // a backslash only needs doubling before punctuation, and only if there is one
+ const slashes = input.indexOf('\\') >= 0
+ let result = ''
let start = 0
- for (let index = 0; index < positions.length; index++) {
- const position = positions[index]!
- if (position < start) continue
+ for (let i = 0; i < n; i++) {
+ const info = matchAt(byChar, input, i, previous, next)
+ if (info < 0) continue
// an intraword underscore run (snake_case) needs no escape
- if (
- input.charCodeAt(position) === 95 &&
- (position > 0 || before !== '') &&
- classify(at(position - 1)) === 0 &&
- !(position === 1 && (previous === 42 || previous === 95))
- ) {
- let sequenceEnd = position + 1
- while (sequenceEnd < n && input.charCodeAt(sequenceEnd) === 95) sequenceEnd++
- const skip = sequenceEnd - position - 1
- if (
- positions[index + skip] === sequenceEnd - 1 &&
- (sequenceEnd < n || after !== '') &&
- classify(at(sequenceEnd)) === 0 &&
- !(sequenceEnd === n - 1 && (next === 42 || next === 95))
- ) {
- index += skip
- continue
+ if (input.charCodeAt(i) === 95 && (i > 0 || before !== '')) {
+ const back = i ? input.charCodeAt(i - 1) : previous
+ if (classify(back) === 0 && !(i === 1 && (previous === 42 || previous === 95))) {
+ let sequenceEnd = i + 1
+ while (sequenceEnd < n && input.charCodeAt(sequenceEnd) === 95) sequenceEnd++
+ let all = true
+ for (let k = i + 1; k < sequenceEnd && all; k++)
+ all = matchAt(byChar, input, k, previous, next) >= 0
+ if (
+ all &&
+ (sequenceEnd < n || after !== '') &&
+ classify(sequenceEnd < n ? input.charCodeAt(sequenceEnd) : next) === 0 &&
+ !(sequenceEnd === n - 1 && (next === 42 || next === 95))
+ ) {
+ i = sequenceEnd - 1
+ continue
+ }
}
}
- const info = infos[index]!
// escaping what follows (or precedes) is enough
if (
- (position + 1 < n &&
- positions[index + 1] === position + 1 &&
- info & 2 &&
- infos[index + 1] === 0) ||
- (position - 1 >= 0 &&
- positions[index - 1] === position - 1 &&
- info & 1 &&
- infos[index - 1] === 0)
+ (info & 2 && i + 1 < n && matchAt(byChar, input, i + 1, previous, next) === 0) ||
+ (info & 1 && i > 0 && matchAt(byChar, input, i - 1, previous, next) === 0)
)
continue
- if (start !== position) result.push(escapeBackslashes(input.slice(start, position), '\\'))
- start = position + 1
- const char = input.charAt(position)
- result.push(
+ if (start !== i)
+ result += slashes ? escapeBackslashes(input.slice(start, i), '\\') : input.slice(start, i)
+ start = i + 1
+ const char = input.charAt(i)
+ result +=
ASCII_PUNCTUATION.test(char) && !encode.includes(char)
? '\\' + char
- : reference(input.charCodeAt(position)),
- )
+ : reference(input.charCodeAt(i))
}
- result.push(escapeBackslashes(input.slice(start), after))
- return result.join('')
+ const tail = slashes || after.indexOf('\\') >= 0
+ if (start === 0) return tail ? escapeBackslashes(input, after) : input
+ const rest = start < n ? input.slice(start) : ''
+ // the text's own last character ends what's written, unless an escape does
+ endsAsInput = rest !== '' && !tail
+ return result + (tail ? escapeBackslashes(rest, after) : rest)
}
// the slow path, for tests: safe() by the regexes, whatever the text
export const regexSafe = (
@@ -944,6 +956,51 @@ const improve = (
return undefined
}
+// whether check() would find nothing wrong, answered without its bookkeeping for the usual shape: every attention
+// run a single sequence, properly nested, each opener able to open and each closer to close. false means "ask check"
+const pending: Attention[][] = [[], [], []]
+const stackOf = (marker: number) => pending[marker === 42 ? 0 : marker === 95 ? 1 : 2]!
+const fastValid = (tokens: Token[], before: string, after: string): boolean => {
+ pending[0]!.length = 0
+ pending[1]!.length = 0
+ pending[2]!.length = 0
+ for (let index = 0; index < tokens.length; index++) {
+ const token = tokens[index]!
+ if (!token.attention) continue
+ const marker = token.value.charCodeAt(0)
+ const left = index > 0 ? tokens[index - 1]! : undefined
+ const right = index + 1 < tokens.length ? tokens[index + 1]! : undefined
+ // a run of more than one sequence is check's to read
+ if (left?.attention && left.value.charCodeAt(0) === marker) return false
+ if (right?.attention && right.value.charCodeAt(0) === marker) return false
+ const head = left ? left.value : before
+ const previous = classify(head.charCodeAt(head.length - 1))
+ const next = classify((right ? right.value : after).charCodeAt(0))
+ let open = !next || (next === 2 && Boolean(previous))
+ let close = !previous || (previous === 2 && Boolean(next))
+ if (marker === 95) {
+ const opens = open && (Boolean(previous) || !close)
+ close = close && (Boolean(next) || !open)
+ open = opens
+ }
+ const opened = stackOf(marker)
+ if (opened[opened.length - 1] === token.attention) {
+ if (!close) return false
+ opened.pop()
+ } else {
+ if (!open || (close && opened.length)) return false
+ opened.push(token.attention)
+ }
+ }
+ return !pending[0]!.length && !pending[1]!.length && !pending[2]!.length
+}
+// for tests: whether fastValid and check agree on these items
+export const attentionAgrees = (items: Item[], before: string, after: string) => {
+ const tokens = render(items, new Map(), before, after)
+ return !fastValid(tokens, before, after) || check(tokens, before, after) === undefined
+}
+export type { Attention, Item }
+
const serialize = (items: Item[], before: string, after: string) => {
let plain = true
for (const item of items)
@@ -954,6 +1011,11 @@ const serialize = (items: Item[], before: string, after: string) => {
if (plain) return items.join('')
let chosen = new Map()
const initial = render(items, chosen, before, after)
+ if (fastValid(initial, before, after)) {
+ let joined = ''
+ for (let i = 0; i < initial.length; i++) joined += initial[i]!.value
+ return joined
+ }
let tokens = initial
let mistake = check(tokens, before, after)
while (mistake) {
@@ -1032,7 +1094,9 @@ const phrasing = (parent: Md, before: string, after: string): Item[] => {
? ')'
: child.type === INLINE_CODE
? '`'
- : lastCharacter(value)
+ : child.type === TEXT && (value === child.value || endsAsInput)
+ ? lastCharacter(child.value)
+ : lastCharacter(value)
}
}
indexStack.pop()
@@ -1177,6 +1241,7 @@ const handle = (node: Md, parent: Md | undefined, before: string, after: string)
case TEXT:
return safe(node.value, before, after)
case PARAGRAPH: {
+ if (node.raw !== null) return node.raw
enter('paragraph')
enter('phrasing')
const value = containerPhrasing(node, before, after)
@@ -1185,7 +1250,7 @@ const handle = (node: Md, parent: Md | undefined, before: string, after: string)
return value
}
case HEADING:
- return heading(node)
+ return node.raw !== null ? node.raw : heading(node)
case ROOT: {
if (!tidy(node).some(isPhrasing)) return containerFlow(node)
enter('phrasing')
@@ -1561,6 +1626,104 @@ const markdownTable = (matrix: string[][], align: (string | null)[]) => {
return lines.join('\n')
}
+// a paragraph or heading written as a flow writes it (between line endings, in no construct but its own), for the
+// fast path, which writes them as it converts them. the serializer's state is balanced between calls, so this is
+// the same markdown handle() gives it later
+export const renderBlock = (node: Md) => {
+ const written = writeFlat(node)
+ return written === undefined ? handle(node, undefined, '\n', '\n') : written
+}
+
+// a paragraph or heading written in one pass over its children, for the usual shape: text, code, links and
+// emphasis around a single text that starts and ends with a letter where nothing could make the markers mean
+// anything else. that's phrasing() and serialize() when every attention run pairs as written and nothing needs
+// encoding; anything else returns undefined, for the general way
+const writeFlat = (node: Md): string | undefined => {
+ const isHeading = node.type === HEADING
+ const rank = isHeading ? Math.max(Math.min(6, node.depth || 1), 1) : 0
+ const kids = tidy(node)
+ enter(isHeading ? 'headingAtx' : 'paragraph')
+ enter('phrasing')
+ let before = isHeading ? '# ' : '\n'
+ const end = '\n'
+ let out = ''
+ // the marker of the attention just written, when nothing has come after it yet
+ let lastMarker = 0
+ let failed = false
+ for (let i = 0; i < kids.length && !failed; i++) {
+ const child = kids[i]!
+ const next = i + 1 < kids.length ? firstCharacter(peek(kids[i + 1]!, node)) : end
+ switch (child.type) {
+ case TEXT: {
+ const value = safe(child.value, before, next)
+ if (!value) continue
+ out += value
+ before =
+ value === child.value || endsAsInput ? lastCharacter(child.value) : lastCharacter(value)
+ lastMarker = 0
+ break
+ }
+ case STRONG:
+ case EMPHASIS: {
+ const inner = tidy(child)
+ const sequence = child.type === STRONG ? '**' : '_'
+ const marker = sequence.charCodeAt(0)
+ if (inner.length !== 1 || inner[0]!.type !== TEXT || lastMarker === marker) {
+ failed = true
+ break
+ }
+ enter(child.type === STRONG ? 'strong' : 'emphasis')
+ const text = safe(inner[0]!.value, sequence, sequence)
+ exit()
+ // letters at both ends inside; for _, no letter right outside either
+ if (
+ text === '' ||
+ classify(text.charCodeAt(0)) !== 0 ||
+ classify(text.charCodeAt(text.length - 1)) !== 0 ||
+ (marker === 95 &&
+ (classify(before.charCodeAt(before.length - 1)) === 0 ||
+ classify(next.charCodeAt(0)) === 0))
+ ) {
+ failed = true
+ break
+ }
+ out += sequence + text + sequence
+ before = sequence.charAt(sequence.length - 1)
+ lastMarker = marker
+ break
+ }
+ case INLINE_CODE:
+ out += inlineCode(child)
+ before = '`'
+ lastMarker = 0
+ break
+ case LINK:
+ out += link(child, before)
+ before = autolinked(child) ? '>' : ')'
+ lastMarker = 0
+ break
+ case BREAK: {
+ const value = isHeading ? (/[\t ]/.test(before) ? '' : ' ') : '\\\n'
+ if (!value) continue
+ out += value
+ before = lastCharacter(value)
+ lastMarker = 0
+ break
+ }
+ default:
+ failed = true
+ }
+ }
+ exit()
+ exit()
+ if (failed) return undefined
+ if (!isHeading) return out
+ const head = out.charCodeAt(0)
+ if (head === 9 || head === 32) out = reference(head) + out.slice(1)
+ const sequence = '#'.repeat(rank)
+ return out ? sequence + ' ' + out : sequence
+}
+
// the markdown for a root, as toMarkdown writes it
export const toMarkdown = (root: Md): string => {
stack = []
@@ -1569,10 +1732,9 @@ export const toMarkdown = (root: Md): string => {
indexStack = []
bulletCurrent = undefined
bulletLastUsed = undefined
- let result = handle(root, undefined, '\n', '\n')
- const last = result.charCodeAt(result.length - 1)
- if (result && last !== 10 && last !== 13) result += '\n'
- return result
+ // toMarkdown ends what it writes with a line ending; finish trims it straight off, so it's never added (reading
+ // the last character would copy the whole markdown into one string just for that)
+ return handle(root, undefined, '\n', '\n')
}
// a heading's text as a reader sees it (headingOf in @affordances/md): what it says, without images or a url shown as
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md-core/src/emit-prune.ts
index 0a17aaa..1d98fac 100644
--- a/packages/md-core/src/emit-prune.ts
+++ b/packages/md-core/src/emit-prune.ts
@@ -104,9 +104,21 @@ const editor = (el: Element) => {
// what prune leaves out, with everything in it: what's hidden from people (unless marked for agents), what's marked
// skip, and editors, whose text is what someone typed
+// what an attribute source says about being dropped, remembered: highlighted code repeats a few style="color:…"
+// sources thousands of times. kept small, and only for what the source alone decides (not affordances-md's tag)
+const droppedBy = new Map()
const dropped = (el: Element): boolean => {
+ if ((el.flags & PRUNES) === 0) return false
+ if (el.tag === 'affordances-md') return droppedNow(el)
+ let known = droppedBy.get(el.attrs)
+ if (known === undefined) {
+ if (droppedBy.size > 1024) droppedBy.clear()
+ droppedBy.set(el.attrs, (known = droppedNow(el)))
+ }
+ return known
+}
+const droppedNow = (el: Element): boolean => {
const found = flags(el)
- if ((found & PRUNES) === 0) return false
const mode = found & MARKED ? marked(el) : undefined
if (mode === 'skip') return true
if (found & (ROLE | EDITABLE) && editor(el)) return true
@@ -429,6 +441,23 @@ const spaced = (parent: Element, kids: Node[]): Node[] => {
if (!leftInline && !rightInline) continue
if ((!leftInline && typeof left !== 'string') || (!rightInline && typeof right !== 'string'))
continue
+ // text beside an element: no gap unless a letter or digit meets one, or the element is a box. both are cheap to
+ // rule out before reading the element's text: the text's own edge isn't a letter, the element has no class or style
+ if (!leftInline || !rightInline) {
+ const beside = (leftInline ? right : left) as string
+ const edge = beside.charCodeAt(leftInline ? 0 : beside.length - 1)
+ const element = (leftInline ? left : right) as Element
+ if (
+ edge < 128 &&
+ !(
+ (edge >= 48 && edge <= 57) ||
+ (edge >= 65 && edge <= 90) ||
+ (edge >= 97 && edge <= 122)
+ ) &&
+ !(element.flags & (FLAG.class | FLAG.style))
+ )
+ continue
+ }
let gap: boolean
if (leftInline && rightInline && edgeLink(left, true) && edgeLink(right, false)) gap = true
else {
diff --git a/packages/md-core/src/emit.ts b/packages/md-core/src/emit.ts
index 9bd322b..47bccaf 100644
--- a/packages/md-core/src/emit.ts
+++ b/packages/md-core/src/emit.ts
@@ -1,4 +1,4 @@
-import { convertRoot, startConvert } from './emit-convert.ts'
+import { convertRoot, materialize, startConvert } from './emit-convert.ts'
import { HEADING, headingText, IMAGE, Md, setext, TEXT, toMarkdown } from './emit-markdown.ts'
import { begin, findMain, made, setPage } from './emit-prune.ts'
import type { Document, Options, Result } from './types.ts'
@@ -114,7 +114,7 @@ const finish = (root: Md, meta: Meta, url: string | undefined, options: Options)
frontmatter &&
meta.description &&
next &&
- collapsed(valueText(next)) === collapsed(meta.description)
+ collapsed(valueText(materialize(next))) === collapsed(meta.description)
)
root.kids.splice(h1 + 1, 1)
let output = toMarkdown(root)
@@ -138,6 +138,7 @@ const finish = (root: Md, meta: Meta, url: string | undefined, options: Options)
// the text of the markdown's first # heading: the first h1 written atx style at the top
const firstHeading = (root: Md) => {
- for (const node of root.kids) if (isH1(node) && !setext(node)) return headingText(node)
+ for (const node of root.kids)
+ if (isH1(node) && !setext(node)) return headingText(materialize(node))
return undefined
}
diff --git a/packages/md-core/test/emit-coverage.ts b/packages/md-core/test/emit-coverage.ts
new file mode 100644
index 0000000..a8a92f0
--- /dev/null
+++ b/packages/md-core/test/emit-coverage.ts
@@ -0,0 +1,20 @@
+// how many top-level paragraphs and headings each corpus page writes by the fast path, and why the rest declined:
+// node test/emit-coverage.ts
+import { loadCorpus } from '../bench/corpus.ts'
+import { emit } from '../src/emit.ts'
+import { fastStats } from '../src/emit-convert.ts'
+import { parse } from '../src/parse.ts'
+
+for (const page of loadCorpus()) {
+ fastStats.taken = 0
+ fastStats.declined.clear()
+ emit(parse(page.html), { url: page.url ?? 'https://site.test/a' })
+ const declined = [...fastStats.declined.values()].reduce((a, b) => a + b, 0)
+ const reasons = [...fastStats.declined]
+ .toSorted((a, b) => b[1] - a[1])
+ .slice(0, 4)
+ .map(([why, n]) => `${why} ${n}`)
+ console.log(
+ `${page.name.padEnd(26)} fast ${String(fastStats.taken).padStart(4)} declined ${String(declined).padStart(4)} ${reasons.join(', ')}`,
+ )
+}
diff --git a/packages/md-core/test/emit-fuzz.ts b/packages/md-core/test/emit-fuzz.ts
new file mode 100644
index 0000000..9bbd71f
--- /dev/null
+++ b/packages/md-core/test/emit-fuzz.ts
@@ -0,0 +1,166 @@
+// generated pages for the fast path's gate: the shapes it accepts and their near misses, seeded so a failure repeats.
+// as a script, it runs many and stops at the first page whose markdown differs with the fast path on and off:
+// node test/emit-fuzz.ts [count] [seed]
+import { emit } from '../src/emit.ts'
+import { parse } from '../src/parse.ts'
+
+export const generator = (seed: number) => {
+ let state = seed >>> 0 || 1
+ const random = (n: number) => {
+ // xorshift: fast, and the same everywhere
+ state ^= state << 13
+ state >>>= 0
+ state ^= state >>> 17
+ state ^= state << 5
+ state >>>= 0
+ return state % n
+ }
+ const pick = (list: readonly T[]): T => list[random(list.length)]!
+ const SPACES = [' ', ' ', '\n', '\t', ' \n ', ' ', ' ', '', '', '']
+ const WORDS = [
+ 'a',
+ 'word',
+ 'Two words',
+ '1.',
+ '2)',
+ '10.',
+ 'x_y',
+ 'snake_case_name',
+ 'é',
+ '中文',
+ '😀',
+ ]
+ const MARKS = '*_[]()<>#+-!|\\`~&.:@='.split('')
+ const ENTITIES = ['&', '<', '>', '"', '*', '_', '©']
+ const text = (): string => {
+ let out = ''
+ for (let i = random(4); i >= 0; i--)
+ out +=
+ random(3) === 0
+ ? pick(MARKS)
+ : random(5) === 0
+ ? pick(ENTITIES)
+ : random(4) === 0
+ ? pick(SPACES)
+ : pick(WORDS)
+ return random(3) === 0 ? pick(SPACES) + out + pick(SPACES) : out
+ }
+ const HREFS = [
+ '/docs/x',
+ 'https://example.com/a',
+ 'https://example.com',
+ 'http://x.test/a b',
+ '/a(b)c',
+ '#frag',
+ '#',
+ '',
+ ' /padded ',
+ 'mailto:me@x.test',
+ 'javascript:alert(1)',
+ 'ftp://x.test',
+ '../up',
+ '?q=1&b=2',
+ '/a',
+ 'https://example.com/a',
+ 'HTTPS://X.TEST',
+ '//proto.test/x',
+ ]
+ const TITLES = ['', ' title="T"', ' title=\'a "q" b\'', ' title=""', ' TITLE=x']
+ const SPANS = [
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ ]
+ const inline = (depth: number): string => {
+ let out = ''
+ for (let i = random(5); i >= 0; i--) {
+ const choice = depth > 2 ? 0 : random(14)
+ switch (choice) {
+ case 1:
+ case 2:
+ out += `<${pick(['strong', 'b', 'em', 'i'])}>${inline(depth + 1)}${pick(['strong', 'b', 'em', 'i'])}>`
+ break
+ case 3:
+ out += `${pick(['x', '`tick`', ' sp ', 'a|b', '', '``', text()])}`
+ break
+ case 4: {
+ const href = pick(HREFS)
+ out += `${random(6) === 0 ? pick(['', ' ', href]) : inline(depth + 1)} `
+ break
+ }
+ case 5:
+ out += random(2) ? ' ' : ' '
+ break
+ case 6:
+ out += `${pick(SPANS)}${inline(depth + 1)} `
+ break
+ case 7:
+ // near misses: what the fast path declines
+ out += pick([
+ ' ',
+ '1 ',
+ 'd',
+ 'k ',
+ 'u ',
+ ' ',
+ 'b ',
+ 'q ',
+ '',
+ ' ',
+ ' ',
+ ])
+ break
+ default:
+ out += text()
+ }
+ }
+ return out
+ }
+ const block = (): string => {
+ switch (random(8)) {
+ case 0:
+ return `${inline(0)} `
+ case 1:
+ return ``
+ case 2:
+ return `${inline(0)}
`
+ case 3:
+ return ``
+ default:
+ return `${inline(0)}
`
+ }
+ }
+ return () => {
+ let body = ''
+ for (let i = 1 + random(4); i > 0; i--) body += pick(SPACES) + block()
+ return `T ${body} `
+ }
+}
+
+// a page's markdown with the fast path and without
+export const both = (html: string) => ({
+ fast: emit(parse(html), { url: 'https://site.test/a/b' }).markdown,
+ slow: emit(parse(html), { url: 'https://site.test/a/b', fast: false } as never).markdown,
+})
+
+if (import.meta.main) {
+ const count = Number(process.argv[2]) || 100000
+ const next = generator(Number(process.argv[3]) || 1)
+ for (let i = 0; i < count; i++) {
+ const html = next()
+ const { fast, slow } = both(html)
+ if (fast !== slow) {
+ const a = fast.split('\n')
+ const b = slow.split('\n')
+ let line = 0
+ while (a[line] === b[line]) line++
+ console.log(`mismatch at case ${i}:\n${html}\n--- fast\n${a[line]}\n--- slow\n${b[line]}`)
+ process.exit(1)
+ }
+ }
+ console.log(`${count} pages, no mismatch`)
+}
diff --git a/packages/md-core/test/emit.test.ts b/packages/md-core/test/emit.test.ts
index 0f1693e..1ad14b9 100644
--- a/packages/md-core/test/emit.test.ts
+++ b/packages/md-core/test/emit.test.ts
@@ -1,10 +1,11 @@
import { htmlToMarkdown } from '@affordances/md'
import { describe, expect, test } from 'vitest'
import { emit } from '../src/emit.ts'
-import { regexSafe, scannedSafe } from '../src/emit-markdown.ts'
+import { attentionAgrees, type Item, regexSafe, scannedSafe } from '../src/emit-markdown.ts'
import type { Options, Result } from '../src/types.ts'
import { corpusPages, fixturePages, type Page, similarity } from './emit-pages.ts'
import { parse } from '../src/parse.ts'
+import { both as fuzzBoth, generator } from './emit-fuzz.ts'
import { oracle } from './support/oracle.ts'
// emit's result for a page, and @affordances/md's for the same page: the target is the same bytes (and title, url
@@ -460,7 +461,7 @@ describe('escaping by scan', () => {
const chars = [...ALPHABET, ...MORE]
test('random texts, every scope and edge', () => {
let checked = 0
- for (let round = 0; round < 20000; round++) {
+ for (let round = 0; round < Number(process.env.ESCAPE_FUZZ ?? 20000); round++) {
const scope = SCOPES[random(SCOPES.length)]!
const length = 1 + random(8)
let input = ''
@@ -482,3 +483,77 @@ describe('escaping by scan', () => {
expect(checked).toBeGreaterThan(10000)
})
})
+
+// the quick test that emphasis pairs as written must never pass what the full check rejects
+describe('emphasis pairing shortcut', () => {
+ let seed = 11
+ const random = (n: number) => {
+ seed = (seed * 1103515245 + 12345) % 2147483648
+ return seed % n
+ }
+ const TEXTS = [
+ 'a',
+ 'ab',
+ ' ',
+ ' a',
+ 'a ',
+ '.',
+ ',',
+ '(',
+ ')',
+ '*',
+ '_',
+ 'a.',
+ '.a',
+ '\\*',
+ '1',
+ 'é',
+ '😀',
+ '',
+ ]
+ const SEQUENCES = [
+ ['_', '*'],
+ ['**', '__'],
+ ['~~', '~'],
+ ]
+ const items = (depth: number): Item[] =>
+ Array.from({ length: 1 + random(4) }, (): Item =>
+ depth < 3 && random(3) === 0
+ ? { children: items(depth + 1), sequences: SEQUENCES[random(3)]! }
+ : TEXTS[random(TEXTS.length)]!,
+ )
+ test('random runs of text and emphasis', () => {
+ const count = Number(process.env.ATTENTION_FUZZ ?? 20000)
+ for (let round = 0; round < count; round++) {
+ const list = items(0)
+ const before = TEXTS[random(TEXTS.length)]! || '\n'
+ const after = TEXTS[random(TEXTS.length)]! || '\n'
+ expect([JSON.stringify(list), before, after, attentionAgrees(list, before, after)]).toEqual([
+ JSON.stringify(list),
+ before,
+ after,
+ true,
+ ])
+ }
+ })
+})
+
+// the fast path's gate: with it and without it, the same markdown, for every case above, every page, and pages
+// generated from the shapes it takes and their near misses (test/emit-fuzz.ts runs many more of those)
+const withFast = (html: string, fast: boolean) =>
+ emit(oracle(document(html)), { url, fast } as Options).markdown
+describe('the fast path changes nothing', () => {
+ test.each(collected)('%s', (html) => expect(withFast(html, true)).toBe(withFast(html, false)))
+ test.each([...corpus, ...fixtures].map((page) => [page.name, page] as const))('%s', (_, page) => {
+ const fast = emit(oracle(page.html), { url: page.url, fast: true } as Options).markdown
+ expect(fast).toBe(emit(oracle(page.html), { url: page.url, fast: false } as Options).markdown)
+ })
+ test('generated pages', () => {
+ const next = generator(42)
+ for (let i = 0; i < Number(process.env.FAST_FUZZ ?? 3000); i++) {
+ const html = next()
+ const { fast, slow } = fuzzBoth(html)
+ expect([html, fast]).toEqual([html, slow])
+ }
+ })
+})
From 11cf77db7116c35ab2a7d16ea7bd4f447750f8dd Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 02:37:29 +0000
Subject: [PATCH 06/74] chore(md-core): the bench gives slow tools a second a
page, and the total without synthetic/200
--budget defaults to 1000 ms, and a last line gives md-core's and mdream's
totals without synthetic/200, which is nearly half of md-core's time. No
source change. Baseline on it: md-core 107 ms (parse 34.2, emit 70.8),
mdream 37.4; without synthetic/200, 59.1 and 25.4.
Co-Authored-By: Claude Opus 5.5
---
packages/md-core/bench/README.md | 5 +++--
packages/md-core/bench/run.ts | 12 +++++++++++-
2 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/packages/md-core/bench/README.md b/packages/md-core/bench/README.md
index f5f2578..6c5ebea 100644
--- a/packages/md-core/bench/README.md
+++ b/packages/md-core/bench/README.md
@@ -26,7 +26,7 @@ node bench/run.ts --json # machine-readable, nothing else on s
```
Other flags: `--runs` (timed runs per page, default 20), `--warmup` (default 3), `--budget` (ms a
-slow tool may spend on one page before it stops at 3 runs, default 300), `--no-gc`.
+slow tool may spend on one page before it stops at 3 runs, default 1000), `--no-gc`.
Tools: md-core, `@affordances/md`, mdream, turndown with the gfm plugin, node-html-markdown. When
`src/parse.ts` (`parse(html)`) and `src/emit.ts` (`emit(doc, options)`) exist, `md-core parse` and
@@ -40,7 +40,8 @@ Reading the output:
- `spread` is half the interquartile range, summed over pages, as a share of the total: a rough ± for
the total. A few percent is normal; more means the machine was busy, so rerun
- `runs` is the range of timed runs per page; slow tools stop early (see `--budget`)
-- the last line is md-core's total over mdream's on the same pages
+- the last lines are md-core's total over mdream's on the same pages, then both totals without
+ `synthetic/200`, which is nearly half of md-core's time
How it measures: one untimed pass over the corpus warms the jit. Then, page by page, each tool gets
a full gc, its warm-up runs and its timed runs back to back, so it's timed in its own steady state
diff --git a/packages/md-core/bench/run.ts b/packages/md-core/bench/run.ts
index 37a9538..0eba119 100644
--- a/packages/md-core/bench/run.ts
+++ b/packages/md-core/bench/run.ts
@@ -11,7 +11,7 @@ const { values } = parseArgs({
options: {
runs: { type: 'string', default: '20' },
warmup: { type: 'string', default: '3' },
- budget: { type: 'string', default: '300' },
+ budget: { type: 'string', default: '1000' },
tool: { type: 'string' },
page: { type: 'string' },
json: { type: 'boolean', default: false },
@@ -366,6 +366,16 @@ else {
console.log(
`\nmd-core / mdream: ${ratio.toFixed(2)}x (${ratio <= 1 ? `${(1 / ratio).toFixed(2)}x faster` : `${ratio.toFixed(2)}x slower`})`,
)
+ // synthetic/200 is a fifth of the corpus's bytes and nearly half of md-core's time: the total without it too
+ const without = (t: ToolResult) =>
+ Object.entries(t.pages).reduce(
+ (s, [name, c]) => s + (name === 'synthetic/200' ? 0 : c.median),
+ 0,
+ )
+ if (core.pages['synthetic/200'] && mdream.pages['synthetic/200'])
+ console.log(
+ `without synthetic/200: md-core ${ms(without(core))}, mdream ${ms(without(mdream))} (${(without(core) / without(mdream)).toFixed(2)}x)`,
+ )
}
}
}
From 778542042f571fe078113279dc7639cb57417927 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 03:59:39 +0000
Subject: [PATCH 07/74] perf(md-core): a list of inline items and the lists in
them is written as it's read
A list at the top of a flow whose items are runs of inline content and the
lists between them (99% of the corpus's items) is read in one walk into a
small DList, each run written as its paragraph closes, and written as list(),
listItem(), containerFlow() and between() would: spread items, the line
endings in and between items, ordered starts, and the bullet rules (the other
bullet after a list, the empty-first-item chain three lists deep). Only the
top bullet is left to the serializer, which knows the list before it. Anything
else declines before a byte is kept, and the full emitter stays the oracle.
The gate's fuzz now generates nested, ordered and empty-item lists, clean or
noisy as a whole (1885 direct lists in 20k pages, 0 mismatches; 2x100k pages
clean), so its 3000-page test gets a 60 s timeout.
337 of the corpus's 364 lists. Bench: 107 -> 103 ms (emit 70.8 -> 66.0),
mdream 37.1; quick A/B over 8 alternations -2 to -3 ms. Parity unchanged.
Co-Authored-By: Claude Opus 5.5
---
packages/md-core/src/emit-convert.ts | 150 +++++++++++++++++++++++---
packages/md-core/src/emit-markdown.ts | 108 ++++++++++++++++++-
packages/md-core/test/emit-fuzz.ts | 73 +++++++++++--
packages/md-core/test/emit.test.ts | 3 +-
4 files changed, 313 insertions(+), 21 deletions(-)
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md-core/src/emit-convert.ts
index 6703e96..b31cae1 100644
--- a/packages/md-core/src/emit-convert.ts
+++ b/packages/md-core/src/emit-convert.ts
@@ -7,6 +7,9 @@ import {
HTML,
IMAGE,
INLINE_CODE,
+ directItems,
+ type DItem,
+ type DList,
isPhrasing,
renderBlock,
setext,
@@ -180,6 +183,7 @@ export const startConvert = (options: Options, page: string | undefined) => {
skips = new Set()
controls = 0
titledCode = undefined
+ nested = 0
before = undefined
after = undefined
mode = NORMAL
@@ -259,6 +263,18 @@ export const all = (parent: Element, out: Md[] = []): Md[] => {
(result = fastBlock(kid, kind)) !== DECLINED
) {
// written by the fast path (or nothing, for a paragraph with nothing in it)
+ } else if (
+ flow &&
+ fast &&
+ kind === LIST_TAG &&
+ nested === 0 &&
+ controls === 0 &&
+ !inTable &&
+ skips.size === 0 &&
+ mode === NORMAL &&
+ (result = directList(kid)) !== DECLINED
+ ) {
+ // a list of inline items and the lists in them, written as it's read
} else {
// a block the fast path declined starts again where it started: at a block's edge
if (block) before = true
@@ -403,8 +419,12 @@ const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined
return textNode('\u200B')
case STRONG_TAG:
return node(STRONG, all(el))
- case QUOTE:
- return node(BLOCKQUOTE, toFlow(all(el)))
+ case QUOTE: {
+ nested++
+ const quote = node(BLOCKQUOTE, toFlow(all(el)))
+ nested--
+ return quote
+ }
case LIST_TAG:
return list(el)
case ITEM:
@@ -731,23 +751,27 @@ const listItem = (el: Element) => {
const item = node(LIST_ITEM)
item.checked = box ? attr(box, 'checked') !== undefined : null
item.spread = spreadOut(el)
+ nested++
item.kids = toFlow(all(el))
+ nested--
return item
}
const list = (el: Element) => {
const result = node(LIST, specific(all(el), LIST_ITEM))
result.ordered = el.tag === 'ol'
- if (result.ordered) {
- const start = attr(el, 'start')
- // as hast reads it: a number when it is one, and 0 is no start
- const value =
- start !== undefined && start !== '' && !Number.isNaN(Number(start)) ? Number(start) : start
- result.depth = value ? Number.parseInt(String(value), 10) : 1
- }
+ if (result.ordered) result.depth = startOf(el)
result.spread = result.kids.length > 1 && result.kids.some((item) => item.spread)
return result
}
+// an ordered list's first number, as hast reads its start: a number when it is one, and 0 is no start
+const startOf = (el: Element) => {
+ const start = attr(el, 'start')
+ const value =
+ start !== undefined && start !== '' && !Number.isNaN(Number(start)) ? Number(start) : start
+ return value ? Number.parseInt(String(value), 10) : 1
+}
+
// **term**: definition, one paragraph per pair
const FLOW_TYPES = new Set([PARAGRAPH, HEADING, LIST, BLOCKQUOTE, CODE, TABLE, THEMATIC_BREAK])
const says = (item: Md): boolean =>
@@ -1228,7 +1252,7 @@ const FLOWS = new Set([
])
const DECLINED = null as unknown as Md
// how the fast path fared, for the reports: blocks written, and declined by the tag that stopped them
-export const fastStats = { taken: 0, declined: new Map() }
+export const fastStats = { taken: 0, lists: 0, declined: new Map() }
const decline = (why: string) => {
fastStats.declined.set(why, (fastStats.declined.get(why) ?? 0) + 1)
return false
@@ -1272,14 +1296,25 @@ export const materialize = (block: Md): Md => {
after = true
mode = NORMAL
const el = block.el
- const made = one(el, el.tag === 'p' ? PARAGRAPH_TAG : HEADING_TAG, el.up ?? el)
+ const made = one(el, (INFO.get(el.tag) ?? 0) & KIND_MASK, el.up ?? el)
fast = savedFast
return made instanceof Md ? made : block
}
// an element's inline children into out, as all() converts them, or false at the first thing it doesn't know
const fastInline = (parent: Element, heading: Element, out: Md[]): boolean => {
const kids = kidsOf(parent)
- for (let i = 0; i < kids.length; i++) {
+ return fastRun(kids, 0, kids.length, parent, heading, out)
+}
+// the same for kids[from, to), with what comes after them read as all() would (a list after a run of an item's text)
+const fastRun = (
+ kids: Node[],
+ from: number,
+ to: number,
+ parent: Element,
+ heading: Element,
+ out: Md[],
+): boolean => {
+ for (let i = from; i < to; i++) {
const kid = kids[i]!
if (typeof kid === 'string') {
const value = minified(kid, kids, i)
@@ -1361,3 +1396,94 @@ const fastLink = (el: Element, inHeading: boolean, out: Md[]): boolean => {
out.push(result)
return true
}
+
+// how deep in list items and blockquotes the walk is: a list at the top of a flow (0) is written on its own, since
+// its bullet depends only on whether a list came right before it
+let nested = 0
+// the direct path for a list: items of inline content and the lists in them, read in one walk into a DList (each
+// paragraph written as its run of text closes) and written by directItems, as list() and listItem() would convert
+// them and the serializer write them. anything else declines it before anything is kept
+const directList = (el: Element): Md | undefined => {
+ const savedBefore = before
+ const savedAfter = after
+ const read = readList(el)
+ // a first item that opens with a list reads the bullet of the list before this one: the slow way
+ const first = read?.items[0]
+ if (!read || (first!.blocks.length !== 0 && typeof first!.blocks[0] !== 'string')) {
+ before = savedBefore
+ after = savedAfter
+ decline(read ? 'list first in its first item' : 'list')
+ return DECLINED
+ }
+ before = true
+ after = savedAfter
+ const result = node(LIST)
+ result.ordered = read.ordered
+ result.depth = read.start
+ result.spread = read.spread
+ result.raw = directItems(read).join('\0')
+ result.el = el
+ fastStats.taken++
+ fastStats.lists++
+ return result
+}
+const readList = (el: Element): DList | null => {
+ if (el.flags & FLAG['data-mdast']) return null
+ const kids = kidsOf(el)
+ const items: DItem[] = []
+ for (let i = 0; i < kids.length; i++) {
+ const kid = kids[i]!
+ // whitespace between items is nothing; anything else moves into an item, the slow way
+ if (typeof kid === 'string') {
+ if (!blank(kid)) return null
+ continue
+ }
+ if (kid.tag !== 'li' || kid.flags & FLAG['data-mdast']) return null
+ const item = readItem(kid)
+ if (!item) return null
+ items.push(item)
+ }
+ if (!items.length) return null
+ const ordered = el.tag === 'ol'
+ let spread = false
+ if (items.length > 1) for (let i = 0; i < items.length && !spread; i++) spread = items[i]!.spread
+ return { ordered, start: ordered ? startOf(el) : 0, spread, items }
+}
+// an item: runs of inline content, each a paragraph, and the lists between them. an item is a block, so what's in it
+// starts and ends at its edges, and so does each list in it
+const readItem = (li: Element): DItem | null => {
+ before = true
+ after = true
+ const kids = kidsOf(li)
+ const blocks: (string | DList)[] = []
+ let from = 0
+ for (let i = 0; i <= kids.length; i++) {
+ const kid = kids[i]
+ const isList =
+ kid !== undefined &&
+ typeof kid !== 'string' &&
+ (kid.tag === 'ul' || kid.tag === 'ol' || kid.tag === 'dir')
+ if (i < kids.length && !isList) continue
+ if (from < i) {
+ const out: Md[] = []
+ if (!fastRun(kids, from, i, li, li, out)) return null
+ // toFlow: a run of whitespace alone is no paragraph
+ for (let k = 0; k < out.length; k++) {
+ const part = out[k]!
+ if (part.type !== TEXT || !whitespaceOnly(part.value)) {
+ blocks.push(renderBlock(node(PARAGRAPH, dropBreaks(out))))
+ break
+ }
+ }
+ }
+ if (isList) {
+ const inner = readList(kid as Element)
+ if (!inner) return null
+ blocks.push(inner)
+ before = true
+ after = true
+ }
+ from = i + 1
+ }
+ return { spread: spreadOut(li), blocks }
+}
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md-core/src/emit-markdown.ts
index e178fa6..395534a 100644
--- a/packages/md-core/src/emit-markdown.ts
+++ b/packages/md-core/src/emit-markdown.ts
@@ -1269,7 +1269,7 @@ const handle = (node: Md, parent: Md | undefined, before: string, after: string)
return value
}
case LIST:
- return list(node, parent)
+ return node.raw !== null ? directListText(node, parent) : list(node, parent)
case LIST_ITEM:
return listItem(node, parent)
case CODE:
@@ -1376,6 +1376,112 @@ const list = (node: Md, parent: Md | undefined) => {
return value
}
+// a list the direct path read (emit-convert's directList): its items and the lists in them, written as list(),
+// listItem(), containerFlow() and between() write a tight or loose list of paragraphs. a paragraph is its markdown
+export type DList = { ordered: boolean; start: number; spread: boolean; items: DItem[] }
+export type DItem = { spread: boolean; blocks: (string | DList)[] }
+// bulletLastUsed, as it is while a direct list's items are written
+let lastUsed: string | undefined
+// each item of a list at the top of a flow, written: its own bullet is the serializer's, once it knows what's before
+// it. a first item opening with a list never gets here, so what came before the list matters to nothing in it
+export const directItems = (top: DList): string[] => {
+ const items: string[] = []
+ for (let i = 0; i < top.items.length; i++) {
+ lastUsed = undefined
+ items.push(itemText(top.items[i]!, 1, i, true))
+ }
+ return items
+}
+// an item's blocks and the line endings between them, as containerFlow() writes a list item's
+const itemText = (item: DItem, level: number, index: number, listFirst: boolean): string => {
+ const blocks = item.blocks
+ let value = ''
+ for (let k = 0; k < blocks.length; k++) {
+ const block = blocks[k]!
+ if (typeof block === 'string') {
+ value += block
+ lastUsed = undefined
+ } else
+ value += listText(
+ block,
+ level + 1,
+ k === 0,
+ level + 1 >= 3 &&
+ k === 0 &&
+ index === 0 &&
+ listFirst &&
+ block.items[0]!.blocks.length === 0,
+ )
+ if (k < blocks.length - 1) value += itemBetween(item, block, blocks[k + 1]!)
+ }
+ return value
+}
+// a list in an item, as list() writes it: the other bullet after a list right before it, or when it's the first of
+// three lists each opening the one before with an empty item (the stack and index test there)
+const listText = (nest: DList, level: number, first: boolean, emptyChain: boolean): string => {
+ let bullet = nest.ordered ? '.' : '-'
+ if (lastUsed ? bullet === lastUsed : false) bullet = nest.ordered ? ')' : '*'
+ else if (!nest.ordered && emptyChain) bullet = '*'
+ let value = ''
+ for (let i = 0; i < nest.items.length; i++) {
+ const marker = nest.ordered ? (nest.start > -1 ? nest.start : 1) + i + bullet : bullet
+ value += bulleted(itemText(nest.items[i]!, level, i, first), marker)
+ lastUsed = undefined
+ if (i < nest.items.length - 1) value += nest.spread ? '\n\n' : '\n'
+ }
+ lastUsed = bullet
+ return value
+}
+// between() for two blocks in an item
+const itemBetween = (item: DItem, left: string | DList, right: string | DList) => {
+ if (item.spread) return '\n\n'
+ if (
+ typeof left === 'string' &&
+ typeof right !== 'string' &&
+ ((right.ordered && right.start !== 1) || right.items[0]!.blocks.length === 0)
+ )
+ return '\n\n'
+ // what left ends with, down through the lists in it
+ let tail: string | DList | DItem = left
+ while (typeof tail !== 'string') {
+ if ('items' in tail) tail = tail.items[tail.items.length - 1]!
+ else if (tail.blocks.length) tail = tail.blocks[tail.blocks.length - 1]!
+ else return '\n'
+ }
+ return typeof right === 'string' ? '\n\n' : '\n'
+}
+// an item's text under its bullet, as listItem()'s indentLines: the bullet on the first line, the rest padded
+// under it, blank lines left blank
+const bulleted = (content: string, marker: string) => {
+ if (content === '') return marker
+ if (content.indexOf('\n') < 0 && content.indexOf('\r') < 0) return marker + ' ' + content
+ const pad = ' '.repeat(marker.length + 1)
+ return indentLines(content, (line, index, blank) =>
+ index ? (blank ? '' : pad) + line : (blank ? marker : marker + ' ') + line,
+ )
+}
+// the top list, once its bullet is known: the other one after a list right before it in the same flow
+const directListText = (node: Md, parent: Md | undefined) => {
+ const bullet = node.ordered
+ ? parent && bulletLastUsed === '.'
+ ? ')'
+ : '.'
+ : parent && bulletLastUsed === '-'
+ ? '*'
+ : '-'
+ const items = node.raw!.split('\0')
+ let value = ''
+ for (let i = 0; i < items.length; i++) {
+ if (i) value += node.spread ? '\n\n' : '\n'
+ value += bulleted(
+ items[i]!,
+ node.ordered ? (node.depth > -1 ? node.depth : 1) + i + bullet : bullet,
+ )
+ }
+ bulletLastUsed = bullet
+ return value
+}
+
const listItem = (node: Md, parent: Md | undefined) => {
let bullet = bulletCurrent || '-'
if (parent && parent.type === LIST && parent.ordered)
diff --git a/packages/md-core/test/emit-fuzz.ts b/packages/md-core/test/emit-fuzz.ts
index 9bbd71f..c9ceb25 100644
--- a/packages/md-core/test/emit-fuzz.ts
+++ b/packages/md-core/test/emit-fuzz.ts
@@ -75,28 +75,32 @@ export const generator = (seed: number) => {
'',
'',
]
- const inline = (depth: number): string => {
+ // plain: without the near misses, so what holds it (a list) is mostly taken
+ const inline = (depth: number, plain = false): string => {
let out = ''
for (let i = random(5); i >= 0; i--) {
- const choice = depth > 2 ? 0 : random(14)
+ const choice = depth > 2 ? 0 : random(plain ? 7 : 14)
switch (choice) {
case 1:
- case 2:
- out += `<${pick(['strong', 'b', 'em', 'i'])}>${inline(depth + 1)}${pick(['strong', 'b', 'em', 'i'])}>`
+ case 2: {
+ // plain content closes what it opens: one left open carries into what follows (a list ends up inside it)
+ const open = pick(['strong', 'b', 'em', 'i'])
+ out += `<${open}>${inline(depth + 1, plain)}${plain ? open : pick(['strong', 'b', 'em', 'i'])}>`
break
+ }
case 3:
out += `${pick(['x', '`tick`', ' sp ', 'a|b', '', '``', text()])}`
break
case 4: {
const href = pick(HREFS)
- out += `${random(6) === 0 ? pick(['', ' ', href]) : inline(depth + 1)} `
+ out += `${random(6) === 0 ? pick(['', ' ', href]) : inline(depth + 1, plain)} `
break
}
case 5:
out += random(2) ? ' ' : ' '
break
case 6:
- out += `${pick(SPANS)}${inline(depth + 1)} `
+ out += `${pick(SPANS)}${inline(depth + 1, plain)} `
break
case 7:
// near misses: what the fast path declines
@@ -120,10 +124,65 @@ export const generator = (seed: number) => {
}
return out
}
+ // lists the direct path reads (inline items, the lists in them, ordered starts, empty items) and near misses
+ const BLANKS = [' ', ' ', '\n', '\t', ' \n ', '', '']
+ const START = [
+ '',
+ ' start="1"',
+ ' start="3"',
+ ' start="0"',
+ ' start="-2"',
+ ' start="x"',
+ ' start=""',
+ ]
+ // a clean list holds only what the direct path reads; a noisy one may hold anything that declines it
+ const list = (depth: number, clean = random(4) !== 0): string => {
+ const tag = pick(['ul', 'ul', 'ol', 'dir'])
+ let out = `<${tag}${tag === 'ol' ? pick(START) : ''}>`
+ for (let i = random(4); i >= 0; i--) {
+ // a no-break space between items is text in the list, which declines it
+ out += pick(clean ? BLANKS : SPACES) + ''
+ switch (depth > 2 ? random(3) : random(clean ? 8 : 9)) {
+ case 0:
+ break
+ case 1:
+ case 2:
+ out += inline(1, clean)
+ break
+ case 3:
+ case 4:
+ out += inline(1, clean) + pick(SPACES) + list(depth + 1, clean)
+ break
+ case 5:
+ out += list(depth + 1, clean) + inline(1, clean)
+ break
+ case 6:
+ out += inline(1, clean) + list(depth + 1, clean) + pick(SPACES) + list(depth + 1, clean)
+ break
+ case 7:
+ out +=
+ inline(1, clean) + list(depth + 1, clean) + inline(1, clean) + list(depth + 1, clean)
+ break
+ default:
+ // near misses: a paragraph, a block, a checkbox
+ out += pick([
+ `${inline(1, clean)}
`,
+ `${inline(1, clean)}
`,
+ ' x',
+ ])
+ }
+ out += ' '
+ }
+ return out + (clean || random(8) ? '' : 'stray') + `${tag}>`
+ }
const block = (): string => {
- switch (random(8)) {
+ switch (random(10)) {
case 0:
return `${inline(0)} `
+ case 8:
+ return list(0)
+ case 9:
+ return list(0) + pick(SPACES) + list(0)
case 1:
return ``
case 2:
diff --git a/packages/md-core/test/emit.test.ts b/packages/md-core/test/emit.test.ts
index 1ad14b9..e8f4002 100644
--- a/packages/md-core/test/emit.test.ts
+++ b/packages/md-core/test/emit.test.ts
@@ -555,5 +555,6 @@ describe('the fast path changes nothing', () => {
const { fast, slow } = fuzzBoth(html)
expect([html, fast]).toEqual([html, slow])
}
- })
+ // nested lists make the generated pages longer: about 13 s for the 3000
+ }, 60_000)
})
From ce62bbfd56b94d7b76fc1d6b1a0fc6c3f8613564 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:24:31 +0000
Subject: [PATCH 08/74] refactor(md): move md-core's converter and its tests
into md
md-core's src is now packages/md/src/convert/core and its converter tests
packages/md/test/convert/core: one copy of the source, in md, which nothing
in md calls yet. Only paths and imports change, but for one thing: the
corpus parse test is skipped as a whole describe when the corpus isn't
fetched, since md's vitest fails a file with an empty suite. packages/md-core
keeps the bench, parity and eval tools, importing the converter by relative
path, and loses its package export.
Co-Authored-By: Claude Opus 5.5
---
packages/md-core/bench/README.md | 4 ++--
packages/md-core/bench/parity.ts | 2 +-
packages/md-core/bench/run.ts | 6 +++---
packages/md-core/package.json | 5 +----
packages/md-core/test/emit-coverage.ts | 6 +++---
packages/md-core/test/emit-fresh.ts | 4 ++--
packages/md-core/test/emit-parity.ts | 13 ++++++------
packages/md-core/test/emit-phases.ts | 17 ++++++++-------
packages/md-core/test/parse-entities-gen.ts | 8 +++----
packages/md-core/test/parse-time.ts | 2 +-
.../src => md/src/convert/core}/attr.ts | 0
.../src/convert/core}/emit-convert.ts | 0
.../src/convert/core}/emit-markdown.ts | 0
.../src => md/src/convert/core}/emit-prune.ts | 0
.../src => md/src/convert/core}/emit.ts | 0
.../src/convert/core}/entities-table.ts | 2 +-
.../src => md/src/convert/core}/entities.ts | 0
.../src => md/src/convert/core}/index.ts | 0
.../src => md/src/convert/core}/parse.ts | 0
.../src => md/src/convert/core}/types.ts | 0
.../test/convert/core}/emit-fuzz.ts | 4 ++--
.../test/convert/core}/emit-pages.ts | 4 ++--
.../test/convert/core}/emit.test.ts | 15 ++++++++-----
.../test/convert/core}/parse-fuzz.ts | 0
.../test/convert/core}/parse-support.ts | 6 +++---
.../test/convert/core}/parse.test.ts | 21 ++++++++++++-------
.../test/convert/core}/support/oracle.ts | 2 +-
27 files changed, 65 insertions(+), 56 deletions(-)
rename packages/{md-core/src => md/src/convert/core}/attr.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/emit-convert.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/emit-markdown.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/emit-prune.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/emit.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/entities-table.ts (99%)
rename packages/{md-core/src => md/src/convert/core}/entities.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/index.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/parse.ts (100%)
rename packages/{md-core/src => md/src/convert/core}/types.ts (100%)
rename packages/{md-core/test => md/test/convert/core}/emit-fuzz.ts (98%)
rename packages/{md-core/test => md/test/convert/core}/emit-pages.ts (94%)
rename packages/{md-core/test => md/test/convert/core}/emit.test.ts (98%)
rename packages/{md-core/test => md/test/convert/core}/parse-fuzz.ts (100%)
rename packages/{md-core/test => md/test/convert/core}/parse-support.ts (86%)
rename packages/{md-core/test => md/test/convert/core}/parse.test.ts (96%)
rename packages/{md-core/test => md/test/convert/core}/support/oracle.ts (98%)
diff --git a/packages/md-core/bench/README.md b/packages/md-core/bench/README.md
index 6c5ebea..79fb9db 100644
--- a/packages/md-core/bench/README.md
+++ b/packages/md-core/bench/README.md
@@ -1,6 +1,6 @@
# md-core bench
-Speed and output parity for `@affordances/md-core`. Run everything from `packages/md-core`.
+Speed and output parity for `@affordances/md`'s single-pass converter, `packages/md/src/convert/core`. Run everything from `packages/md-core`.
| command | what it does |
| ---------------------- | -------------------------------------------------------------------------------------------------------- |
@@ -29,7 +29,7 @@ Other flags: `--runs` (timed runs per page, default 20), `--warmup` (default 3),
slow tool may spend on one page before it stops at 3 runs, default 1000), `--no-gc`.
Tools: md-core, `@affordances/md`, mdream, turndown with the gfm plugin, node-html-markdown. When
-`src/parse.ts` (`parse(html)`) and `src/emit.ts` (`emit(doc, options)`) exist, `md-core parse` and
+`packages/md/src/convert/core/parse.ts` (`parse(html)`) and `emit.ts` (`emit(doc, options)`) exist, `md-core parse` and
`md-core emit` time the two stages alone; emit runs on a tree parsed outside the clock.
Reading the output:
diff --git a/packages/md-core/bench/parity.ts b/packages/md-core/bench/parity.ts
index b48057a..aa7c421 100644
--- a/packages/md-core/bench/parity.ts
+++ b/packages/md-core/bench/parity.ts
@@ -24,7 +24,7 @@ type Convert = (
let core: Convert | undefined
let coreFailure = ''
try {
- core = (await import('../src/index.ts')).htmlToMarkdown
+ core = (await import('../../md/src/convert/core/index.ts')).htmlToMarkdown
} catch (error) {
coreFailure = `import failed: ${(error as Error).message.split('\n')[0]}`
}
diff --git a/packages/md-core/bench/run.ts b/packages/md-core/bench/run.ts
index 0eba119..0f331f1 100644
--- a/packages/md-core/bench/run.ts
+++ b/packages/md-core/bench/run.ts
@@ -50,7 +50,7 @@ const isNotImplemented = (error: unknown) =>
// md-core is imported dynamically: it's mid-rewrite and must not take the whole bench down
try {
- const core = await import('../src/index.ts')
+ const core = await import('../../md/src/convert/core/index.ts')
add({ name: 'md-core', setup: (html) => () => core.htmlToMarkdown(html, { url }).markdown })
} catch (error) {
add({ name: 'md-core', setup: () => () => '' }, `import failed: ${failure(error)}`)
@@ -70,8 +70,8 @@ const stage = async (file: string) => {
return undefined
}
}
-const parseMod = await stage('../src/parse.ts')
-const emitMod = await stage('../src/emit.ts')
+const parseMod = await stage('../../md/src/convert/core/parse.ts')
+const emitMod = await stage('../../md/src/convert/core/emit.ts')
const parse =
typeof parseMod?.parse === 'function' ? (parseMod.parse as (h: string) => unknown) : undefined
const emit =
diff --git a/packages/md-core/package.json b/packages/md-core/package.json
index c04f19e..94ccbdc 100644
--- a/packages/md-core/package.json
+++ b/packages/md-core/package.json
@@ -2,13 +2,10 @@
"name": "@affordances/md-core",
"version": "0.0.0",
"private": true,
- "description": "Experimental single-pass HTML to markdown converter for @affordances/md",
+ "description": "Bench, parity and eval tools for @affordances/md's single-pass converter",
"license": "MIT",
"type": "module",
"sideEffects": false,
- "exports": {
- ".": "./src/index.ts"
- },
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
diff --git a/packages/md-core/test/emit-coverage.ts b/packages/md-core/test/emit-coverage.ts
index a8a92f0..300acf7 100644
--- a/packages/md-core/test/emit-coverage.ts
+++ b/packages/md-core/test/emit-coverage.ts
@@ -1,9 +1,9 @@
// how many top-level paragraphs and headings each corpus page writes by the fast path, and why the rest declined:
// node test/emit-coverage.ts
import { loadCorpus } from '../bench/corpus.ts'
-import { emit } from '../src/emit.ts'
-import { fastStats } from '../src/emit-convert.ts'
-import { parse } from '../src/parse.ts'
+import { emit } from '../../md/src/convert/core/emit.ts'
+import { fastStats } from '../../md/src/convert/core/emit-convert.ts'
+import { parse } from '../../md/src/convert/core/parse.ts'
for (const page of loadCorpus()) {
fastStats.taken = 0
diff --git a/packages/md-core/test/emit-fresh.ts b/packages/md-core/test/emit-fresh.ts
index 560b81f..74e30eb 100644
--- a/packages/md-core/test/emit-fresh.ts
+++ b/packages/md-core/test/emit-fresh.ts
@@ -1,8 +1,8 @@
// emit on fresh trees, as bench/run.ts times it: a pool of parsed documents, each emitted once. prints, per page,
// the best of several pool medians (other work on the machine only ever adds time): node test/emit-fresh.ts [page]
import { loadCorpus } from '../bench/corpus.ts'
-import { emit } from '../src/emit.ts'
-import { parse } from '../src/parse.ts'
+import { emit } from '../../md/src/convert/core/emit.ts'
+import { parse } from '../../md/src/convert/core/parse.ts'
const want = process.argv[2]
const gc = (globalThis as { gc?: () => void }).gc
diff --git a/packages/md-core/test/emit-parity.ts b/packages/md-core/test/emit-parity.ts
index b786e23..0dd8229 100644
--- a/packages/md-core/test/emit-parity.ts
+++ b/packages/md-core/test/emit-parity.ts
@@ -4,10 +4,10 @@
// node test/emit-parity.ts --time emit-only time for the corpus (median of runs, warm)
import { writeFileSync } from 'node:fs'
import { htmlToMarkdown } from '@affordances/md'
-import { emit } from '../src/emit.ts'
-import type { Document } from '../src/types.ts'
-import { oracle } from './support/oracle.ts'
-import { corpusPages, fixturePages, similarity } from './emit-pages.ts'
+import { emit } from '../../md/src/convert/core/emit.ts'
+import type { Document } from '../../md/src/convert/core/types.ts'
+import { oracle } from '../../md/test/convert/core/support/oracle.ts'
+import { corpusPages, fixturePages, similarity } from '../../md/test/convert/core/emit-pages.ts'
// the first differing hunks, as a unified-ish listing
const hunks = (reference: string, ours: string, count = 6) => {
@@ -44,11 +44,12 @@ const hunks = (reference: string, ours: string, count = 6) => {
const median = (values: number[]) => values.toSorted((a, b) => a - b)[values.length >> 1]!
const args = process.argv.slice(2)
const parser = async (): Promise<(html: string) => Document> =>
- ((await import('../src/parse.ts')) as { parse: (html: string) => Document }).parse
+ ((await import('../../md/src/convert/core/parse.ts')) as { parse: (html: string) => Document })
+ .parse
const pages = [...corpusPages(), ...fixturePages()]
if (args[0] === '--time') {
// emit alone, over documents built once; --runs n, and per page with --pages
- // --parser: documents from src/parse.ts (while it's being written, it may not load), else the oracle's
+ // --parser: documents from md's src/convert/core/parse.ts (while it's being written, it may not load), else the oracle's
const build = args.includes('--parser') ? await parser() : oracle
const real = corpusPages()
let corpus = real.map((page) => ({ page, doc: build(page.html) }))
diff --git a/packages/md-core/test/emit-phases.ts b/packages/md-core/test/emit-phases.ts
index 65dc861..a4f552e 100644
--- a/packages/md-core/test/emit-phases.ts
+++ b/packages/md-core/test/emit-phases.ts
@@ -1,14 +1,15 @@
// where emit's time goes, phase by phase, over the corpus: node test/emit-phases.ts
-import { convertRoot, startConvert } from '../src/emit-convert.ts'
-import { toMarkdown } from '../src/emit-markdown.ts'
-import { begin, findMain, made, setPage } from '../src/emit-prune.ts'
-import type { Document } from '../src/types.ts'
-import { oracle } from './support/oracle.ts'
-import { corpusPages } from './emit-pages.ts'
+import { convertRoot, startConvert } from '../../md/src/convert/core/emit-convert.ts'
+import { toMarkdown } from '../../md/src/convert/core/emit-markdown.ts'
+import { begin, findMain, made, setPage } from '../../md/src/convert/core/emit-prune.ts'
+import type { Document } from '../../md/src/convert/core/types.ts'
+import { oracle } from '../../md/test/convert/core/support/oracle.ts'
+import { corpusPages } from '../../md/test/convert/core/emit-pages.ts'
-// --parser: documents from src/parse.ts, else the oracle's
+// --parser: documents from md's src/convert/core/parse.ts, else the oracle's
const build = process.argv.includes('--parser')
- ? ((await import('../src/parse.ts')) as { parse: (html: string) => Document }).parse
+ ? ((await import('../../md/src/convert/core/parse.ts')) as { parse: (html: string) => Document })
+ .parse
: oracle
const corpus = corpusPages().map((page) => ({ page, doc: build(page.html) }))
// per phase, the fastest whole-corpus run: other work on the machine only ever adds time
diff --git a/packages/md-core/test/parse-entities-gen.ts b/packages/md-core/test/parse-entities-gen.ts
index 045f5b3..2b0233b 100644
--- a/packages/md-core/test/parse-entities-gen.ts
+++ b/packages/md-core/test/parse-entities-gen.ts
@@ -1,6 +1,6 @@
-// writes src/entities-table.ts: every named character reference html knows, read out of the decode tree that parse5
+// writes md's src/convert/core/entities-table.ts: every named character reference html knows, read out of the decode tree that parse5
// itself decodes with (the entities package, parse5's dependency), so the table is the oracle's by construction. run
-// with `node test/parse-entities-gen.ts` from the package, then `oxfmt src/entities-table.ts`
+// with `node test/parse-entities-gen.ts` from the package, then `oxfmt ../md/src/convert/core/entities-table.ts`
import { writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
@@ -54,8 +54,8 @@ if (strict !== 2125 || table.length - strict !== 106)
const body = table.map(([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`)
writeFileSync(
- new URL('../src/entities-table.ts', import.meta.url),
- `// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
+ new URL('../../md/src/convert/core/entities-table.ts', import.meta.url),
+ `// generated by md-core's test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
// (decoded without a ';') also under their bare name. do not edit
export const ENTITIES: Record = {\n${body.join('\n')}\n}\n`,
)
diff --git a/packages/md-core/test/parse-time.ts b/packages/md-core/test/parse-time.ts
index b80b809..4267e2d 100644
--- a/packages/md-core/test/parse-time.ts
+++ b/packages/md-core/test/parse-time.ts
@@ -1,7 +1,7 @@
// times parse() over the corpus: `node test/parse-time.ts` from the package. each page is parsed warm and timed in
// turn with the others (so no page has the optimizer to itself), and the median of each is reported
import { existsSync, readdirSync, readFileSync } from 'node:fs'
-import { parse } from '../src/parse.ts'
+import { parse } from '../../md/src/convert/core/parse.ts'
const dir = new URL('../bench/corpus/.cache/', import.meta.url)
if (!existsSync(dir)) throw new Error('no corpus: run the bench fetch first')
diff --git a/packages/md-core/src/attr.ts b/packages/md/src/convert/core/attr.ts
similarity index 100%
rename from packages/md-core/src/attr.ts
rename to packages/md/src/convert/core/attr.ts
diff --git a/packages/md-core/src/emit-convert.ts b/packages/md/src/convert/core/emit-convert.ts
similarity index 100%
rename from packages/md-core/src/emit-convert.ts
rename to packages/md/src/convert/core/emit-convert.ts
diff --git a/packages/md-core/src/emit-markdown.ts b/packages/md/src/convert/core/emit-markdown.ts
similarity index 100%
rename from packages/md-core/src/emit-markdown.ts
rename to packages/md/src/convert/core/emit-markdown.ts
diff --git a/packages/md-core/src/emit-prune.ts b/packages/md/src/convert/core/emit-prune.ts
similarity index 100%
rename from packages/md-core/src/emit-prune.ts
rename to packages/md/src/convert/core/emit-prune.ts
diff --git a/packages/md-core/src/emit.ts b/packages/md/src/convert/core/emit.ts
similarity index 100%
rename from packages/md-core/src/emit.ts
rename to packages/md/src/convert/core/emit.ts
diff --git a/packages/md-core/src/entities-table.ts b/packages/md/src/convert/core/entities-table.ts
similarity index 99%
rename from packages/md-core/src/entities-table.ts
rename to packages/md/src/convert/core/entities-table.ts
index b4819e2..dae440a 100644
--- a/packages/md-core/src/entities-table.ts
+++ b/packages/md/src/convert/core/entities-table.ts
@@ -1,4 +1,4 @@
-// generated by test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
+// generated by md-core's test/parse-entities-gen.ts from parse5's decode tree: every named character reference, the legacy ones
// (decoded without a ';') also under their bare name. do not edit
export const ENTITIES: Record = {
AElig: 'Æ',
diff --git a/packages/md-core/src/entities.ts b/packages/md/src/convert/core/entities.ts
similarity index 100%
rename from packages/md-core/src/entities.ts
rename to packages/md/src/convert/core/entities.ts
diff --git a/packages/md-core/src/index.ts b/packages/md/src/convert/core/index.ts
similarity index 100%
rename from packages/md-core/src/index.ts
rename to packages/md/src/convert/core/index.ts
diff --git a/packages/md-core/src/parse.ts b/packages/md/src/convert/core/parse.ts
similarity index 100%
rename from packages/md-core/src/parse.ts
rename to packages/md/src/convert/core/parse.ts
diff --git a/packages/md-core/src/types.ts b/packages/md/src/convert/core/types.ts
similarity index 100%
rename from packages/md-core/src/types.ts
rename to packages/md/src/convert/core/types.ts
diff --git a/packages/md-core/test/emit-fuzz.ts b/packages/md/test/convert/core/emit-fuzz.ts
similarity index 98%
rename from packages/md-core/test/emit-fuzz.ts
rename to packages/md/test/convert/core/emit-fuzz.ts
index c9ceb25..83f1047 100644
--- a/packages/md-core/test/emit-fuzz.ts
+++ b/packages/md/test/convert/core/emit-fuzz.ts
@@ -1,8 +1,8 @@
// generated pages for the fast path's gate: the shapes it accepts and their near misses, seeded so a failure repeats.
// as a script, it runs many and stops at the first page whose markdown differs with the fast path on and off:
// node test/emit-fuzz.ts [count] [seed]
-import { emit } from '../src/emit.ts'
-import { parse } from '../src/parse.ts'
+import { emit } from '../../../src/convert/core/emit.ts'
+import { parse } from '../../../src/convert/core/parse.ts'
export const generator = (seed: number) => {
let state = seed >>> 0 || 1
diff --git a/packages/md-core/test/emit-pages.ts b/packages/md/test/convert/core/emit-pages.ts
similarity index 94%
rename from packages/md-core/test/emit-pages.ts
rename to packages/md/test/convert/core/emit-pages.ts
index b527e15..50904a0 100644
--- a/packages/md-core/test/emit-pages.ts
+++ b/packages/md/test/convert/core/emit-pages.ts
@@ -4,8 +4,8 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'
// @affordances/md's fixtures, each with the url it's converted against
export type Page = { name: string; html: string; url: string; corpus: boolean }
-const corpusDir = new URL('../bench/corpus/', import.meta.url)
-const fixturesDir = new URL('../../md/test/fixtures/', import.meta.url)
+const corpusDir = new URL('../../../../md-core/bench/corpus/', import.meta.url)
+const fixturesDir = new URL('../../fixtures/', import.meta.url)
export const corpusPages = (): Page[] => {
const cache = new URL('.cache/', corpusDir)
diff --git a/packages/md-core/test/emit.test.ts b/packages/md/test/convert/core/emit.test.ts
similarity index 98%
rename from packages/md-core/test/emit.test.ts
rename to packages/md/test/convert/core/emit.test.ts
index e8f4002..ec6ad53 100644
--- a/packages/md-core/test/emit.test.ts
+++ b/packages/md/test/convert/core/emit.test.ts
@@ -1,10 +1,15 @@
-import { htmlToMarkdown } from '@affordances/md'
+import { htmlToMarkdown } from '../../../src/index.ts'
import { describe, expect, test } from 'vitest'
-import { emit } from '../src/emit.ts'
-import { attentionAgrees, type Item, regexSafe, scannedSafe } from '../src/emit-markdown.ts'
-import type { Options, Result } from '../src/types.ts'
+import { emit } from '../../../src/convert/core/emit.ts'
+import {
+ attentionAgrees,
+ type Item,
+ regexSafe,
+ scannedSafe,
+} from '../../../src/convert/core/emit-markdown.ts'
+import type { Options, Result } from '../../../src/convert/core/types.ts'
import { corpusPages, fixturePages, type Page, similarity } from './emit-pages.ts'
-import { parse } from '../src/parse.ts'
+import { parse } from '../../../src/convert/core/parse.ts'
import { both as fuzzBoth, generator } from './emit-fuzz.ts'
import { oracle } from './support/oracle.ts'
diff --git a/packages/md-core/test/parse-fuzz.ts b/packages/md/test/convert/core/parse-fuzz.ts
similarity index 100%
rename from packages/md-core/test/parse-fuzz.ts
rename to packages/md/test/convert/core/parse-fuzz.ts
diff --git a/packages/md-core/test/parse-support.ts b/packages/md/test/convert/core/parse-support.ts
similarity index 86%
rename from packages/md-core/test/parse-support.ts
rename to packages/md/test/convert/core/parse-support.ts
index 977803a..c6d1739 100644
--- a/packages/md-core/test/parse-support.ts
+++ b/packages/md/test/convert/core/parse-support.ts
@@ -1,7 +1,7 @@
import { isDeepStrictEqual } from 'node:util'
-import { parseAttrs } from '../src/attr.ts'
-import { parse } from '../src/parse.ts'
-import type { Element } from '../src/types.ts'
+import { parseAttrs } from '../../../src/convert/core/attr.ts'
+import { parse } from '../../../src/convert/core/parse.ts'
+import type { Element } from '../../../src/convert/core/types.ts'
import { oracle, plain } from './support/oracle.ts'
const attrs = (el: Element) => Object.fromEntries(parseAttrs(el.attrs))
diff --git a/packages/md-core/test/parse.test.ts b/packages/md/test/convert/core/parse.test.ts
similarity index 96%
rename from packages/md-core/test/parse.test.ts
rename to packages/md/test/convert/core/parse.test.ts
index 835b1f0..801dd76 100644
--- a/packages/md-core/test/parse.test.ts
+++ b/packages/md/test/convert/core/parse.test.ts
@@ -1,9 +1,9 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { describe, expect, test } from 'vitest'
-import { attr, parseAttrs, scanAttr } from '../src/attr.ts'
-import { ENTITIES } from '../src/entities-table.ts'
-import { parse } from '../src/parse.ts'
-import { NEVER, type Element, type Node } from '../src/types.ts'
+import { attr, parseAttrs, scanAttr } from '../../../src/convert/core/attr.ts'
+import { ENTITIES } from '../../../src/convert/core/entities-table.ts'
+import { parse } from '../../../src/convert/core/parse.ts'
+import { NEVER, type Element, type Node } from '../../../src/convert/core/types.ts'
import { generate, KNOWN, ORACLE_THROWS } from './parse-fuzz.ts'
import { difference } from './parse-support.ts'
@@ -574,10 +574,15 @@ describe('character references, the whole table', () => {
})
})
-describe('the corpus pages', () => {
- const dir = new URL('../bench/corpus/.cache/', import.meta.url)
- const pages = existsSync(dir) ? readdirSync(dir).filter((file) => file.endsWith('.html')) : []
- test.skipIf(pages.length === 0).each(pages)('%s', (file) => {
+// the corpus is fetched, not committed: without it there's nothing to register
+const corpusDir = new URL('../../../../md-core/bench/corpus/.cache/', import.meta.url)
+const corpusFiles = existsSync(corpusDir)
+ ? readdirSync(corpusDir).filter((file) => file.endsWith('.html'))
+ : []
+describe.skipIf(corpusFiles.length === 0)('the corpus pages', () => {
+ const dir = corpusDir
+ const pages = corpusFiles
+ test.each(pages)('%s', (file) => {
const html = readFileSync(new URL(file, dir), 'utf8')
expect(difference(html)).toBeUndefined()
})
diff --git a/packages/md-core/test/support/oracle.ts b/packages/md/test/convert/core/support/oracle.ts
similarity index 98%
rename from packages/md-core/test/support/oracle.ts
rename to packages/md/test/convert/core/support/oracle.ts
index 56e2153..852c310 100644
--- a/packages/md-core/test/support/oracle.ts
+++ b/packages/md/test/convert/core/support/oracle.ts
@@ -6,7 +6,7 @@ import {
type Element,
type Head,
type Node,
-} from '../../src/types.ts'
+} from '../../../../src/convert/core/types.ts'
// the Document parse.ts must build, made the slow way: parse5 reads the page as a browser does, and this walks its
// tree into the contract's shape. the parser is tested against it, and the emitter can be written against it before
From 590a7f19e899beb88cb885aa4b8ab1041fc95cb7 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:28:42 +0000
Subject: [PATCH 09/74] feat(md): convert with md-core behind an internal
switch
readPage and readStreamed strip the flight data first, as before, then
hand the page to md-core unless the call has handlers or a function
extract, which need the tree. A page md-core can't write yet (markers,
flight data, streamed boundaries) is declined before anything is written,
counted by why, and the tree pipeline takes it; 'strict' throws instead,
for tests. The switch is a module-level setter in convert/path.ts, never
an option or env var, and the default stays the tree for now.
On core, each markdown() call parses the page again: md-core's emit
prunes the tree it's given in place.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/index.ts | 70 +++++++++++++++++++---
packages/md/src/convert/path.ts | 28 +++++++++
packages/md/test/convert/core/path.test.ts | 39 ++++++++++++
3 files changed, 128 insertions(+), 9 deletions(-)
create mode 100644 packages/md/src/convert/path.ts
create mode 100644 packages/md/test/convert/core/path.test.ts
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index d5d225a..9e5ec9a 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -22,6 +22,10 @@ import { decodeString } from 'micromark-util-decode-string'
import { normalizeIdentifier } from 'micromark-util-normalize-identifier'
import { visit } from 'unist-util-visit'
import { minifyWhitespace } from './whitespace.ts'
+import { emit as emitCore } from './core/emit.ts'
+import { parse as parseCore } from './core/parse.ts'
+import type { Options as CoreOptions } from './core/types.ts'
+import { declined, forcedPath } from './path.ts'
export type Handlers = Record
@@ -2323,6 +2327,8 @@ export const readPage = (html: string, options: Options = {}): Page => {
const strip = flightStripper()
const lean = strip.write(html) + strip.end()
const swapped = strip.swapped()
+ const core = coreTakes(options) ? readCore(lean, swapped, options) : undefined
+ if (core) return core
const { tree, streamed, reason } = strippedTree(lean, swapped)
if (!reason) {
streamed.resolve()
@@ -2338,6 +2344,8 @@ export const readPage = (html: string, options: Options = {}): Page => {
// trusted throw: the handler answers 502, and a caller that forgets to catch it fails closed too. not part of the
// package's api: only the handler, which did the stripping, says a page was
export const readStreamed = (html: string, swapped: Swapped, options: Options = {}): Page => {
+ const core = coreTakes(options) ? readCore(html, swapped, options) : undefined
+ if (core) return core
const { tree, streamed, reason } = strippedTree(html, swapped)
if (reason) throw new FlightDataError(reason)
streamed.resolve()
@@ -2349,8 +2357,6 @@ const readTree = (
options: Options,
): Page => {
const meta = head(tree, options.url)
- // a redirect() or notFound() next streamed into the page: the first error row that's one of next's control flow
- const control = errors.map(fromDigest).find((said) => said !== undefined)
const content = contentOf(tree, options.extract)
// a name rendered twice fills neither copy: one of them may be a forgery in user content, and there's no telling which
const markers = slotMarkers(content)
@@ -2369,13 +2375,7 @@ const readTree = (
unique: names.flatMap(([name, count]) => (count === 1 ? [name] : [])),
duplicate: names.flatMap(([name, count]) => (count > 1 ? [name] : [])),
},
- errors,
- ...(control &&
- ('location' in control
- ? (control.status === 307 || control.status === 308) && {
- redirect: { status: control.status, location: control.location },
- }
- : { fallback: control })),
+ ...controlOf(errors),
// the page itself is left as it is, so it can be converted again with other fills
markdown: (slots) => {
const fillOf = (node: Element) => {
@@ -2407,6 +2407,58 @@ const readTree = (
}
}
+// the page's error rows, and the first that's one of next's control flow: a redirect() or notFound() next streamed
+// into the page
+const controlOf = (errors: string[]): Pick => {
+ const control = errors.map(fromDigest).find((said) => said !== undefined)
+ return {
+ errors,
+ ...(control &&
+ ('location' in control
+ ? (control.status === 307 || control.status === 308) && {
+ redirect: { status: control.status, location: control.location },
+ }
+ : { fallback: control })),
+ }
+}
+
+// md-core converts a page unless the call needs a tree (handlers convert hast; a function extract is given one), or
+// the switch says otherwise. until md-core is the default, only the switch sends a page to it
+const coreTakes = (options: Options) => {
+ const path = forcedPath()
+ return (
+ (path === 'core' || path === 'strict') &&
+ !options.handlers &&
+ typeof options.extract !== 'function'
+ )
+}
+
+// what md-core can't write yet as the tree pipeline does: a page with any of it is declined, before it's converted
+const NOT_YET: [why: string, test: (html: string, swapped: Swapped) => boolean][] = [
+ ['marker', (html) => / swapped.count > 0 || swapped.unreadable || PUSHED_ANYWHERE.test(html),
+ ],
+ ['streamed', (html) => /\$R[CRS]\(|data-r[crs]i/i.test(html)],
+]
+const PUSHED_ANYWHERE = /self\.__next_f/
+
+// the page as md-core reads it, or undefined when it declines (the tree pipeline takes it instead)
+const readCore = (html: string, swapped: Swapped, options: Options): Page | undefined => {
+ for (const [why, test] of NOT_YET)
+ if (test(html, swapped)) {
+ declined(why)
+ return undefined
+ }
+ return {
+ slots: { unique: [], duplicate: [] },
+ ...controlOf(swapped.errors),
+ // each call parses the page again: md-core's emit prunes the tree it's given in place
+ markdown: () => emitCore(parseCore(html), options as CoreOptions),
+ }
+}
+
// a tree as hast-util-to-mdast converts it, without what it does first: a structured clone of all it's given, so its
// whitespace pass can change it, then that pass. it does both to an empty root instead, whose handler converts this
// copy: only what the whitespace pass changes (children, a text's value) is new, and a node's place in the html, which
diff --git a/packages/md/src/convert/path.ts b/packages/md/src/convert/path.ts
new file mode 100644
index 0000000..832b8ab
--- /dev/null
+++ b/packages/md/src/convert/path.ts
@@ -0,0 +1,28 @@
+// which converter a page takes. md-core (./core) by default; the tree pipeline (hast) for custom handlers and a
+// function extract, and for any page md-core declines, before it writes anything. internal: for the tests and the
+// bench, never an option or an environment variable a deployment could set
+export type Path = 'hast' | 'core' | 'strict'
+
+// 'core' converts as the default does; 'strict' does too, but a decline throws instead of taking the tree pipeline
+let forced: Path | undefined
+export const forcePath = (path: Path | undefined) => {
+ forced = path
+}
+export const forcedPath = () => forced
+
+// how many pages md-core declined, by why, since the last reset
+export const declines = new Map()
+
+// md-core can't write this page as the tree pipeline would
+export class Declined extends Error {
+ readonly why: string
+ constructor(why: string) {
+ super(`md-core declined the page (${why})`)
+ this.name = 'Declined'
+ this.why = why
+ }
+}
+export const declined = (why: string) => {
+ declines.set(why, (declines.get(why) ?? 0) + 1)
+ if (forced === 'strict') throw new Declined(why)
+}
diff --git a/packages/md/test/convert/core/path.test.ts b/packages/md/test/convert/core/path.test.ts
new file mode 100644
index 0000000..9f085f7
--- /dev/null
+++ b/packages/md/test/convert/core/path.test.ts
@@ -0,0 +1,39 @@
+import { afterEach, expect, test } from 'vitest'
+import { htmlToMarkdown, readPage } from '../../../src/index.ts'
+import { declines, forcePath } from '../../../src/convert/path.ts'
+
+afterEach(() => {
+ forcePath(undefined)
+ declines.clear()
+})
+
+const page = 'Hi Some text .
'
+
+test('md-core and the tree pipeline write the same markdown for a page both can convert', () => {
+ const tree = htmlToMarkdown(page, { url: 'https://shop.test/page' })
+ forcePath('strict')
+ expect(htmlToMarkdown(page, { url: 'https://shop.test/page' })).toEqual(tree)
+ expect(declines.size).toBe(0)
+})
+
+test('handlers and a function extract take the tree pipeline, without a decline', () => {
+ forcePath('strict')
+ const custom = htmlToMarkdown(page, {
+ handlers: { em: () => ({ type: 'text', value: 'custom' }) },
+ })
+ expect(custom.markdown).toContain('Some custom.')
+ const extracted = htmlToMarkdown(page, { extract: (tree) => tree })
+ expect(extracted.markdown).toContain('# Hi')
+ expect(declines.size).toBe(0)
+})
+
+test('a page md-core declines is counted, and the tree pipeline writes it; strict throws instead', () => {
+ const marked =
+ 'skip
kept
'
+ const tree = htmlToMarkdown(marked)
+ forcePath('core')
+ expect(htmlToMarkdown(marked)).toEqual(tree)
+ expect(declines.get('marker')).toBe(1)
+ forcePath('strict')
+ expect(() => readPage(marked)).toThrow(/md-core declined the page \(marker\)/)
+})
From 6c9a499583d029691e34f15b00d5c06bc8010736 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:34:56 +0000
Subject: [PATCH 10/74] feat(md): the flight trust check on md-core's path
md-core's parser now keeps every script element's own text, in any
namespace (svg and math too, where it keeps nothing else), leaving out a
template's content and a body a frameset removed: what the tree pipeline
reads in parse5's tree. untrusted() takes those texts, so both paths run
the same check: readStreamed throws FlightDataError, and readPage re-reads
the page as sent with an error of its own, on md-core.
Keeping the scripts' text costs parse about 1.9 ms over the bench corpus
(32.5 to 34.4 ms). A test holds the script texts to parse5's over the
fixtures, the corpus, cases and 6000 generated pages; another reads every
fixture and push attack on both paths and compares rows, redirect,
fallback and throws.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/parse.ts | 28 ++++--
packages/md/src/convert/core/types.ts | 3 +
packages/md/src/convert/index.ts | 48 +++++++----
packages/md/test/convert/core/flight.test.ts | 86 +++++++++++++++++++
packages/md/test/convert/core/scripts.test.ts | 69 +++++++++++++++
.../md/test/convert/core/support/oracle.ts | 3 +-
6 files changed, 213 insertions(+), 24 deletions(-)
create mode 100644 packages/md/test/convert/core/flight.test.ts
create mode 100644 packages/md/test/convert/core/scripts.test.ts
diff --git a/packages/md/src/convert/core/parse.ts b/packages/md/src/convert/core/parse.ts
index 0e2a2e2..ee0f0c1 100644
--- a/packages/md/src/convert/core/parse.ts
+++ b/packages/md/src/convert/core/parse.ts
@@ -290,6 +290,8 @@ let pending: string[] = []
let pendingText = false
let watched: El[] = []
let mains: El[] = []
+// every script element, in any namespace: the flight check reads each one's text
+let scripts: El[] = []
// the elements with a dropped child among their kids, to take out at the end
let pruned = new Set()
// whether a node was put anywhere but after everything before it: then the Head's elements are sorted into tree order
@@ -353,10 +355,10 @@ const make = (name: string, id: number, ns: number, attrs: string, flags: number
// the Head's elements; of the scripts and links, only those that could be json-ld or the canonical link
if (WATCH[id]) {
if (id === SCRIPT) {
- if (maybe(attrs, 'ld+json') && attr(el, 'type') === 'application/ld+json') {
- watched.push(el)
- keepAll(el)
- }
+ // its text is kept, even inside svg, so it can be checked
+ scripts.push(el)
+ keepAll(el)
+ if (maybe(attrs, 'ld+json') && attr(el, 'type') === 'application/ld+json') watched.push(el)
} else if (id !== LINK || maybe(attrs, 'canonical')) {
watched.push(el)
// a foreign title is read by all the text inside it, even what is in a dropped element
@@ -2978,6 +2980,19 @@ const readHead = (): Head => {
return head
}
+// each script's own text (its text children, not what's in an element inside it, which svg allows), for the scripts
+// in the document: not in a template's content, or a body a frameset threw out
+const readScripts = (): string[] =>
+ scripts.flatMap((el) => {
+ let top: El = el
+ for (let up = el.up; up; top = up, up = up.up)
+ if (up.id === TEMPLATE && up.ns === HTML) return []
+ if (top !== doc) return []
+ let text = ''
+ for (const kid of el.kids) if (typeof kid === 'string') text += kid
+ return [text]
+ })
+
// the mains in the root's tree (under it, and in nothing dropped), in tree order
const readMains = (root: El) => {
const found: El[] = []
@@ -3015,6 +3030,7 @@ export const parse = (input: string): Document => {
pendingText = false
watched = []
mains = []
+ scripts = []
pruned.clear()
reordered = false
tok = 0
@@ -3024,6 +3040,7 @@ export const parse = (input: string): Document => {
tokenize()
onEof()
const head = readHead()
+ const scriptTexts = readScripts()
// the dropped elements leave the tree, and the text either side of one is one text
for (const el of pruned) {
const kids: Node[] = []
@@ -3035,7 +3052,7 @@ export const parse = (input: string): Document => {
el.kids = kids
}
const root = bodyEl && !bodyGone ? bodyEl : doc
- const document: Document = { root, head, mains: readMains(root) }
+ const document: Document = { root, head, mains: readMains(root), scripts: scriptTexts }
root.tag = '#root'
root.up = null
// let the page go: the tree holds slices of it, not the parse's state
@@ -3045,6 +3062,7 @@ export const parse = (input: string): Document => {
afe = []
watched = []
mains = []
+ scripts = []
pruned.clear()
pending = []
current = doc = headEl = formEl = htmlEl = bodyEl = null as unknown as El
diff --git a/packages/md/src/convert/core/types.ts b/packages/md/src/convert/core/types.ts
index 2478c0a..85af0e1 100644
--- a/packages/md/src/convert/core/types.ts
+++ b/packages/md/src/convert/core/types.ts
@@ -71,6 +71,9 @@ export interface Document {
// every and every element whose role attribute is exactly 'main', in tree order, wherever it is in the
// root's tree (hidden or not: the emitter decides which one counts)
mains: Element[]
+ // the own text of every script element in the document, any namespace, in no particular order: what the flight
+ // check reads, as it would read each script in parse5's tree
+ scripts: string[]
}
// what the parser never builds, with everything inside: never content, whatever the page says. the same set as
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index 9e5ec9a..2cf0e2a 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -24,7 +24,7 @@ import { visit } from 'unist-util-visit'
import { minifyWhitespace } from './whitespace.ts'
import { emit as emitCore } from './core/emit.ts'
import { parse as parseCore } from './core/parse.ts'
-import type { Options as CoreOptions } from './core/types.ts'
+import type { Document as CoreDocument, Options as CoreOptions } from './core/types.ts'
import { declined, forcedPath } from './path.ts'
export type Handlers = Record
@@ -1053,10 +1053,9 @@ export class FlightDataError extends Error {
// a script's own text: an svg script can hold elements, and another script's text isn't its own
const scriptText = (script: Element) =>
script.children.map((child) => (child.type === 'text' ? child.value : '')).join('')
-const untrusted = (scripts: Element[], swapped: Swapped): FlightDataError['reason'] | undefined => {
+const untrusted = (scripts: string[], swapped: Swapped): FlightDataError['reason'] | undefined => {
let count = 0
- for (const script of scripts) {
- const text = scriptText(script)
+ for (const text of scripts) {
if (text === swapped.nonce) count += 1
else if (PUSHED.test(text)) return 'unswapped'
}
@@ -1191,7 +1190,7 @@ const fromHtml = (html: string) =>
const strippedTree = (html: string, swapped: Swapped) => {
const tree = fromHtml(html)
const streamed = resolveStreamed(tree)
- const reason = untrusted(streamed.scripts, swapped)
+ const reason = untrusted(streamed.scripts.map(scriptText), swapped)
return { tree, streamed, reason }
}
@@ -2327,8 +2326,13 @@ export const readPage = (html: string, options: Options = {}): Page => {
const strip = flightStripper()
const lean = strip.write(html) + strip.end()
const swapped = strip.swapped()
- const core = coreTakes(options) ? readCore(lean, swapped, options) : undefined
- if (core) return core
+ if (coreTakes(options)) {
+ const core = readCore(lean, swapped, options)
+ if (core && !core.reason) return core.page
+ // swaps that can't be trusted: the page as sent, as md-core reads it, and an error of its own
+ const sent = core && readCore(html, { ...swapped, errors: [''] }, options)
+ if (sent) return sent.page
+ }
const { tree, streamed, reason } = strippedTree(lean, swapped)
if (!reason) {
streamed.resolve()
@@ -2345,7 +2349,8 @@ export const readPage = (html: string, options: Options = {}): Page => {
// package's api: only the handler, which did the stripping, says a page was
export const readStreamed = (html: string, swapped: Swapped, options: Options = {}): Page => {
const core = coreTakes(options) ? readCore(html, swapped, options) : undefined
- if (core) return core
+ if (core?.reason) throw new FlightDataError(core.reason)
+ if (core) return core.page
const { tree, streamed, reason } = strippedTree(html, swapped)
if (reason) throw new FlightDataError(reason)
streamed.resolve()
@@ -2436,27 +2441,34 @@ const coreTakes = (options: Options) => {
// what md-core can't write yet as the tree pipeline does: a page with any of it is declined, before it's converted
const NOT_YET: [why: string, test: (html: string, swapped: Swapped) => boolean][] = [
['marker', (html) => / swapped.count > 0 || swapped.unreadable || PUSHED_ANYWHERE.test(html),
- ],
['streamed', (html) => /\$R[CRS]\(|data-r[crs]i/i.test(html)],
]
-const PUSHED_ANYWHERE = /self\.__next_f/
-// the page as md-core reads it, or undefined when it declines (the tree pipeline takes it instead)
-const readCore = (html: string, swapped: Swapped, options: Options): Page | undefined => {
+// the page as md-core reads it, and whether its flight swaps can be trusted, as the tree pipeline checks them: every
+// script's own text, where parse5 puts it. undefined when md-core declines (the tree pipeline takes it instead)
+const readCore = (
+ html: string,
+ swapped: Swapped,
+ options: Options,
+): { page: Page; reason: FlightDataError['reason'] | undefined } | undefined => {
for (const [why, test] of NOT_YET)
if (test(html, swapped)) {
declined(why)
return undefined
}
- return {
+ // the first call converts the tree read here; md-core's emit prunes a tree in place, so another parses again
+ let doc: CoreDocument | undefined = parseCore(html)
+ const reason = untrusted(doc.scripts, swapped)
+ const page: Page = {
slots: { unique: [], duplicate: [] },
...controlOf(swapped.errors),
- // each call parses the page again: md-core's emit prunes the tree it's given in place
- markdown: () => emitCore(parseCore(html), options as CoreOptions),
+ markdown: () => {
+ const tree = doc ?? parseCore(html)
+ doc = undefined
+ return emitCore(tree, options as CoreOptions)
+ },
}
+ return { page, reason }
}
// a tree as hast-util-to-mdast converts it, without what it does first: a structured clone of all it's given, so its
diff --git a/packages/md/test/convert/core/flight.test.ts b/packages/md/test/convert/core/flight.test.ts
new file mode 100644
index 0000000..0821694
--- /dev/null
+++ b/packages/md/test/convert/core/flight.test.ts
@@ -0,0 +1,86 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import { afterEach, expect, test } from 'vitest'
+import { flightStripper, readPage, readStreamed } from '../../../src/convert/index.ts'
+import { Declined, forcePath } from '../../../src/convert/path.ts'
+
+afterEach(() => forcePath(undefined))
+
+const dir = new URL('../../fixtures/', import.meta.url)
+const fixtures = readdirSync(dir)
+ .filter((file) => file.endsWith('.html'))
+ .map((file) => [file, readFileSync(new URL(file, dir), 'utf8')] as const)
+
+const push = (row: string) => ``
+const body = (content: string, flight: string) =>
+ `Hi ${content} ${flight}`
+const attacks: [string, string][] = [
+ [
+ 'a push in an attribute',
+ body(
+ `
`,
+ push('6:E{"digest":"NEXT_HTTP_ERROR_FALLBACK;403"}\n'),
+ ),
+ ],
+ [
+ 'a push in a comment',
+ body('', push('1:{}\n')),
+ ],
+ ['a push in svg', body(' ', '')],
+ [
+ 'a push in a template',
+ body(' ', ''),
+ ],
+ [
+ 'a push in a textarea',
+ body('', ''),
+ ],
+ ['unclosed', body('Text.
', '')],
+ ['empty', body('Text.
', '')],
+ ['not json', body('Text.
', '')],
+ ['a row that is not json', body('Text.
', push('5:E{not json\n'))],
+ ['bad base64', body('Text.
', '')],
+ ['a redirect', body('x
', push('7:E{"digest":"NEXT_REDIRECT;replace;/to;307;"}\n'))],
+]
+
+// what reading a page gives: its rows, its redirect or fallback, its markdown, or what it throws
+const read = (html: string, how: 'page' | 'streamed') => {
+ try {
+ let page
+ if (how === 'page') page = readPage(html, { url: 'https://shop.test/page' })
+ else {
+ const strip = flightStripper()
+ const kept = strip.write(html) + strip.end()
+ page = readStreamed(kept, strip.swapped(), { url: 'https://shop.test/page' })
+ }
+ const { slots, markdown, ...rest } = page
+ return { ...rest, slots, markdown: markdown().markdown }
+ } catch (error) {
+ if (error instanceof Declined) throw error
+ return { threw: String(error) }
+ }
+}
+
+test('md-core reads flight data as the tree pipeline does: rows, trust, errors, markdown', () => {
+ let compared = 0
+ for (const [name, html] of [...fixtures, ...attacks])
+ for (const how of ['page', 'streamed'] as const) {
+ forcePath('hast')
+ const tree = read(html, how)
+ forcePath('strict')
+ let core
+ try {
+ core = read(html, how)
+ } catch (error) {
+ // what md-core doesn't write yet (markers, streamed boundaries) is another feature's test
+ if (error instanceof Declined) continue
+ throw error
+ }
+ // the markdown of the attacks; a fixture's is the core suite's, once forms are md-core's too
+ const attack = attacks.some(([, page]) => page === html)
+ if (!attack && 'markdown' in core && 'markdown' in tree) core.markdown = tree.markdown
+ expect({ page: `${name} (${how})`, ...core }).toEqual({ page: `${name} (${how})`, ...tree })
+ compared++
+ }
+ // every attack, both ways, and most fixtures
+ expect(compared).toBeGreaterThan(attacks.length * 2 + 20)
+})
diff --git a/packages/md/test/convert/core/scripts.test.ts b/packages/md/test/convert/core/scripts.test.ts
new file mode 100644
index 0000000..35aa981
--- /dev/null
+++ b/packages/md/test/convert/core/scripts.test.ts
@@ -0,0 +1,69 @@
+import type { Element, Root } from 'hast'
+import { fromParse5 } from 'hast-util-from-parse5'
+import { parse as parseHtml } from 'parse5'
+import { describe, expect, test } from 'vitest'
+import { parse } from '../../../src/convert/core/parse.ts'
+import { corpusPages, fixturePages } from './emit-pages.ts'
+import { generate } from './parse-fuzz.ts'
+
+// the flight check reads every script's own text: md-core's parser has to find the same scripts, with the same text,
+// as the tree pipeline does in parse5's tree (the template's content and a removed body aren't in it)
+const oracle = (html: string) => {
+ const tree = fromParse5(parseHtml(html, { scriptingEnabled: false })) as Root
+ const texts: string[] = []
+ const walk = (parent: Root | Element) => {
+ for (const node of parent.children) {
+ if (node.type !== 'element') continue
+ if (node.tagName === 'script')
+ texts.push(node.children.map((kid) => (kid.type === 'text' ? kid.value : '')).join(''))
+ walk(node)
+ }
+ }
+ walk(tree)
+ return texts.toSorted()
+}
+const found = (html: string) => parse(html).scripts.toSorted()
+
+describe('every script, with its own text', () => {
+ test.each([
+ ['in head and body', 'x
'],
+ ['inside svg, around an element', ' '],
+ ['inside svg, self-closed', 'x
'],
+ ['inside math', ' '],
+ ['inside a template', ' '],
+ ['in a body a frameset threw out', ' '],
+ ['in a table', ''],
+ ['in noscript, with scripting off', ' '],
+ ['in a comment, which is none', ''],
+ ['nul characters', ' '],
+ ['after the html end', ''],
+ ['escaped script data', 'y-->'],
+ ])('%s', (_, html) => {
+ expect(found(html)).toEqual(oracle(html))
+ })
+})
+
+test('the fixtures and the corpus', () => {
+ for (const page of [...fixturePages(), ...corpusPages()])
+ expect({ page: page.name, scripts: found(page.html) }).toEqual({
+ page: page.name,
+ scripts: oracle(page.html),
+ })
+})
+
+test('6000 generated pages', () => {
+ const failures: string[] = []
+ for (let seed = 1; seed <= 6000; seed++) {
+ const html = generate(seed)
+ let expected: string[]
+ try {
+ expected = oracle(html)
+ } catch {
+ continue
+ }
+ const actual = found(html)
+ if (JSON.stringify(actual) !== JSON.stringify(expected))
+ failures.push(`seed ${seed} ${JSON.stringify(html)}: ${JSON.stringify(actual)}`)
+ }
+ expect(failures.slice(0, 5)).toEqual([])
+})
diff --git a/packages/md/test/convert/core/support/oracle.ts b/packages/md/test/convert/core/support/oracle.ts
index 852c310..4afcb1c 100644
--- a/packages/md/test/convert/core/support/oracle.ts
+++ b/packages/md/test/convert/core/support/oracle.ts
@@ -81,7 +81,8 @@ export const oracle = (html: string): Document => {
}
return el
}
- return { root: build(body ?? document, null, '#root'), head, mains }
+ // the emitter never reads the scripts; scripts.test.ts holds the parser's to parse5's
+ return { root: build(body ?? document, null, '#root'), head, mains, scripts: [] }
}
// a Document as plain data, for comparing two of them: attributes parsed, parents left out
From 2ec23466c5b4ebeedb326dd8f96c2896d78de444 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:37:47 +0000
Subject: [PATCH 11/74] fix(md): md-core keeps hidden content only where md
does
On an element that isn't an marker, md reads
data-affordances-md as skip or show only. md-core took any value, so a
hidden element (or chrome on a page without a main) carrying
data-affordances-md="only" was written. md-core's converter now reads the
attribute as md does. Nothing reached this through md yet: marked pages
decline to the tree pipeline.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/emit-prune.ts | 8 +++++--
packages/md/test/convert/core/markers.test.ts | 24 +++++++++++++++++++
2 files changed, 30 insertions(+), 2 deletions(-)
create mode 100644 packages/md/test/convert/core/markers.test.ts
diff --git a/packages/md/src/convert/core/emit-prune.ts b/packages/md/src/convert/core/emit-prune.ts
index 1d98fac..d36ba86 100644
--- a/packages/md/src/convert/core/emit-prune.ts
+++ b/packages/md/src/convert/core/emit-prune.ts
@@ -46,8 +46,12 @@ const MARKED = FLAG['data-affordances-md'] | FLAG['data-mode']
const PRUNES = HIDDEN | ARIA_HIDDEN | STYLE | ROLE | EDITABLE | MARKED
const flags = (el: Element): number => el.flags
const mentions = (el: Element) => (el.flags & PRUNES) !== 0
-const marked = (el: Element) =>
- el.tag === 'affordances-md' ? attr(el, 'data-mode') : attr(el, 'data-affordances-md')
+// a marker's mode; on any other element, data-affordances-md says only skip or show (only and the rest are a marker's)
+const marked = (el: Element) => {
+ if (el.tag === 'affordances-md') return attr(el, 'data-mode')
+ const mode = attr(el, 'data-affordances-md')
+ return mode === 'skip' || mode === 'show' ? mode : undefined
+}
const unhidden = (el: Element) => {
const mode = flags(el) & MARKED ? marked(el) : undefined
return mode === 'only' || mode === 'show'
diff --git a/packages/md/test/convert/core/markers.test.ts b/packages/md/test/convert/core/markers.test.ts
new file mode 100644
index 0000000..ddf3f4e
--- /dev/null
+++ b/packages/md/test/convert/core/markers.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'vitest'
+import { htmlToMarkdown as core } from '../../../src/convert/core/index.ts'
+import { htmlToMarkdown } from '../../../src/index.ts'
+
+// md-core against the tree pipeline, on what markers keep and leave out
+const same = (html: string) =>
+ expect(core(html, { url: 'https://shop.test/page' }).markdown).toBe(
+ htmlToMarkdown(html, { url: 'https://shop.test/page' }).markdown,
+ )
+
+test('on an element that is not a marker, data-affordances-md keeps nothing hidden but show', () => {
+ for (const mode of ['only', 'main', 'text', 'slot', 'values', ''])
+ for (const hide of ['hidden', 'style="display:none"', 'aria-hidden="true"']) {
+ same(`a
LEAK
`)
+ same(`a
LEAK `)
+ }
+ // chrome stays out of a page without a main, unless it's shown
+ same(
+ 'a
LEAK kept ',
+ )
+ expect(
+ core('LEAK
').markdown,
+ ).not.toContain('LEAK')
+})
From 8188ea8027e33e5cc483a0bd5428e1a6fd830030 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:48:52 +0000
Subject: [PATCH 12/74] feat(md): markers on md-core's path
md-core now writes what md's markers ask for, so a marked page no longer
declines:
- is its markdown, verbatim: inline or block, said even when
hidden, never naming anything with what's inside it. As md does once a
page is converted, its links are relinked with md's own rewrite (passed
in, so the converter doesn't import md), it keeps to one line in a table
cell, and a block of it is lifted out of its paragraph or heading.
- : the outermost kept ones are the page.
- A shown tab panel is headed by its tab, and a tablist whose tab labels
one goes.
md finds AgentMains and shown panels on a tree it prunes in place, so
where prune changes what's around one first (inside a link, a table, a
label host, a tablist, an AgentText, or a shown panel under something
hidden), md-core declines the page up front. Slots are still declined.
It costs md-core about 0.7 ms over the bench corpus (-0.2 to +1.6 in
three interleaved runs).
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/emit-convert.ts | 18 ++-
packages/md/src/convert/core/emit-lift.ts | 98 ++++++++++++++
packages/md/src/convert/core/emit-markdown.ts | 12 +-
packages/md/src/convert/core/emit-markers.ts | 69 ++++++++++
packages/md/src/convert/core/emit-prune.ts | 77 ++++++++++-
packages/md/src/convert/core/emit.ts | 27 +++-
packages/md/src/convert/core/parse.ts | 7 +-
packages/md/src/convert/core/types.ts | 7 +
packages/md/src/convert/index.ts | 11 +-
packages/md/test/convert/core/emit.test.ts | 7 +-
packages/md/test/convert/core/markers.test.ts | 127 +++++++++++++++++-
packages/md/test/convert/core/path.test.ts | 12 +-
.../md/test/convert/core/support/oracle.ts | 4 +-
13 files changed, 444 insertions(+), 32 deletions(-)
create mode 100644 packages/md/src/convert/core/emit-lift.ts
create mode 100644 packages/md/src/convert/core/emit-markers.ts
diff --git a/packages/md/src/convert/core/emit-convert.ts b/packages/md/src/convert/core/emit-convert.ts
index b31cae1..636bcd8 100644
--- a/packages/md/src/convert/core/emit-convert.ts
+++ b/packages/md/src/convert/core/emit-convert.ts
@@ -5,6 +5,8 @@ import {
EMPHASIS,
HEADING,
HTML,
+ MARKED_BLOCK,
+ MARKED_INLINE,
IMAGE,
INLINE_CODE,
directItems,
@@ -251,7 +253,8 @@ export const all = (parent: Element, out: Md[] = []): Md[] => {
if (info & IS_SPACED) mode = whitespaceOf(kid, mode)
let result: Md | Md[] | undefined
if (controls !== 0 && CONTROL_TAGS.has(kid.tag)) result = walkOnly(kid)
- else if (kind === PASS && !(kid.flags & FLAG['data-mdast'])) all(kid, out)
+ else if (kind === PASS && !(kid.flags & FLAG['data-mdast']) && kid.verbatim === undefined)
+ all(kid, out)
else if (
flow &&
fast &&
@@ -390,6 +393,11 @@ for (const tag of new Set([...KIND.keys(), ...BLOCKS, ...CONTENT, 'nobr', 'texta
)
const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined => {
+ if (el.verbatim !== undefined) {
+ // its text is the markdown, as the whitespace walk reads it; what's written is the markdown as it is
+ all(el)
+ return marker(el.verbatim, el.tag === 'span' ? MARKED_INLINE : MARKED_BLOCK)
+ }
if (el.flags & FLAG['data-mdast'] && attr(el, 'data-mdast') === 'ignore') return walkOnly(el)
switch (kind) {
case PASS:
@@ -471,6 +479,13 @@ const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined
return all(el)
}
+// markdown from a marker, written as it is
+export const marker = (value: string, as: number) => {
+ const made = new Md(HTML, undefined, value)
+ made.depth = as
+ return made
+}
+
const dropBreaks = (nodes: Md[]) => {
let start = 0
let end = nodes.length
@@ -1326,6 +1341,7 @@ const fastRun = (
}
const tag = kid.tag
if (kid.flags & FLAG['data-mdast']) return decline('data-mdast')
+ if (kid.verbatim !== undefined) return decline('marker markdown')
const isBreak = tag === 'br'
const savedAfter = after
const end = isBreak ? true : collapsableAfter(kids, i, after)
diff --git a/packages/md/src/convert/core/emit-lift.ts b/packages/md/src/convert/core/emit-lift.ts
new file mode 100644
index 0000000..a95ed66
--- /dev/null
+++ b/packages/md/src/convert/core/emit-lift.ts
@@ -0,0 +1,98 @@
+import {
+ HEADING,
+ HTML,
+ isLeaf,
+ MARKED_BLOCK,
+ MARKED_INLINE,
+ Md,
+ PARAGRAPH,
+ TABLE_CELL,
+ TEXT,
+ tidy,
+} from './emit-markdown.ts'
+
+// what @affordances/md does to a page's marker markdown (an 's, a slot's fill) once it's converted, in its
+// order, and only when there is some: its links resolved like the page's, one in a table cell kept to its line, and a
+// block of it lifted out of the paragraph or heading it's in
+
+// each marker's markdown, in tree order
+const markedIn = (node: Md, found: Md[] = []) => {
+ if (node.type === HTML && node.depth) found.push(node)
+ else for (const kid of tidy(node)) markedIn(kid, found)
+ return found
+}
+
+// whether there was any; links resolved with the page's base, by @affordances/md's own rewrite of them
+export const relinkMarked = (
+ root: Md,
+ relink: ((markdown: string) => string) | undefined,
+): boolean => {
+ const marked = markedIn(root)
+ if (relink) for (const node of marked) node.value = relink(node.value)
+ return marked.length > 0
+}
+
+// a table cell is one line: its marker markdown keeps line breaks as and pipes escaped, and is inline there
+export const inCells = (node: Md, inCell = false) => {
+ for (const kid of tidy(node)) {
+ if (kid.type === HTML && kid.depth && inCell) {
+ kid.value = kid.value
+ .trim()
+ .replace(/(?')
+ kid.depth = MARKED_INLINE
+ } else inCells(kid, inCell || kid.type === TABLE_CELL)
+ }
+}
+
+const hasBlock = (node: Md): boolean =>
+ (node.type === HTML && node.depth === MARKED_BLOCK) || tidy(node).some(hasBlock)
+const says = (node: Md): boolean =>
+ node.type === TEXT ? Boolean(node.value.trim()) : isLeaf(node) || tidy(node).some(says)
+// the text at one end of a node
+const edge = (node: Md | undefined, end: boolean): Md | undefined =>
+ node === undefined || (isLeaf(node) && node.type !== TEXT)
+ ? undefined
+ : node.type === TEXT
+ ? node
+ : edge(end ? node.kids.at(-1) : node.kids[0], end)
+const empty = (node: Md): Md => {
+ const copy = Object.assign(Object.create(Md.prototype) as Md, node)
+ copy.kids = []
+ copy.clean = true
+ return copy
+}
+const lifted = (node: Md): Md[] => {
+ const out: Md[] = []
+ let side = empty(node)
+ const close = () => {
+ const first = edge(side, false)
+ if (first && out.length) first.value = first.value.trimStart()
+ if (says(side)) out.push(side)
+ side = empty(node)
+ }
+ for (const child of tidy(node))
+ for (const part of !isLeaf(child) && hasBlock(child) ? lifted(child) : [child])
+ if (part.type === HTML && part.depth === MARKED_BLOCK) {
+ const last = edge(side, true)
+ if (last) last.value = last.value.trimEnd()
+ close()
+ out.push(part)
+ } else side.kids.push(part)
+ close()
+ return out
+}
+export const liftBlocks = (node: Md) => {
+ const kids = tidy(node)
+ for (let i = 0; i < kids.length; i++) {
+ const kid = kids[i]!
+ if (kid.type !== PARAGRAPH && kid.type !== HEADING) {
+ liftBlocks(kid)
+ continue
+ }
+ if (!hasBlock(kid)) continue
+ const parts = lifted(kid)
+ kids.splice(i, 1, ...parts)
+ i += parts.length - 1
+ }
+}
diff --git a/packages/md/src/convert/core/emit-markdown.ts b/packages/md/src/convert/core/emit-markdown.ts
index 395534a..c9ff51f 100644
--- a/packages/md/src/convert/core/emit-markdown.ts
+++ b/packages/md/src/convert/core/emit-markdown.ts
@@ -30,7 +30,12 @@ export const IMAGE = 19
const NO_KIDS: Md[] = []
const LEAF: boolean[] = []
for (const type of [TEXT, INLINE_CODE, BREAK, IMAGE, HTML, CODE, THEMATIC_BREAK]) LEAF[type] = true
+// a node with no children in mdast
+export const isLeaf = (node: Md) => LEAF[node.type] === true
// one shape for every node, so the walks over them stay monomorphic
+export const MARKED_INLINE = 1
+export const MARKED_BLOCK = 2
+
export class Md {
type: number
kids: Md[]
@@ -40,7 +45,8 @@ export class Md {
title: string | null
lang: string | null
meta: string | null
- // a heading's depth, an ordered list's start
+ // a heading's depth, an ordered list's start; for html, whether it's a marker's markdown (an , a slot's
+ // fill): MARKED_INLINE or MARKED_BLOCK, else 0
depth: number
ordered: boolean
spread: boolean
@@ -75,7 +81,9 @@ export class Md {
}
}
-export const isPhrasing = (node: Md) => node.type >= TEXT
+// as hast-util-to-mdast's wrap reads it: mdast's phrasing, and a marker's inline markdown, which says it's a span
+export const isPhrasing = (node: Md) =>
+ node.type >= TEXT || (node.type === HTML && node.depth === MARKED_INLINE)
// what hast-util-to-mdast does last, to each node's children: adjacent texts as one, the line ending's spaces, a
// paragraph's (heading's, root's) outer spaces, and empty texts gone. it depends on nothing but the node's own
diff --git a/packages/md/src/convert/core/emit-markers.ts b/packages/md/src/convert/core/emit-markers.ts
new file mode 100644
index 0000000..b5614e5
--- /dev/null
+++ b/packages/md/src/convert/core/emit-markers.ts
@@ -0,0 +1,69 @@
+import { attr } from './attr.ts'
+import { dropped, isText, marked } from './emit-prune.ts'
+import { FLAG, type Element } from './types.ts'
+
+// a page's markers, read from the tree as parsed, before it's converted: the s, and the tabs that label a
+// shown panel. @affordances/md finds both on its tree while it prunes it in place, so in a few shapes what it finds
+// depends on what it pruned first; md-core says why it can't match those (the caller converts them the other way)
+export type Markers = {
+ // the outermost s among what prune keeps, in page order
+ mains: Element[]
+ // the ids a shown panel's aria-labelledby names
+ tabs: Set
+ // why md-core can't write the page as @affordances/md does, if it can't
+ decline?: string
+}
+
+// what prune may change inside, beyond leaving out what's hidden: a link loses its empty blocks and values, a table
+// can be a skeleton, a heading or summary can be read as its button, a tablist can go
+const CHANGED = new Set([
+ 'a',
+ 'table',
+ 'th',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'caption',
+ 'summary',
+ 'dt',
+])
+const changed = (el: Element) =>
+ CHANGED.has(el.tag) || (el.flags & FLAG.role && attr(el, 'role') === 'tablist') || isText(el)
+
+const mode = (el: Element) =>
+ el.flags & (FLAG['data-affordances-md'] | FLAG['data-mode']) ? marked(el) : undefined
+
+export const readMarkers = (root: Element): Markers => {
+ const found: Markers = { mains: [], tabs: new Set() }
+ const decline = (why: string) => {
+ found.decline ??= why
+ }
+ // under: something prune leaves out or may change is above
+ const walk = (parent: Element, gone: boolean, under: boolean) => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string') continue
+ const text = isText(kid)
+ const out = gone || (!text && dropped(kid))
+ const m = mode(kid)
+ if (kid.tag === 'affordances-md' && m === 'main' && !out) {
+ if (under) decline('main marker inside what prune changes')
+ found.mains.push(kid)
+ continue
+ }
+ if (m === 'slot') decline('slot')
+ // data-affordances-md="show", as the attribute says it: what a tablist's tabs are checked against
+ if (kid.tag !== 'affordances-md' && attr(kid, 'data-affordances-md') === 'show') {
+ if (gone || under) decline('shown panel inside what prune changes')
+ if (CHANGED.has(kid.tag)) decline('shown panel prune changes')
+ for (const id of (attr(kid, 'aria-labelledby') ?? '').split(/\s+/))
+ if (id) found.tabs.add(id)
+ }
+ walk(kid, out || text, under || changed(kid))
+ }
+ }
+ walk(root, false, false)
+ return found
+}
diff --git a/packages/md/src/convert/core/emit-prune.ts b/packages/md/src/convert/core/emit-prune.ts
index d36ba86..0a67898 100644
--- a/packages/md/src/convert/core/emit-prune.ts
+++ b/packages/md/src/convert/core/emit-prune.ts
@@ -11,6 +11,13 @@ let stripChrome = false
export const begin = (strip: boolean) => {
stripChrome = strip
byId = undefined
+ tabs = undefined
+}
+// the tabs that label a shown panel (data-affordances-md="show"), on a page with markers: their tablists go, since
+// each panel is headed by its tab
+let tabs: Set | undefined
+export const setTabs = (labels: Set | undefined) => {
+ tabs = labels?.size ? labels : undefined
}
let page: Element | undefined
export const setPage = (root: Element) => {
@@ -29,6 +36,7 @@ export const made = (from: Element, kids: Node[], tag = from.tag): Element => {
map: from.map,
pruned: true,
code: from.code,
+ verbatim: undefined,
}
return el
}
@@ -47,7 +55,7 @@ const PRUNES = HIDDEN | ARIA_HIDDEN | STYLE | ROLE | EDITABLE | MARKED
const flags = (el: Element): number => el.flags
const mentions = (el: Element) => (el.flags & PRUNES) !== 0
// a marker's mode; on any other element, data-affordances-md says only skip or show (only and the rest are a marker's)
-const marked = (el: Element) => {
+export const marked = (el: Element) => {
if (el.tag === 'affordances-md') return attr(el, 'data-mode')
const mode = attr(el, 'data-affordances-md')
return mode === 'skip' || mode === 'show' ? mode : undefined
@@ -111,7 +119,7 @@ const editor = (el: Element) => {
// what an attribute source says about being dropped, remembered: highlighted code repeats a few style="color:…"
// sources thousands of times. kept small, and only for what the source alone decides (not affordances-md's tag)
const droppedBy = new Map()
-const dropped = (el: Element): boolean => {
+export const dropped = (el: Element): boolean => {
if ((el.flags & PRUNES) === 0) return false
if (el.tag === 'affordances-md') return droppedNow(el)
let known = droppedBy.get(el.attrs)
@@ -167,7 +175,8 @@ const ids = () => {
if (typeof kid === 'string' || dropped(kid)) continue
const id = attr(kid, 'id')
if (id !== undefined && !byId!.has(id)) byId!.set(id, kid)
- walk(kid)
+ // an says its markdown, never what's inside it
+ if (!isText(kid)) walk(kid)
}
}
if (page) walk(page)
@@ -339,9 +348,71 @@ const hasTag = (el: Element, tag: string): boolean => {
return false
}
+// an : replaced by its markdown, whatever it holds and however it's hidden
+export const isText = (el: Element) =>
+ el.tag === 'affordances-md' && (el.flags & MARKED) !== 0 && marked(el) === 'text'
+// a span or div (as the page flows around it) whose text is the markdown, written as it is
+const verbatimOf = (el: Element): Element => {
+ const md = attr(el, 'data-md') ?? ''
+ const said: Element = {
+ tag: attr(el, 'data-block') === undefined ? 'span' : 'div',
+ attrs: '',
+ flags: 0,
+ kids: [md],
+ up: el.up,
+ map: undefined,
+ pruned: true,
+ code: undefined,
+ verbatim: md,
+ }
+ return said
+}
+// a tablist with a tab that labels a shown panel
+const shownTablist = (el: Element) => {
+ if (!tabs || !(el.flags & ROLE) || role(el) !== 'tablist') return false
+ const walk = (parent: Element): boolean => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string') continue
+ if (kid.flags & ROLE && role(kid) === 'tab' && tabs!.has(attr(kid, 'id') ?? '')) return true
+ if (walk(kid)) return true
+ }
+ return false
+ }
+ return walk(el)
+}
+const fresh = (tag: string, kids: Node[], up: Element | null): Element => ({
+ tag,
+ attrs: '',
+ flags: 0,
+ kids,
+ up,
+ map: undefined,
+ pruned: true,
+ code: undefined,
+ verbatim: undefined,
+})
+// a shown tab panel, headed by its tab's label
+const headed = (panel: Element): Element => {
+ const label = (attr(panel, 'aria-labelledby') ?? '')
+ .split(/\s+/)
+ .filter(Boolean)
+ .flatMap((id) => ids().get(id) ?? [])
+ .filter((tab) => tab.flags & ROLE && role(tab) === 'tab')
+ .map(words)
+ .filter(Boolean)
+ .join(' ')
+ if (!label) return panel
+ const heading = fresh('p', [], panel.up)
+ heading.kids = [fresh('strong', [label], heading)]
+ return made(panel, [heading, ...kidsOf(panel)])
+}
+
// what a child becomes: itself, something prune made of it, or nothing
const pruned = (kid: Element): Element | undefined => {
+ if (kid.flags & MARKED && isText(kid)) return verbatimOf(kid)
if (dropped(kid) || (stripChrome && chrome(kid))) return undefined
+ if (shownTablist(kid)) return undefined
+ if (kid.flags & MARKED && marked(kid) === 'show' && role(kid) === 'tabpanel') return headed(kid)
if (kid.tag === 'a') {
const inner = kidsOf(kid)
const kept = without(inner, linkDrop)
diff --git a/packages/md/src/convert/core/emit.ts b/packages/md/src/convert/core/emit.ts
index 47bccaf..64c28fb 100644
--- a/packages/md/src/convert/core/emit.ts
+++ b/packages/md/src/convert/core/emit.ts
@@ -1,26 +1,39 @@
import { convertRoot, materialize, startConvert } from './emit-convert.ts'
import { HEADING, headingText, IMAGE, Md, setext, TEXT, toMarkdown } from './emit-markdown.ts'
-import { begin, findMain, made, setPage } from './emit-prune.ts'
+import { inCells, liftBlocks, relinkMarked } from './emit-lift.ts'
+import { readMarkers } from './emit-markers.ts'
+import { begin, findMain, made, setPage, setTabs } from './emit-prune.ts'
import type { Document, Options, Result } from './types.ts'
// markdown straight from the parser's tree: what @affordances/md's htmlToMarkdown writes for the same page. one walk
// prunes, extracts, collapses whitespace and converts (emit-prune, emit-convert) into a lean tree that's written out
// (emit-markdown); finish adds what the page's head says.
-// not here yet, where they'd hook in: markers and slots (prune's mode() and convert's one()), the form
-// summary (convert's form()), shown tab panels (prune), streamed suspense boundaries (the parser), custom handlers
+// not here yet, where they'd hook in: slots (prune and convert's one()), the form summary (convert's form()), streamed
+// suspense boundaries (the parser), custom handlers
export const emit = (doc: Document, options: Options = {}): Result => {
const { head } = doc
const meta = (key: string) => (head.meta.get(key) ?? '').trim() || undefined
const canonical = canonicalOf(head.canonical, options.url)
const base = options.url ?? canonical
- // extract: the page's , else the body without its chrome; or the whole body
+ // extract: the page's s, else its , else the body without its chrome; or the whole body
const auto = (options.extract ?? 'auto') === 'auto'
+ const markers = doc.marked ? readMarkers(doc.root) : undefined
+ const outer = auto && markers?.mains.length ? markers.mains : undefined
begin(false)
setPage(doc.root)
- const main = auto ? findMain(doc.mains) : undefined
- if (auto && !main) begin(true)
+ const main = auto && !outer ? findMain(doc.mains) : undefined
+ if (auto && !outer && !main) begin(true)
+ setTabs(markers?.tabs)
startConvert(options, base)
- const root = convertRoot(main ? made(doc.root, [main], '#root') : doc.root)
+ const root = convertRoot(
+ outer ? made(doc.root, outer, '#root') : main ? made(doc.root, [main], '#root') : doc.root,
+ )
+ // marker markdown, as @affordances/md treats it once the page is converted
+ const relink = base && options.relinkMarkdown
+ if (relinkMarked(root, relink ? (md) => relink(md, base, options.link) : undefined)) {
+ inCells(root)
+ liftBlocks(root)
+ }
return finish(
root,
{
diff --git a/packages/md/src/convert/core/parse.ts b/packages/md/src/convert/core/parse.ts
index ee0f0c1..a6186e2 100644
--- a/packages/md/src/convert/core/parse.ts
+++ b/packages/md/src/convert/core/parse.ts
@@ -292,6 +292,8 @@ let watched: El[] = []
let mains: El[] = []
// every script element, in any namespace: the flight check reads each one's text
let scripts: El[] = []
+// whether the page has a marker, or an element with data-affordances-md
+let marked = false
// the elements with a dropped child among their kids, to take out at the end
let pruned = new Set()
// whether a node was put anywhere but after everything before it: then the Head's elements are sorted into tree order
@@ -345,10 +347,12 @@ const make = (name: string, id: number, ns: number, attrs: string, flags: number
// the emitter's fields, here so every element has one shape from the start
pruned: false,
code: undefined,
+ verbatim: undefined,
id,
ns,
rec: ns === SVG ? 0 : DROP[id] ? 1 : 2,
}
+ if (flags & FLAG['data-affordances-md'] || (id === 0 && name === 'affordances-md')) marked = true
// a main, by tag or by role; which of them end up in the tree is settled at the end
if (id === MAIN || (flags & FLAG.role && maybe(attrs, 'main') && attr(el, 'role') === 'main'))
mains.push(el)
@@ -3031,6 +3035,7 @@ export const parse = (input: string): Document => {
watched = []
mains = []
scripts = []
+ marked = false
pruned.clear()
reordered = false
tok = 0
@@ -3052,7 +3057,7 @@ export const parse = (input: string): Document => {
el.kids = kids
}
const root = bodyEl && !bodyGone ? bodyEl : doc
- const document: Document = { root, head, mains: readMains(root), scripts: scriptTexts }
+ const document: Document = { root, head, mains: readMains(root), scripts: scriptTexts, marked }
root.tag = '#root'
root.up = null
// let the page go: the tree holds slices of it, not the parse's state
diff --git a/packages/md/src/convert/core/types.ts b/packages/md/src/convert/core/types.ts
index 85af0e1..de37a6a 100644
--- a/packages/md/src/convert/core/types.ts
+++ b/packages/md/src/convert/core/types.ts
@@ -22,6 +22,8 @@ export interface Element {
// leaves them; and whether the element is code or inside it (undefined until asked)
pruned?: boolean | undefined
code?: boolean | undefined
+ // on the span or div prune makes of an : the markdown it stands for, written as it is
+ verbatim?: string | undefined
}
// the attributes an element's flags record, by name (ascii case-insensitive, as html matches them)
@@ -74,6 +76,8 @@ export interface Document {
// the own text of every script element in the document, any namespace, in no particular order: what the flight
// check reads, as it would read each script in parse5's tree
scripts: string[]
+ // whether any element is an marker or has data-affordances-md: only then are markers looked for
+ marked: boolean
}
// what the parser never builds, with everything inside: never content, whatever the page says. the same set as
@@ -105,6 +109,9 @@ export type Options = {
jsonLd?: boolean
// another url for a link once it's absolute; undefined keeps it. not called for images or #fragment links
link?: (url: URL) => string | undefined
+ // @affordances/md's rewrite of the links in marker markdown (an 's), with the page's base; without it
+ // they're written as they are. internal: md passes its own
+ relinkMarkdown?: (markdown: string, base: string, link: Options['link']) => string
}
export type Result = { markdown: string; title?: string; url?: string; tokens: number }
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index 2cf0e2a..08ef21d 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -24,6 +24,7 @@ import { visit } from 'unist-util-visit'
import { minifyWhitespace } from './whitespace.ts'
import { emit as emitCore } from './core/emit.ts'
import { parse as parseCore } from './core/parse.ts'
+import { readMarkers } from './core/emit-markers.ts'
import type { Document as CoreDocument, Options as CoreOptions } from './core/types.ts'
import { declined, forcedPath } from './path.ts'
@@ -2440,7 +2441,6 @@ const coreTakes = (options: Options) => {
// what md-core can't write yet as the tree pipeline does: a page with any of it is declined, before it's converted
const NOT_YET: [why: string, test: (html: string, swapped: Swapped) => boolean][] = [
- ['marker', (html) => / /\$R[CRS]\(|data-r[crs]i/i.test(html)],
]
@@ -2459,13 +2459,20 @@ const readCore = (
// the first call converts the tree read here; md-core's emit prunes a tree in place, so another parses again
let doc: CoreDocument | undefined = parseCore(html)
const reason = untrusted(doc.scripts, swapped)
+ // a marked page whose markers md-core can't read as prune does
+ const why = doc.marked ? readMarkers(doc.root).decline : undefined
+ if (why) {
+ declined(why)
+ return undefined
+ }
+ const coreOptions: CoreOptions = { ...(options as CoreOptions), relinkMarkdown }
const page: Page = {
slots: { unique: [], duplicate: [] },
...controlOf(swapped.errors),
markdown: () => {
const tree = doc ?? parseCore(html)
doc = undefined
- return emitCore(tree, options as CoreOptions)
+ return emitCore(tree, coreOptions)
},
}
return { page, reason }
diff --git a/packages/md/test/convert/core/emit.test.ts b/packages/md/test/convert/core/emit.test.ts
index ec6ad53..b009115 100644
--- a/packages/md/test/convert/core/emit.test.ts
+++ b/packages/md/test/convert/core/emit.test.ts
@@ -305,17 +305,12 @@ describe('options', () => {
// before the package is built again)
const fixtures = fixturePages()
// known differences, all from what emit doesn't do yet, each with the share of its reference lines emit reproduces in
-// order: markers and slots (: main, text), the form summary, shown tab panels, streamed suspense
+// order: slots, the form summary, streamed suspense
// boundaries. a page that gets closer should raise its floor; one that gets exact moves out of the list
const KNOWN = new Map([
- ['disclosure-fumadocs-tabs', 0.76],
- ['disclosure-radix-tabs', 0.76],
['form', 0.58],
['form-labels', 0.53],
['form-values', 0.33],
- ['main-markers', 0.99],
- ['markers', 0.66],
- ['package-page', 0.93],
['settings-form', 0.56],
['streamed-instructions', 0.68],
['streamed-next16.3', 0.46],
diff --git a/packages/md/test/convert/core/markers.test.ts b/packages/md/test/convert/core/markers.test.ts
index ddf3f4e..256ba8a 100644
--- a/packages/md/test/convert/core/markers.test.ts
+++ b/packages/md/test/convert/core/markers.test.ts
@@ -1,10 +1,12 @@
import { expect, test } from 'vitest'
-import { htmlToMarkdown as core } from '../../../src/convert/core/index.ts'
+import { declines, forcePath } from '../../../src/convert/path.ts'
+import type { Options } from '../../../src/index.ts'
+import { htmlToMarkdown as coreMarkdown } from '../../../src/convert/core/index.ts'
import { htmlToMarkdown } from '../../../src/index.ts'
// md-core against the tree pipeline, on what markers keep and leave out
const same = (html: string) =>
- expect(core(html, { url: 'https://shop.test/page' }).markdown).toBe(
+ expect(coreMarkdown(html, { url: 'https://shop.test/page' }).markdown).toBe(
htmlToMarkdown(html, { url: 'https://shop.test/page' }).markdown,
)
@@ -19,6 +21,125 @@ test('on an element that is not a marker, data-affordances-md keeps nothing hidd
'a
LEAK kept ',
)
expect(
- core('LEAK
').markdown,
+ coreMarkdown('LEAK
').markdown,
).not.toContain('LEAK')
})
+
+// a page through readPage on both paths: md-core must write exactly what the tree pipeline does, without declining
+const both = (html: string, options: Options = {}) => {
+ forcePath('hast')
+ const tree = htmlToMarkdown(html, options).markdown
+ forcePath('strict')
+ try {
+ return [htmlToMarkdown(html, options).markdown, tree]
+ } finally {
+ forcePath(undefined)
+ }
+}
+const at = {
+ url: 'https://example.test/page',
+ link: (url: URL) => `${url.origin}${url.pathname}.md`,
+}
+const text = (md: string, inner = '', block = false) =>
+ `${inner} `
+
+test.each([
+ ['inline, in a paragraph', `By ${text('**Ann**')}.
`],
+ [
+ 'inline, in a link, beside another',
+ ``,
+ ],
+ [
+ 'with links, relinked',
+ `By ${text('Ann')} , ${text('[Bob](/~bob)')} ${text('')}
`,
+ ],
+ ['a block, lifted out of a paragraph', `Before ${text('- one\n- two', '', true)} after
`],
+ [
+ 'a block, lifted out of a heading and a link',
+ ``,
+ ],
+ [
+ 'in a table cell',
+ `A ${text('a | b\nc', '', true)}
`,
+ ],
+ [
+ 'hidden, still said',
+ `a
`,
+ ],
+ [
+ 'names nothing with what is inside it',
+ `${text('shown', 'LEAK ')}
`,
+ ],
+ ['an empty one', `a ${text('')} b
`],
+ ['in a heading read as its button', `Open ${text('**said**')} `],
+ ['the page cannot forge one', 'kept
'],
+])(': %s', (_, html) => {
+ const [core, tree] = both(html, at)
+ expect(core).toBe(tree)
+})
+
+test.each([
+ ['one main', 'out
in
'],
+ [
+ 'two, and one inside another',
+ 'a
b
n c
',
+ ],
+ [
+ 'hidden ones never count',
+ 'm
',
+ ],
+ [
+ 'before a ',
+ 'm
marked
',
+ ],
+ [
+ 'skip and only',
+ 'LEAK
agents
',
+ ],
+ ['with extract none', 'out
in
'],
+])(', , : %s', (name, html) => {
+ const [core, tree] = both(html, name === 'with extract none' ? { extract: 'none' } : {})
+ expect(core).toBe(tree)
+})
+
+const tabs = (mark: string) =>
+ 'npm pnpm
' +
+ `` +
+ `after
`
+test.each([
+ ['shown panels', tabs('data-affordances-md="show"')],
+ ['not shown', tabs('')],
+ [
+ 'a marker shows, without a heading from the attribute',
+ tabs('')
+ .replaceAll('
', ' '),
+ ],
+ [
+ 'a panel labelled by something hidden',
+ 'LEAK ',
+ ],
+ [
+ 'hidden inside a shown panel',
+ '',
+ ],
+])('shown tab panels: %s', (_, html) => {
+ const [core, tree] = both(html)
+ expect(core).toBe(tree)
+})
+
+test('a marker where the tree pipeline prunes in place first is declined, never written differently', () => {
+ for (const html of [
+ 'in
',
+ 't
',
+ '',
+ ]) {
+ declines.clear()
+ forcePath('core')
+ const core = htmlToMarkdown(html).markdown
+ forcePath('hast')
+ expect(core).toBe(htmlToMarkdown(html).markdown)
+ expect(declines.size).toBe(1)
+ forcePath(undefined)
+ }
+})
diff --git a/packages/md/test/convert/core/path.test.ts b/packages/md/test/convert/core/path.test.ts
index 9f085f7..d553da8 100644
--- a/packages/md/test/convert/core/path.test.ts
+++ b/packages/md/test/convert/core/path.test.ts
@@ -28,12 +28,12 @@ test('handlers and a function extract take the tree pipeline, without a decline'
})
test('a page md-core declines is counted, and the tree pipeline writes it; strict throws instead', () => {
- const marked =
- 'skip
kept
'
- const tree = htmlToMarkdown(marked)
+ const slotted =
+ 'a
fallback
'
+ const tree = htmlToMarkdown(slotted)
forcePath('core')
- expect(htmlToMarkdown(marked)).toEqual(tree)
- expect(declines.get('marker')).toBe(1)
+ expect(htmlToMarkdown(slotted)).toEqual(tree)
+ expect(declines.get('slot')).toBe(1)
forcePath('strict')
- expect(() => readPage(marked)).toThrow(/md-core declined the page \(marker\)/)
+ expect(() => readPage(slotted)).toThrow(/md-core declined the page \(slot\)/)
})
diff --git a/packages/md/test/convert/core/support/oracle.ts b/packages/md/test/convert/core/support/oracle.ts
index 4afcb1c..1fb53d7 100644
--- a/packages/md/test/convert/core/support/oracle.ts
+++ b/packages/md/test/convert/core/support/oracle.ts
@@ -82,7 +82,9 @@ export const oracle = (html: string): Document => {
return el
}
// the emitter never reads the scripts; scripts.test.ts holds the parser's to parse5's
- return { root: build(body ?? document, null, '#root'), head, mains, scripts: [] }
+ // markers are looked for wherever the page might have one
+ const marked = /affordances-md/i.test(html)
+ return { root: build(body ?? document, null, '#root'), head, mains, scripts: [], marked }
}
// a Document as plain data, for comparing two of them: attributes parsed, parents left out
From 2920aba874b6eefdd8e4aa2dbf676130d5fe1f57 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 17:57:53 +0000
Subject: [PATCH 13/74] feat(md): slots on md-core's path
readPage on md-core lists the names that reach the markdown,
unique and duplicate in page order, as md finds them on its pruned and
extracted tree: never hidden, skipped, in an AgentText, outside the
AgentMain or main, in stripped chrome, or inside another slot. A fill for
a unique name is block marker markdown in the slot's place, relinked and
lifted like an AgentText's; prune still reads the slot's children (a link
or table around it is judged by them), conversion never does.
Where prune could take a slot out and md-core can't tell from the parsed
tree (in a link, with nothing to read; in a table that may be a skeleton;
in a tablist a shown panel's tab labels), the page declines up front.
Each markdown() call converts again with its own fills; a test holds a
second call with other fills to the tree pipeline's.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/emit-convert.ts | 11 +-
packages/md/src/convert/core/emit-markers.ts | 3 +-
packages/md/src/convert/core/emit-prune.ts | 15 +-
packages/md/src/convert/core/emit.ts | 143 +++++++++++++++++--
packages/md/src/convert/core/types.ts | 2 +
packages/md/src/convert/index.ts | 20 +--
packages/md/test/convert/core/emit.test.ts | 2 +-
packages/md/test/convert/core/path.test.ts | 7 +-
packages/md/test/convert/core/slots.test.ts | 119 +++++++++++++++
9 files changed, 288 insertions(+), 34 deletions(-)
create mode 100644 packages/md/test/convert/core/slots.test.ts
diff --git a/packages/md/src/convert/core/emit-convert.ts b/packages/md/src/convert/core/emit-convert.ts
index 636bcd8..bf61e22 100644
--- a/packages/md/src/convert/core/emit-convert.ts
+++ b/packages/md/src/convert/core/emit-convert.ts
@@ -30,7 +30,13 @@ import {
BLOCKQUOTE,
} from './emit-markdown.ts'
import { attr } from './attr.ts'
-import { classes, kidsOf, linkLabel, text } from './emit-prune.ts'
+import { classes, kidsOf as prunedKids, linkLabel, text } from './emit-prune.ts'
+
+// an element's children as conversion reads them: prune's, except a filled slot's, which never convert (prune still
+// reads them, as @affordances/md's does before it empties the slot)
+const NONE: Node[] = []
+const kidsOf = (el: Element): Node[] =>
+ el.verbatim !== undefined && el.tag === 'affordances-md' ? NONE : prunedKids(el)
import { FLAG, type Element, type Node, type Options } from './types.ts'
// the page's content as the emitter's tree, as hast-util-to-mdast (MIT, Titus Wormer) converts it with
@@ -394,7 +400,8 @@ for (const tag of new Set([...KIND.keys(), ...BLOCKS, ...CONTENT, 'nobr', 'texta
const one = (el: Element, kind: number, parent: Element): Md | Md[] | undefined => {
if (el.verbatim !== undefined) {
- // its text is the markdown, as the whitespace walk reads it; what's written is the markdown as it is
+ // an 's text is its markdown, as the whitespace walk reads it (a filled slot has none); what's
+ // written is the markdown as it is
all(el)
return marker(el.verbatim, el.tag === 'span' ? MARKED_INLINE : MARKED_BLOCK)
}
diff --git a/packages/md/src/convert/core/emit-markers.ts b/packages/md/src/convert/core/emit-markers.ts
index b5614e5..903cb3c 100644
--- a/packages/md/src/convert/core/emit-markers.ts
+++ b/packages/md/src/convert/core/emit-markers.ts
@@ -30,7 +30,7 @@ const CHANGED = new Set([
'summary',
'dt',
])
-const changed = (el: Element) =>
+export const changed = (el: Element) =>
CHANGED.has(el.tag) || (el.flags & FLAG.role && attr(el, 'role') === 'tablist') || isText(el)
const mode = (el: Element) =>
@@ -53,7 +53,6 @@ export const readMarkers = (root: Element): Markers => {
found.mains.push(kid)
continue
}
- if (m === 'slot') decline('slot')
// data-affordances-md="show", as the attribute says it: what a tablist's tabs are checked against
if (kid.tag !== 'affordances-md' && attr(kid, 'data-affordances-md') === 'show') {
if (gone || under) decline('shown panel inside what prune changes')
diff --git a/packages/md/src/convert/core/emit-prune.ts b/packages/md/src/convert/core/emit-prune.ts
index 0a67898..495454c 100644
--- a/packages/md/src/convert/core/emit-prune.ts
+++ b/packages/md/src/convert/core/emit-prune.ts
@@ -16,6 +16,11 @@ export const begin = (strip: boolean) => {
// the tabs that label a shown panel (data-affordances-md="show"), on a page with markers: their tablists go, since
// each panel is headed by its tab
let tabs: Set | undefined
+// the slots with a fill, and the fill: each is the fill, as block markdown, and what's in it never converts
+let fills: Map | undefined
+export const setFills = (filled: Map) => {
+ fills = filled.size ? filled : undefined
+}
export const setTabs = (labels: Set | undefined) => {
tabs = labels?.size ? labels : undefined
}
@@ -36,7 +41,8 @@ export const made = (from: Element, kids: Node[], tag = from.tag): Element => {
map: from.map,
pruned: true,
code: from.code,
- verbatim: undefined,
+ // a copy of an or a filled slot is still its markdown
+ verbatim: from.verbatim,
}
return el
}
@@ -141,7 +147,7 @@ const droppedNow = (el: Element): boolean => {
((found & STYLE) !== 0 && styleHidden(attr(el, 'style')))
)
}
-const chrome = (el: Element) => {
+export const chrome = (el: Element) => {
const maybe = mentions(el)
return (
(CHROME_TAGS.has(el.tag) || (maybe && CHROME_ROLES.has(role(el)))) && !(maybe && unhidden(el))
@@ -212,7 +218,7 @@ const VALUED = new Set([
])
const VALUE_ROLES = new Set(['spinbutton', 'slider'])
// a control whose text is a value, not a name
-const valueBearing = (el: Element) =>
+export const valueBearing = (el: Element) =>
VALUED.has(el.tag) || (mentions(el) && (VALUE_ROLES.has(role(el)) || editor(el)))
// children without the descendants drop picks, at any depth; the same array when nothing goes
@@ -410,6 +416,9 @@ const headed = (panel: Element): Element => {
// what a child becomes: itself, something prune made of it, or nothing
const pruned = (kid: Element): Element | undefined => {
if (kid.flags & MARKED && isText(kid)) return verbatimOf(kid)
+ const fill = fills?.get(kid)
+ // prune reads what's in it, as ever (a link or table around it is judged by it); only conversion leaves it out
+ if (fill !== undefined && !dropped(kid)) return { ...made(kid, kidsOf(kid)), verbatim: fill }
if (dropped(kid) || (stripChrome && chrome(kid))) return undefined
if (shownTablist(kid)) return undefined
if (kid.flags & MARKED && marked(kid) === 'show' && role(kid) === 'tabpanel') return headed(kid)
diff --git a/packages/md/src/convert/core/emit.ts b/packages/md/src/convert/core/emit.ts
index 64c28fb..10977e4 100644
--- a/packages/md/src/convert/core/emit.ts
+++ b/packages/md/src/convert/core/emit.ts
@@ -1,28 +1,46 @@
+import { attr } from './attr.ts'
import { convertRoot, materialize, startConvert } from './emit-convert.ts'
import { HEADING, headingText, IMAGE, Md, setext, TEXT, toMarkdown } from './emit-markdown.ts'
import { inCells, liftBlocks, relinkMarked } from './emit-lift.ts'
import { readMarkers } from './emit-markers.ts'
-import { begin, findMain, made, setPage, setTabs } from './emit-prune.ts'
-import type { Document, Options, Result } from './types.ts'
+import {
+ begin,
+ chrome,
+ dropped,
+ findMain,
+ isText,
+ made,
+ marked,
+ setFills,
+ setPage,
+ setTabs,
+ valueBearing,
+} from './emit-prune.ts'
+import { FLAG, type Document, type Element, type Options, type Result } from './types.ts'
// markdown straight from the parser's tree: what @affordances/md's htmlToMarkdown writes for the same page. one walk
// prunes, extracts, collapses whitespace and converts (emit-prune, emit-convert) into a lean tree that's written out
// (emit-markdown); finish adds what the page's head says.
-// not here yet, where they'd hook in: slots (prune and convert's one()), the form summary (convert's form()), streamed
-// suspense boundaries (the parser), custom handlers
+// not here yet, where they'd hook in: the form summary (convert's form()), streamed suspense boundaries (the
+// parser), custom handlers
export const emit = (doc: Document, options: Options = {}): Result => {
const { head } = doc
const meta = (key: string) => (head.meta.get(key) ?? '').trim() || undefined
const canonical = canonicalOf(head.canonical, options.url)
const base = options.url ?? canonical
- // extract: the page's s, else its , else the body without its chrome; or the whole body
- const auto = (options.extract ?? 'auto') === 'auto'
- const markers = doc.marked ? readMarkers(doc.root) : undefined
- const outer = auto && markers?.mains.length ? markers.mains : undefined
- begin(false)
- setPage(doc.root)
- const main = auto && !outer ? findMain(doc.mains) : undefined
- if (auto && !outer && !main) begin(true)
+ const content = contentOf(doc, options)
+ const { outer, main, markers } = content
+ // a slot with a fill is the fill, and what's in it never converts
+ const fills = new Map()
+ if (options.fills && markers) {
+ const { slots, unique } = slotsIn(doc, content)
+ for (const slot of slots) {
+ const name = attr(slot, 'data-name') ?? ''
+ const fill = Object.hasOwn(options.fills, name) ? options.fills[name] : undefined
+ if (unique.has(name) && typeof fill === 'string') fills.set(slot, fill)
+ }
+ }
+ setFills(fills)
setTabs(markers?.tabs)
startConvert(options, base)
const root = convertRoot(
@@ -49,6 +67,107 @@ export const emit = (doc: Document, options: Options = {}): Result => {
)
}
+// what becomes markdown: the page's s, else its , else the body without its chrome; or the whole body
+type Content = {
+ markers: ReturnType | undefined
+ outer: Element[] | undefined
+ main: Element | undefined
+ strip: boolean
+}
+const contentOf = (doc: Document, options: Options): Content => {
+ const auto = (options.extract ?? 'auto') === 'auto'
+ const markers = doc.marked ? readMarkers(doc.root) : undefined
+ const outer = auto && markers?.mains.length ? markers.mains : undefined
+ begin(false)
+ setPage(doc.root)
+ const main = auto && !outer ? findMain(doc.mains) : undefined
+ const strip = auto && !outer && !main
+ if (strip) begin(true)
+ return { markers, outer, main, strip }
+}
+
+// the s that reach the markdown, in page order, as @affordances/md finds them once the page is pruned and
+// extracted: not hidden, not in an , not in chrome that's stripped, and never one inside another. and the
+// names rendered once, which are the ones a fill can go to
+// what prune could take a slot out with: a link drops a block with nothing to read, a skeleton table goes, and so
+// does a tablist whose tab labels a shown panel. where md-core can't tell from the tree as parsed, it declines
+const slotsIn = (doc: Document, { outer, main, strip, markers }: Content) => {
+ const slots: Element[] = []
+ let decline: string | undefined
+ const walk = (parent: Element, around: Element[]) => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string' || isText(kid) || dropped(kid) || (strip && chrome(kid))) continue
+ if (kid.tag === 'affordances-md' && marked(kid) === 'slot') {
+ for (const el of around)
+ if (el.tag === 'a' ? !says(kid) : el.tag === 'table' ? !standing(el) : markers?.tabs.size)
+ decline ??= `slot inside ${el.tag === 'a' || el.tag === 'table' ? `<${el.tag}>` : 'a tablist'}`
+ slots.push(kid)
+ continue
+ }
+ const risky =
+ kid.tag === 'a' ||
+ kid.tag === 'table' ||
+ (kid.flags & FLAG.role && attr(kid, 'role') === 'tablist')
+ walk(kid, risky ? [...around, kid] : around)
+ }
+ }
+ for (const root of outer ?? [main ?? doc.root]) walk(root, [])
+ const counts = new Map()
+ for (const slot of slots) {
+ const name = attr(slot, 'data-name') ?? ''
+ if (name) counts.set(name, (counts.get(name) ?? 0) + 1)
+ }
+ const unique = new Set([...counts].flatMap(([name, count]) => (count === 1 ? [name] : [])))
+ const duplicate = [...counts].flatMap(([name, count]) => (count > 1 ? [name] : []))
+ return { slots, unique, duplicate, decline }
+}
+// whether prune leaves an element something to read: text outside what's hidden and what carries a value, an
+// 's markdown, or a described image
+const says = (el: Element): boolean =>
+ el.kids.some((kid) =>
+ typeof kid === 'string'
+ ? kid.trim() !== ''
+ : isText(kid)
+ ? (attr(kid, 'data-md') ?? '') !== ''
+ : !dropped(kid) &&
+ !valueBearing(kid) &&
+ ((kid.tag === 'img' && !!attr(kid, 'alt')) || says(kid)),
+ )
+const cells = (row: Element, tags: string[]) =>
+ row.kids.filter((cell): cell is Element => typeof cell !== 'string' && tags.includes(cell.tag))
+// a table that's no skeleton: a body row (not under thead, nor a first row of headers alone) has a cell that says
+// something
+const standing = (table: Element) => {
+ const rows: [Element, boolean][] = []
+ const walk = (parent: Element, inHead: boolean) => {
+ for (const kid of parent.kids) {
+ if (typeof kid === 'string' || dropped(kid)) continue
+ if (kid.tag === 'tr') rows.push([kid, inHead])
+ walk(kid, inHead || kid.tag === 'thead')
+ }
+ }
+ walk(table, false)
+ const headed = rows.some(([, inHead]) => inHead)
+ return rows.some(
+ ([row, inHead], i) =>
+ !inHead &&
+ !(i === 0 && !headed && cells(row, ['td']).length === 0) &&
+ cells(row, ['td', 'th']).some(says),
+ )
+}
+
+// a page's slot names, unique and duplicate, or why md-core can't read them as @affordances/md does
+export const readSlots = (
+ doc: Document,
+ options: Options = {},
+): { unique: string[]; duplicate: string[] } | { decline: string } => {
+ const content = contentOf(doc, options)
+ if (content.markers?.decline) return { decline: content.markers.decline }
+ if (!content.markers) return { unique: [], duplicate: [] }
+ const { unique, duplicate, decline } = slotsIn(doc, content)
+ return decline ? { decline } : { unique: [...unique], duplicate }
+}
+
// the page's canonical, if it's an http(s) url that fits in a Link header
const canonicalOf = (href: string | undefined, base: string | undefined) => {
if (!href) return undefined
diff --git a/packages/md/src/convert/core/types.ts b/packages/md/src/convert/core/types.ts
index de37a6a..53eba2b 100644
--- a/packages/md/src/convert/core/types.ts
+++ b/packages/md/src/convert/core/types.ts
@@ -112,6 +112,8 @@ export type Options = {
// @affordances/md's rewrite of the links in marker markdown (an 's), with the page's base; without it
// they're written as they are. internal: md passes its own
relinkMarkdown?: (markdown: string, base: string, link: Options['link']) => string
+ // markdown for each , in place of its children; a name the page renders more than once fills nothing
+ fills?: Record
}
export type Result = { markdown: string; title?: string; url?: string; tokens: number }
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index 08ef21d..7837c44 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -22,9 +22,8 @@ import { decodeString } from 'micromark-util-decode-string'
import { normalizeIdentifier } from 'micromark-util-normalize-identifier'
import { visit } from 'unist-util-visit'
import { minifyWhitespace } from './whitespace.ts'
-import { emit as emitCore } from './core/emit.ts'
+import { emit as emitCore, readSlots } from './core/emit.ts'
import { parse as parseCore } from './core/parse.ts'
-import { readMarkers } from './core/emit-markers.ts'
import type { Document as CoreDocument, Options as CoreOptions } from './core/types.ts'
import { declined, forcedPath } from './path.ts'
@@ -2330,7 +2329,8 @@ export const readPage = (html: string, options: Options = {}): Page => {
if (coreTakes(options)) {
const core = readCore(lean, swapped, options)
if (core && !core.reason) return core.page
- // swaps that can't be trusted: the page as sent, as md-core reads it, and an error of its own
+ // swaps that can't be trusted: the page as sent, as md-core reads it, and an error of its own. a rare path, so the
+ // page is parsed again with every push still in it as a script's text
const sent = core && readCore(html, { ...swapped, errors: [''] }, options)
if (sent) return sent.page
}
@@ -2459,20 +2459,20 @@ const readCore = (
// the first call converts the tree read here; md-core's emit prunes a tree in place, so another parses again
let doc: CoreDocument | undefined = parseCore(html)
const reason = untrusted(doc.scripts, swapped)
+ const coreOptions: CoreOptions = { ...(options as CoreOptions), relinkMarkdown }
// a marked page whose markers md-core can't read as prune does
- const why = doc.marked ? readMarkers(doc.root).decline : undefined
- if (why) {
- declined(why)
+ const slots = readSlots(doc, coreOptions)
+ if ('decline' in slots) {
+ declined(slots.decline)
return undefined
}
- const coreOptions: CoreOptions = { ...(options as CoreOptions), relinkMarkdown }
const page: Page = {
- slots: { unique: [], duplicate: [] },
+ slots: { unique: slots.unique, duplicate: slots.duplicate },
...controlOf(swapped.errors),
- markdown: () => {
+ markdown: (fills) => {
const tree = doc ?? parseCore(html)
doc = undefined
- return emitCore(tree, coreOptions)
+ return emitCore(tree, { ...coreOptions, ...(fills && { fills }) })
},
}
return { page, reason }
diff --git a/packages/md/test/convert/core/emit.test.ts b/packages/md/test/convert/core/emit.test.ts
index b009115..2e89df6 100644
--- a/packages/md/test/convert/core/emit.test.ts
+++ b/packages/md/test/convert/core/emit.test.ts
@@ -305,7 +305,7 @@ describe('options', () => {
// before the package is built again)
const fixtures = fixturePages()
// known differences, all from what emit doesn't do yet, each with the share of its reference lines emit reproduces in
-// order: slots, the form summary, streamed suspense
+// order: the form summary, streamed suspense
// boundaries. a page that gets closer should raise its floor; one that gets exact moves out of the list
const KNOWN = new Map([
['form', 0.58],
diff --git a/packages/md/test/convert/core/path.test.ts b/packages/md/test/convert/core/path.test.ts
index d553da8..8d38afe 100644
--- a/packages/md/test/convert/core/path.test.ts
+++ b/packages/md/test/convert/core/path.test.ts
@@ -28,12 +28,11 @@ test('handlers and a function extract take the tree pipeline, without a decline'
})
test('a page md-core declines is counted, and the tree pipeline writes it; strict throws instead', () => {
- const slotted =
- 'a
fallback
'
+ const slotted = 'a
'
const tree = htmlToMarkdown(slotted)
forcePath('core')
expect(htmlToMarkdown(slotted)).toEqual(tree)
- expect(declines.get('slot')).toBe(1)
+ expect(declines.get('streamed')).toBe(1)
forcePath('strict')
- expect(() => readPage(slotted)).toThrow(/md-core declined the page \(slot\)/)
+ expect(() => readPage(slotted)).toThrow(/md-core declined the page \(streamed\)/)
})
diff --git a/packages/md/test/convert/core/slots.test.ts b/packages/md/test/convert/core/slots.test.ts
new file mode 100644
index 0000000..a3f4fc7
--- /dev/null
+++ b/packages/md/test/convert/core/slots.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, expect, test } from 'vitest'
+import { declines, forcePath } from '../../../src/convert/path.ts'
+import { readPage } from '../../../src/index.ts'
+
+afterEach(() => {
+ forcePath(undefined)
+ declines.clear()
+})
+
+const slot = (name: string, inner = '…') =>
+ `${inner} `
+const at = {
+ url: 'https://example.test/page',
+ link: (url: URL) => `${url.origin}${url.pathname}.md`,
+}
+
+// a page read on both paths, md-core's in strict mode: its slots, then its markdown with each set of fills in turn,
+// all from the one read
+const read = (html: string, fills: (Record | undefined)[]) => {
+ const page = readPage(html, at)
+ return { slots: page.slots, markdown: fills.map((fill) => page.markdown(fill).markdown) }
+}
+const both = (html: string, fills: (Record | undefined)[] = [undefined]) => {
+ forcePath('hast')
+ const tree = read(html, fills)
+ forcePath('strict')
+ return { core: read(html, fills), tree }
+}
+
+test.each([
+ [
+ 'in page order, unique and duplicate',
+ `${slot('b')}x
${slot('a')}${slot('b')}${slot('c')}`,
+ ],
+ ['one inside another never counts', slot('outer', `${slot('inner')}
`)],
+ [
+ 'hidden, skipped or in an AgentText, never',
+ `${slot('h')}
${slot('s')} ${slot('t')} ${slot('kept')}`,
+ ],
+ ['outside the main, never', `${slot('out')}${slot('in')} `],
+ [
+ 'outside an AgentMain, never',
+ `${slot('m')} ${slot('am')} `,
+ ],
+ [
+ 'in chrome a page without a main strips, never',
+ `${slot('nav')} ${slot('body')}
`,
+ ],
+ ['without a name, never', `${slot('')}x
`],
+])('slot names: %s', (_, html) => {
+ const { core, tree } = both(html)
+ expect(core).toEqual(tree)
+})
+
+test.each([
+ ['a block, in a paragraph', `Latest ${slot('v')} today
`, { v: '**5.1.0**' }],
+ [
+ 'in a heading, a link and emphasis',
+ `Package ${slot('v')} See ${slot('w')} more
A ${slot('x')} b
`,
+ { v: 'express', w: '[docs](/docs)', x: '- one' },
+ ],
+ [
+ 'in table cells',
+ `Name Notes ${slot('a')} ${slot('b')}
`,
+ { a: 'line1\n\nline2 a|b', b: '- x\n- y' },
+ ],
+ [
+ 'in code, which never shows it',
+ `x ${slot('a', 'fallback')} y
x ${slot('a', 'fallback')} y `,
+ { a: 'FILL' },
+ ],
+ [
+ 'a duplicate fills nothing',
+ `${slot('d', 'one
')}${slot('d', 'two
')}`,
+ { d: 'FILL' },
+ ],
+ [
+ 'an empty fill leaves nothing',
+ `Before
${slot('e', 'Loading…
')}After
`,
+ { e: '' },
+ ],
+ [
+ 'in a heading read as its button, and in one whose slot holds a value',
+ `Open ${slot('x', '')}${slot('y', ' ')} body
`,
+ { x: 'FILLED', y: 'TOO' },
+ ],
+ [
+ 'its children still name and judge what is around it',
+ `${slot('a', 'name ')}
`,
+ { a: 'FILL' },
+ ],
+])('fills: %s', (_, html, fill) => {
+ const { core, tree } = both(html, [fill])
+ expect(core).toEqual(tree)
+})
+
+test('a second markdown() with other fills is what the tree pipeline writes, as is a first without any', () => {
+ const { core, tree } = both(
+ `Pkg ${slot('readme', 'Loading readme…
')}${slot('v')}
`,
+ [{ readme: '## Readme\n\nFast.', v: '1.0.0' }, { readme: 'Other [link](/l)' }, undefined],
+ )
+ expect(core).toEqual(tree)
+})
+
+test('a slot md-core cannot tell prune keeps is declined, never written differently', () => {
+ for (const html of [
+ // a link drops a block with nothing to read
+ `${slot('a', '')}
`,
+ // a skeleton table goes whole
+ ``,
+ ]) {
+ forcePath('hast')
+ const tree = readPage(html).markdown({ a: 'FILL' }).markdown
+ forcePath('core')
+ declines.clear()
+ expect(readPage(html).markdown({ a: 'FILL' }).markdown).toBe(tree)
+ expect(declines.size).toBe(1)
+ }
+})
From fb04b98e881cfa5695e2c8c60c565637a72fd5c0 Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 18:09:38 +0000
Subject: [PATCH 14/74] feat(md): forms on md-core's path, by md's own form
code
A form on md-core's path is converted by the tree pipeline's code, as an
island: md-core hands over the form as parse5 would have made it (the
elements prune left, as conversion reads them, attributes as written,
with md's own prune edits: no page-set data-affordances-md-text, no hidden
on what's shown), the content's elements by id, and its filled slots. md
turns that into hast with hast-util-from-parse5, minifies its whitespace
and converts it with toMdast and its handlers, so the field summary, the
names, which values show and the secret filters are md's own. md-core maps
the mdast to its nodes and resolves their links as md does afterwards.
The form is minified in the whitespace it's in (a doesn't wrap, a
keeps it), as md's pass over the whole page has it.
Without the hook (md-core on its own, as the bench runs it) a form still
says what it says without its fields.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/emit-convert.ts | 128 ++++++++++++++++++-
packages/md/src/convert/core/emit-prune.ts | 2 +-
packages/md/src/convert/core/emit.ts | 4 +-
packages/md/src/convert/core/types.ts | 38 ++++++
packages/md/src/convert/index.ts | 77 ++++++++++-
packages/md/src/convert/whitespace.ts | 5 +-
packages/md/test/convert/core/forms.test.ts | 115 +++++++++++++++++
7 files changed, 359 insertions(+), 10 deletions(-)
create mode 100644 packages/md/test/convert/core/forms.test.ts
diff --git a/packages/md/src/convert/core/emit-convert.ts b/packages/md/src/convert/core/emit-convert.ts
index bf61e22..4f5647a 100644
--- a/packages/md/src/convert/core/emit-convert.ts
+++ b/packages/md/src/convert/core/emit-convert.ts
@@ -29,15 +29,22 @@ import {
THEMATIC_BREAK,
BLOCKQUOTE,
} from './emit-markdown.ts'
-import { attr } from './attr.ts'
-import { classes, kidsOf as prunedKids, linkLabel, text } from './emit-prune.ts'
+import { attr, parseAttrs } from './attr.ts'
+import { classes, kidsOf as prunedKids, linkLabel, text, unhidden } from './emit-prune.ts'
// an element's children as conversion reads them: prune's, except a filled slot's, which never convert (prune still
// reads them, as @affordances/md's does before it empties the slot)
const NONE: Node[] = []
const kidsOf = (el: Element): Node[] =>
el.verbatim !== undefined && el.tag === 'affordances-md' ? NONE : prunedKids(el)
-import { FLAG, type Element, type Node, type Options } from './types.ts'
+import {
+ FLAG,
+ type Element,
+ type FormNode,
+ type MdastNode,
+ type Node,
+ type Options,
+} from './types.ts'
// the page's content as the emitter's tree, as hast-util-to-mdast (MIT, Titus Wormer) converts it with
// @affordances/md's handlers. whitespace is collapsed on the way, as hast-util-minify-whitespace would before: the
@@ -187,6 +194,9 @@ export const startConvert = (options: Options, page: string | undefined) => {
fast = (options as { fast?: boolean }).fast !== false
base = page
relink = options.link
+ convertForm = options.convertForm
+ contentRoot = undefined
+ contentIds = undefined
inTable = false
skips = new Set()
controls = 0
@@ -861,12 +871,123 @@ const details = (el: Element) => {
// a form says what it says, without its controls (the field summary is @affordances/md's alone, for now)
const form = (el: Element) => {
+ if (convertForm) return island(el)
controls++
const flow = toFlow(all(el))
controls--
return flow
}
+// a form as @affordances/md converts it, by its own code: md-core hands over the form as parse5 would have made it
+// (what prune left, as conversion reads it), and maps the mdast that comes back to its own nodes
+let convertForm: Options['convertForm']
+let contentRoot: Element | undefined
+// the first element with each id in what's converted, as the tree pipeline collects them
+let contentIds: Map | undefined
+const idsOfContent = () => {
+ if (contentIds) return contentIds
+ const found = new Map()
+ const walk = (parent: Element) => {
+ for (const kid of kidsOf(parent)) {
+ if (typeof kid === 'string') continue
+ const id = attr(kid, 'id')
+ if (id && !found.has(id)) found.set(id, kid)
+ walk(kid)
+ }
+ }
+ if (contentRoot) walk(contentRoot)
+ return (contentIds = found)
+}
+const HTML_NS = 'http://www.w3.org/1999/xhtml'
+const island = (el: Element): Md[] => {
+ const nodes = new Map()
+ const fills = new Map()
+ const nodeOf = (from: Element): FormNode => {
+ let made = nodes.get(from)
+ if (made) return made
+ // an is a span or div that says its markdown; a filled slot is the marker, emptied, with its fill
+ const agentText = from.verbatim !== undefined && from.tag !== 'affordances-md'
+ const attrs = agentText
+ ? [{ name: 'data-affordances-md-text', value: from.verbatim! }]
+ : [...parseAttrs(from.attrs)].flatMap(([name, value]) =>
+ // only an is markdown said as it is, and what's shown has no hidden
+ name === 'data-affordances-md-text' || (name === 'hidden' && unhidden(from))
+ ? []
+ : [{ name, value }],
+ )
+ made = { nodeName: from.tag, tagName: from.tag, attrs, namespaceURI: HTML_NS, childNodes: [] }
+ nodes.set(from, made)
+ if (agentText) made.childNodes = [{ nodeName: '#text', value: from.verbatim! }]
+ else if (from.verbatim !== undefined) fills.set(made, from.verbatim)
+ else
+ made.childNodes = kidsOf(from).map((kid) =>
+ typeof kid === 'string' ? { nodeName: '#text', value: kid } : nodeOf(kid),
+ )
+ return made
+ }
+ const root = nodeOf(el)
+ const ids = {
+ get: (id: string) => {
+ const found = idsOfContent().get(id)
+ return found && nodeOf(found)
+ },
+ }
+ const whitespace = mode === PRE ? 'pre' : mode === NOWRAP ? 'nowrap' : 'normal'
+ return convertForm!(root, ids, fills, whitespace).map(fromMdast)
+}
+const MDAST: Record = {
+ paragraph: PARAGRAPH,
+ heading: HEADING,
+ thematicBreak: THEMATIC_BREAK,
+ blockquote: BLOCKQUOTE,
+ list: LIST,
+ listItem: LIST_ITEM,
+ code: CODE,
+ table: TABLE,
+ tableRow: TABLE_ROW,
+ tableCell: TABLE_CELL,
+ html: HTML,
+ text: TEXT,
+ emphasis: EMPHASIS,
+ strong: STRONG,
+ delete: DELETE,
+ inlineCode: INLINE_CODE,
+ break: BREAK,
+ link: LINK,
+ image: IMAGE,
+}
+// mdast as md-core's nodes, with links and images resolved as the tree pipeline resolves them once it has converted
+const fromMdast = (from: MdastNode): Md => {
+ const type = MDAST[from.type]
+ if (type === undefined) throw new Error(`md-core can't read mdast ${from.type}`)
+ const made = new Md(
+ type,
+ from.children?.map(fromMdast),
+ type === IMAGE ? (from.alt ?? '') : (from.value ?? ''),
+ )
+ made.clean = true
+ if (type === HEADING) made.depth = from.depth ?? 1
+ else if (type === LIST) {
+ made.ordered = Boolean(from.ordered)
+ if (made.ordered) made.depth = from.start ?? 0
+ made.spread = Boolean(from.spread)
+ } else if (type === LIST_ITEM) {
+ made.spread = Boolean(from.spread)
+ made.checked = from.checked ?? null
+ } else if (type === CODE) {
+ made.lang = from.lang ?? null
+ made.meta = from.meta ?? null
+ } else if (type === TABLE) made.align = from.align ?? null
+ else if (type === LINK || type === IMAGE) {
+ made.url = resolve(from.url ?? '', type === IMAGE)
+ made.title = from.title ?? null
+ } else if (type === HTML) {
+ const as = from.data?.affordancesMd
+ made.depth = as === 'inline' ? MARKED_INLINE : as === 'block' ? MARKED_BLOCK : 0
+ } else if (type === TEXT && made.value.includes('\n')) made.depth = 1
+ return made
+}
+
// a code block's language: a language-* class on its , data-language on it or the , or a class on the
const classLanguage = (el: Element | undefined) =>
el &&
@@ -1253,6 +1374,7 @@ const trimAndCollapse = (value: string, breakBefore: unknown, breakAfter: unknow
// the walk over the content's root, as hast-util-to-mdast's root handler: wrapped when it holds blocks
export const convertRoot = (root: Element): Md => {
+ contentRoot = root
flow = true
before = true
after = true
diff --git a/packages/md/src/convert/core/emit-prune.ts b/packages/md/src/convert/core/emit-prune.ts
index 495454c..e2ce62f 100644
--- a/packages/md/src/convert/core/emit-prune.ts
+++ b/packages/md/src/convert/core/emit-prune.ts
@@ -66,7 +66,7 @@ export const marked = (el: Element) => {
const mode = attr(el, 'data-affordances-md')
return mode === 'skip' || mode === 'show' ? mode : undefined
}
-const unhidden = (el: Element) => {
+export const unhidden = (el: Element) => {
const mode = flags(el) & MARKED ? marked(el) : undefined
return mode === 'only' || mode === 'show'
}
diff --git a/packages/md/src/convert/core/emit.ts b/packages/md/src/convert/core/emit.ts
index 10977e4..794eb05 100644
--- a/packages/md/src/convert/core/emit.ts
+++ b/packages/md/src/convert/core/emit.ts
@@ -21,8 +21,8 @@ import { FLAG, type Document, type Element, type Options, type Result } from './
// markdown straight from the parser's tree: what @affordances/md's htmlToMarkdown writes for the same page. one walk
// prunes, extracts, collapses whitespace and converts (emit-prune, emit-convert) into a lean tree that's written out
// (emit-markdown); finish adds what the page's head says.
-// not here yet, where they'd hook in: the form summary (convert's form()), streamed suspense boundaries (the
-// parser), custom handlers
+// a form is @affordances/md's own conversion of it, when md passes it in (options.convertForm). not here yet, where
+// they'd hook in: streamed suspense boundaries (the parser), custom handlers
export const emit = (doc: Document, options: Options = {}): Result => {
const { head } = doc
const meta = (key: string) => (head.meta.get(key) ?? '').trim() || undefined
diff --git a/packages/md/src/convert/core/types.ts b/packages/md/src/convert/core/types.ts
index 53eba2b..2d44c62 100644
--- a/packages/md/src/convert/core/types.ts
+++ b/packages/md/src/convert/core/types.ts
@@ -114,6 +114,44 @@ export type Options = {
relinkMarkdown?: (markdown: string, base: string, link: Options['link']) => string
// markdown for each , in place of its children; a name the page renders more than once fills nothing
fills?: Record
+ // @affordances/md's own conversion of a form (its field summary, which values show and which are secrets), given
+ // the form as parse5 would have made it, the content's elements by id, and its filled slots. internal: md passes
+ // its own; without it a form says what it says, without its fields
+ convertForm?: (
+ form: FormNode,
+ ids: { get: (id: string) => FormNode | undefined },
+ fills: Map,
+ // the whitespace the form is in: a doesn't wrap, a keeps it as written
+ whitespace: 'normal' | 'nowrap' | 'pre',
+ ) => MdastNode[]
+}
+
+// a node as parse5 makes it, as much of it as hast-util-from-parse5 reads
+export type FormNode = {
+ nodeName: string
+ tagName?: string
+ value?: string
+ attrs?: { name: string; value: string }[]
+ namespaceURI?: string
+ childNodes?: FormNode[]
+}
+// an mdast node, as much of it as md-core reads
+export type MdastNode = {
+ type: string
+ children?: MdastNode[]
+ value?: string
+ depth?: number
+ ordered?: boolean | null
+ start?: number | null
+ spread?: boolean | null
+ checked?: boolean | null
+ lang?: string | null
+ meta?: string | null
+ url?: string
+ title?: string | null
+ alt?: string | null
+ align?: (string | null)[] | null
+ data?: { affordancesMd?: 'inline' | 'block' }
}
export type Result = { markdown: string; title?: string; url?: string; tokens: number }
diff --git a/packages/md/src/convert/index.ts b/packages/md/src/convert/index.ts
index 7837c44..3c67210 100644
--- a/packages/md/src/convert/index.ts
+++ b/packages/md/src/convert/index.ts
@@ -24,7 +24,12 @@ import { visit } from 'unist-util-visit'
import { minifyWhitespace } from './whitespace.ts'
import { emit as emitCore, readSlots } from './core/emit.ts'
import { parse as parseCore } from './core/parse.ts'
-import type { Document as CoreDocument, Options as CoreOptions } from './core/types.ts'
+import type {
+ Document as CoreDocument,
+ FormNode,
+ MdastNode,
+ Options as CoreOptions,
+} from './core/types.ts'
import { declined, forcedPath } from './path.ts'
export type Handlers = Record
@@ -2459,7 +2464,7 @@ const readCore = (
// the first call converts the tree read here; md-core's emit prunes a tree in place, so another parses again
let doc: CoreDocument | undefined = parseCore(html)
const reason = untrusted(doc.scripts, swapped)
- const coreOptions: CoreOptions = { ...(options as CoreOptions), relinkMarkdown }
+ const coreOptions: CoreOptions = { ...(options as CoreOptions), relinkMarkdown, convertForm }
// a marked page whose markers md-core can't read as prune does
const slots = readSlots(doc, coreOptions)
if ('decline' in slots) {
@@ -2478,6 +2483,74 @@ const readCore = (
return { page, reason }
}
+// a form on md-core's path, converted as the tree pipeline converts it: md-core hands over the form as parse5 would
+// have made it (the elements prune left, attributes as written), the elements the page's content names by id, and
+// its filled slots. the whitespace pass, the form summary and every handler are this pipeline's own, so what a form
+// says (its fields' names, which values show and which are secrets) is the same on both paths
+type Parse5Node = Parameters[0]
+const hastOf = (node: FormNode) => fromParse5(node as unknown as Parse5Node) as Element
+export const convertForm: NonNullable = (
+ handed,
+ byIds,
+ fills,
+ whitespace,
+) => {
+ const hast = hastOf(handed)
+ // each node handed over and the element made of it
+ const made = new Map()
+ const pair = (from: FormNode, to: ElementContent) => {
+ if (to.type !== 'element') return
+ made.set(from, to)
+ const kids = from.childNodes ?? []
+ for (let i = 0; i < kids.length; i++) pair(kids[i]!, to.children[i]!)
+ }
+ pair(handed, hast)
+ // a filled slot says so by a property no attribute parses to, which survives the copies the form summary makes
+ const filled = new Map()
+ for (const [node, md] of fills) {
+ const el = made.get(node)
+ if (!el) continue
+ const key = String(filled.size)
+ el.properties[FILLABLE] = key
+ filled.set(key, md)
+ }
+ minifyWhitespace({ type: 'root', children: [hast] }, whitespace)
+ // the content's ids: an element in the form is the form's own, any other is made when it's first asked for
+ class ById extends Map {
+ override get(id: string) {
+ if (!super.has(id)) {
+ const named = byIds.get(id)
+ if (named) super.set(id, made.get(named) ?? hastOf(named))
+ }
+ return super.get(id)
+ }
+ override has(id: string) {
+ return this.get(id) !== undefined
+ }
+ }
+ const marker: Handle = (state, node) => {
+ const key = node.properties[FILLABLE]
+ const md = typeof key === 'string' ? filled.get(key) : undefined
+ return (md === undefined ? state.all(node) : markerMarkdown(md, 'block')) as never
+ }
+ let entered = false
+ const mdast = toMdast(
+ { type: 'root', children: [] },
+ {
+ handlers: { ...handlers, 'affordances-md': marker },
+ nodeHandlers: {
+ root: (state, node) => {
+ if (entered) return defaultNodeHandlers.root(state, node)
+ entered = true
+ state.elementById = new ById()
+ return defaultNodeHandlers.root(state, { type: 'root', children: [hast] })
+ },
+ },
+ },
+ ) as MdastRoot
+ return mdast.children as MdastNode[]
+}
+
// a tree as hast-util-to-mdast converts it, without what it does first: a structured clone of all it's given, so its
// whitespace pass can change it, then that pass. it does both to an empty root instead, whose handler converts this
// copy: only what the whitespace pass changes (children, a text's value) is new, and a node's place in the html, which
diff --git a/packages/md/src/convert/whitespace.ts b/packages/md/src/convert/whitespace.ts
index 346011d..3e44d63 100644
--- a/packages/md/src/convert/whitespace.ts
+++ b/packages/md/src/convert/whitespace.ts
@@ -115,8 +115,9 @@ const blank = (value: string) => !/[^ \t\n\f\r]/.test(value)
const collapse = (value: string) => String(value).replace(/[\t\n\v\f\r ]+/g, ' ')
const removable = (character: string) => character === ' ' || character === '\n'
-export const minifyWhitespace = (tree: Nodes) => {
- minify(tree, { whitespace: 'normal', before: undefined, after: undefined })
+// whitespace: what the tree is in, for one taken from a page (md-core's form, in a or a )
+export const minifyWhitespace = (tree: Nodes, whitespace: Whitespace = 'normal') => {
+ minify(tree, { whitespace, before: undefined, after: undefined })
}
const minify = (node: Nodes, state: State): Result => {
diff --git a/packages/md/test/convert/core/forms.test.ts b/packages/md/test/convert/core/forms.test.ts
new file mode 100644
index 0000000..4d91fdc
--- /dev/null
+++ b/packages/md/test/convert/core/forms.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, expect, test } from 'vitest'
+import { forcePath } from '../../../src/convert/path.ts'
+import { readPage } from '../../../src/index.ts'
+
+afterEach(() => forcePath(undefined))
+
+const at = {
+ url: 'https://example.test/page',
+ link: (url: URL) => `${url.origin}${url.pathname}.md`,
+}
+// a page's markdown on both paths, md-core's in strict mode, with fills if given
+const both = (html: string, fills?: Record) => {
+ forcePath('hast')
+ const tree = readPage(html, at).markdown(fills).markdown
+ forcePath('strict')
+ return { core: readPage(html, at).markdown(fills).markdown, tree }
+}
+
+const values = (fields: string) => ``
+test.each([
+ [
+ 'values, and what a secret looks like',
+ values(
+ 'Plan API key ',
+ ),
+ ],
+ [
+ 'secrets by autocomplete, as a list of tokens',
+ values(
+ ' ',
+ ),
+ ],
+ [
+ 'toggles and choices',
+ values(
+ 'Wi-Fi Bold Size M L ',
+ ),
+ ],
+ [
+ 'selects and textareas',
+ values(
+ 'One a b Many x Notes Picked Choose ',
+ ),
+ ],
+ [
+ 'without values, none show',
+ '',
+ ],
+])('fields: %s', (_, html) => {
+ const { core, tree } = both(html)
+ expect(core).toBe(tree)
+})
+
+test.each([
+ [
+ 'aria-labelledby inside and outside the form',
+ 'Billing
',
+ ],
+ [
+ 'a label for two ids names neither',
+ '',
+ ],
+ [
+ 'names never carry a value out',
+ 'LEAK ',
+ ],
+ [
+ 'a name in something hidden names nothing',
+ 'LEAK ',
+ ],
+ [
+ 'an id outside the main names nothing',
+ 'Outside
',
+ ],
+ [
+ 'placeholders and names are never labels',
+ ' ',
+ ],
+])('names: %s', (_, html) => {
+ const { core, tree } = both(html)
+ expect(core).toBe(tree)
+})
+
+test.each([
+ [
+ 'a table keeps its shape',
+ ' ',
+ ],
+ [
+ 'a definition list',
+ 'Seats ',
+ ],
+ [
+ 'prose around fields, with links and images',
+ 'Sign up Read the terms
Hint
',
+ ],
+ [
+ 'in a list item and a table cell',
+ '',
+ ],
+ ['no fields says what it says', 'Just text
Go '],
+ // in the whitespace it's in: a doesn't wrap
+ ['in a nobr', 'text\r\n t u '],
+])('shape: %s', (_, html) => {
+ const { core, tree } = both(html)
+ expect(core).toBe(tree)
+})
+
+const slot = (name: string) =>
+ `Loading
`
+test('markers in a form: an AgentText, a filled slot and one without a fill', () => {
+ const html = ` ${slot('a')}${slot('b')} `
+ const { core, tree } = both(html, { a: '- [x](/x)' })
+ expect(core).toBe(tree)
+})
From 3464735ec47595d8da4c2ea5e1c7f18f4e5f43df Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 18:11:28 +0000
Subject: [PATCH 15/74] fix(md-core): ask the link option once per link
md asks options.link once for each link it writes, in tree order. md-core
asked again when the fast path declined a block after resolving its
links, and when a block was converted again to be read (the description
check), so a callback saw some links twice. Each link element's url is now
resolved once per conversion. md's own behaviour doesn't change.
Co-Authored-By: Claude Opus 5.5
---
packages/md/src/convert/core/emit-convert.ts | 13 ++++-
packages/md/test/convert/core/link.test.ts | 61 ++++++++++++++++++++
2 files changed, 72 insertions(+), 2 deletions(-)
create mode 100644 packages/md/test/convert/core/link.test.ts
diff --git a/packages/md/src/convert/core/emit-convert.ts b/packages/md/src/convert/core/emit-convert.ts
index 4f5647a..a00d574 100644
--- a/packages/md/src/convert/core/emit-convert.ts
+++ b/packages/md/src/convert/core/emit-convert.ts
@@ -206,6 +206,7 @@ export const startConvert = (options: Options, page: string | undefined) => {
after = undefined
mode = NORMAL
urls.clear()
+ linkUrls.clear()
setBase(page)
}
@@ -719,6 +720,14 @@ const resolve = (url: string, image: boolean) => {
return href
}
+// a link's url, once per link: a block the fast path declines, or one converted again to be read (materialize), never
+// asks the link option twice, as the tree pipeline asks it once for each link it writes
+const linkUrls = new Map()
+const linkUrl = (el: Element, href: string) => {
+ let url = linkUrls.get(el)
+ if (url === undefined) linkUrls.set(el, (url = resolve(href, false)))
+ return url
+}
const HEADINGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
const link = (el: Element, parent: Element) => {
const href = (attr(el, 'href') ?? '').trim()
@@ -727,7 +736,7 @@ const link = (el: Element, parent: Element) => {
// a heading's link to its own anchor is the heading
if (href.startsWith('#') && HEADINGS.has(parent.tag)) return children
const result = node(LINK, children)
- result.url = resolve(href, false)
+ result.url = linkUrl(el, href)
result.title = el.flags & FLAG.title ? (attr(el, 'title') ?? null) : null
// an icon or avatar link reads as its label
if (!children.some((child) => child.type !== TEXT || child.value.trim())) {
@@ -1536,7 +1545,7 @@ const fastLink = (el: Element, inHeading: boolean, out: Md[]): boolean => {
if (!children.some((child) => child.type !== TEXT || child.value.trim()))
return decline('link named by its label')
const result = node(LINK, children)
- result.url = resolve(href, false)
+ result.url = linkUrl(el, href)
result.title = el.flags & FLAG.title ? (attr(el, 'title') ?? null) : null
out.push(result)
return true
diff --git a/packages/md/test/convert/core/link.test.ts b/packages/md/test/convert/core/link.test.ts
new file mode 100644
index 0000000..8506ae6
--- /dev/null
+++ b/packages/md/test/convert/core/link.test.ts
@@ -0,0 +1,61 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import { afterEach, expect, test } from 'vitest'
+import { Declined, forcePath } from '../../../src/convert/path.ts'
+import { htmlToMarkdown } from '../../../src/index.ts'
+
+afterEach(() => forcePath(undefined))
+
+const dir = new URL('../../fixtures/', import.meta.url)
+const fixtures = readdirSync(dir)
+ .filter((file) => file.endsWith('.html'))
+ .map((file) => [file, readFileSync(new URL(file, dir), 'utf8')] as const)
+
+// the urls the link option is asked about, in order, and the markdown
+const asked = (html: string) => {
+ const seen: string[] = []
+ const { markdown } = htmlToMarkdown(html, {
+ url: 'https://shop.test/page',
+ link: (url) => {
+ seen.push(url.href)
+ return `${url.href}.md`
+ },
+ })
+ return { seen, markdown }
+}
+
+test.each([
+ [
+ 'a block the fast path declines after its links',
+ 'A Top B
',
+ ],
+ [
+ 'a block right after the h1, read again for the description',
+ 'T A
',
+ ],
+ [
+ 'a list written as it is read',
+ '',
+ ],
+ ['the same url twice', 'One and two
'],
+])('the link option is asked once per link, in order: %s', (_, html) => {
+ forcePath('hast')
+ const tree = asked(html)
+ forcePath('strict')
+ expect(asked(html)).toEqual(tree)
+})
+
+test('and over every fixture md-core writes', () => {
+ let compared = 0
+ for (const [, html] of fixtures) {
+ forcePath('hast')
+ const tree = asked(html)
+ forcePath('strict')
+ try {
+ expect(asked(html)).toEqual(tree)
+ compared++
+ } catch (error) {
+ if (!(error instanceof Declined)) throw error
+ }
+ }
+ expect(compared).toBeGreaterThan(fixtures.length / 2)
+})
From 97d2c10250ad51d96e6388f0069618ce3b917bcd Mon Sep 17 00:00:00 2001
From: Jason Korol
Date: Fri, 13 Nov 2026 18:15:42 +0000
Subject: [PATCH 16/74] feat(md): md-core declines what only the tree pipeline
reads as it does
These go to the tree pipeline, counted, before md-core writes anything.
md-core's parser reads each exactly, in place of a regex over the html:
- 'streamed': react's Suspense boundaries move into place
(resolveStreamed), which md-core doesn't do. That takes a
and an instruction (a script whose text has $RC, $RR or $RS, or a
template with data-bid or data-pid). A test holds every fixture, corpus
and generated page resolveStreamed changes to being one md-core declines.
- 'selector tag name': an element named with a # or a ., which
hast-util-from-parse5 builds with hastscript's h() and so reads as a
selector ( is a link with id x, '
+ const slotted =
+ 'a
b
'
const tree = htmlToMarkdown(slotted)
forcePath('core')
expect(htmlToMarkdown(slotted)).toEqual(tree)
@@ -36,3 +38,25 @@ test('a page md-core declines is counted, and the tree pipeline writes it; stric
forcePath('strict')
expect(() => readPage(slotted)).toThrow(/md-core declined the page \(streamed\)/)
})
+
+test('an element named like a selector, which the tree pipeline renames, declines the page', () => {
+ const push = ''
+ for (const html of [
+ 'link para ',
+ `a
${push} `,
+ ]) {
+ forcePath('hast')
+ const tree = htmlToMarkdown(html).markdown
+ forcePath('core')
+ declines.clear()
+ expect(htmlToMarkdown(html).markdown).toBe(tree)
+ expect(Object.fromEntries(declines)).toEqual({ 'selector tag name': 1 })
+ }
+ // on the handler's path, the push in what the tree pipeline reads as a script is never trusted, on either path
+ const strip = flightStripper()
+ const kept = strip.write(`a
${push} `) + strip.end()
+ for (const path of ['hast', 'core'] as const) {
+ forcePath(path)
+ expect(() => readStreamed(kept, strip.swapped())).toThrow(/unswapped/)
+ }
+})
diff --git a/packages/md/test/convert/core/recovery.test.ts b/packages/md/test/convert/core/recovery.test.ts
new file mode 100644
index 0000000..fd100f7
--- /dev/null
+++ b/packages/md/test/convert/core/recovery.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, expect, test } from 'vitest'
+import { declines, forcePath } from '../../../src/convert/path.ts'
+import { htmlToMarkdown, readPage, type Options } from '../../../src/index.ts'
+
+afterEach(() => {
+ forcePath(undefined)
+ declines.clear()
+})
+
+// a malformed page through md on both paths (htmlToMarkdown, and readPage with a fill): what md-core writes, what the
+// tree pipeline writes, and why md-core declined it, if it did
+const read = (html: string, options: Options) => {
+ const page = readPage(html, options)
+ const { markdown, ...rest } = page
+ return JSON.stringify([htmlToMarkdown(html, options), rest, markdown({ a: 'F' })])
+}
+const both = (html: string, options: Options = {}) => {
+ forcePath('hast')
+ const tree = read(html, options)
+ forcePath('core')
+ declines.clear()
+ const core = read(html, options)
+ return { core, tree, declined: [...declines.keys()] }
+}
+
+// md-core declines these: the tree pipeline prunes the page in place before it reads it, and what it finds there
+// depends on what it pruned first; and it writes a strikethrough outside a paragraph (right in a list, or around
+// one), where what's escaped isn't what md-core escapes
+test.each([
+ ['a main in a link', 'text', 'main inside what prune changes'],
+ ['a main in a heading', '