diff --git a/.changeset/html-first-release.md b/.changeset/html-first-release.md index 7c18a95..28be598 100644 --- a/.changeset/html-first-release.md +++ b/.changeset/html-first-release.md @@ -2,4 +2,6 @@ '@bomb.sh/html': minor --- -Adds `@bomb.sh/html`, a spec-conformant HTML parser compiled to WebAssembly. `parse()` turns a document or a fragment in a context element into an op log, and `replay()` applies it to any DOM through a `TreeSink`. `parse(html, { limits: { nodes, logBytes } })` stops a parse that builds more than its budget with a `LimitError`. The engine is embedded in the package, seeds its hash tables per instance, and compiles on the first parse. +Adds `@bomb.sh/html`, a spec-conformant HTML parser compiled to WebAssembly. `parse(html)` returns a document tree of plain objects, and `parseFragment(html, { context: 'div' })` parses a fragment the way `innerHTML` does. Both take a string, UTF-8 bytes, or an iterable of either, and return synchronously; given an async iterable or a `ReadableStream`, they return a promise. + +`@bomb.sh/html/sink` parses into any DOM through a `TreeSink`, and `@bomb.sh/html/log` returns the engine's op log and `replay()`s it. `limits: { nodes, logBytes }` stops a parse that builds more than its budget with a `LimitError`, before a sink sees any of it. The engine is embedded in the package, seeds its hash tables per instance, and compiles on the first parse. diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 6268990..96331f2 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -13,7 +13,7 @@ pnpm metrics --only size # size alone, about 1 s pnpm metrics --compare HEAD # A/B against the last commit, about 40 s ``` -The command builds nothing. It reads `build/html.wasm`, `build/tokens.wasm` and the current `src/index.ts`, so run +The command builds nothing. It reads `build/html.wasm`, `build/tokens.wasm` and the current `src/engine.ts`, so run `scripts/build.sh` (or `pnpm test`, which runs it) after changing the engine. The speed section also needs `vendor/corpus`, which `scripts/corpus.sh` fetches and the test script vendors. @@ -24,8 +24,8 @@ operation, plus the commit, whether the tree is dirty, the load average and the | Option | Effect | | --- | --- | | `--only size` / `--only speed` | One section. | -| `--compare ` | A/B: the committed engine at a git ref (the wasm its `src/wasm.ts` embeds, and its `src/index.ts`) against the working tree's `build/html.wasm` and `src/index.ts`. | -| `--compare ` | A/B against a saved build, driven by `--compare-index ` or the current `src/index.ts`. | +| `--compare ` | A/B: the committed engine at a git ref (the wasm its `src/wasm.ts` embeds, and its `src/engine.ts`, or `src/index.ts` before the public layers split from it) against the working tree's `build/html.wasm` and `src/index.ts`. | +| `--compare ` | A/B against a saved build, driven by `--compare-index ` or the current `src/engine.ts`. | | `--candidate `, `--candidate-index ` | Replace the working tree's side of an A/B. | | `--suite fragment\|corpus\|ui` | Run only these suites (repeatable). | | `--samples N`, `--lanes N` | Rounds and sampling lanes: 32 and 8 for an A/B, 32 and 2 otherwise. | @@ -38,7 +38,7 @@ operation, plus the commit, whether the tree is dirty, the load average and the ### Size The size metric is **the brotli -11 size of `build/html.wasm`**, the bytes `src/wasm.ts` embeds. The report also -gives raw and `gzip -9n` sizes of `html.wasm` and `tokens.wasm`, the bytes of `src/wasm.ts`, and `src/index.ts` +gives raw and `gzip -9n` sizes of `html.wasm` and `tokens.wasm`, the bytes of `src/wasm.ts`, and `src/engine.ts` bundled and minified with esbuild (`--bundle --minify --format=esm`, with `wasm.ts` left external). Size is exact: no noise, no sampling. `gzip -9n` omits the file name, so it reads a few bytes below the `gzip -9c` figures that `scripts/build.sh` prints. diff --git a/docs/op-log.md b/docs/op-log.md index 967789b..dc01d56 100644 --- a/docs/op-log.md +++ b/docs/op-log.md @@ -1,7 +1,7 @@ # Op log format `build/html.wasm` does not build a tree. Tree construction appends operations to a log in linear memory, and a host -applies them to its own nodes. `replay()` in `src/index.ts` is the reference consumer. +applies them to its own nodes. `replay()` in `src/engine.ts`, exported from `@bomb.sh/html/log`, is the reference consumer. The log is append-only, so a later streaming parser can hand out a prefix of it while parsing continues. The adoption agency algorithm and foster parenting move nodes that earlier records already placed, so the log has diff --git a/package.json b/package.json index a128e2b..61e6a5e 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,8 @@ "sideEffects": false, "exports": { ".": "./src/index.ts", + "./sink": "./src/sink.ts", + "./log": "./src/log.ts", "./package.json": "./package.json" }, "files": [ @@ -34,11 +36,19 @@ "types": "./dist/index.d.mts", "import": "./dist/index.mjs" }, + "./sink": { + "types": "./dist/sink.d.mts", + "import": "./dist/sink.mjs" + }, + "./log": { + "types": "./dist/log.d.mts", + "import": "./dist/log.mjs" + }, "./package.json": "./package.json" } }, "scripts": { - "build": "pnpm run build:engine && bsh build --dts src/index.ts", + "build": "pnpm run build:engine && bsh build --dts src/index.ts src/sink.ts src/log.ts", "build:engine": "node scripts/engine.mjs", "check:engine": "node scripts/engine.mjs --check", "prepack": "test -f dist/wasm.mjs || { echo \"prepack: run pnpm build first\" >&2; exit 1; }", diff --git a/scripts/adversarial.ts b/scripts/adversarial.ts index bf7b506..ec3ab8b 100644 --- a/scripts/adversarial.ts +++ b/scripts/adversarial.ts @@ -1,7 +1,7 @@ // Times every test/adversarial.ts case at two sizes and flags growth well past linear. // Usage: node scripts/adversarial.ts [--parse5] [--small N] [--large N] [name filter] import { parse as parse5, parseFragment as parse5Fragment } from 'parse5'; -import { parse } from '../src/index.ts'; +import { parse } from '../src/engine.ts'; import { cases, type AdversarialCase } from '../test/adversarial.ts'; const args = process.argv.slice(2); diff --git a/scripts/bench-fragment.ts b/scripts/bench-fragment.ts index d94d289..d1cb586 100644 --- a/scripts/bench-fragment.ts +++ b/scripts/bench-fragment.ts @@ -3,7 +3,7 @@ // and parse5's parseFragment, medians of alternating rounds. Also the cost of a bail. Usage: // node scripts/bench-fragment.ts [rounds] import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { PlainSink } from '../test/dom.ts'; import { parseInDiv, FULL, rng, subsetFragment } from '../test/fragments.ts'; diff --git a/scripts/bench-tree.ts b/scripts/bench-tree.ts index 6608789..933d9a1 100644 --- a/scripts/bench-tree.ts +++ b/scripts/bench-tree.ts @@ -2,7 +2,7 @@ // alternating rounds. Usage: node scripts/bench-tree.ts [rounds] [wasm path] import { readdirSync, readFileSync } from 'node:fs'; import { parse as parse5 } from 'parse5'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { createNode, PlainSink, type Node } from '../test/dom.ts'; interface Engine { diff --git a/scripts/metrics.ts b/scripts/metrics.ts index 57977a2..1ad542d 100644 --- a/scripts/metrics.ts +++ b/scripts/metrics.ts @@ -1,5 +1,5 @@ // The size and speed metrics the engine's hillclimbs judge changes by (docs/benchmarks.md). Builds nothing: it reads -// build/html.wasm, build/tokens.wasm and the current src/index.ts. The readable report goes to stderr, JSON to stdout. +// build/html.wasm, build/tokens.wasm and the current src/engine.ts. The readable report goes to stderr, JSON to stdout. // // node scripts/metrics.ts size, speed, and the comparison parsers // node scripts/metrics.ts --only size size alone (instant) @@ -42,7 +42,7 @@ const root = new URL('../', import.meta.url); const path = (p: string): string => fileURLToPath(new URL(p, root)); const HTML_WASM = path('build/html.wasm'); const TOKENS_WASM = path('build/tokens.wasm'); -const INDEX = path('src/index.ts'); +const INDEX = path('src/engine.ts'); // The ui suite runs @clack/ui from a checkout of bombshell-dev/ui, beside this repo unless UI_DOM names its dom.ts. const UI_DOM = process.env.UI_DOM ?? path('../ui/packages/ui/src/dom.ts'); const CORPUS = new URL('vendor/corpus/', root); @@ -193,7 +193,7 @@ async function sizes(): Promise> { 'html.wasm': size(readFileSync(HTML_WASM)), 'tokens.wasm': size(readFileSync(TOKENS_WASM)), 'wasm.ts': readFileSync(path('src/wasm.ts')).length, - 'index.ts (bundled, minified)': await wrapper(INDEX), + 'engine.ts (bundled, minified)': await wrapper(INDEX), }; } @@ -234,8 +234,8 @@ const candidateSubject = (): EngineSubject => index: read(args['candidate-index'] ?? INDEX), }); -// A .wasm file with --compare-index or the current src/index.ts, or a git ref's committed engine: the wasm its -// src/wasm.ts embeds, and the src/index.ts beside it. +// A .wasm file with --compare-index or the current src/engine.ts, or a git ref's committed engine: the wasm its +// src/wasm.ts embeds, and the src/engine.ts beside it. async function baseSubject(spec: string): Promise { if (spec.endsWith('.wasm')) { return staged({ @@ -249,12 +249,22 @@ async function baseSubject(spec: string): Promise { execFileSync('git', ['show', `${spec}:./${file}`], { cwd: fileURLToPath(root), encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, }); const module = new URL('wasm.ts', stage); writeFileSync(module, show('src/wasm.ts')); const { wasmBytes } = (await import(module.href)) as { wasmBytes(): Uint8Array }; - return staged({ slot: 'a', label: 'base', wasm: wasmBytes(), index: show('src/index.ts') }); + return staged({ slot: 'a', label: 'base', wasm: wasmBytes(), index: engineHost(show) }); +} + +// The module that drives the engine: src/engine.ts, or src/index.ts before the public layers split from it. +function engineHost(show: (file: string) => string): string { + try { + return show('src/engine.ts'); + } catch { + return show('src/index.ts'); + } } // ---- workloads diff --git a/scripts/metrics/protocol.ts b/scripts/metrics/protocol.ts index dfc2860..42360d4 100644 --- a/scripts/metrics/protocol.ts +++ b/scripts/metrics/protocol.ts @@ -1,6 +1,6 @@ // What scripts/metrics.ts and its sampling workers (scripts/metrics/worker.ts) exchange. -/** An engine is a build of html.wasm with the src/index.ts that drives it; a library is a comparison parser. */ +/** An engine is a build of html.wasm with the src/engine.ts that drives it; a library is a comparison parser. */ export type Subject = | { kind: 'engine'; label: string; wasm: string; index: string } | { kind: 'library'; label: string; name: LibraryName }; @@ -31,7 +31,7 @@ export interface WorkerData { subject: Subject; bands: string[][]; corpus: string[]; - /** src/index.ts as a file URL: imports of it resolve to the subject's index instead. */ + /** src/engine.ts as a file URL: imports of it resolve to the subject's index instead. */ realIndex: string; /** packages/ui/src/dom.ts as a file URL, when innerHTML workloads run. */ ui: string | null; diff --git a/scripts/metrics/sensitivity.ts b/scripts/metrics/sensitivity.ts index 1caf24b..433ce39 100644 --- a/scripts/metrics/sensitivity.ts +++ b/scripts/metrics/sensitivity.ts @@ -1,6 +1,6 @@ // Checks that scripts/metrics.ts's A/B mode resolves known differences and finds none between identical engines, // under whatever load the machine has now (docs/benchmarks.md#sensitivity). Builds its variants in a temporary -// directory from build/ and src/index.ts: the wrapper forced onto the full tree builder, html.wasm optimized with -O3 +// directory from build/ and src/engine.ts: the wrapper forced onto the full tree builder, html.wasm optimized with -O3 // instead of -Oz, and the wrapper with a spin loop in parse() that adds about 1.2% to fragment parse() time per 0.01. // Usage: node scripts/metrics/sensitivity.ts [spin factors, default 0.0125 0.025 0.05] import { execFileSync } from 'node:child_process'; @@ -13,16 +13,16 @@ const spins = process.argv.length > 2 ? process.argv.slice(2) : ['0.0125', '0.02 const dir = pathToFileURL(`${mkdtempSync(`${tmpdir()}/html-sensitivity-`)}/`); process.on('exit', () => rmSync(dir, { recursive: true, force: true })); -/** src/index.ts no longer has the line a variant rewrites. */ +/** src/engine.ts no longer has the line a variant rewrites. */ class VariantError extends Error { constructor(anchor: string) { super( - `src/index.ts has no ${JSON.stringify(anchor)} to rewrite; update scripts/metrics/sensitivity.ts`, + `src/engine.ts has no ${JSON.stringify(anchor)} to rewrite; update scripts/metrics/sensitivity.ts`, ); } } -const index = readFileSync(new URL('src/index.ts', root), 'utf8'); +const index = readFileSync(new URL('src/engine.ts', root), 'utf8'); function variant(name: string, edit: { anchor: string; replacement: string }): string { if (!index.includes(edit.anchor)) throw new VariantError(edit.anchor); const file = new URL(`${name}.ts`, dir); diff --git a/scripts/metrics/worker.ts b/scripts/metrics/worker.ts index 28bdc51..69a4685 100644 --- a/scripts/metrics/worker.ts +++ b/scripts/metrics/worker.ts @@ -8,14 +8,14 @@ import type { Attribute, ElementNamespace, OpLog, - ParseOptions, + EngineOptions, TreeSink, -} from '../../src/index.ts'; +} from '../../src/engine.ts'; import type { DefaultTreeAdapterTypes } from 'parse5'; import type { EngineSubject, Prepared, Request, Sample, Workload, WorkerData } from './protocol.ts'; interface Html { - parse(html: string, options?: ParseOptions): OpLog; + parse(html: string, options?: EngineOptions): OpLog; replay(log: OpLog, sink: TreeSink): N[]; } @@ -177,9 +177,9 @@ async function engineImplementation(engine: EngineSubject): Promise + const fragment = (w: Workload): EngineOptions => w.fast ? { context: 'div' } : { context: 'div', fastPath: false }; - const document: ParseOptions = { scripting: true }; + const document: EngineOptions = { scripting: true }; const tree = (w: Workload, source: string): PlainNode => html.replay( diff --git a/src/engine.ts b/src/engine.ts new file mode 100644 index 0000000..7de3a22 --- /dev/null +++ b/src/engine.ts @@ -0,0 +1,585 @@ +import { wasmBytes } from './wasm.ts'; + +// The WebAssembly API's types live in the DOM lib, which a consumer type-checking this source for Node may not load. +declare const WebAssembly: { + Module: new (bytes: Uint8Array) => object; + Instance: new (module: object, imports: object) => { readonly exports: unknown }; +}; + +interface Exports { + memory: { readonly buffer: ArrayBuffer }; + inbuf(cap: number): number; + parse(len: number, context: number, flags: number, maxNodes: number, maxLog: number): number; + log(): number; + logLen(): number; + nodeCount(): number; + textEnd(): number; + errors(): number; + errorCount(): number; + scratch(): number; + atom(p: number, n: number): number; + atomText(id: number): number; + atomLen(id: number): number; + seed(a: number, b: number, c: number, d: number): void; +} + +export const Namespace = { + HTML: 'http://www.w3.org/1999/xhtml', + SVG: 'http://www.w3.org/2000/svg', + MathML: 'http://www.w3.org/1998/Math/MathML', + XLink: 'http://www.w3.org/1999/xlink', + XML: 'http://www.w3.org/XML/1998/namespace', + XMLNS: 'http://www.w3.org/2000/xmlns/', +} as const; +export type ElementNamespace = + | typeof Namespace.HTML + | typeof Namespace.SVG + | typeof Namespace.MathML; +export type AttributeNamespace = + | typeof Namespace.XLink + | typeof Namespace.XML + | typeof Namespace.XMLNS; +export type QuirksMode = 'no-quirks' | 'limited-quirks' | 'quirks'; + +/** The element a fragment is parsed in, as for `innerHTML`. */ +export interface FragmentContext { + /** The element's local name, e.g. `td` or `foreignObject`. */ + name: string; + namespace?: ElementNamespace; + /** A MathML `annotation-xml` whose `encoding` is `text/html` or `application/xhtml+xml`. */ + htmlIntegrationPoint?: boolean; + /** The element is, or is inside, a `form`. */ + inForm?: boolean; + /** The context document's mode. */ + quirksMode?: QuirksMode; +} + +export interface ParseOptions { + /** The scripting flag: `noscript` content is raw text when on. Defaults to off. */ + scripting?: boolean; + /** + * Stops a parse that builds more than this, with a LimitError. Unlimited by default. The spec makes some input + * build a tree quadratic in its size (`

