// Content-hash keying of top-level blocks. // // The reactive markdown() helper renders top-level blocks through a keyed `each`. // Keying each block by a hash of its SOURCE SLICE means unchanged blocks keep the // same key across re-parses, so the reconciler reuses their DOM untouched and only // the changing tail (and any appended blocks) rebuild — the streaming sweet spot. import type { Node } from 'unist' import type { Root, RootContent, Nodes, Definition } from 'mdast' import type { ResolvedOptions } from './types.js' declare global { // Vite/Rollup substitute `import.meta.env.DEV`; raw tsc/vitest see undefined // (dev warnings stay off). Merges with @llui/dom's identical augmentation. interface ImportMeta { env?: { DEV?: boolean; MODE?: string } } } export interface KeyedBlock { /** Reconcile identity for the outer keyed list (from `keyOf`, else content-based). */ key: string | number /** Content identity — changes iff the block's source (or the reference * definitions it resolves) changes. Drives in-place row rebuilds when a custom * `keyOf` gives blocks stable identity. */ hash: string node: Nodes } /** Per-block content-id memo, keyed on NODE IDENTITY. The incremental parser * reuses the SAME node objects for the sealed prefix (incremental.ts), so on each * streamed chunk the prefix blocks hit this cache in O(1) and only the changed * tail (new node objects) is re-hashed — turning per-chunk keying from O(document) * into O(tail). A cache miss (a genuinely new node object) recomputes and stores. * * Correctness across definition edits: a REF-FREE block's content-id depends only * on its (stable) source slice, so it is memoized outright. A REF-BEARING block's * id folds in the url/title of the definitions it resolves, which can change while * the node object is reused (`[a][r]` with `[r]: /old` → `/new`); for those we * recompute the (cheap) reference fingerprint each time and only reuse the cached * id when it is unchanged. The produced content-id is byte-identical to the * non-memoized formula. */ interface BlockMemo { contentId: string /** Whether the block consumes any link/image/footnote references (fingerprint * non-empty). */ hasRefs: boolean /** The reference fingerprint the cached id was computed against (`''` if ref-free). */ fingerprint: string } const blockMemo = new WeakMap() /** FNV-1a over TWO independent bases, length-seeded → a 64-bit digest as two * base36 words. A single 32-bit FNV collides on ~1-in-4-billion distinct blocks * (silent wrong-block DOM reuse); doubling the width + seeding the length makes a * collision astronomically unlikely for the block counts markdown() ever keys. */ function hash(str: string): string { let a = 0x811c9dc5 ^ str.length let b = 0x811c9dc5 for (let i = 0; i < str.length; i++) { const c = str.charCodeAt(i) a = Math.imul(a ^ c, 0x01000193) b = Math.imul(b ^ c, 0x01000197) } return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}` } /** The block's source text (via mdast position offsets), or a structural fallback. */ export function blockSource(node: RootContent, source: string): string { const pos = node.position if (pos && pos.start.offset != null && pos.end.offset != null) { return source.slice(pos.start.offset, pos.end.offset) } return JSON.stringify(node) } /** Field separator inside the reference fingerprint below. * * WRITTEN AS THE `\0` ESCAPE, NEVER AS A LITERAL BYTE. git sniffs content: one raw * NUL and it classifies this file as BINARY, so `git diff`, `git log -p` and * GitHub's review view all hide changes to it by default — in the one file that * decides whether a reused prefix block re-renders during streaming (#94, and #84 * was a one-line omission here that nothing forced anyone to look at). The escape * keeps the byte out of the file while leaving the VALUE untouched. * * SEP is a DELIMITER, not a guarantee. What makes the fingerprint unambiguous is * that every field is length-prefixed (`referenceFingerprint` below) — that holds * for any field content, including a field containing SEP itself. Nothing here may * be restructured to depend on a field not containing SEP. * * U+0000 is nonetheless the right delimiter, for defence in depth: it is the one * character no Markdown source can put into a field in the first place. CommonMark * mandates replacing U+0000 with U+FFFD and micromark does it in its PREPROCESSOR — * upstream of every tokenizer and of any user-supplied syntax/mdast extension — so * for a parser-produced table it is unreachable, raw or as `�`. A printable * delimiter (`|`, `=`, `␟`, …) occurs in real urls and titles constantly, and the * earlier `${id}=${url}|${title}` layout is what a delimiter doing the work * unaided looks like: it gave `[r]: /a|b` and `[r]: /a "b|"` ONE fingerprint, * leaving a reused block's href stale after that edit. * * `test/keying.test.ts` pins the invariant and the collisions; * `scripts/test/source-encoding.test.ts` pins that no tracked source holds the * raw byte, repo-wide. */ const SEP = '\0' /** Collect the (lowercased, NAMESPACED) reference identifiers a block CONSUMES. * * These are mdast's three reference nodes, and all three matter: `linkReference` / * `imageReference` (namespaced `l:`) resolve their destination through the * document's definition table, and `footnoteReference` (namespaced `f:`) exists at * all only while a matching `[^id]:` definition does — until then the same source * is plain text, so the node's PRESENCE is the whole dependency. * * The `l:`/`f:` namespaces mirror `definitions.ts`'s label ids: a link definition * `x` and a footnote definition `x` are different labels, and a block may consume * both (`see [a][x] and[^x]`). Collapsing them into one entry would make the * fingerprint blind to one of the two arriving. */ function collectReferences(node: Node, out: Set): void { const id = (node as { identifier?: unknown }).identifier if (typeof id === 'string') { if (node.type === 'linkReference' || node.type === 'imageReference') { out.add('l:' + id.toLowerCase()) } else if (node.type === 'footnoteReference') { out.add('f:' + id.toLowerCase()) } } const kids = (node as { children?: readonly Node[] }).children if (kids) for (const child of kids) collectReferences(child, out) } /** A stable fingerprint of the reference definitions a block resolves. Empty for * ref-free blocks (their key stays a pure content hash). For ref-bearing blocks it * folds each consumed definition's current url/title in, so a block re-renders * EXACTLY when a `[ref]: url` it depends on arrives later or is edited — the * streaming case where a definition lands after the block that uses it. */ function referenceFingerprint(node: Node, definitions: ReadonlyMap): string { const ids = new Set() collectReferences(node, ids) if (ids.size === 0) return '' // FIXED-ARITY RECORDS OF LENGTH-PREFIXED FIELDS: every consumed id contributes // exactly four fields — id, state code, url, title — each emitted as // `SEP`. Decoding is deterministic for ANY field content (read the // digits up to the SEP, then take exactly that many characters), so the encoding // is INJECTIVE UNCONDITIONALLY: a fingerprint is unchanged iff every definition // the block resolves is unchanged, full stop. // // The length prefixes are the load-bearing part, NOT the choice of separator. // Fixed arity over plain SEP-JOINED fields would only fix field POSITIONS while // every field happened to be SEP-free, and one SEP inside a url shifts the whole // join — `{url: 'p\0q', title: 'r'}` and `{url: 'p', title: 'q\0r'}` join // identically, which is the `${id}=${url}|${title}` bug again with a rarer // character. Markdown cannot produce that (see SEP), but this table arrives as a // PARAMETER: `toKeyedBlocks`, `renderMarkdown` and `createMarkdown(parse)` are all // public, and a caller's `ParseFn` or `mdastExtensions` never passes micromark's // preprocessor. Do not "simplify" this back to a join. (Length-prefixing the // RECORD instead of the FIELDS does not work either: both splittings above // produce a body of the same length.) // // The state code is its own field because url+title cannot carry all of the // states on their own: `[r]: <>` is a DEFINED reference with an empty url, which // must not read like an UNDEFINED one, and a `''` title must not read like an // absent one (mdast-util-from-markdown normalizes `[r]: /u ""` to `title: null`, // but `title` is `string | null | undefined` and, again, the table is a // parameter — do not lean on that normalization). const parts: string[] = [] /** Append one record's fields, each self-delimiting. */ const push = (...fields: string[]): void => { for (const value of fields) parts.push(`${value.length}${SEP}${value}`) } for (const id of [...ids].sort()) { if (id.startsWith('f:')) { // A footnote reference renders from its own identifier/label alone // (`renderers/block.ts`), and the render context exposes no footnote table, // so its only dependency is whether the reference node EXISTS — which the // entry's mere presence records. That covers both directions: the definition // arriving turns literal text into a `footnoteReference` (empty fingerprint // to `f:a`), and removing it turns it back. push(id, 'f', '', '') continue } const def = definitions.get(id.slice(2)) const title = def?.title if (!def) push(id, '-', '', '') else if (title == null) push(id, 'u', def.url, '') else push(id, 't', def.url, title) } // Each field already carries its own length, so the fields need no separator // between them; joining with one would add a second, redundant framing. return `${SEP}ref:${parts.join('')}` } /** Number of times a block's content-id was hashed from scratch (a memo MISS or a * ref-bearing recompute). A memo HIT does no hashing. Exposed for tests/benchmarks * to assert reused prefix blocks are NOT re-hashed per streamed chunk. */ let blockHashComputations = 0 /** Test/benchmark hook: reads (and optionally resets) the from-scratch hash count. */ export function keyingHashComputations(reset = false): number { const n = blockHashComputations if (reset) blockHashComputations = 0 return n } /** The memoized content-id for one top-level block (see {@link blockMemo}). */ function contentIdFor( node: RootContent, source: string, definitions: ReadonlyMap, ): string { const cached = blockMemo.get(node) // A ref-free cached block can never change id for a (stable-identity) node, so // return it without even walking the subtree for references. if (cached && !cached.hasRefs) return cached.contentId const fingerprint = referenceFingerprint(node, definitions) if (cached && cached.fingerprint === fingerprint) return cached.contentId blockHashComputations++ // LENGTH-PREFIXED, the same device the fingerprint's own fields use: plain // concatenation has no split point, so a `blockSource` slice ending in the bytes // of a fingerprint would hash exactly like a shorter source carrying that // fingerprint. The source half is the one component that can contain ANYTHING — // it is sliced from the string the CALLER passed, before micromark substitutes // U+0000 — so the boundary has to be encoded rather than assumed. const hashInput = `${fingerprint.length}${SEP}${fingerprint}${blockSource(node, source)}` const contentId = `${node.type}:${hash(hashInput)}` blockMemo.set(node, { contentId, hasRefs: fingerprint !== '', fingerprint }) return contentId } /** Derive a stable, unique-per-render key for each top-level block. Identical block * source (AND identical resolved references) ⇒ identical base key; duplicate keys — * whether from identical content or a user `keyOf` — get a `#n` suffix so the outer * `each` never receives a colliding key (which would corrupt its keyed reconcile). */ export function toKeyedBlocks( root: Root, source: string, options: ResolvedOptions, definitions: ReadonlyMap, ): KeyedBlock[] { const seen = new Map() const dedupe = (base: string | number, fromKeyOf: boolean): string | number => { const s = String(base) const dup = seen.get(s) ?? 0 seen.set(s, dup + 1) if (dup === 0) return base if (fromKeyOf && import.meta.env?.DEV === true) { console.warn( `[LLui markdown] keyOf produced a duplicate block key ${JSON.stringify(s)}; ` + `disambiguating with "#${dup}". Duplicate keys corrupt the keyed reconcile — ` + `return a unique key per top-level block.`, ) } return `${s}#${dup}` } return root.children.map((node, index) => { const contentId = contentIdFor(node, source, definitions) if (options.keyOf) { return { key: dedupe(options.keyOf(node, index), true), hash: contentId, node } } return { key: dedupe(contentId, false), hash: contentId, node } }) }