x

` repeated n times builds about n²/2 elements), so a host + * parsing untrusted input sets these. A parse that stays within them gives the same log as an unlimited one. + */ + limits?: ParseLimits; +} + +/** What the engine takes beyond the public options. The public layers decide context by the function called. */ +export interface EngineOptions extends ParseOptions { + /** Parse a fragment in this context element instead of a document. */ + context?: string | FragmentContext; + /** + * Try the fragment fast path first (docs/decisions.md), which gives the same log on the input it accepts. Off + * forces the full tree builder, for testing. Defaults to on. + */ + fastPath?: boolean; +} + +export interface ParseLimits { + /** The most nodes the log may create, not counting the root. */ + nodes?: number; + /** The most bytes the op log may hold. */ + logBytes?: number; +} + +/** The engine's output: an op log (docs/op-log.md) and the UTF-8 bytes its strings point into. */ +export interface OpLog { + readonly ops: Int32Array; + readonly text: Uint8Array; + /** Nodes the log creates, counting the root (id 0). */ + readonly nodeCount: number; + readonly fragment: boolean; +} + +export interface Attribute { + /** The qualified name, e.g. `href` or `xlink:href`. */ + readonly name: string; + readonly namespace: AttributeNamespace | null; + readonly prefix: string | null; + readonly localName: string; + readonly value: string; +} + +/** What replay drives. N is the host's node type. */ +export interface TreeSink { + /** The root, node 0: a document, or the fragment a fragment parse fills. */ + createRoot(fragment: boolean): N; + createElement( + localName: string, + namespace: ElementNamespace, + attributes: readonly Attribute[], + ): N; + createText(data: string): N; + createComment(data: string): N; + createDoctype(name: string, publicId: string, systemId: string): N; + createProcessingInstruction(target: string, data: string): N; + /** The contents fragment of a `template` element just created. */ + templateContents(template: N): N; + /** Inserts a detached child before ref, or as the last child when ref is null. */ + insert(parent: N, child: N, ref: N | null): void; + /** Detaches child from its parent. */ + remove(child: N): void; + /** Moves every child of from, in order, to the end of to. */ + moveChildren(from: N, to: N): void; + appendText(text: N, data: string): void; + /** Adds attributes (none already present) to an html or body element. */ + addAttributes(element: N, attributes: readonly Attribute[]): void; + setQuirksMode(mode: QuirksMode): void; +} + +const Op = { + Element: 1, + Text: 2, + Comment: 3, + Doctype: 4, + ProcessingInstruction: 5, + Content: 6, + Insert: 7, + Remove: 8, + MoveChildren: 9, + AppendText: 10, + AddAttributes: 11, + Quirks: 12, +} as const; + +const FLAG = { + scripting: 1, + nsShift: 1, + htmlIntegrationPoint: 8, + inForm: 16, + quirksShift: 5, + full: 128, +} as const; +const NS_CODE = { [Namespace.HTML]: 0, [Namespace.SVG]: 1, [Namespace.MathML]: 2 } as const; +const ELEMENT_NS: readonly ElementNamespace[] = [Namespace.HTML, Namespace.SVG, Namespace.MathML]; +const ATTR_NS: readonly (AttributeNamespace | null)[] = [ + null, + Namespace.XLink, + Namespace.XML, + Namespace.XMLNS, +]; +const QUIRKS: readonly QuirksMode[] = ['no-quirks', 'limited-quirks', 'quirks']; + +/** The op log held an op code the replayer does not know. */ +export class OpLogError extends Error { + readonly op: number; + readonly at: number; + constructor(op: number, at: number) { + super(`unknown op ${op} at word ${at}`); + this.op = op; + this.at = at; + } +} + +/** + * The engine could not get the memory a parse needs. `input`: the input is too large to hold. `memory`: the input or + * the tree it builds needs more memory than the engine can grow to (2 GiB, or less where the host limits it). + */ +export class ResourceError extends Error { + readonly reason: 'input' | 'memory'; + constructor(reason: 'input' | 'memory') { + super(reason === 'input' ? 'input too large to parse' : 'out of memory while parsing'); + this.reason = reason; + } +} + +/** A parse built more than `ParseOptions.limits` allows. */ +export class LimitError extends Error { + readonly limit: keyof ParseLimits; + readonly max: number; + constructor(limit: keyof ParseLimits, max: number) { + super(`parse exceeded its limit of ${max} ${limit === 'nodes' ? 'nodes' : 'log bytes'}`); + this.limit = limit; + this.max = max; + } +} + +const MAX_I32 = 0x7fffffff; + +/** A `ParseOptions.limits` value is not an integer from 1 to 2^31 - 1. */ +export class InvalidLimitError extends RangeError { + readonly limit: keyof ParseLimits; + readonly value: number; + constructor(limit: keyof ParseLimits, value: number) { + super(`limits.${limit} must be an integer from 1 to ${MAX_I32}, not ${value}`); + this.limit = limit; + this.value = value; + } +} + +// parse()'s statuses (wit/html.wit). +const Status = { ok: 0, memory: 1, nodes: 2, log: 3, input: 4 } as const; + +let engine: Exports | undefined; +const atomNames: string[] = []; +const ASCII = /^[^\u0080-\uffff]*$/; +const encoder = new TextEncoder(); +// ignoreBOM keeps a U+FEFF at the start of a string, which is ordinary text everywhere but the start of a stream. +const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); +const strictDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +function instance(): Exports { + if (engine === undefined) { + engine = new WebAssembly.Instance(new WebAssembly.Module(wasmBytes()), {}) + .exports as unknown as Exports; + // Keys the engine's hash tables so input cannot be crafted to collide in them. The output never depends on it. + const key = crypto.getRandomValues(new Int32Array(4)); + engine.seed(key[0]!, key[1]!, key[2]!, key[3]!); + } + return engine; +} + +function atomName(x: Exports, id: number): string { + let name = atomNames[id]; + if (name === undefined) { + name = decoder.decode(new Uint8Array(x.memory.buffer, x.atomText(id), x.atomLen(id))); + atomNames[id] = name; + } + return name; +} + +// The last context name and its atom, so a host that parses many fragments in one context element looks it up once. +let contextName: string | undefined; +let contextAtomId = -1; + +function contextAtom(x: Exports, name: string): number { + if (name === contextName) return contextAtomId; + const bytes = encoder.encode(name.toLowerCase()); + let atom = -1; + if (bytes.length <= 32) { + new Uint8Array(x.memory.buffer, x.scratch(), bytes.length).set(bytes); + atom = x.atom(x.scratch(), bytes.length) || -1; + } + contextName = name; + contextAtomId = atom; + return atom; +} + +function contextFlags(c: FragmentContext): number { + let flags = NS_CODE[c.namespace ?? Namespace.HTML] << FLAG.nsShift; + if (c.htmlIntegrationPoint) flags |= FLAG.htmlIntegrationPoint; + if (c.inForm) flags |= FLAG.inForm; + flags |= QUIRKS.indexOf(c.quirksMode ?? 'no-quirks') << FLAG.quirksShift; + return flags; +} + +/** + * Parses an HTML document, or a fragment when `options.context` is set, into an op log. The engine compiles on the + * first call. + */ +export function parse(html: string, options: EngineOptions = {}): OpLog { + const x = instance(); + // V8's UTF-8 encoder runs near 1 GB/s even on one-byte strings, while Buffer's latin1 write is a memcpy, and + // ASCII is the same bytes in both. + if (typeof Buffer === 'function' && ASCII.test(html)) { + const base = reserve(x, html.length); + latin1View(x).write(html, base, 'latin1'); + return run(html.length, options); + } + const cap = html.length * 3; + const base = reserve(x, cap); + const { written } = encoder.encodeInto(html, memoryView(x).subarray(base, base + cap)); + return run(written, options); +} + +/** Like parse, for input that is already UTF-8. */ +export function parseBytes(html: Uint8Array, options: EngineOptions = {}): OpLog { + const x = instance(); + const base = reserve(x, html.length); + memoryView(x).set(html, base); + return run(html.length, options); +} + +// The engine's memory as bytes, and as a Buffer for latin1 writes. Growing the memory detaches both, which empties +// them, so each use checks. +let memoryBytes = new Uint8Array(0); +let memoryBuffer: Buffer | undefined; + +function memoryView(x: Exports): Uint8Array { + if (memoryBytes.length === 0) { + memoryBytes = new Uint8Array(x.memory.buffer); + memoryBuffer = undefined; + } + return memoryBytes; +} + +function latin1View(x: Exports): Buffer { + const bytes = memoryView(x); + memoryBuffer ??= Buffer.from(bytes.buffer); + return memoryBuffer; +} + +// A limit as the engine takes it: 0 for none. +function limitArg(name: keyof ParseLimits, limits: ParseLimits | undefined): number { + const max = limits?.[name]; + if (max === undefined) return 0; + if (!Number.isInteger(max) || max < 1 || max > MAX_I32) throw new InvalidLimitError(name, max); + return max; +} + +// The input buffer's address, as the last reserve returned it. +let inputBase = 0; + +// The input buffer's address for cap bytes. The engine returns 0 when it cannot hold them. +function reserve(x: Exports, cap: number): number { + const base = cap > MAX_I32 ? 0 : x.inbuf(cap); + if (base === 0) throw new ResourceError('input'); + inputBase = base; + return base; +} + +// Parses the len bytes already written at the input buffer. +function run(len: number, options: EngineOptions): OpLog { + const x = instance(); + const base = inputBase; + let context = 0; + let flags = 0; + const c = options.context; + if (typeof c === 'string') context = contextAtom(x, c); + else if (c !== undefined) { + context = contextAtom(x, c.name); + flags = contextFlags(c); + } + if (options.scripting) flags |= FLAG.scripting; + if (options.fastPath === false) flags |= FLAG.full; + const nodes = limitArg('nodes', options.limits); + const logBytes = limitArg('logBytes', options.limits); + const status = x.parse(len, context, flags, nodes, logBytes); + if (status === Status.nodes) throw new LimitError('nodes', nodes); + if (status === Status.log) throw new LimitError('logBytes', logBytes); + if (status === Status.memory) throw new ResourceError('memory'); + if (status !== Status.ok) throw new ResourceError('input'); + // One copy holds the log and then the text, since each buffer a parse allocates costs more than its bytes. + const log = x.log(); + const logLen = x.logLen(); + const textLen = x.textEnd() - base; + const out = new Uint8Array(logLen + textLen); + const memory = memoryView(x); + out.set(memory.subarray(log, log + logLen)); + out.set(memory.subarray(base, base + textLen), logLen); + return { + ops: new Int32Array(out.buffer, 0, logLen >> 2), + text: out.subarray(logLen), + nodeCount: x.nodeCount(), + fragment: options.context !== undefined, + }; +} + +/** + * Block size for the byte to UTF-16 offset table, as a shift. A string's offset is a byte offset, so the host + * decodes the whole text once and slices it, which needs each offset in code units. The table holds the unit count + * at the start of every block, shifted left once, with the low bit set when the block has a non-ASCII byte. + */ +const BLOCK_SHIFT = 5; +const BLOCK = 1 << BLOCK_SHIFT; + +// The start of the first block that holds a non-ASCII byte, or the length when there is none. +function asciiBlocks(bytes: Uint8Array): number { + const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2); + const full = bytes.length >> BLOCK_SHIFT; + for (let k = 0; k < full; k++) { + const w = k * (BLOCK / 4); + if ( + (words[w]! | + words[w + 1]! | + words[w + 2]! | + words[w + 3]! | + words[w + 4]! | + words[w + 5]! | + words[w + 6]! | + words[w + 7]!) & + 0x80808080 + ) + return k << BLOCK_SHIFT; + } + for (let j = full << BLOCK_SHIFT; j < bytes.length; j++) + if (bytes[j]! & 0x80) return full << BLOCK_SHIFT; + return bytes.length; +} + +function unitTable(bytes: Uint8Array): Int32Array { + const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2); + const full = bytes.length >> BLOCK_SHIFT; + const table = new Int32Array(full + 1); + let units = 0; + for (let k = 0; k < full; k++) { + const w = k * (BLOCK / 4); + const high = + (words[w]! | + words[w + 1]! | + words[w + 2]! | + words[w + 3]! | + words[w + 4]! | + words[w + 5]! | + words[w + 6]! | + words[w + 7]!) & + 0x80808080; + if (high === 0) { + table[k] = units << 1; + units += BLOCK; + } else { + table[k] = (units << 1) | 1; + for (let j = k << BLOCK_SHIFT, end = j + BLOCK; j < end; j++) units += unitsOf(bytes[j]!); + } + } + table[full] = (units << 1) | 1; + return table; +} + +// The code units a byte adds to valid UTF-8: its lead byte decides, a continuation adds none. +const unitsOf = (b: number): number => (b < 0x80 ? 1 : b >= 0xf0 ? 2 : b >= 0xc0 ? 1 : 0); + +/** Applies an op log to a sink. Returns the nodes by id; node 0 is the root. */ +export function replay(log: OpLog, sink: TreeSink): N[] { + const x = instance(); + const { ops } = log; + let bytes = log.text; + if (bytes.byteOffset & 3) bytes = bytes.slice(); + // Decoded once, in two parts split at the first block with a non-ASCII byte: the ASCII head, which strings slice + // by byte offset and which stays a one-byte string, and the rest, which they slice through the table. ASCII input + // usually has non-ASCII bytes only in the arena, after it. Text that is not valid UTF-8 falls back to decoding + // each string. + let split = bytes.length; + let ascii = ''; + let rest = bytes; + let tail = ''; + let table: Int32Array | null = null; + let whole = true; + try { + split = asciiBlocks(bytes); + ascii = strictDecoder.decode(bytes.subarray(0, split)); + if (split < bytes.length) { + rest = bytes.subarray(split); + tail = strictDecoder.decode(rest); + table = unitTable(rest); + } + } catch { + whole = false; + } + // The table lookup is written out twice rather than called, so a string in the tail costs no more calls than + // one decoded whole. + const str = (off: number, len: number): string => { + if (len <= 0) return ''; + if (!whole) return decoder.decode(bytes.subarray(off, off + len)); + const end = off + len; + if (end <= split) return ascii.substring(off, end); + const b = end - split; + const eb = table![b >> BLOCK_SHIFT]!; + let ub = eb >> 1; + if (eb & 1) for (let j = b & ~(BLOCK - 1); j < b; j++) ub += unitsOf(rest[j]!); + else ub += b & (BLOCK - 1); + if (off < split) return ascii.substring(off) + tail.substring(0, ub); + const a = off - split; + const ea = table![a >> BLOCK_SHIFT]!; + let ua = ea >> 1; + if (ea & 1) for (let j = a & ~(BLOCK - 1); j < a; j++) ua += unitsOf(rest[j]!); + else ua += a & (BLOCK - 1); + return tail.substring(ua, ub); + }; + const nodes: N[] = [sink.createRoot(log.fragment)]; + let next = 1; + const attrs = (at: number, n: number): Attribute[] => { + const list: Attribute[] = []; + for (let k = 0; k < n; k++) { + const r = at + k * 5; + const a = ops[r]!; + const id = a & 0xffff; + const name = id ? atomName(x, id) : str(ops[r + 1]!, ops[r + 2]!); + const value = str(ops[r + 3]!, ops[r + 4]!); + const ns = a >>> 16; + if (ns === 0) { + list.push({ name, namespace: null, prefix: null, localName: name, value }); + continue; + } + const namespace = ATTR_NS[ns] ?? null; + const colon = namespace ? name.indexOf(':') : -1; + list.push({ + name, + namespace, + prefix: colon < 0 ? null : name.slice(0, colon), + localName: colon < 0 ? name : name.slice(colon + 1), + value, + }); + } + return list; + }; + const created = (n: N, parent: number): void => { + nodes[next++] = n; + if (parent >= 0) sink.insert(nodes[parent] as N, n, null); + }; + const end = ops.length; + let i = 0; + while (i < end) { + const head = ops[i]!; + const code = head & 0xff; + if (code === Op.Element) { + const atom = ops[i + 2]!; + const n = ops[i + 5]!; + const name = atom ? atomName(x, atom) : str(ops[i + 3]!, ops[i + 4]!); + const ns = ELEMENT_NS[head >>> 8] ?? Namespace.HTML; + created(sink.createElement(name, ns, attrs(i + 6, n)), ops[i + 1]!); + i += 6 + n * 5; + } else if (code === Op.Text) { + created(sink.createText(str(ops[i + 2]!, ops[i + 3]!)), ops[i + 1]!); + i += 4; + } else if (code === Op.Comment) { + created(sink.createComment(str(ops[i + 2]!, ops[i + 3]!)), ops[i + 1]!); + i += 4; + } else if (code === Op.Insert) { + const ref = ops[i + 3]!; + sink.insert( + nodes[ops[i + 1]!] as N, + nodes[ops[i + 2]!] as N, + ref < 0 ? null : (nodes[ref] as N), + ); + i += 4; + } else if (code === Op.AppendText) { + sink.appendText(nodes[ops[i + 1]!] as N, str(ops[i + 2]!, ops[i + 3]!)); + i += 4; + } else if (code === Op.Content) { + nodes[next++] = sink.templateContents(nodes[ops[i + 1]!] as N); + i += 2; + } else if (code === Op.Remove) { + sink.remove(nodes[ops[i + 1]!] as N); + i += 2; + } else if (code === Op.MoveChildren) { + sink.moveChildren(nodes[ops[i + 1]!] as N, nodes[ops[i + 2]!] as N); + i += 3; + } else if (code === Op.Doctype) { + created( + sink.createDoctype( + str(ops[i + 2]!, ops[i + 3]!), + str(ops[i + 4]!, ops[i + 5]!), + str(ops[i + 6]!, ops[i + 7]!), + ), + ops[i + 1]!, + ); + i += 8; + } else if (code === Op.ProcessingInstruction) { + created( + sink.createProcessingInstruction( + str(ops[i + 2]!, ops[i + 3]!), + str(ops[i + 4]!, ops[i + 5]!), + ), + ops[i + 1]!, + ); + i += 6; + } else if (code === Op.AddAttributes) { + const n = ops[i + 3]!; + sink.addAttributes(nodes[ops[i + 1]!] as N, attrs(i + 4, n)); + i += 4 + n * 5; + } else if (code === Op.Quirks) { + sink.setQuirksMode(QUIRKS[ops[i + 1]!] ?? 'quirks'); + i += 2; + } else { + throw new OpLogError(code, i); + } + } + return nodes; +} + +/** Parses input that the public layers have gathered into one string or one UTF-8 buffer. */ +export function parseInput(input: string | Uint8Array, options: EngineOptions): OpLog { + return typeof input === 'string' ? parse(input, options) : parseBytes(input, options); +} diff --git a/src/index.ts b/src/index.ts index 1cd85b7..0451f60 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,576 +1,43 @@ -import { wasmBytes } from './wasm.ts'; - -// The WebAssembly API's types live in the DOM lib, which a consumer type-checking this source for Node may not load. -declare const WebAssembly: { - Module: new (bytes: Uint8Array) => object; - Instance: new (module: object, imports: object) => { readonly exports: unknown }; -}; - -interface Exports { - memory: { readonly buffer: ArrayBuffer }; - inbuf(cap: number): number; - parse(len: number, context: number, flags: number, maxNodes: number, maxLog: number): number; - log(): number; - logLen(): number; - nodeCount(): number; - textEnd(): number; - errors(): number; - errorCount(): number; - scratch(): number; - atom(p: number, n: number): number; - atomText(id: number): number; - atomLen(id: number): number; - seed(a: number, b: number, c: number, d: number): void; -} - -export const Namespace = { - HTML: 'http://www.w3.org/1999/xhtml', - SVG: 'http://www.w3.org/2000/svg', - MathML: 'http://www.w3.org/1998/Math/MathML', - XLink: 'http://www.w3.org/1999/xlink', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/', -} as const; -export type ElementNamespace = - | typeof Namespace.HTML - | typeof Namespace.SVG - | typeof Namespace.MathML; -export type AttributeNamespace = - | typeof Namespace.XLink - | typeof Namespace.XML - | typeof Namespace.XMLNS; -export type QuirksMode = 'no-quirks' | 'limited-quirks' | 'quirks'; - -/** The element a fragment is parsed in, as for `innerHTML`. */ -export interface FragmentContext { - /** The element's local name, e.g. `td` or `foreignObject`. */ - name: string; - namespace?: ElementNamespace; - /** A MathML `annotation-xml` whose `encoding` is `text/html` or `application/xhtml+xml`. */ - htmlIntegrationPoint?: boolean; - /** The element is, or is inside, a `form`. */ - inForm?: boolean; - /** The context document's mode. */ - quirksMode?: QuirksMode; -} - -export interface ParseOptions { - /** Parse a fragment in this context element instead of a document. */ - context?: string | FragmentContext; - /** The scripting flag: `noscript` content is raw text when on. Defaults to off. */ - scripting?: boolean; - /** - * Try the fragment fast path first (docs/decisions.md), which gives the same log on the input it accepts. Off - * forces the full tree builder, for testing. Defaults to on. - */ - fastPath?: boolean; - /** - * Stops a parse that builds more than this, with a LimitError. Unlimited by default. The spec makes some input - * build a tree quadratic in its size (`

x

` repeated n times builds about n²/2 elements), so a host - * parsing untrusted input sets these. A parse that stays within them gives the same log as an unlimited one. - */ - limits?: ParseLimits; -} - -export interface ParseLimits { - /** The most nodes the log may create, not counting the root. */ - nodes?: number; - /** The most bytes the op log may hold. */ - logBytes?: number; -} - -/** The engine's output: an op log (docs/op-log.md) and the UTF-8 bytes its strings point into. */ -export interface OpLog { - readonly ops: Int32Array; - readonly text: Uint8Array; - /** Nodes the log creates, counting the root (id 0). */ - readonly nodeCount: number; - readonly fragment: boolean; -} - -export interface Attribute { - /** The qualified name, e.g. `href` or `xlink:href`. */ - readonly name: string; - readonly namespace: AttributeNamespace | null; - readonly prefix: string | null; - readonly localName: string; - readonly value: string; -} - -/** What replay drives. N is the host's node type. */ -export interface TreeSink { - /** The root, node 0: a document, or the fragment a fragment parse fills. */ - createRoot(fragment: boolean): N; - createElement( - localName: string, - namespace: ElementNamespace, - attributes: readonly Attribute[], - ): N; - createText(data: string): N; - createComment(data: string): N; - createDoctype(name: string, publicId: string, systemId: string): N; - createProcessingInstruction(target: string, data: string): N; - /** The contents fragment of a `template` element just created. */ - templateContents(template: N): N; - /** Inserts a detached child before ref, or as the last child when ref is null. */ - insert(parent: N, child: N, ref: N | null): void; - /** Detaches child from its parent. */ - remove(child: N): void; - /** Moves every child of from, in order, to the end of to. */ - moveChildren(from: N, to: N): void; - appendText(text: N, data: string): void; - /** Adds attributes (none already present) to an html or body element. */ - addAttributes(element: N, attributes: readonly Attribute[]): void; - setQuirksMode(mode: QuirksMode): void; -} - -const Op = { - Element: 1, - Text: 2, - Comment: 3, - Doctype: 4, - ProcessingInstruction: 5, - Content: 6, - Insert: 7, - Remove: 8, - MoveChildren: 9, - AppendText: 10, - AddAttributes: 11, - Quirks: 12, -} as const; - -const FLAG = { - scripting: 1, - nsShift: 1, - htmlIntegrationPoint: 8, - inForm: 16, - quirksShift: 5, - full: 128, -} as const; -const NS_CODE = { [Namespace.HTML]: 0, [Namespace.SVG]: 1, [Namespace.MathML]: 2 } as const; -const ELEMENT_NS: readonly ElementNamespace[] = [Namespace.HTML, Namespace.SVG, Namespace.MathML]; -const ATTR_NS: readonly (AttributeNamespace | null)[] = [ - null, - Namespace.XLink, - Namespace.XML, - Namespace.XMLNS, -]; -const QUIRKS: readonly QuirksMode[] = ['no-quirks', 'limited-quirks', 'quirks']; - -/** The op log held an op code the replayer does not know. */ -export class OpLogError extends Error { - readonly op: number; - readonly at: number; - constructor(op: number, at: number) { - super(`unknown op ${op} at word ${at}`); - this.op = op; - this.at = at; - } -} - -/** - * The engine could not get the memory a parse needs. `input`: the input is too large to hold. `memory`: the input or - * the tree it builds needs more memory than the engine can grow to (2 GiB, or less where the host limits it). - */ -export class ResourceError extends Error { - readonly reason: 'input' | 'memory'; - constructor(reason: 'input' | 'memory') { - super(reason === 'input' ? 'input too large to parse' : 'out of memory while parsing'); - this.reason = reason; - } -} - -/** A parse built more than `ParseOptions.limits` allows. */ -export class LimitError extends Error { - readonly limit: keyof ParseLimits; - readonly max: number; - constructor(limit: keyof ParseLimits, max: number) { - super(`parse exceeded its limit of ${max} ${limit === 'nodes' ? 'nodes' : 'log bytes'}`); - this.limit = limit; - this.max = max; - } -} - -const MAX_I32 = 0x7fffffff; - -/** A `ParseOptions.limits` value is not an integer from 1 to 2^31 - 1. */ -export class InvalidLimitError extends RangeError { - readonly limit: keyof ParseLimits; - readonly value: number; - constructor(limit: keyof ParseLimits, value: number) { - super(`limits.${limit} must be an integer from 1 to ${MAX_I32}, not ${value}`); - this.limit = limit; - this.value = value; - } -} - -// parse()'s statuses (wit/html.wit). -const Status = { ok: 0, memory: 1, nodes: 2, log: 3, input: 4 } as const; - -let engine: Exports | undefined; -const atomNames: string[] = []; -const ASCII = /^[^\u0080-\uffff]*$/; -const encoder = new TextEncoder(); -// ignoreBOM keeps a U+FEFF at the start of a string, which is ordinary text everywhere but the start of a stream. -const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); -const strictDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); - -function instance(): Exports { - if (engine === undefined) { - engine = new WebAssembly.Instance(new WebAssembly.Module(wasmBytes()), {}) - .exports as unknown as Exports; - // Keys the engine's hash tables so input cannot be crafted to collide in them. The output never depends on it. - const key = crypto.getRandomValues(new Int32Array(4)); - engine.seed(key[0]!, key[1]!, key[2]!, key[3]!); - } - return engine; -} - -function atomName(x: Exports, id: number): string { - let name = atomNames[id]; - if (name === undefined) { - name = decoder.decode(new Uint8Array(x.memory.buffer, x.atomText(id), x.atomLen(id))); - atomNames[id] = name; - } - return name; -} - -// The last context name and its atom, so a host that parses many fragments in one context element looks it up once. -let contextName: string | undefined; -let contextAtomId = -1; - -function contextAtom(x: Exports, name: string): number { - if (name === contextName) return contextAtomId; - const bytes = encoder.encode(name.toLowerCase()); - let atom = -1; - if (bytes.length <= 32) { - new Uint8Array(x.memory.buffer, x.scratch(), bytes.length).set(bytes); - atom = x.atom(x.scratch(), bytes.length) || -1; - } - contextName = name; - contextAtomId = atom; - return atom; -} - -function contextFlags(c: FragmentContext): number { - let flags = NS_CODE[c.namespace ?? Namespace.HTML] << FLAG.nsShift; - if (c.htmlIntegrationPoint) flags |= FLAG.htmlIntegrationPoint; - if (c.inForm) flags |= FLAG.inForm; - flags |= QUIRKS.indexOf(c.quirksMode ?? 'no-quirks') << FLAG.quirksShift; - return flags; -} - -/** - * Parses an HTML document, or a fragment when `options.context` is set, into an op log. The engine compiles on the - * first call. - */ -export function parse(html: string, options: ParseOptions = {}): OpLog { - const x = instance(); - // V8's UTF-8 encoder runs near 1 GB/s even on one-byte strings, while Buffer's latin1 write is a memcpy, and - // ASCII is the same bytes in both. - if (typeof Buffer === 'function' && ASCII.test(html)) { - const base = reserve(x, html.length); - latin1View(x).write(html, base, 'latin1'); - return run(html.length, options); - } - const cap = html.length * 3; - const base = reserve(x, cap); - const { written } = encoder.encodeInto(html, memoryView(x).subarray(base, base + cap)); - return run(written, options); -} - -/** Like parse, for input that is already UTF-8. */ -export function parseBytes(html: Uint8Array, options: ParseOptions = {}): OpLog { - const x = instance(); - const base = reserve(x, html.length); - memoryView(x).set(html, base); - return run(html.length, options); -} - -// The engine's memory as bytes, and as a Buffer for latin1 writes. Growing the memory detaches both, which empties -// them, so each use checks. -let memoryBytes = new Uint8Array(0); -let memoryBuffer: Buffer | undefined; - -function memoryView(x: Exports): Uint8Array { - if (memoryBytes.length === 0) { - memoryBytes = new Uint8Array(x.memory.buffer); - memoryBuffer = undefined; - } - return memoryBytes; -} - -function latin1View(x: Exports): Buffer { - const bytes = memoryView(x); - memoryBuffer ??= Buffer.from(bytes.buffer); - return memoryBuffer; -} - -// A limit as the engine takes it: 0 for none. -function limitArg(name: keyof ParseLimits, limits: ParseLimits | undefined): number { - const max = limits?.[name]; - if (max === undefined) return 0; - if (!Number.isInteger(max) || max < 1 || max > MAX_I32) throw new InvalidLimitError(name, max); - return max; -} - -// The input buffer's address, as the last reserve returned it. -let inputBase = 0; - -// The input buffer's address for cap bytes. The engine returns 0 when it cannot hold them. -function reserve(x: Exports, cap: number): number { - const base = cap > MAX_I32 ? 0 : x.inbuf(cap); - if (base === 0) throw new ResourceError('input'); - inputBase = base; - return base; -} - -// Parses the len bytes already written at the input buffer. -function run(len: number, options: ParseOptions): OpLog { - const x = instance(); - const base = inputBase; - let context = 0; - let flags = 0; - const c = options.context; - if (typeof c === 'string') context = contextAtom(x, c); - else if (c !== undefined) { - context = contextAtom(x, c.name); - flags = contextFlags(c); - } - if (options.scripting) flags |= FLAG.scripting; - if (options.fastPath === false) flags |= FLAG.full; - const nodes = limitArg('nodes', options.limits); - const logBytes = limitArg('logBytes', options.limits); - const status = x.parse(len, context, flags, nodes, logBytes); - if (status === Status.nodes) throw new LimitError('nodes', nodes); - if (status === Status.log) throw new LimitError('logBytes', logBytes); - if (status === Status.memory) throw new ResourceError('memory'); - if (status !== Status.ok) throw new ResourceError('input'); - // One copy holds the log and then the text, since each buffer a parse allocates costs more than its bytes. - const log = x.log(); - const logLen = x.logLen(); - const textLen = x.textEnd() - base; - const out = new Uint8Array(logLen + textLen); - const memory = memoryView(x); - out.set(memory.subarray(log, log + logLen)); - out.set(memory.subarray(base, base + textLen), logLen); - return { - ops: new Int32Array(out.buffer, 0, logLen >> 2), - text: out.subarray(logLen), - nodeCount: x.nodeCount(), - fragment: options.context !== undefined, - }; -} - -/** - * Block size for the byte to UTF-16 offset table, as a shift. A string's offset is a byte offset, so the host - * decodes the whole text once and slices it, which needs each offset in code units. The table holds the unit count - * at the start of every block, shifted left once, with the low bit set when the block has a non-ASCII byte. - */ -const BLOCK_SHIFT = 5; -const BLOCK = 1 << BLOCK_SHIFT; - -// The start of the first block that holds a non-ASCII byte, or the length when there is none. -function asciiBlocks(bytes: Uint8Array): number { - const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2); - const full = bytes.length >> BLOCK_SHIFT; - for (let k = 0; k < full; k++) { - const w = k * (BLOCK / 4); - if ( - (words[w]! | - words[w + 1]! | - words[w + 2]! | - words[w + 3]! | - words[w + 4]! | - words[w + 5]! | - words[w + 6]! | - words[w + 7]!) & - 0x80808080 - ) - return k << BLOCK_SHIFT; - } - for (let j = full << BLOCK_SHIFT; j < bytes.length; j++) - if (bytes[j]! & 0x80) return full << BLOCK_SHIFT; - return bytes.length; -} - -function unitTable(bytes: Uint8Array): Int32Array { - const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2); - const full = bytes.length >> BLOCK_SHIFT; - const table = new Int32Array(full + 1); - let units = 0; - for (let k = 0; k < full; k++) { - const w = k * (BLOCK / 4); - const high = - (words[w]! | - words[w + 1]! | - words[w + 2]! | - words[w + 3]! | - words[w + 4]! | - words[w + 5]! | - words[w + 6]! | - words[w + 7]!) & - 0x80808080; - if (high === 0) { - table[k] = units << 1; - units += BLOCK; - } else { - table[k] = (units << 1) | 1; - for (let j = k << BLOCK_SHIFT, end = j + BLOCK; j < end; j++) units += unitsOf(bytes[j]!); - } - } - table[full] = (units << 1) | 1; - return table; -} - -// The code units a byte adds to valid UTF-8: its lead byte decides, a continuation adds none. -const unitsOf = (b: number): number => (b < 0x80 ? 1 : b >= 0xf0 ? 2 : b >= 0xc0 ? 1 : 0); - -/** Applies an op log to a sink. Returns the nodes by id; node 0 is the root. */ -export function replay(log: OpLog, sink: TreeSink): N[] { - const x = instance(); - const { ops } = log; - let bytes = log.text; - if (bytes.byteOffset & 3) bytes = bytes.slice(); - // Decoded once, in two parts split at the first block with a non-ASCII byte: the ASCII head, which strings slice - // by byte offset and which stays a one-byte string, and the rest, which they slice through the table. ASCII input - // usually has non-ASCII bytes only in the arena, after it. Text that is not valid UTF-8 falls back to decoding - // each string. - let split = bytes.length; - let ascii = ''; - let rest = bytes; - let tail = ''; - let table: Int32Array | null = null; - let whole = true; - try { - split = asciiBlocks(bytes); - ascii = strictDecoder.decode(bytes.subarray(0, split)); - if (split < bytes.length) { - rest = bytes.subarray(split); - tail = strictDecoder.decode(rest); - table = unitTable(rest); - } - } catch { - whole = false; - } - // The table lookup is written out twice rather than called, so a string in the tail costs no more calls than - // one decoded whole. - const str = (off: number, len: number): string => { - if (len <= 0) return ''; - if (!whole) return decoder.decode(bytes.subarray(off, off + len)); - const end = off + len; - if (end <= split) return ascii.substring(off, end); - const b = end - split; - const eb = table![b >> BLOCK_SHIFT]!; - let ub = eb >> 1; - if (eb & 1) for (let j = b & ~(BLOCK - 1); j < b; j++) ub += unitsOf(rest[j]!); - else ub += b & (BLOCK - 1); - if (off < split) return ascii.substring(off) + tail.substring(0, ub); - const a = off - split; - const ea = table![a >> BLOCK_SHIFT]!; - let ua = ea >> 1; - if (ea & 1) for (let j = a & ~(BLOCK - 1); j < a; j++) ua += unitsOf(rest[j]!); - else ua += a & (BLOCK - 1); - return tail.substring(ua, ub); - }; - const nodes: N[] = [sink.createRoot(log.fragment)]; - let next = 1; - const attrs = (at: number, n: number): Attribute[] => { - const list: Attribute[] = []; - for (let k = 0; k < n; k++) { - const r = at + k * 5; - const a = ops[r]!; - const id = a & 0xffff; - const name = id ? atomName(x, id) : str(ops[r + 1]!, ops[r + 2]!); - const value = str(ops[r + 3]!, ops[r + 4]!); - const ns = a >>> 16; - if (ns === 0) { - list.push({ name, namespace: null, prefix: null, localName: name, value }); - continue; - } - const namespace = ATTR_NS[ns] ?? null; - const colon = namespace ? name.indexOf(':') : -1; - list.push({ - name, - namespace, - prefix: colon < 0 ? null : name.slice(0, colon), - localName: colon < 0 ? name : name.slice(colon + 1), - value, - }); - } - return list; - }; - const created = (n: N, parent: number): void => { - nodes[next++] = n; - if (parent >= 0) sink.insert(nodes[parent] as N, n, null); - }; - const end = ops.length; - let i = 0; - while (i < end) { - const head = ops[i]!; - const code = head & 0xff; - if (code === Op.Element) { - const atom = ops[i + 2]!; - const n = ops[i + 5]!; - const name = atom ? atomName(x, atom) : str(ops[i + 3]!, ops[i + 4]!); - const ns = ELEMENT_NS[head >>> 8] ?? Namespace.HTML; - created(sink.createElement(name, ns, attrs(i + 6, n)), ops[i + 1]!); - i += 6 + n * 5; - } else if (code === Op.Text) { - created(sink.createText(str(ops[i + 2]!, ops[i + 3]!)), ops[i + 1]!); - i += 4; - } else if (code === Op.Comment) { - created(sink.createComment(str(ops[i + 2]!, ops[i + 3]!)), ops[i + 1]!); - i += 4; - } else if (code === Op.Insert) { - const ref = ops[i + 3]!; - sink.insert( - nodes[ops[i + 1]!] as N, - nodes[ops[i + 2]!] as N, - ref < 0 ? null : (nodes[ref] as N), - ); - i += 4; - } else if (code === Op.AppendText) { - sink.appendText(nodes[ops[i + 1]!] as N, str(ops[i + 2]!, ops[i + 3]!)); - i += 4; - } else if (code === Op.Content) { - nodes[next++] = sink.templateContents(nodes[ops[i + 1]!] as N); - i += 2; - } else if (code === Op.Remove) { - sink.remove(nodes[ops[i + 1]!] as N); - i += 2; - } else if (code === Op.MoveChildren) { - sink.moveChildren(nodes[ops[i + 1]!] as N, nodes[ops[i + 2]!] as N); - i += 3; - } else if (code === Op.Doctype) { - created( - sink.createDoctype( - str(ops[i + 2]!, ops[i + 3]!), - str(ops[i + 4]!, ops[i + 5]!), - str(ops[i + 6]!, ops[i + 7]!), - ), - ops[i + 1]!, - ); - i += 8; - } else if (code === Op.ProcessingInstruction) { - created( - sink.createProcessingInstruction( - str(ops[i + 2]!, ops[i + 3]!), - str(ops[i + 4]!, ops[i + 5]!), - ), - ops[i + 1]!, - ); - i += 6; - } else if (code === Op.AddAttributes) { - const n = ops[i + 3]!; - sink.addAttributes(nodes[ops[i + 1]!] as N, attrs(i + 4, n)); - i += 4 + n * 5; - } else if (code === Op.Quirks) { - sink.setQuirksMode(QUIRKS[ops[i + 1]!] ?? 'quirks'); - i += 2; - } else { - throw new OpLogError(code, i); - } - } - return nodes; -} +import { parseInput, replay, type EngineOptions, type ParseOptions } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; +import { TreeBuilder, type Document, type DocumentFragment, type Node } from './tree.ts'; + +export * from './shared.ts'; +export type { + ChildNode, + Comment, + Document, + DocumentFragment, + DocumentType, + Element, + Node, + ParentNode, + ProcessingInstruction, + Text, +} from './tree.ts'; + +/** Parses an HTML document into a tree of plain objects. The engine compiles on the first call. */ +export function parse(input: SyncInput, options?: ParseOptions): Document; +/** Parses an HTML document from an async iterable or stream into a tree of plain objects. */ +export function parse(input: AsyncInput, options?: ParseOptions): Promise; +export function parse(input: Input, options?: ParseOptions): Document | Promise { + return withInput(input, (html) => build(html, options) as Document); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into a tree of plain objects. */ +export function parseFragment(input: SyncInput, options: FragmentOptions): DocumentFragment; +/** Parses an HTML fragment from an async iterable or stream into a tree of plain objects. */ +export function parseFragment( + input: AsyncInput, + options: FragmentOptions, +): Promise; +export function parseFragment( + input: Input, + options: FragmentOptions, +): DocumentFragment | Promise { + return withInput(input, (html) => build(html, options) as DocumentFragment); +} + +const build = (html: string | Uint8Array, options: EngineOptions = {}): Node => + replay(parseInput(html, options), new TreeBuilder())[0]!; diff --git a/src/input.ts b/src/input.ts new file mode 100644 index 0000000..193c1ad --- /dev/null +++ b/src/input.ts @@ -0,0 +1,121 @@ +/** Input every layer takes and returns synchronously: a string, UTF-8 bytes, or an iterable of either. */ +export type SyncInput = string | Uint8Array | Iterable; +/** Input every layer takes and returns a promise for. */ +export type AsyncInput = AsyncIterable | ReadableStream; +export type Input = SyncInput | AsyncInput; + +/** Input that is not a string, bytes, an iterable or a stream, or a chunk that is not a string or bytes. */ +export class InputError extends TypeError { + /** What was received instead: `typeof`, or the constructor's name for an object. */ + readonly received: string; + constructor(what: 'input' | 'chunk', received: string) { + super( + what === 'input' + ? `html input must be a string, a Uint8Array, an iterable or a stream, not ${received}` + : `html input chunks must be strings or Uint8Arrays, not ${received}`, + ); + this.received = received; + } +} + +/** What the engine parses: one string, or one buffer of UTF-8. */ +type Gathered = string | Uint8Array; + +const encoder = new TextEncoder(); + +// Gathers chunks in order. Consecutive strings join before encoding, so a surrogate pair split across two string +// chunks stays one character. A UTF-8 byte order mark is dropped when the input starts with bytes, as the spec's +// decoder does; a string's leading U+FEFF is text, and stays. +class Chunks { + #parts: Gathered[] = []; + #strings: string[] = []; + #bytes = false; + + add(chunk: unknown): void { + if (typeof chunk === 'string') { + this.#strings.push(chunk); + return; + } + if (!(chunk instanceof Uint8Array)) { + throw new InputError('chunk', describe(chunk)); + } + if (this.#parts.length === 0 && this.#strings.length === 0) this.#bytes = true; + this.#flush(); + this.#parts.push(chunk); + } + + done(): Gathered { + this.#flush(); + const parts = this.#parts; + if (parts.length === 0) return ''; + if (parts.length === 1) { + const only = parts[0]!; + return typeof only === 'string' ? only : withoutBom(only); + } + const encoded = parts.map((p) => (typeof p === 'string' ? encoder.encode(p) : p)); + let length = 0; + for (const p of encoded) length += p.length; + const out = new Uint8Array(length); + let at = 0; + for (const p of encoded) { + out.set(p, at); + at += p.length; + } + return this.#bytes ? withoutBom(out) : out; + } + + #flush(): void { + if (this.#strings.length === 0) return; + this.#parts.push(this.#strings.join('')); + this.#strings = []; + } +} + +const withoutBom = (bytes: Uint8Array): Uint8Array => + bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? bytes.subarray(3) : bytes; + +function describe(value: unknown): string { + if (value === null) return 'null'; + if (typeof value === 'object') return value.constructor?.name ?? 'an object'; + return typeof value; +} + +const isAsync = (input: object): input is AsyncInput => + Symbol.asyncIterator in input || 'getReader' in input; + +function gather(input: SyncInput): Gathered { + if (typeof input === 'string') return input; + if (input instanceof Uint8Array) return withoutBom(input); + if (input == null || typeof input[Symbol.iterator] !== 'function') { + throw new InputError('input', describe(input)); + } + const chunks = new Chunks(); + for (const chunk of input) chunks.add(chunk); + return chunks.done(); +} + +async function gatherAsync(input: AsyncInput): Promise { + const chunks = new Chunks(); + if (Symbol.asyncIterator in input) { + for await (const chunk of input as AsyncIterable) chunks.add(chunk); + } else { + const reader = (input as ReadableStream).getReader(); + try { + for (let r = await reader.read(); !r.done; r = await reader.read()) chunks.add(r.value); + } finally { + reader.releaseLock(); + } + } + return chunks.done(); +} + +/** + * Gathers input and hands it to parse: synchronously for strings, bytes and iterables, through a promise for async + * iterables and streams. Phase 1 of streaming (docs/api-sketch.md): the engine parses once the input ends. + */ +export function withInput(input: Input, parse: (gathered: Gathered) => T): T | Promise { + if (typeof input === 'string') return parse(input); + if (input !== null && typeof input === 'object' && isAsync(input)) + return gatherAsync(input).then(parse); + return parse(gather(input as SyncInput)); +} diff --git a/src/log.ts b/src/log.ts new file mode 100644 index 0000000..427b9c6 --- /dev/null +++ b/src/log.ts @@ -0,0 +1,22 @@ +import { parseInput, type OpLog, type ParseOptions } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; + +export * from './shared.ts'; +export { OpLogError, replay, type OpLog, type TreeSink } from './engine.ts'; + +/** Parses an HTML document into an op log (docs/op-log.md). The engine compiles on the first call. */ +export function parse(input: SyncInput, options?: ParseOptions): OpLog; +/** Parses an HTML document from an async iterable or stream into an op log. */ +export function parse(input: AsyncInput, options?: ParseOptions): Promise; +export function parse(input: Input, options: ParseOptions = {}): OpLog | Promise { + return withInput(input, (html) => parseInput(html, options)); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into an op log. */ +export function parseFragment(input: SyncInput, options: FragmentOptions): OpLog; +/** Parses an HTML fragment from an async iterable or stream into an op log. */ +export function parseFragment(input: AsyncInput, options: FragmentOptions): Promise; +export function parseFragment(input: Input, options: FragmentOptions): OpLog | Promise { + return withInput(input, (html) => parseInput(html, options)); +} diff --git a/src/shared.ts b/src/shared.ts new file mode 100644 index 0000000..d246601 --- /dev/null +++ b/src/shared.ts @@ -0,0 +1,22 @@ +export { + InvalidLimitError, + LimitError, + Namespace, + ResourceError, + type Attribute, + type AttributeNamespace, + type ElementNamespace, + type FragmentContext, + type ParseLimits, + type ParseOptions, + type QuirksMode, +} from './engine.ts'; +export { InputError, type AsyncInput, type Input, type SyncInput } from './input.ts'; + +import type { FragmentContext, ParseOptions } from './engine.ts'; + +/** Options for parsing a fragment: the element it is parsed in, as for `innerHTML`. */ +export interface FragmentOptions extends ParseOptions { + /** A local name such as `div`, or a FragmentContext for SVG, MathML, forms and quirks. */ + context: string | FragmentContext; +} diff --git a/src/sink.ts b/src/sink.ts new file mode 100644 index 0000000..9ee18ea --- /dev/null +++ b/src/sink.ts @@ -0,0 +1,35 @@ +import { parseInput, replay, type ParseOptions, type TreeSink } from './engine.ts'; +import { withInput, type AsyncInput, type Input, type SyncInput } from './input.ts'; +import type { FragmentOptions } from './shared.ts'; + +export * from './shared.ts'; +export type { TreeSink } from './engine.ts'; + +// The whole input parses before the sink sees its first call, so a LimitError or ResourceError leaves the sink's +// tree untouched. A future incremental engine may call the sink before an async input ends (docs/api-sketch.md). + +/** Options for parsing into a sink: the TreeSink that builds the host's nodes. */ +export interface SinkOptions extends ParseOptions { + sink: TreeSink; +} + +/** Options for parsing a fragment into a sink. */ +export interface SinkFragmentOptions extends FragmentOptions { + sink: TreeSink; +} + +/** Parses an HTML document into `options.sink`, and returns the root it created. The engine compiles on the first call. */ +export function parse(input: SyncInput, options: SinkOptions): N; +/** Parses an HTML document from an async iterable or stream into `options.sink`. */ +export function parse(input: AsyncInput, options: SinkOptions): Promise; +export function parse(input: Input, options: SinkOptions): N | Promise { + return withInput(input, (html) => replay(parseInput(html, options), options.sink)[0]!); +} + +/** Parses an HTML fragment in `options.context`, as `innerHTML` does, into `options.sink`, and returns the fragment root. */ +export function parseFragment(input: SyncInput, options: SinkFragmentOptions): N; +/** Parses an HTML fragment from an async iterable or stream into `options.sink`. */ +export function parseFragment(input: AsyncInput, options: SinkFragmentOptions): Promise; +export function parseFragment(input: Input, options: SinkFragmentOptions): N | Promise { + return withInput(input, (html) => replay(parseInput(html, options), options.sink)[0]!); +} diff --git a/src/tree.ts b/src/tree.ts new file mode 100644 index 0000000..b89bd24 --- /dev/null +++ b/src/tree.ts @@ -0,0 +1,113 @@ +import type { Attribute, ElementNamespace, QuirksMode, TreeSink } from './engine.ts'; + +export interface Document { + type: 'document'; + mode: QuirksMode; + children: ChildNode[]; +} +export interface DocumentFragment { + type: 'fragment'; + children: ChildNode[]; +} +export interface Element { + type: 'element'; + /** The local name, e.g. `div` or `foreignObject`. */ + name: string; + namespace: ElementNamespace; + /** In source order. */ + attributes: Attribute[]; + children: ChildNode[]; + /** A `template` element's contents. */ + content?: DocumentFragment; +} +export interface Text { + type: 'text'; + data: string; +} +export interface Comment { + type: 'comment'; + data: string; +} +export interface DocumentType { + type: 'doctype'; + name: string; + publicId: string; + systemId: string; +} +export interface ProcessingInstruction { + type: 'processing-instruction'; + target: string; + data: string; +} +export type ParentNode = Document | DocumentFragment | Element; +export type ChildNode = Element | Text | Comment | DocumentType | ProcessingInstruction; +export type Node = ParentNode | ChildNode; + +/** The sink behind `parse` and `parseFragment`: builds plain objects. Parents live here, not on the nodes. */ +export class TreeBuilder implements TreeSink { + #root: Document | DocumentFragment | undefined; + #parents = new Map(); + + createRoot(fragment: boolean): Node { + this.#root = fragment + ? { type: 'fragment', children: [] } + : { type: 'document', mode: 'no-quirks', children: [] }; + return this.#root; + } + createElement(name: string, namespace: ElementNamespace, attributes: readonly Attribute[]): Node { + return { + type: 'element', + name, + namespace, + attributes: attributes as Attribute[], + children: [], + }; + } + createText(data: string): Node { + return { type: 'text', data }; + } + createComment(data: string): Node { + return { type: 'comment', data }; + } + createDoctype(name: string, publicId: string, systemId: string): Node { + return { type: 'doctype', name, publicId, systemId }; + } + createProcessingInstruction(target: string, data: string): Node { + return { type: 'processing-instruction', target, data }; + } + templateContents(template: Node): Node { + const content: DocumentFragment = { type: 'fragment', children: [] }; + (template as Element).content = content; + return content; + } + insert(parent: Node, child: Node, ref: Node | null): void { + const children = (parent as ParentNode).children; + if (ref === null) children.push(child as ChildNode); + else children.splice(children.indexOf(ref as ChildNode), 0, child as ChildNode); + this.#parents.set(child, parent as ParentNode); + } + remove(child: Node): void { + const parent = this.#parents.get(child); + if (parent === undefined) return; + parent.children.splice(parent.children.indexOf(child as ChildNode), 1); + this.#parents.delete(child); + } + moveChildren(from: Node, to: Node): void { + const source = (from as ParentNode).children; + const target = (to as ParentNode).children; + for (const child of source) { + target.push(child); + this.#parents.set(child, to as ParentNode); + } + source.length = 0; + } + appendText(text: Node, data: string): void { + (text as Text).data += data; + } + addAttributes(element: Node, attributes: readonly Attribute[]): void { + (element as Element).attributes.push(...attributes); + } + setQuirksMode(mode: QuirksMode): void { + if (this.#root?.type === 'document') this.#root.mode = mode; + } +} diff --git a/test/api.test.ts b/test/api.test.ts new file mode 100644 index 0000000..045c50d --- /dev/null +++ b/test/api.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest'; +import { + InputError, + LimitError, + Namespace, + parse, + parseFragment, + type ChildNode, + type Element, + type Node, +} from '../src/index.ts'; +import * as log from '../src/log.ts'; +import * as sink from '../src/sink.ts'; + +// A compact rendering of the default tree, so each case asserts one literal string. +function show(n: Node): string { + switch (n.type) { + case 'document': + return `#document(${n.mode})[${n.children.map(show).join(',')}]`; + case 'fragment': + return `#fragment[${n.children.map(show).join(',')}]`; + case 'element': { + const attrs = n.attributes.map((a) => ` ${a.name}=${JSON.stringify(a.value)}`).join(''); + const content = n.content ? ` content=${show(n.content)}` : ''; + return `<${n.name}${attrs}${content}>[${n.children.map(show).join(',')}]`; + } + case 'text': + return JSON.stringify(n.data); + case 'comment': + return ``; + case 'doctype': + return ``; + case 'processing-instruction': + return ``; + } +} + +const encode = (s: string): Uint8Array => new TextEncoder().encode(s); +const first = (children: ChildNode[]): Element => children[0] as Element; + +describe('parse', () => { + it('builds a document tree', () => { + expect(show(parse('t

hix

'))).toBe( + '#document(no-quirks)[,[[["t"]],<body>[<p class="a">["hi",<b>["x"]],<!--c-->]]]', + ); + }); + + it('records the quirks mode', () => { + expect(parse('<p>').mode).toBe('quirks'); + }); + + it('applies the scripting flag', () => { + const noscript = (scripting: boolean): string => + show(parseFragment('<noscript><b>x</b></noscript>', { context: 'div', scripting })); + expect(noscript(true)).toBe('#fragment[<noscript>["<b>x</b>"]]'); + expect(noscript(false)).toBe('#fragment[<noscript>[<b>["x"]]]'); + }); +}); + +describe('parseFragment', () => { + it('parses in a context element named by a string', () => { + expect(show(parseFragment('<td>1<td>2', { context: 'tr' }))).toBe( + '#fragment[<td>["1"],<td>["2"]]', + ); + }); + + it('parses in a FragmentContext', () => { + const svg = parseFragment('<circle/>', { context: { name: 'svg', namespace: Namespace.SVG } }); + expect(first(svg.children).namespace).toBe(Namespace.SVG); + }); + + it('puts template contents on content', () => { + expect(show(parseFragment('<template><i>x</i></template>', { context: 'div' }))).toBe( + '#fragment[<template content=#fragment[<i>["x"]]>[]]', + ); + }); + + it('reorders through the adoption agency and foster parenting', () => { + expect(show(parseFragment('<b>1<p>2</b>3</p>', { context: 'div' }))).toBe( + '#fragment[<b>["1"],<p>[<b>["2"],"3"]]', + ); + expect(show(parseFragment('<table>x<tr><td>y</table>', { context: 'div' }))).toBe( + '#fragment["x",<table>[<tbody>[<tr>[<td>["y"]]]]]', + ); + }); +}); + +describe('input', () => { + it('decodes bytes as UTF-8 and drops a byte order mark', () => { + const bytes = new Uint8Array([0xef, 0xbb, 0xbf, ...encode('<b>é</b>')]); + expect(show(parseFragment(bytes, { context: 'div' }))).toBe('#fragment[<b>["é"]]'); + }); + + it('keeps a string’s leading U+FEFF, which is text', () => { + expect(show(parseFragment('x', { context: 'div' }))).toBe('#fragment["x"]'); + }); + + it('joins an iterable of strings across a split surrogate pair', () => { + expect(show(parseFragment(['<b>\uD83D', '\uDE00</b>'], { context: 'div' }))).toBe( + '#fragment[<b>["😀"]]', + ); + }); + + it('joins an iterable of bytes across a split UTF-8 sequence', () => { + const chunks = [encode('<b>é').subarray(0, 4), encode('é</b>').subarray(1)]; + expect(show(parseFragment(chunks, { context: 'div' }))).toBe('#fragment[<b>["é"]]'); + }); + + it('takes mixed chunks from an async iterable and returns a promise', async () => { + async function* chunks(): AsyncGenerator<string | Uint8Array> { + yield '<ul><li>a'; + yield encode('<li>b</ul>'); + } + const result = parseFragment(chunks(), { context: 'div' }); + expect(result).toBeInstanceOf(Promise); + expect(show(await result)).toBe('#fragment[<ul>[<li>["a"],<li>["b"]]]'); + }); + + it('takes a ReadableStream', async () => { + const stream = new ReadableStream<string>({ + start(c) { + c.enqueue('<p>s'); + c.enqueue('tream'); + c.close(); + }, + }); + expect(show(await parseFragment(stream, { context: 'div' }))).toBe('#fragment[<p>["stream"]]'); + }); + + it('takes an empty iterable as empty input', () => { + expect(show(parseFragment([], { context: 'div' }))).toBe('#fragment[]'); + }); + + it('rejects input that is not text', () => { + expect(() => parse(42 as never)).toThrow(new InputError('input', 'number')); + expect(() => parse([1] as never)).toThrow(new InputError('chunk', 'number')); + expect(new InputError('input', 'number').message).toBe( + 'html input must be a string, a Uint8Array, an iterable or a stream, not number', + ); + }); +}); + +describe('layers', () => { + it('log returns an op log that replays into the same tree', () => { + const opLog = log.parseFragment('<p>x', { context: 'div' }); + expect(opLog.fragment).toBe(true); + expect(opLog.nodeCount).toBe(3); + const names: string[] = []; + log.replay(opLog, { + createRoot: () => 'root', + createElement: (name: string) => (names.push(name), name), + createText: (data: string) => (names.push(data), data), + insert: () => {}, + } as unknown as log.TreeSink<string>); + expect(names).toEqual(['p', 'x']); + }); + + it('sink returns the root it created, and an over-budget parse never reaches the sink', () => { + const calls: string[] = []; + const recorder = new Proxy({} as sink.TreeSink<string>, { + get: (_, method: string) => () => (calls.push(method), method), + }); + expect(sink.parseFragment('<p>', { context: 'div', sink: recorder })).toBe('createRoot'); + expect(calls).toEqual(['createRoot', 'createElement', 'insert']); + calls.length = 0; + expect(() => sink.parse('<p>'.repeat(100), { sink: recorder, limits: { nodes: 10 } })).toThrow( + LimitError, + ); + expect(calls).toEqual([]); + }); +}); diff --git a/test/complexity.test.ts b/test/complexity.test.ts index 02be4ce..80aaeb4 100644 --- a/test/complexity.test.ts +++ b/test/complexity.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { parse } from '../src/index.ts'; +import { parse } from '../src/engine.ts'; import { cases, growth, SCALE } from './adversarial.ts'; // Each case is timed at n and 8n and must grow well under quadratically: linear time gives about 8x, a quadratic diff --git a/test/dom.ts b/test/dom.ts index a8fe7df..9236949 100644 --- a/test/dom.ts +++ b/test/dom.ts @@ -5,7 +5,8 @@ import { type ElementNamespace, type QuirksMode, type TreeSink, -} from '../src/index.ts'; +} from '../src/engine.ts'; +import type { Node as TreeNode } from '../src/tree.ts'; export interface Node { kind: 'document' | 'fragment' | 'element' | 'text' | 'comment' | 'doctype' | 'pi'; @@ -144,3 +145,25 @@ export function dump(root: Node): string { for (const c of root.children) walk(c, 0); return lines.join('\n'); } + +/** The public tree (src/tree.ts) as a test Node, so dump can print it. */ +export function fromTree(n: TreeNode): Node { + const out = createNode(n.type === 'processing-instruction' ? 'pi' : n.type); + if (n.type === 'element') { + out.name = n.name; + out.namespace = n.namespace; + out.attributes = n.attributes; + if (n.content) out.content = fromTree(n.content); + } else if (n.type === 'text' || n.type === 'comment') { + out.data = n.data; + } else if (n.type === 'processing-instruction') { + out.name = n.target; + out.data = n.data; + } else if (n.type === 'doctype') { + out.name = n.name; + out.publicId = n.publicId; + out.systemId = n.systemId; + } + if ('children' in n) out.children = n.children.map(fromTree); + return out; +} diff --git a/test/fast.test.ts b/test/fast.test.ts index cd4bf32..d4ad755 100644 --- a/test/fast.test.ts +++ b/test/fast.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { parse, replay } from '../src/index.ts'; +import { parse, replay } from '../src/engine.ts'; import { dump, PlainSink, type Node } from './dom.ts'; import { corpusFragments, diff --git a/test/fragments.ts b/test/fragments.ts index acbfc18..60de2c1 100644 --- a/test/fragments.ts +++ b/test/fragments.ts @@ -1,5 +1,5 @@ // Fragment inputs for the fast path's differential test (test/fast.test.ts) and acceptance report -// (scripts/fast-report.ts), and a raw handle on build/html.wasm that exposes what src/index.ts hides: the fast path's +// (scripts/fast-report.ts), and a raw handle on build/html.wasm that exposes what src/engine.ts hides: the fast path's // result and the log's exact bytes. import { readdirSync, readFileSync } from 'node:fs'; import { parse as parse5, type DefaultTreeAdapterTypes } from 'parse5'; diff --git a/test/fuzz.ts b/test/fuzz.ts index cf14fa2..9647733 100644 --- a/test/fuzz.ts +++ b/test/fuzz.ts @@ -8,7 +8,7 @@ // Some iterations also check what must not change a log: a different seed, a fresh instance, a budget it stays within // (and one it does not, which must stop it with the budget's status), and a memory cap (status 0 or 1, never a trap). import { readdirSync, readFileSync } from 'node:fs'; -import { replay, type OpLog } from '../src/index.ts'; +import { replay, type OpLog } from '../src/engine.ts'; import { PlainSink } from './dom.ts'; import { cappedModule, diff --git a/test/limits.test.ts b/test/limits.test.ts index 335d404..303bed3 100644 --- a/test/limits.test.ts +++ b/test/limits.test.ts @@ -1,6 +1,6 @@ import { readdirSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { InvalidLimitError, LimitError, parse } from '../src/index.ts'; +import { InvalidLimitError, LimitError, parse } from '../src/engine.ts'; import { cases } from './adversarial.ts'; import { cappedModule, rawEngine, rawParse, sameRun } from './engine.ts'; import { rng, subsetFragment, wptFragments } from './fragments.ts'; diff --git a/test/memory-child.ts b/test/memory-child.ts index dc93fd5..309c472 100644 --- a/test/memory-child.ts +++ b/test/memory-child.ts @@ -1,5 +1,5 @@ // Run by test/memory.test.ts in its own process: caps the memory of every module compiled here, so the wrapper's -// engine (which src/index.ts caches) runs out of memory without affecting other test files. +// engine (which src/engine.ts caches) runs out of memory without affecting other test files. import { readdirSync, readFileSync } from 'node:fs'; import { capMemory } from './engine.ts'; @@ -8,7 +8,7 @@ WebAssembly.Module = function (bytes: BufferSource) { return new Module(capMemory(new Uint8Array(bytes as ArrayBuffer), 40)); } as unknown as typeof WebAssembly.Module; -const { parse, ResourceError } = await import('../src/index.ts'); +const { parse, ResourceError } = await import('../src/engine.ts'); const root = new URL('../', import.meta.url); // ASCII, so the input buffer needs one byte per character and fits; the arena and the tree do not. diff --git a/test/replay.test.ts b/test/replay.test.ts index 55bf986..c0d8f24 100644 --- a/test/replay.test.ts +++ b/test/replay.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { rawEngine, rawParse } from './engine.ts'; -import { parse, parseBytes, replay } from '../src/index.ts'; +import { parse, parseBytes, replay } from '../src/engine.ts'; import { PlainSink, type Node } from './dom.ts'; function tree(html: string): Node { diff --git a/test/tree.test.ts b/test/tree.test.ts index cfc6d2a..123489f 100644 --- a/test/tree.test.ts +++ b/test/tree.test.ts @@ -1,7 +1,8 @@ import { readdirSync, readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { Namespace, parse, replay, type FragmentContext } from '../src/index.ts'; -import { dump, PlainSink, type Node } from './dom.ts'; +import { Namespace, parse, replay, type FragmentContext } from '../src/engine.ts'; +import * as api from '../src/index.ts'; +import { dump, fromTree, PlainSink, type Node } from './dom.ts'; const root = new URL('../', import.meta.url); const suite = new URL('vendor/wpt/html/syntax/parsing/resources/', root); @@ -75,6 +76,15 @@ export function treeDump(test: Case, scripting: boolean): string { return dump(replay(log, new PlainSink())[0] as Node); } +/** The same dump through the public API's default tree, which must match replaying into PlainSink. */ +function apiDump(test: Case, scripting: boolean): string { + const tree = + test.fragment === undefined + ? api.parse(test.data, { scripting }) + : api.parseFragment(test.data, { context: context(test.fragment), scripting }); + return dump(fromTree(tree)); +} + const files = readdirSync(suite).filter((f) => f.endsWith('.dat')); describe('WPT tree construction', () => { @@ -89,7 +99,9 @@ describe('WPT tree construction', () => { const id = `${file}#${index}${scripting ? ' script-on' : ''}`; const run = baseline.has(id) ? it.fails : it; run(`${id}: ${JSON.stringify(test.data)}`, () => { - expect(treeDump(test, scripting)).toBe(test.document); + const tree = treeDump(test, scripting); + expect(apiDump(test, scripting)).toBe(tree); + expect(tree).toBe(test.document); }); } });