@gmb/bitmark-parser 6.7.0 → 6.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/generated/package_info.ts","../src/core/hooked-transform.ts","../src/core/parallel.ts","../src/node/pool.ts","../src/node/transform-parallel.ts","../src/node/legacy-init.ts","../src/legacy/runtime.ts","../src/legacy/index.ts","../src/legacy/errors.ts","../src/legacy/translate.ts","../src/legacy/pseudo-ast.ts","../src/legacy/generated/resource-collection-keys.ts","../src/legacy/builder.ts","../src/legacy/bpg-class.ts","../src/legacy/resource-builder.ts","../src/legacy/options.ts","../src/legacy/enums-extra.ts","../src/legacy/stubs.ts","../src/types.ts"],"sourcesContent":["// @zen-component: WASM-TSBindings\n\nimport { createRequire } from \"node:module\";\nimport { PACKAGE_INFO } from \"./generated/package_info.js\";\nimport { runHookedTransform, type HookedWasm } from \"./core/hooked-transform.js\";\nimport { runParallelTransform } from \"./node/transform-parallel.js\";\nimport type { LexOptions, ParseOptions, ConvertOptions, BreakscapeOptions, InfoOptions, CanonicalizeOptions, TransformOptions, BitSlice } from \"./types.js\";\nimport type { AnyBit, Bit, BitEntry } from \"./generated/bit-types.js\";\nconst require = createRequire(import.meta.url);\nconst wasm = require(\"../wasm/bitmark_wasm.js\") as typeof import(\"../wasm/bitmark_wasm.js\");\n\n// Legacy (bpg-compatible) API — namespaced, never merged into the root surface\nimport { initLegacyNode } from \"./node/legacy-init.js\";\ninitLegacyNode(wasm);\nexport * as legacy from \"./legacy/index.js\";\n\nexport type { LexOptions, LexStage, ParseOptions, ConvertOptions, OutputMode, BreakscapeOptions, TextFormat, TextLocation, InfoOptions, InfoType, InfoFormat, InputFormat, OutputFormat, CanonicalizeOptions, TransformOptions, PatchOp, PatchEntry, PathValue, PatchValueFor, BitSlice, BitView, PreHook, PostHook, PreHookResult } from \"./types.js\";\nexport { patchEntry } from \"./types.js\";\n\n// Generated types for the parser's JSON (from bitmark.json via schemagen, PLAN-128)\nexport type * from \"./generated/bit-types.js\";\n\n/**\n * Get the version of the @gmb/bitmark-parser library.\n *\n * @returns Version string (e.g. \"3.0.0\").\n */\nexport function version(): string {\n return PACKAGE_INFO.version;\n}\n\n/**\n * Lex bitmark input text, returning one line per token.\n *\n * @param input - The bitmark source text.\n * @param options - Lex options (e.g. `{ stage: \"lex\" }`).\n * @returns Token dump string (one token per line).\n */\nexport function lex(input: string, options: LexOptions = {}): string {\n return wasm.lex(input, options.stage ?? \"lex\");\n}\n\n/**\n * Parse bitmark into typed bit entries.\n *\n * The typed (object) counterpart of\n * `convert(input, { inputFormat: \"bitmark\", outputFormat: \"json\" })`:\n * returns the entries as objects instead of a JSON string. **Bitmark input\n * only** — the format is pinned, no auto-detection.\n *\n * @example\n * const entries = bitmarkToObjects(\"[.article]\\nHello **world**\");\n * const bit = entries[0].bit;\n * if (bit.type === \"article\") console.log(bit.body);\n *\n * @throws If the core reports a conversion error.\n */\nexport function bitmarkToObjects(input: string, options: ParseOptions = {}): BitEntry[] {\n const out = wasm.convert(\n input,\n \"bitmark\",\n \"json\",\n options.mode ?? \"optimized\",\n false,\n 2,\n 1,\n options.includeUnknownProperties ?? false,\n false,\n );\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return JSON.parse(out) as BitEntry[];\n}\n\n/**\n * Compose bitmark text from typed bits or entries.\n *\n * The typed (object) counterpart of\n * `convert(json, { inputFormat: \"json\", outputFormat: \"bitmark\" })` — typed\n * objects are JSON by construction, so the format is pinned, no\n * auto-detection. Bare bits are auto-wrapped into entries; the config-driven\n * composer normalizes, defaults and validates on ingest — construct bits as\n * plain typed literals (no builder needed).\n *\n * @example\n * const bitmark = objectsToBitmark([{ type: \"article\", body: \"Hello\" }]);\n *\n * @throws If the core reports a compose error.\n */\nexport function objectsToBitmark(bits: readonly (Bit | AnyBit | BitEntry)[], options: ParseOptions = {}): string {\n const entries = bits.map((b) =>\n b !== null && typeof b === \"object\" && \"bit\" in b && typeof (b as BitEntry).bit === \"object\"\n ? b\n : { bit: b },\n );\n const out = wasm.convert(\n JSON.stringify(entries),\n \"json\",\n \"bitmark\",\n options.mode ?? \"optimized\",\n false,\n 2,\n 1,\n false,\n false,\n );\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return out;\n}\n\n/**\n * Convert between bitmark, JSON, and the mapped markup formats (html/xml/…) —\n * the single string-based conversion surface.\n *\n * Performance: `inputFormat` defaults to `\"auto\"`, which detects the format\n * by scanning the input for a bitmark bit header — for non-bitmark input\n * that is a full pass over the whole input before parsing starts, and the\n * detection is heuristic (markup formats are never auto-detected). **If you\n * know the input format, set `inputFormat` explicitly.** For typed objects\n * use {@link bitmarkToObjects} / {@link objectsToBitmark}, which pin their\n * formats.\n *\n * @param input - Bitmark, JSON, or mapped-format input text.\n * @param options - Convert options (e.g. `{ inputFormat: \"bitmark\", mode: \"full\" }`).\n * @returns Converted output string. For bitmark input, this is a JSON string\n * array of structured parsed entries (`bit`, `parser`, `bitmark`).\n */\nexport function convert(input: string, options: ConvertOptions = {}): string {\n return wasm.convert(\n input,\n options.inputFormat ?? \"auto\",\n options.outputFormat ?? \"auto\",\n options.mode ?? \"optimized\",\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n options.includeUnknownProperties ?? false,\n options.mappingReport ?? false,\n );\n}\n\n/**\n * Re-emit input in its own format in canonical form — the single same-format\n * surface (the former `optimize`/`fullize`/`expand` were pure mode pins of\n * this function and were removed).\n *\n * @param input - Input text (bitmark, JSON, or a markup format such as html/xml).\n * @param options - `mode`: `\"optimized\"` (default — omit natural defaults) or\n * `\"full\"` (emit all keys). `inputFormat` selects the format (default:\n * `\"auto\"`; prefer explicit — see {@link convert}); the output is\n * re-emitted in that same format.\n */\nexport function canonicalize(input: string, options: CanonicalizeOptions = {}): string {\n return wasm.canonicalize(\n input,\n options.inputFormat ?? \"auto\",\n options.mode ?? \"optimized\",\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n );\n}\n\n/**\n * Count the bits in `input`, auto-detecting bitmark vs JSON (heuristic —\n * a full input scan when the input is not bitmark; see {@link convert}).\n *\n * @throws If the input cannot be parsed.\n */\nexport function countBits(input: string): number {\n const out = wasm.count_bits(input);\n if (out.startsWith(\"error:\")) throw new Error(out);\n return Number.parseInt(out, 10);\n}\n\n/**\n * Split a bitmark document into per-bit source slices.\n *\n * @returns Array of `{ index, byteStart, byteEnd, source }`.\n */\nexport function splitBits(input: string): BitSlice[] {\n return JSON.parse(wasm.split_bits(input)) as BitSlice[];\n}\n\n/**\n * Transform a document bit-by-bit: apply an optional static `patch` and/or\n * per-bit `preHook`/`postHook`, then re-emit.\n *\n * With neither hook, the whole document is transformed in a single WASM pass\n * (the fast path). When a `preHook` or `postHook` is supplied, `transform`\n * drives the bits one at a time on the calling thread — the hook inspects each\n * bit, may return patches / an output-format override / `drop`, and only data\n * crosses into WASM. The patch may be an array of entries or a JSON string.\n *\n * `options.inputFormat` defaults to `\"auto\"`; prefer an explicit format when\n * known — see {@link convert}.\n *\n * @returns The transformed document, or an `error:`-prefixed string on failure.\n */\nexport function transform(input: string, options: TransformOptions = {}): string {\n if (options.preHook || options.postHook) {\n return runHookedTransform(wasm as unknown as HookedWasm, input, options);\n }\n const patchJson =\n options.patch === undefined\n ? \"\"\n : typeof options.patch === \"string\"\n ? options.patch\n : JSON.stringify(options.patch);\n return wasm.transform(\n input,\n options.inputFormat ?? \"auto\",\n options.outputFormat ?? \"json\",\n options.mode ?? \"optimized\",\n patchJson,\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n );\n}\n\n/**\n * Parallel counterpart of {@link transform} (Node only). Fans the per-bit WASM\n * compute across a `worker_threads` pool (`options.workers`, default `4`),\n * while `preHook`/`postHook` still run on the calling thread. Output is\n * identical to {@link transform}; this trades startup cost for throughput on\n * large documents.\n *\n * @returns A Promise of the transformed document, or an `error:`-prefixed\n * string on failure.\n */\nexport function transformParallel(input: string, options: TransformOptions = {}): Promise<string> {\n return runParallelTransform(wasm as unknown as HookedWasm, input, options);\n}\n\n/**\n * Breakscape text (escape bitmark special characters).\n *\n * @param input - The text to breakscape.\n * @param options - Breakscape options (e.g. `{ format: \"plainText\", location: \"tag\" }`).\n * @returns Breakscaped text.\n */\nexport function breakscapeText(input: string, options: BreakscapeOptions = {}): string {\n const format = options.format ?? \"bitmark++\";\n const location = options.location ?? \"body\";\n return wasm.breakscape_text(input, format, location);\n}\n\n/**\n * Unbreakscape text (unescape bitmark special characters).\n *\n * @param input - The text to unbreakscape.\n * @param options - Unbreakscape options (e.g. `{ format: \"plainText\", location: \"tag\" }`).\n * @returns Unbreakscaped text.\n */\nexport function unbreakscapeText(input: string, options: BreakscapeOptions = {}): string {\n const format = options.format ?? \"bitmark++\";\n const location = options.location ?? \"body\";\n return wasm.unbreakscape_text(input, format, location);\n}\n\n/**\n * Query information about supported bit types.\n *\n * @param options - Info options (e.g. `{ infoType: \"bit\", format: \"json\", bit: \"cloze\" }`).\n * @returns Information string.\n */\nexport function info(options: InfoOptions = {}): string {\n const infoType = options.infoType ?? \"list\";\n const format = options.format ?? \"text\";\n const bit = options.bit ?? \"\";\n const pretty = options.pretty ?? false;\n const indent = options.indent ?? 2;\n return wasm.info(infoType, format, bit, pretty, indent);\n}\n\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// This file is automatically generated. DO NOT EDIT.\n\n/* eslint-disable */\n\nexport const PACKAGE_INFO = {\n \"name\": \"@gmb/bitmark-parser\",\n \"version\": \"6.7.0\",\n \"author\": \"Get More Brain Ltd <info@getmorebrain.com>\",\n \"license\": \"ISC\",\n \"description\": \"A parser for bitmark text, powered by WebAssembly.\"\n};\n","// @zen-component: TS-HookedTransform\n\nimport type { BitView, OutputFormat, PatchEntry, TransformOptions } from \"../types.js\";\n\n/**\n * The minimal WASM surface the per-bit hook driver needs. Both the Node and\n * browser entry points satisfy this with their loaded module.\n */\nexport interface HookedWasm {\n is_bitmark(input: string): boolean;\n split_bits(input: string): string;\n split_json_bits(input: string): string;\n prettify(json: string, indent: number): string;\n transform(\n input: string,\n inputFormat: string,\n outputFormat: string,\n mode: string,\n patchJson: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n ): string;\n}\n\n/** A single bit's compute job: data only, safe to ship to a worker thread. */\nexport interface BitJob {\n index: number;\n source: string;\n inputFormat: \"bitmark\" | \"json\";\n outputFormat: OutputFormat;\n mode: string;\n patchJson: string;\n spacesAroundValues: number;\n}\n\n/**\n * The result of running `preHook` over a document's bits: the compute `jobs`\n * for the bits that survived (in document order) and the matching `views`\n * (so `postHook` can be called per surviving bit), plus the document-level\n * recombination settings.\n */\nexport interface TransformPlan {\n jobs: BitJob[];\n views: BitView[];\n output: OutputFormat;\n pretty: boolean;\n indent: number;\n}\n\nexport function isError(s: string): boolean {\n return s.startsWith(\"error:\");\n}\n\n/**\n * Normalise a thrown value to an `error:`-prefixed string, without\n * double-prefixing a message that already carries the prefix (split helpers\n * surface WASM `error:` strings as thrown `Error`s).\n */\nexport function errorString(e: unknown): string {\n const m = e instanceof Error ? e.message : String(e);\n return m.startsWith(\"error:\") ? m : `error: ${m}`;\n}\n\n/** Strip the outer `[ … ]` of a compact one-element JSON array. */\nexport function stripArray(doc: string): string {\n const t = doc.trim();\n return t.startsWith(\"[\") && t.endsWith(\"]\") ? t.slice(1, -1) : doc;\n}\n\nfunction normalisePatch(patch: TransformOptions[\"patch\"]): PatchEntry[] {\n if (patch === undefined) return [];\n if (typeof patch === \"string\") {\n const trimmed = patch.trim();\n return trimmed === \"\" ? [] : (JSON.parse(trimmed) as PatchEntry[]);\n }\n return patch;\n}\n\nfunction buildUnits(\n wasm: HookedWasm,\n input: string,\n inputIsBitmark: boolean,\n): { view: BitView; source: string }[] {\n if (inputIsBitmark) {\n const out = wasm.split_bits(input);\n if (isError(out)) throw new Error(out);\n const slices = JSON.parse(out) as { index: number; source: string }[];\n return slices.map((s) => ({\n view: { format: \"bitmark\", index: s.index, total: slices.length, source: s.source },\n source: s.source,\n }));\n }\n const out = wasm.split_json_bits(input);\n if (isError(out)) throw new Error(out);\n const envelopes = JSON.parse(out) as { bit?: import(\"../generated/bit-types.js\").AnyBit }[];\n return envelopes.map((env, index) => ({\n view: { format: \"json\", index, total: envelopes.length, bit: env.bit ?? {} },\n // Per-bit transform consumes a one-bit JSON document.\n source: JSON.stringify([env]),\n }));\n}\n\n/**\n * Split the document and run `preHook` (on the calling thread) for each bit,\n * producing the surviving compute jobs + their views. This is the main-thread\n * half shared by the sync and worker-pool drivers — only the resulting\n * data-only {@link BitJob}s ever cross to a worker.\n */\nexport function planTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): TransformPlan {\n const mode = options.mode ?? \"optimized\";\n const output: OutputFormat = options.outputFormat ?? \"json\";\n const spacesAroundValues = options.spacesAroundValues ?? 1;\n const indent = options.indent ?? 2;\n const pretty = options.pretty ?? false;\n\n const sel = options.inputFormat ?? \"auto\";\n const inputIsBitmark = sel === \"bitmark\" || (sel !== \"json\" && wasm.is_bitmark(input));\n const inputFormat = inputIsBitmark ? \"bitmark\" : \"json\";\n\n const staticPatch = normalisePatch(options.patch);\n const units = buildUnits(wasm, input, inputIsBitmark);\n const total = units.length;\n\n const jobs: BitJob[] = [];\n const views: BitView[] = [];\n for (let index = 0; index < total; index++) {\n const { view, source } = units[index];\n view.index = index;\n view.total = total;\n\n const result = options.preHook ? options.preHook(view) || {} : {};\n if (result.drop) continue;\n\n const patches = result.patches ? [...staticPatch, ...result.patches] : staticPatch;\n jobs.push({\n index,\n source,\n inputFormat,\n outputFormat: result.outputFormat ?? output,\n mode,\n patchJson: JSON.stringify(patches),\n spacesAroundValues,\n });\n views.push(view);\n }\n return { jobs, views, output, pretty, indent };\n}\n\n/**\n * Compute one bit's rendered element synchronously via WASM. The per-bit\n * element is always compact JSON (the document is prettified once on\n * recombination). Returns an `error:`-prefixed string on failure.\n */\nexport function computeBit(wasm: HookedWasm, job: BitJob): string {\n const out = wasm.transform(\n job.source,\n job.inputFormat,\n job.outputFormat,\n job.mode,\n job.patchJson,\n false,\n 2,\n job.spacesAroundValues,\n );\n if (isError(out)) return out;\n return job.outputFormat === \"json\" ? stripArray(out) : out;\n}\n\n/** Recombine per-bit elements into the final document, in document order. */\nexport function recombine(\n wasm: HookedWasm,\n elements: string[],\n output: OutputFormat,\n pretty: boolean,\n indent: number,\n): string {\n // Bitmark and plain-text bits both join with newlines; only JSON wraps as an\n // array. (`text` is output-only, lossy plain-text extraction.)\n if (output === \"bitmark\" || output === \"text\") return elements.join(\"\\n\");\n const arr = `[${elements.join(\",\")}]`;\n return pretty ? wasm.prettify(arr, indent) : arr;\n}\n\n/**\n * Per-bit transform driver (synchronous, in-process): split the document, run\n * `preHook` for each bit on the calling thread, apply the static patch + any\n * hook patches, re-emit the bit, run `postHook`, then recombine in document\n * order.\n *\n * Hooks run synchronously on the calling thread; only data crosses into WASM.\n * Used when a `preHook`/`postHook` is supplied; the hookless path stays a\n * single `wasm.transform` call. Returns the document, or an `error:`-prefixed\n * string on failure.\n */\nexport function runHookedTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): string {\n let plan: TransformPlan;\n try {\n plan = planTransform(wasm, input, options);\n } catch (e) {\n return errorString(e);\n }\n\n const rendered: string[] = [];\n for (let i = 0; i < plan.jobs.length; i++) {\n const element = computeBit(wasm, plan.jobs[i]);\n if (isError(element)) return element;\n options.postHook?.(plan.views[i], element);\n rendered.push(element);\n }\n return recombine(wasm, rendered, plan.output, plan.pretty, plan.indent);\n}\n","// @zen-component: TS-ParallelOrchestrator\n\nimport type { TransformOptions } from \"../types.js\";\nimport { type BitJob, errorString, type HookedWasm, isError, planTransform, recombine } from \"./hooked-transform.js\";\n\n/**\n * A platform pool: compute `jobs` across up to `workers` workers, returning the\n * rendered element per job in submission order. Node and browser supply their\n * own (worker_threads / Worker); the orchestration around it is shared.\n */\nexport type RunJobs = (jobs: BitJob[], workers: number) => Promise<string[]>;\n\n/**\n * Shared parallel transform orchestration. The main-thread half — split +\n * `preHook` + recombine + `postHook` — is identical to the sync driver; only\n * the data-only per-bit jobs cross to `runJobs` (the platform pool). Closures\n * (`preHook`/`postHook`) never leave the calling thread.\n *\n * Returns the document, or an `error:`-prefixed string on failure.\n */\nexport async function orchestrateParallel(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n runJobs: RunJobs,\n): Promise<string> {\n let plan;\n try {\n plan = planTransform(wasm, input, options);\n } catch (e) {\n return errorString(e);\n }\n\n let elements: string[];\n try {\n elements = await runJobs(plan.jobs, options.workers ?? 4);\n } catch (e) {\n return errorString(e);\n }\n\n for (let i = 0; i < elements.length; i++) {\n if (isError(elements[i])) return elements[i];\n options.postHook?.(plan.views[i], elements[i]);\n }\n return recombine(wasm, elements, plan.output, plan.pretty, plan.indent);\n}\n","// @zen-component: TS-WorkerPool\n//\n// A fixed-size Node worker_threads pool that computes per-bit transform jobs in\n// parallel. Jobs are dispatched to idle workers; results are matched by id and\n// returned in submission order. The pool is short-lived (created per\n// transformParallel call) and terminated when all jobs settle.\n\nimport { fileURLToPath } from \"node:url\";\nimport { Worker } from \"node:worker_threads\";\nimport type { BitJob } from \"../core/hooked-transform.js\";\n\ninterface JobResult {\n ok: boolean;\n element?: string;\n error?: string;\n}\n\n// The worker entry is emitted as a sibling CJS file in dist/ (see tsup config),\n// so a CJS-format worker runs regardless of how the package itself was loaded.\nfunction workerPath(): string {\n return fileURLToPath(new URL(\"./worker-entry.cjs\", import.meta.url));\n}\n\n/**\n * Run `jobs` across up to `workers` worker threads, returning the rendered\n * element for each job in the **same order** as `jobs`. Rejects on the first\n * worker error or job error.\n */\nexport function runJobsParallel(jobs: BitJob[], workers: number): Promise<string[]> {\n if (jobs.length === 0) return Promise.resolve([]);\n const poolSize = Math.max(1, Math.min(workers, jobs.length));\n const path = workerPath();\n\n return new Promise<string[]>((resolve, reject) => {\n const results = new Array<string>(jobs.length);\n let next = 0;\n let settled = 0;\n let done = false;\n const pool: Worker[] = [];\n\n const shutdown = () => {\n for (const w of pool) void w.terminate();\n };\n const fail = (err: Error) => {\n if (done) return;\n done = true;\n shutdown();\n reject(err);\n };\n\n const dispatch = (w: Worker) => {\n if (done) return;\n if (next >= jobs.length) return; // no more work for this worker\n const id = next++;\n w.postMessage({ id, job: jobs[id] });\n };\n\n for (let i = 0; i < poolSize; i++) {\n const w = new Worker(path);\n pool.push(w);\n w.on(\"message\", (res: JobResult & { id: number }) => {\n if (done) return;\n if (!res.ok) {\n fail(new Error(res.error ?? \"worker job failed\"));\n return;\n }\n results[res.id] = res.element as string;\n settled++;\n if (settled === jobs.length) {\n done = true;\n shutdown();\n resolve(results);\n return;\n }\n dispatch(w);\n });\n w.on(\"error\", fail);\n w.on(\"exit\", (code) => {\n if (!done && code !== 0) fail(new Error(`worker exited with code ${code}`));\n });\n }\n\n // Prime each worker with one job.\n for (const w of pool) dispatch(w);\n });\n}\n","// @zen-component: TS-TransformParallel\n//\n// Node-only parallel transform: the main-thread half (split + preHook +\n// recombine + postHook) is shared with the synchronous driver and the browser\n// pool via orchestrateParallel; only the per-bit WASM compute is fanned out\n// across a worker_threads pool.\n\nimport { orchestrateParallel } from \"../core/parallel.js\";\nimport type { HookedWasm } from \"../core/hooked-transform.js\";\nimport type { TransformOptions } from \"../types.js\";\nimport { runJobsParallel } from \"./pool.js\";\n\n/**\n * Parallel counterpart of `transform` on Node. `preHook`/`postHook` run on the\n * calling thread; only data-only jobs cross to the worker_threads pool.\n */\nexport function runParallelTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): Promise<string> {\n return orchestrateParallel(wasm, input, options, runJobsParallel);\n}\n","// @zen-component: LEGACY-Facade\n// Node platform wiring for the legacy facade: provides the WASM module and\n// real file I/O (PLAN-126 F-5). The browser entry provides WASM only.\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { setLegacyFileIo, setLegacyWasm, type LegacyWasm } from \"../legacy/runtime.js\";\n\nexport function initLegacyNode(wasm: LegacyWasm): void {\n setLegacyWasm(wasm);\n setLegacyFileIo({\n existsSync: (p) => fs.existsSync(p),\n readFileSync: (p, encoding) => fs.readFileSync(p, { encoding: encoding as BufferEncoding }),\n writeFile: (p, data, opts) => {\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, data, {\n encoding: (opts.encoding ?? \"utf8\") as BufferEncoding,\n flag: opts.append ? \"a\" : \"w\",\n });\n },\n });\n}\n","// @zen-component: LEGACY-Facade\n// Platform injection for the legacy facade. The Node and browser entries\n// provide the WASM module (and, on Node, file I/O) before exposing the\n// `legacy` namespace — the facade itself stays platform-free.\n\n/** The subset of the WASM surface the legacy facade drives. */\nexport interface LegacyWasm {\n convert(\n input: string,\n inputFormat: string,\n outputFormat: string,\n mode: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n includeUnknownProperties: boolean,\n mappingReport: boolean,\n ): string;\n canonicalize(\n input: string,\n inputFormat: string,\n mode: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n ): string;\n breakscape_text(input: string, format: string, location: string): string;\n unbreakscape_text(input: string, format: string, location: string): string;\n info(infoType: string, format: string, bit: string, pretty: boolean, indent: number): string;\n is_bitmark(input: string): boolean;\n prettify(json: string, indent: number): string;\n convert_text(input: string, direction: string, format: string, location: string): string;\n}\n\nlet wasmModule: LegacyWasm | undefined;\n\nexport function setLegacyWasm(wasm: LegacyWasm): void {\n wasmModule = wasm;\n}\n\nexport function getLegacyWasm(): LegacyWasm {\n if (!wasmModule) {\n throw new Error(\n \"legacy API not initialised: the WASM module has not been provided (browser consumers must call init() first)\",\n );\n }\n return wasmModule;\n}\n\n/** Node file I/O, injected by the Node entry only (PLAN-126 F-5). */\nexport interface LegacyFileIo {\n existsSync(path: string): boolean;\n readFileSync(path: string, encoding: string): string;\n /** Write (or append) `data`, creating parent directories as needed. */\n writeFile(path: string, data: string, opts: { append?: boolean; encoding?: string }): void;\n}\n\nlet fileIo: LegacyFileIo | undefined;\n\nexport function setLegacyFileIo(io: LegacyFileIo): void {\n fileIo = io;\n}\n\n/** Returns undefined in the browser (no file I/O). */\nexport function getLegacyFileIo(): LegacyFileIo | undefined {\n return fileIo;\n}\n","// @zen-component: LEGACY-Facade\n// The `legacy` namespace: a bpg-compatible (bitmark-parser-generator\n// v5.31.1) programmatic interface over the WASM core (PLAN-126).\n//\n// Everything here is exposed ONLY via `legacy.*` / the\n// `@gmb/bitmark-parser/legacy` subpath — nothing is re-exported at the\n// package root (reserved for the modern API and its future generated types).\n\nexport { BitmarkParserGenerator, bitmarkTextParse } from \"./bpg-class.js\";\nexport { Builder, type BuildBitOptions } from \"./builder.js\";\nexport { ResourceBuilder, type ResourceMethod } from \"./resource-builder.js\";\nexport { LegacyUnsupportedError } from \"./errors.js\";\nexport { isPseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\n\n// Enum objects + option interfaces (vendored shapes)\nexport * from \"./options.js\";\nexport { BitType, BoundingBoxIndex, NodeType, TextMarkType, TextNodeType } from \"./enums-extra.js\";\n\n// Unsupported bpg internals — present but throwing (PLAN-126 F-2)\nexport {\n Ast,\n BitmarkFileGenerator,\n BitmarkGenerator,\n BitmarkParser,\n BitmarkStringGenerator,\n FileWriter,\n HtmlTableGenerator,\n HtmlTableParser,\n JsonFileGenerator,\n JsonGenerator,\n JsonParser,\n JsonStringGenerator,\n StreamWriter,\n StringWriter,\n} from \"./stubs.js\";\n\n// Vendored bpg JSON model / text-node types (type-only)\nexport type * from \"./vendor/BitJson.js\";\nexport type * from \"./vendor/BitWrapperJson.js\";\nexport type * from \"./vendor/BodyBitJson.js\";\nexport type * from \"./vendor/ParserJson.js\";\nexport type * from \"./vendor/ResourceJson.js\";\nexport type * from \"./vendor/TextNodes.js\";\n// bpg parity: bpg additionally exported JsonText under the alias `Text`\n// (bitmark-parser-generator src/index.ts: `JsonText as Text`).\nexport type { JsonText as Text } from \"./vendor/TextNodes.js\";\nexport type {\n ParserError,\n ParserInfo,\n ParserLocation,\n BitTypeType,\n TextFormatType,\n ResourceTypeType,\n TextMarkTypeType,\n TextNodeTypeType,\n} from \"./vendor/enums.js\";\n","// @zen-component: LEGACY-Facade\n\n/** Error thrown for bpg API members / options the legacy facade does not support. */\nexport class LegacyUnsupportedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LegacyUnsupportedError\";\n }\n}\n\n/** Throw for a bpg API member that is not supported (PLAN-126 F-2). */\nexport function unsupportedMember(member: string, reason?: string): never {\n throw new LegacyUnsupportedError(\n `'${member}' is not supported by the @gmb/bitmark-parser legacy API` + (reason ? `: ${reason}` : \"\"),\n );\n}\n\n/** Throw for an option that cannot be honoured (PLAN-126 F-9: never silently ignore). */\nexport function unsupportedOption(option: string, reason?: string): never {\n throw new LegacyUnsupportedError(\n `Option '${option}' is not supported by the @gmb/bitmark-parser legacy API` +\n (reason ? `: ${reason}` : \"\"),\n );\n}\n","// @zen-component: LEGACY-Facade\n// Central bpg-option → core-parameter translation table (PLAN-126 F-4/F-9).\n// Strict policy: options that map are honoured; options we cannot honour\n// throw a LegacyUnsupportedError naming the option. Sole exception:\n// `bitmarkParserType` is accepted and ignored — bpg v5.31.1 itself hardcodes\n// the peggy parser and ignores the option.\n\nimport { unsupportedOption } from \"./errors.js\";\nimport type { BitmarkOptions, JsonOptions } from \"./options.js\";\n\nconst V3_ONLY = \"bitmark v2 output is not supported (this parser is bitmark v3 only)\";\n\nexport function validateVersionOptions(opts: {\n bitmarkVersion?: number;\n bitmarkParserType?: string;\n}): void {\n if (opts.bitmarkVersion === 2) unsupportedOption(\"bitmarkVersion: 2\", V3_ONLY);\n // bitmarkParserType: accepted + ignored (documented exception).\n}\n\nexport function validateBitmarkOptions(o: BitmarkOptions): void {\n // The option TYPES are narrowed to the supported values (build-time\n // errors for TS consumers), but JS callers can still pass anything —\n // keep validating the runtime values (hence the widening casts).\n // Booleans error only when set truthy (false === bpg default behaviour).\n if (o.explicitTextFormat) unsupportedOption(\"bitmarkOptions.explicitTextFormat\");\n // prettifyJson: honoured — maps to the core's pretty/indent for bitmark\n // output (embedded JSON bodies of json-format bits); see prettyIndent().\n if ((o.cardSetVersion as number | undefined) === 1) {\n unsupportedOption(\"bitmarkOptions.cardSetVersion: 1\", V3_ONLY);\n }\n if (o.debugGenerationInline) unsupportedOption(\"bitmarkOptions.debugGenerationInline\");\n if (o.noBreakscaping) unsupportedOption(\"bitmarkOptions.noBreakscaping\");\n}\n\nexport function validateJsonOptions(o: JsonOptions): void {\n if (o.textAsPlainText) unsupportedOption(\"jsonOptions.textAsPlainText\", V3_ONLY);\n // excludeUnknownProperties: honoured — maps to the core's inverse\n // `includeUnknownProperties` flag (bpg default: include; see bpg-class).\n if (o.debugGenerationInline) unsupportedOption(\"jsonOptions.debugGenerationInline\");\n // enableWarnings: accepted — parser warnings are always carried in the\n // output envelope by this parser, so both values are honoured trivially.\n}\n\n/**\n * bpg `prettify?: boolean | number` → core (pretty, indent).\n *\n * Also used for `bitmarkOptions.prettifyJson` (identical bpg semantics:\n * true → indent 2, positive number → that indent, else off) — for bitmark\n * output the core's pretty/indent prettify the embedded JSON bodies of\n * json-format bits, which is exactly what bpg's prettifyJson did.\n */\nexport function prettyIndent(prettify: boolean | number | undefined): {\n pretty: boolean;\n indent: number;\n} {\n if (prettify === true) return { pretty: true, indent: 2 };\n if (typeof prettify === \"number\" && prettify > 0) return { pretty: true, indent: prettify };\n return { pretty: false, indent: 2 };\n}\n\n/** bpg `spacesAroundValues?: number | boolean` → core spaces count (cap 10, as bpg). */\nexport function spacesAround(v: number | boolean | undefined): number {\n if (v === undefined || v === true) return 1;\n if (v === false) return 0;\n return Math.max(0, Math.min(10, v));\n}\n\n/**\n * bpg text format value → core breakscape format.\n * bpg maps `latex`/`json`/`xml` as aliases of plain text, and defaults\n * anything else (including absent) to bitmark text (`bitmark++`).\n */\nexport function mapTextFormat(f: string | undefined): \"bitmark++\" | \"plainText\" {\n switch (f) {\n case \"text\":\n case \"latex\":\n case \"json\":\n case \"xml\":\n return \"plainText\";\n default:\n return \"bitmark++\";\n }\n}\n","// @zen-component: LEGACY-Facade\n// The legacy \"AST\" is bit JSON (PLAN-126 §3.1): an envelope of the parser's\n// wrapper entries (`{ bit, parser?, bitmark? }`), tagged with a\n// non-enumerable marker so it can be recognised without surviving\n// JSON.stringify. It round-trips through `convert`, but is NOT bpg's\n// internal TS AST node model (no `cardNode` / `BodyPart[]` structure).\n\nexport const PSEUDO_AST_MARKER = Symbol.for(\"@gmb/bitmark-parser/legacy-pseudo-ast\");\n\nexport interface LegacyPseudoAst {\n bits: unknown[];\n}\n\nexport function makePseudoAst(bits: unknown[]): LegacyPseudoAst {\n const ast: LegacyPseudoAst = { bits };\n Object.defineProperty(ast, PSEUDO_AST_MARKER, { value: true, enumerable: false });\n return ast;\n}\n\nexport function isPseudoAst(v: unknown): v is LegacyPseudoAst {\n return (\n v !== null &&\n typeof v === \"object\" &&\n (PSEUDO_AST_MARKER in v || Array.isArray((v as LegacyPseudoAst).bits))\n );\n}\n","// GENERATED FILE — do not edit.\n// Emitted by scripts/gen-legacy-resource-keys.mjs from\n// resources/bitmark-configurator/bitmark.json. Regenerate via `npm run init`.\n//\n// Every bit whose config maps a repeatable resource tag group onto a single\n// JSON collection key. The legacy `Builder.buildBit` routes bpg's\n// `resources` input onto this key (bpg's JsonGenerator special-cased the\n// same family by bit type; here it is derived from config).\n\n/** A bit's resource-collection mapping: target JSON key + accepted resource type. */\nexport interface ResourceCollection {\n key: string;\n resourceType: string;\n}\n\nexport const RESOURCE_COLLECTION_KEYS: Readonly<Record<string, ResourceCollection>> = {\n \"extractor-image\": { key: \"images\", resourceType: \"image\" },\n \"extractor-image-collapsible\": { key: \"images\", resourceType: \"image\" },\n \"images-logo-grave\": { key: \"logos\", resourceType: \"image\" },\n \"prototype-images\": { key: \"images\", resourceType: \"image\" },\n};\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `Builder` (PLAN-126 §3.1): the legacy AST is bit JSON, so\n// building a bit is a data *mapping* (bpg buildBit data → bit JSON keys)\n// followed by one WASM json→json normalization pass — the config-driven core\n// performs the defaulting/coercion/validation that bpg's ~4.2k-line builder\n// does in TS. No parsing logic lives here.\n\nimport { getLegacyWasm } from \"./runtime.js\";\nimport { makePseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\nimport { RESOURCE_COLLECTION_KEYS } from \"./generated/resource-collection-keys.js\";\nimport type { ParserError, ParserInfo } from \"./vendor/enums.js\";\n\n/** Carries bpg `data.parser` (wrapper-level metadata) invisibly on the built bit. */\nexport const BUILT_BIT_PARSER = Symbol.for(\"@gmb/bitmark-parser/legacy-built-bit-parser\");\n\n/**\n * bpg buildBit data keys whose bit-JSON key differs. Everything else in the\n * flat data object maps by identity (the data fields are already the bpg\n * JSON model types) and unknown keys pass through untouched (PLAN-126 F-6).\n */\nconst DATA_KEY_TO_JSON_KEY: Record<string, string> = {\n bitType: \"type\",\n textFormat: \"format\",\n flashcards: \"cards\",\n markConfig: \"marks\",\n};\n\n/** bpg deprecated text-format value accepted by buildBit. */\nconst DEPRECATED_TEXT_FORMATS: Record<string, string> = {\n \"bitmark--\": \"bitmark++\",\n \"bitmark+\": \"bitmark++\",\n};\n\n/**\n * Config `bodyFormat` → bpg TextFormat value. When the caller omits\n * `textFormat`, bpg defaults to the bit config's `textFormatDefault`\n * (bpg Builder.bit), which is derived from the config `bodyFormat` — NOT\n * to bitmark text. E.g. `extractor-information` (bodyFormat: json) built\n * without an explicit `textFormat` must keep its JSON body verbatim.\n */\nconst CONFIG_BODY_FORMAT_TO_TEXT_FORMAT: Record<string, string> = {\n bitmark: \"bitmark++\",\n text: \"text\",\n json: \"json\",\n latex: \"latex\",\n xml: \"xml\",\n};\n\n/** Top-level bit JSON fields typed JsonText (tag location) in bpg. */\nconst TAG_TEXT_KEYS = [\n \"title\",\n \"subtitle\",\n \"item\",\n \"lead\",\n \"pageNumber\",\n \"marginNumber\",\n \"hint\",\n \"instruction\",\n \"caption\",\n] as const;\n\nexport interface BuildBitOptions {\n cardSet?: {\n sideNo: number;\n variantNo: number;\n };\n}\n\nexport class Builder {\n /**\n * Build bitmark AST envelope (bpg-compatible `buildBitmark`).\n */\n buildBitmark(data: { bits?: unknown[]; errors?: ParserError[] }): LegacyPseudoAst {\n const ast = makePseudoAst(data.bits ?? []);\n if (data.errors !== undefined) {\n (ast as LegacyPseudoAst & { errors?: ParserError[] }).errors = data.errors;\n }\n return ast;\n }\n\n /**\n * Build a bit (bpg-compatible `buildBit`).\n *\n * Accepts the full bpg data shape (flat, ~250 optional fields, values in\n * the JSON model types). Returns the normalized bit JSON. Throws\n * `No config found for bit: X` for unknown bit types, as bpg does.\n *\n * NOTE (documented divergences from bpg):\n * - the return value is bit JSON, not bpg's internal AST node model;\n * - `resourceType` (an inference hint in bpg) is not carried into the\n * JSON — the attached `resource` object is authoritative.\n *\n * `resources` follows bpg's JsonGenerator routing: on a bit whose config\n * maps a repeatable resource tag group onto a collection key (e.g.\n * `images` / `logos` — see the generated RESOURCE_COLLECTION_KEYS), the\n * matching-type entries land under that key; on every other bit the first\n * entry becomes the canonical single `resource` (as bpg: \"if there is\n * more than one resource, use the first one\").\n */\n buildBit(data: Record<string, unknown>, _options?: BuildBitOptions): Record<string, unknown> {\n const wasm = getLegacyWasm();\n const src = { ...data };\n\n const bitType = src.bitType as string | undefined;\n const bitConfig = this.getBitConfig(bitType);\n\n // --- divergent keys ---\n const bit: Record<string, unknown> = {};\n bit.type = bitType;\n if (src.isCommented) {\n bit.type = \"_comment\";\n bit.originalType = bitType;\n }\n delete src.bitType;\n delete src.isCommented;\n\n const textFormat = src.textFormat as string | undefined;\n if (textFormat !== undefined) {\n bit.format = DEPRECATED_TEXT_FORMATS[textFormat] ?? textFormat;\n delete src.textFormat;\n } else {\n // bpg parity: `textFormat ?? bitConfig.textFormatDefault` — the\n // config-driven default, so e.g. JSON-bodied bits don't get their\n // body mangled by the bitmark text parser (see parseStringTexts).\n bit.format = CONFIG_BODY_FORMAT_TO_TEXT_FORMAT[bitConfig.bodyFormat ?? \"\"] ?? \"bitmark++\";\n }\n\n // resourceType is an inference hint only (see doc comment)\n delete src.resourceType;\n\n // body: accept bpg's Partial<Body> node ({ body: <JsonText> }) or a bare JsonText\n const body = src.body as { body?: unknown } | unknown;\n if (body !== undefined && body !== null && typeof body === \"object\" && \"body\" in (body as object)) {\n bit.body = (body as { body?: unknown }).body;\n delete src.body;\n }\n\n // example / __isDefaultExample → isExample + example (bpg toExample semantics)\n if (src.example !== undefined) {\n bit.isExample = true;\n bit.example = src.example;\n delete src.example;\n delete src.__isDefaultExample;\n } else if (src.__isDefaultExample) {\n bit.isExample = true;\n delete src.__isDefaultExample;\n }\n\n // resources → the bit's resource-collection key (config-derived), else\n // the canonical single `resource` — bpg's JsonGenerator routing.\n const resources = src.resources;\n if (resources !== undefined && bitType !== undefined) {\n const list = Array.isArray(resources) ? resources : [resources];\n const collection = RESOURCE_COLLECTION_KEYS[bitType];\n if (collection) {\n // bpg keeps only the entries of the collection's resource type.\n bit[collection.key] = list.filter(\n (r) =>\n r !== null &&\n typeof r === \"object\" &&\n (r as { type?: unknown }).type === collection.resourceType,\n );\n } else if (list.length >= 1) {\n bit.resource = list[0];\n }\n delete src.resources;\n }\n\n // parser metadata lives on the wrapper, not in the bit JSON\n const parser = src.parser as ParserInfo | undefined;\n delete src.parser;\n\n // extraProperties spread into the bit JSON top level (bpg semantics)\n const extraProperties = src.extraProperties as Record<string, unknown> | undefined;\n delete src.extraProperties;\n\n // --- renamed + identity + unknown keys (pass through, PLAN-126 F-6) ---\n for (const [key, value] of Object.entries(src)) {\n if (value === undefined) continue;\n bit[DATA_KEY_TO_JSON_KEY[key] ?? key] = value;\n }\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n if (!(key in bit)) bit[key] = value;\n }\n }\n\n // --- bpg parity: string JsonText values are parsed bitmark text ---\n this.parseStringTexts(bit);\n\n // --- normalization pass: the config-driven core defaults/coerces/validates ---\n const out = wasm.convert(JSON.stringify([{ bit }]), \"json\", \"json\", \"optimized\", false, 2, 1, false, false);\n if (out.startsWith(\"error:\")) {\n throw new Error(out.slice(\"error:\".length).trim());\n }\n const entries = JSON.parse(out) as { bit: Record<string, unknown> }[];\n const built = entries[0]?.bit ?? bit;\n\n // F-6: keys the core doesn't know are dropped by the normalize pass —\n // re-attach them so nothing is lost silently. Values matching bpg's own\n // \"unset optional\" strip set (false / \"\" / [] / null) stay stripped,\n // mirroring bpg's removeUnwantedProperties.\n for (const [key, value] of Object.entries(bit)) {\n if (key in built) continue;\n if (\n value === false ||\n value === \"\" ||\n value === null ||\n (Array.isArray(value) && value.length === 0)\n ) {\n continue;\n }\n built[key] = value;\n }\n if (parser !== undefined) {\n Object.defineProperty(built, BUILT_BIT_PARSER, { value: parser, enumerable: false });\n }\n return built;\n }\n\n /**\n * Build a highlight body bit (bpg-compatible `buildHighlight`).\n * Shapes the HighlightJson body-bit; unset optionals are omitted.\n */\n buildHighlight(\n _context: unknown,\n data: Record<string, unknown> | undefined,\n ): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const src = { ...data };\n // bpg: data may arrive nested under 'attrs' (when coming from JSON)\n const attrs = src.attrs as Record<string, unknown> | undefined;\n if (attrs) Object.assign(src, attrs);\n\n const texts = Array.isArray(src.texts)\n ? (src.texts as Record<string, unknown>[]).filter((t) => t != null).map((t) => ({\n text: t.text ?? \"\",\n isCorrect: t.isCorrect ?? false,\n isHighlighted: t.isHighlighted ?? false,\n ...stripUndefined(t, [\"text\", \"isCorrect\", \"isHighlighted\"]),\n }))\n : [];\n\n const node: Record<string, unknown> = {\n type: \"highlight\",\n texts,\n prefix: src.prefix ?? \"\",\n postfix: src.postfix ?? \"\",\n ...stripUndefined(src, [\"type\", \"texts\", \"prefix\", \"postfix\", \"attrs\"]),\n attrs: {},\n };\n return node;\n }\n\n /**\n * bpg's builder parses string-valued JsonText fields as bitmark text\n * (inline marks become TextAst marks); the composer would otherwise treat\n * them as literal text. Converts top-level JsonText fields in place.\n * Nested (card-content) strings are left literal — documented divergence.\n *\n * A string body is dispatched on the bit's resolved text format, as bpg's\n * buildBody: bitmark text is parsed to TextAst, `json` is JSON.parsed\n * (unparseable → null), and plain-text formats (text/latex/xml) stay\n * verbatim. Tag texts are always bitmark text, independent of body format\n * (bpg TextParser.toAst ignores format; only location matters).\n */\n private parseStringTexts(bit: Record<string, unknown>): void {\n const wasm = getLegacyWasm();\n const toAst = (s: string, location: \"body\" | \"tag\"): unknown => {\n if (s === \"\") return s;\n const out = wasm.convert_text(s, \"textToAst\", \"bitmark++\", location);\n try {\n return JSON.parse(out) as unknown;\n } catch {\n return s;\n }\n };\n\n const format = bit.format as string | undefined;\n const bitmarkBody = format === undefined || format === \"bitmark++\" || format === \"bitmark+\";\n if (typeof bit.body === \"string\") {\n if (format === \"json\") {\n // bpg handleJsonBody: parse legacy string bodies; null on failure\n try {\n bit.body = JSON.parse(bit.body) as unknown;\n } catch {\n bit.body = null;\n }\n } else if (bitmarkBody) {\n bit.body = toAst(bit.body, \"body\");\n }\n // plain-text formats (text/latex/xml): body stays a verbatim string\n }\n for (const key of TAG_TEXT_KEYS) {\n const v = bit[key];\n if (typeof v === \"string\") bit[key] = toAst(v, \"tag\");\n }\n }\n\n /**\n * Look up the bit's config (`wasm.info`); throws bpg's exact\n * unknown-bit-type error (`Config.getBitConfig` parity).\n */\n private getBitConfig(bitType: string | undefined): { bodyFormat?: string } {\n const wasm = getLegacyWasm();\n if (bitType !== undefined) {\n try {\n const info = JSON.parse(wasm.info(\"bit\", \"json\", bitType, false, 2)) as {\n error?: string;\n bodyFormat?: string;\n };\n if (info.error === undefined) return info;\n } catch {\n // fall through to the not-found error\n }\n }\n throw new Error(`No config found for bit: ${bitType}`);\n }\n}\n\nfunction stripUndefined(\n src: Record<string, unknown>,\n exclude: string[],\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(src)) {\n if (v !== undefined && !exclude.includes(k)) out[k] = v;\n }\n return out;\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `BitmarkParserGenerator` class — a thin synchronous wrapper\n// over the WASM core (PLAN-126). Behavioural parity is at the call boundary:\n// same method names, option keys and return shapes as bpg v5.31.1.\n\nimport { PACKAGE_INFO } from \"../generated/package_info.js\";\nimport { unsupportedMember, unsupportedOption } from \"./errors.js\";\nimport { getLegacyFileIo, getLegacyWasm } from \"./runtime.js\";\nimport {\n mapTextFormat,\n prettyIndent,\n spacesAround,\n validateBitmarkOptions,\n validateJsonOptions,\n validateVersionOptions,\n} from \"./translate.js\";\nimport type {\n BreakscapeOptions,\n ConvertHtmlTableOptions,\n ConvertOptions,\n ConvertTextOptions,\n CreateAstOptions,\n ExtractPlainTextOptions,\n FileOptions,\n InfoOptions,\n UnbreakscapeOptions,\n UpgradeOptions,\n} from \"./options.js\";\nimport { makePseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\nimport { BUILT_BIT_PARSER } from \"./builder.js\";\n\n/** Classified input for the convert/upgrade pipeline (PLAN-126 F-10). */\ninterface ResolvedInput {\n /** JSON-wrapper-array string (json/ast input) or bitmark source (bitmark input). */\n source: string;\n isBitmark: boolean;\n}\n\nexport class BitmarkParserGenerator {\n /**\n * Get the version of the library.\n *\n * Reports the @gmb/bitmark-parser version (not a bpg version string).\n */\n public version(): string {\n return PACKAGE_INFO.version;\n }\n\n /**\n * Convert bitmark from bitmark to JSON, or JSON to bitmark (bpg-compatible).\n *\n * Input detection order matches bpg: AST → JSON → assume bitmark.\n * Default output: bitmark input → json; json/ast input → bitmark.\n */\n public convert(input: string | unknown, options?: ConvertOptions): string | unknown | void {\n const opts: ConvertOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateVersionOptions(opts);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n\n const outputFormat = opts.outputFormat ?? (isBitmark ? \"json\" : \"bitmark\");\n const coreFormat = outputFormat === \"ast\" ? \"json\" : outputFormat;\n // bpg parity: `jsonOptions.prettify` governs JSON output only;\n // `bitmarkOptions.prettifyJson` governs bitmark output (it prettifies the\n // embedded JSON bodies of json-format bits — same boolean|number shape).\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const emit =\n coreFormat === \"bitmark\" ? prettyIndent(bitmarkOptions.prettifyJson) : { pretty, indent };\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n // bpg parity: unknown properties are included in JSON output unless\n // `jsonOptions.excludeUnknownProperties` is set (the core flag is the\n // inverse and only affects the bitmark → JSON direction).\n const includeUnknown = !jsonOptions.excludeUnknownProperties;\n\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", coreFormat, \"optimized\", emit.pretty, emit.indent, spaces, includeUnknown, false);\n this.throwOnError(out);\n\n // Shape the result per output format (bpg-compatible return shapes)\n if (outputFormat === \"bitmark\" || outputFormat === \"text\") {\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n if (outputFormat === \"json\") {\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n // outputFormat === \"ast\": bit-JSON pseudo-AST (PLAN-126 §3.1)\n const ast = makePseudoAst(JSON.parse(out) as unknown[]);\n if (opts.outputFile) {\n return this.deliver(JSON.stringify(ast), opts.outputFile, opts.fileOptions);\n }\n return ast;\n }\n\n /**\n * Upgrade (prettify / canonicalize) bitmark or JSON to the latest version\n * of itself (bpg-compatible `upgrade`).\n */\n public upgrade(input: string | unknown, options?: UpgradeOptions): string | unknown | void {\n const opts: UpgradeOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateVersionOptions(opts);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n // Same routing as convert(): bitmark in → bitmark out, so prettifyJson\n // applies; JSON in → JSON out, so jsonOptions.prettify applies.\n const { pretty, indent } = prettyIndent(\n isBitmark ? bitmarkOptions.prettifyJson : jsonOptions.prettify,\n );\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n\n const out = wasm.canonicalize(source, isBitmark ? \"bitmark\" : \"json\", \"optimized\", pretty, indent, spaces);\n this.throwOnError(out);\n\n if (isBitmark) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n\n /**\n * Get information about the bitmark language (bpg-compatible `info`).\n */\n public info(options?: InfoOptions): unknown {\n const opts: InfoOptions = Object.assign({}, options);\n const wasm = getLegacyWasm();\n const type = opts.type ?? \"list\";\n const format = opts.outputFormat ?? \"text\";\n const { pretty, indent } = prettyIndent(opts.prettify);\n\n const coreFormat = format === \"pojo\" ? \"json\" : format;\n const out = wasm.info(type, coreFormat, opts.bit ?? \"\", pretty, indent);\n this.throwOnError(out);\n if (format === \"pojo\") return JSON.parse(out) as unknown;\n return out;\n }\n\n /** Not supported: bpg-internal development tool. */\n public generateConfig(_options?: unknown): void {\n unsupportedMember(\"BitmarkParserGenerator.generateConfig\", \"bpg-internal development tool\");\n }\n\n /**\n * Convert between HTML tables and bitmark tables (bpg-compatible\n * `convertHtmlTable`).\n *\n * Backed by the core's schema-driven html mapping: HTML input has each\n * `<table>` wrapped in the core's `<bitmark-bit>` envelope and parsed;\n * bits input is emitted as html and the `<table>` fragments extracted\n * (the envelope stripped). The markup *inside* `<table>` follows this\n * parser's html mapping, which may differ from bpg's in detail.\n */\n public convertHtmlTable(\n input: string | unknown,\n options?: ConvertHtmlTableOptions,\n ): string | unknown | void {\n const opts: ConvertHtmlTableOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n if (opts.keepUnknownTags) unsupportedOption(\"keepUnknownTags\");\n if (opts.noBreakscaping) unsupportedOption(\"noBreakscaping\");\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n\n const inStr = typeof input === \"string\" ? this.maybeReadFile(input, undefined) : \"\";\n const isHtmlInput =\n opts.inputFormat === \"html\" ||\n (opts.inputFormat === undefined && typeof input === \"string\" && /<table[\\s>]/iu.test(inStr));\n\n if (!isHtmlInput) {\n // bits (bitmark / JSON / AST) → HTML `<table>` fragments\n const { source, isBitmark } = this.resolveInput(input, undefined);\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"html\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return this.deliver(extractHtmlTables(out).join(\"\\n\"), opts.outputFile, opts.fileOptions);\n }\n\n // HTML input: wrap each <table> in the core's bit envelope and parse\n const bitType = opts.tableFormat === \"table\" ? \"table\" : \"table-extended\";\n const wrapped = extractHtmlTables(inStr)\n .map((t) => `<bitmark-bit data-type=\"${bitType}\" data-format=\"bitmark++\">${t}</bitmark-bit>`)\n .join(\"\");\n const outputFormat = opts.outputFormat ?? \"bitmark\";\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n\n if (outputFormat === \"html\") {\n const out = wasm.convert(wrapped, \"html\", \"html\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return this.deliver(extractHtmlTables(out).join(\"\\n\"), opts.outputFile, opts.fileOptions);\n }\n const coreFormat = outputFormat === \"ast\" ? \"json\" : outputFormat;\n const out = wasm.convert(wrapped, \"html\", coreFormat, \"optimized\", pretty, indent, spaces, false, false);\n this.throwOnError(out);\n if (outputFormat === \"bitmark\" || outputFormat === \"text\") {\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n if (outputFormat === \"json\") {\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n const ast = makePseudoAst(JSON.parse(out) as unknown[]);\n if (opts.outputFile) return this.deliver(JSON.stringify(ast), opts.outputFile, opts.fileOptions);\n return ast;\n }\n\n /**\n * Create a bit-JSON pseudo-AST from bitmark or JSON input (PLAN-126 §3.1).\n *\n * NOTE: the returned structure is the bit JSON (wrapper entries), not\n * bpg's internal TS AST node model. It round-trips through `convert` but\n * is not walkable with bpg's `Ast`/`NodeType`.\n */\n public createAst(input: unknown, options?: CreateAstOptions): LegacyPseudoAst {\n const opts: CreateAstOptions = Object.assign({}, options);\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n // bpg's AST carries extraProperties unconditionally (createAst has no\n // jsonOptions), so unknown properties are always included here.\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"json\", \"optimized\", false, 2, 1, true, false);\n this.throwOnError(out);\n return makePseudoAst(JSON.parse(out) as unknown[]);\n }\n\n /**\n * Breakscape text (bpg-compatible `breakscapeText`).\n */\n public breakscapeText(input: string, options?: BreakscapeOptions): string | void {\n if (!input) return input;\n const opts: BreakscapeOptions = Object.assign({}, options);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n const inStr = this.maybeReadFile(input, opts.inputFormat);\n const res = wasm.breakscape_text(inStr, mapTextFormat(opts.textFormat), opts.textLocation ?? \"body\");\n return this.deliver(res, opts.outputFile, opts.fileOptions);\n }\n\n /**\n * Unbreakscape text (bpg-compatible `unbreakscapeText`).\n */\n public unbreakscapeText(input: string, options?: UnbreakscapeOptions): string | void {\n if (!input) return input;\n const opts: UnbreakscapeOptions = Object.assign({}, options);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n const inStr = this.maybeReadFile(input, opts.inputFormat);\n const res = wasm.unbreakscape_text(inStr, mapTextFormat(opts.textFormat), opts.textLocation ?? \"body\");\n return this.deliver(res, opts.outputFile, opts.fileOptions);\n }\n\n /**\n * Convert bitmark text ↔ text AST (bpg-compatible `convertText`).\n *\n * Direction is auto-detected: TextAst (JSON) input generates bitmark\n * text; anything else parses as bitmark text and returns the TextAst\n * (plain JS object; a string when `jsonOptions.prettify` is set).\n */\n public convertText(input: string | unknown, options?: ConvertTextOptions): string | unknown | void {\n const opts: ConvertTextOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n\n const isBitmarkText = opts.textFormat === undefined || mapTextFormat(opts.textFormat) === \"bitmark++\";\n const textLocation = opts.textLocation ?? \"body\";\n\n let inStr: string;\n let ast: unknown[] | undefined;\n if (typeof input === \"string\") {\n inStr = this.maybeReadFile(input, opts.inputFormat);\n ast = this.parseTextAstString(inStr);\n } else {\n inStr = JSON.stringify(input);\n ast = Array.isArray(input) ? input : undefined;\n }\n\n if (ast !== undefined) {\n // TextAst → text (reverse honours the location; a plain-text format\n // generates plain text, i.e. marks are dropped — bpg parity)\n const out = isBitmarkText\n ? wasm.convert_text(JSON.stringify(ast), \"astToText\", \"bitmark++\", textLocation)\n : wasm.convert_text(JSON.stringify(ast), \"astToPlainText\", \"plainText\", textLocation);\n this.throwOnError(out);\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n\n // text → TextAst (bpg parses forward at body location)\n const out = wasm.convert_text(inStr, \"textToAst\", isBitmarkText ? \"bitmark++\" : \"plainText\", \"body\");\n this.throwOnError(out);\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const outStr = pretty ? wasm.prettify(out, indent) : out;\n if (opts.outputFile) return this.deliver(outStr, opts.outputFile, opts.fileOptions);\n if (pretty) return outStr;\n return JSON.parse(out) as unknown;\n }\n\n /**\n * Convert a text AST to plain text (bpg-compatible `textAstToPlainText`).\n */\n public textAstToPlainText(textAst: unknown, _options?: ExtractPlainTextOptions): string {\n const wasm = getLegacyWasm();\n const out = wasm.convert_text(\n typeof textAst === \"string\" ? textAst : JSON.stringify(textAst),\n \"astToPlainText\",\n \"bitmark++\",\n \"body\",\n );\n this.throwOnError(out);\n return out;\n }\n\n /**\n * Extract plain text from bitmark or bitmark JSON (bpg-compatible).\n */\n public extractPlainText(input: string | unknown, options?: ExtractPlainTextOptions): string {\n const inputFormat = options?.inputFormat;\n const wasm = getLegacyWasm();\n if (inputFormat === \"plainText\") {\n return typeof input === \"string\" ? String(input) : \"\";\n }\n if (inputFormat === \"bitmarkText\") {\n const ast = wasm.convert_text(String(input), \"textToAst\", \"bitmark++\", \"body\");\n const out = wasm.convert_text(ast, \"astToPlainText\", \"bitmark++\", \"body\");\n this.throwOnError(out);\n return out;\n }\n if (typeof input === \"string\" && this.parseTextAstString(input) === undefined && !wasm.is_bitmark(input)) {\n // Neither JSON nor bitmark: bpg falls through to bitmark text\n const looksJson = ((): boolean => {\n try {\n JSON.parse(input);\n return true;\n } catch {\n return false;\n }\n })();\n if (!looksJson) {\n return this.extractPlainText(input, { inputFormat: \"bitmarkText\" });\n }\n }\n const { source, isBitmark } = this.resolveInput(input, undefined);\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"text\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return out;\n }\n\n /** If `s` parses as a TextAst JSON array, return it. */\n private parseTextAstString(s: string): unknown[] | undefined {\n const t = s.trim();\n if (!t.startsWith(\"[\")) return undefined;\n try {\n const v = JSON.parse(t) as unknown;\n if (Array.isArray(v) && v.every((n) => n !== null && typeof n === \"object\" && \"type\" in n)) {\n return v;\n }\n } catch {\n // not JSON\n }\n return undefined;\n }\n\n // ------------------------------------------------------------------\n // Internal helpers\n // ------------------------------------------------------------------\n\n /**\n * Resolve bpg input (string | file path | JSON value | pseudo-AST) to a\n * source string for the WASM core, classified per bpg's detection order:\n * AST → JSON → assume bitmark (PLAN-126 F-10).\n */\n protected resolveInput(input: unknown, inputFormat: string | undefined): ResolvedInput {\n if (typeof input !== \"string\") {\n // Parsed JSON / pseudo-AST value.\n const entries = this.jsonEntries(input);\n return {\n source: JSON.stringify(entries ? entries.map((b) => this.toWrapperEntry(b)) : input),\n isBitmark: false,\n };\n }\n const inStr = this.maybeReadFile(input, inputFormat);\n const wasm = getLegacyWasm();\n if (wasm.is_bitmark(inStr)) return { source: inStr, isBitmark: true };\n // JSON-ish: normalise loose shapes (AST envelope, single wrapper, bare bit)\n try {\n const parsed = JSON.parse(inStr) as unknown;\n const entries = this.jsonEntries(parsed);\n if (entries) {\n return {\n source: JSON.stringify(entries.map((b) => this.toWrapperEntry(b))),\n isBitmark: false,\n };\n }\n } catch {\n // is_bitmark said \"not bitmark\" but it is not JSON either —\n // fall through and let the core's own detection handle it (bpg\n // behaviour: assume bitmark).\n return { source: inStr, isBitmark: true };\n }\n return { source: inStr, isBitmark: false };\n }\n\n /**\n * Normalise the JSON shapes bpg accepts to a bits/entries array:\n * wrapper array, `{ bits: [...] }` AST envelope, single `{ bit: ... }`\n * wrapper, or a bare bit object (`{ type: ... }`).\n */\n private jsonEntries(v: unknown): unknown[] | undefined {\n if (Array.isArray(v)) return v;\n if (v !== null && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (Array.isArray(o.bits)) return o.bits;\n if (\"bit\" in o) return [o];\n if (typeof o.type === \"string\") return [{ bit: o }];\n }\n return undefined;\n }\n\n /**\n * Normalise a pseudo-AST bits entry to a `{ bit, parser? }` wrapper.\n * `Builder.buildBit` returns bare bit JSON (with any parser metadata\n * attached under a non-enumerable symbol); parsed forward output is\n * already wrapper-shaped.\n */\n private toWrapperEntry(entry: unknown): unknown {\n if (entry !== null && typeof entry === \"object\" && \"bit\" in (entry as object)) return entry;\n const wrapper: { bit: unknown; parser?: unknown } = { bit: entry };\n const parser = (entry as Record<symbol, unknown> | null)?.[BUILT_BIT_PARSER];\n if (parser !== undefined) wrapper.parser = parser;\n return wrapper;\n }\n\n /** bpg parity: read `input` as a file when it names one (Node only). */\n protected maybeReadFile(input: string, inputFormat: string | undefined): string {\n if (inputFormat === \"string\") return input;\n const io = getLegacyFileIo();\n if (!io) return input;\n try {\n if (io.existsSync(input)) return io.readFileSync(input, \"utf8\");\n } catch {\n // treat as literal input\n }\n return input;\n }\n\n /** bpg parity: writing a file is impossible in the browser. */\n protected checkBrowserFileWrite(outputFile: string | undefined): void {\n if (outputFile && !getLegacyFileIo()) {\n throw new Error(\"Cannot write to file in browser environment\");\n }\n }\n\n /** Return `data`, or write it to `outputFile` (returning void), as bpg does. */\n protected deliver(data: string, outputFile?: string, fileOptions?: FileOptions): string | void {\n if (!outputFile) return data;\n const io = getLegacyFileIo();\n if (!io) throw new Error(\"Cannot write to file in browser environment\");\n io.writeFile(outputFile, data, {\n append: fileOptions?.append,\n encoding: fileOptions?.encoding ?? \"utf8\",\n });\n }\n\n /** The core reports failures as `error:`-prefixed strings; bpg throws. */\n protected throwOnError(out: string): void {\n if (out.startsWith(\"error:\")) {\n throw new Error(out.slice(\"error:\".length).trim());\n }\n }\n}\n\n/**\n * Extract every top-level `<table>…</table>` fragment from `html`\n * (case-insensitive, nesting-safe). Pure string scanning — no HTML parsing.\n */\nfunction extractHtmlTables(html: string): string[] {\n const tables: string[] = [];\n const lower = html.toLowerCase();\n let i = 0;\n for (;;) {\n const start = lower.indexOf(\"<table\", i);\n if (start === -1) break;\n let depth = 0;\n let j = start;\n let end = -1;\n while (j < html.length) {\n const open = lower.indexOf(\"<table\", j);\n const close = lower.indexOf(\"</table\", j);\n if (close === -1) break;\n if (open !== -1 && open < close) {\n depth++;\n j = open + \"<table\".length;\n } else {\n depth--;\n const closeEnd = lower.indexOf(\">\", close);\n j = closeEnd === -1 ? html.length : closeEnd + 1;\n if (depth === 0) {\n end = j;\n break;\n }\n }\n }\n if (end === -1) break;\n tables.push(html.slice(start, end));\n i = end;\n }\n return tables;\n}\n\n/**\n * Direct bitmark text parser (bpg-compatible `bitmarkTextParse`):\n * bitmark text → TextAst array.\n */\nexport function bitmarkTextParse(text: string): unknown[] {\n const out = getLegacyWasm().convert_text(text, \"textToAst\", \"bitmark++\", \"body\");\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return JSON.parse(out) as unknown[];\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `ResourceBuilder` (PLAN-126 §3.1): each method shapes the\n// `{ type, <family>: { ... } }` ResourceJson wrapper from bpg's flat data.\n// One generic table-driven implementation — per-bit-type defaulting and\n// URL-derived cosmetics are left to the config-driven core, which normalizes\n// the resource when the bit containing it is converted.\n\ninterface ResourceSpec {\n /** ResourceJson discriminator (`type`). */\n type: string;\n /** Family key holding the resource data object. */\n key: string;\n /** JSON field that bpg's `data.value` maps to. */\n valueField: \"src\" | \"url\" | \"body\";\n}\n\nconst RESOURCE_SPECS = {\n imageResource: { type: \"image\", key: \"image\", valueField: \"src\" },\n imageLinkResource: { type: \"image-link\", key: \"imageLink\", valueField: \"url\" },\n audioResource: { type: \"audio\", key: \"audio\", valueField: \"src\" },\n audioEmbedResource: { type: \"audio-embed\", key: \"audioEmbed\", valueField: \"src\" },\n audioLinkResource: { type: \"audio-link\", key: \"audioLink\", valueField: \"url\" },\n videoResource: { type: \"video\", key: \"video\", valueField: \"src\" },\n videoEmbedResource: { type: \"video-embed\", key: \"videoEmbed\", valueField: \"url\" },\n videoLinkResource: { type: \"video-link\", key: \"videoLink\", valueField: \"url\" },\n stillImageFilmEmbedResource: {\n type: \"still-image-film-embed\",\n key: \"stillImageFilmEmbed\",\n valueField: \"url\",\n },\n stillImageFilmLinkResource: {\n type: \"still-image-film-link\",\n key: \"stillImageFilmLink\",\n valueField: \"url\",\n },\n articleResource: { type: \"article\", key: \"article\", valueField: \"body\" },\n documentResource: { type: \"document\", key: \"document\", valueField: \"url\" },\n documentEmbedResource: { type: \"document-embed\", key: \"documentEmbed\", valueField: \"url\" },\n documentLinkResource: { type: \"document-link\", key: \"documentLink\", valueField: \"url\" },\n documentDownloadResource: {\n type: \"document-download\",\n key: \"documentDownload\",\n valueField: \"url\",\n },\n appLinkResource: { type: \"app-link\", key: \"appLink\", valueField: \"url\" },\n websiteLinkResource: { type: \"website-link\", key: \"websiteLink\", valueField: \"url\" },\n} as const satisfies Record<string, ResourceSpec>;\n\nexport type ResourceMethod = (\n context: unknown,\n data: Record<string, unknown> | undefined,\n __typeAlias?: string,\n) => Record<string, unknown> | undefined;\n\nfunction buildResource(spec: ResourceSpec): ResourceMethod {\n return (_context, data, _typeAlias) => {\n if (!data) return undefined;\n const { value, ...rest } = data;\n const inner: Record<string, unknown> = { [spec.valueField]: value ?? \"\" };\n for (const [k, v] of Object.entries(rest)) {\n if (v !== undefined) inner[k] = v;\n }\n return { type: spec.type, [spec.key]: inner };\n };\n}\n\n/** Resource `type` string → spec (for the generic wrapper/data entry points). */\nconst SPEC_BY_TYPE: Record<string, ResourceSpec> = Object.fromEntries(\n Object.values(RESOURCE_SPECS).map((s) => [s.type, s]),\n);\n\n/** bpg-compatible ResourceBuilder: 17 `<family>Resource(context, data)` methods\n * plus the generic `resourceFromResourceJson` / `resourceFromResourceDataJson`. */\nexport class ResourceBuilder {\n /**\n * Normalise existing ResourceJson wrapper(s) (bpg-compatible).\n * Unknown resource types are dropped (bpg parity: it skips invalid types).\n */\n resourceFromResourceJson(\n _context: unknown,\n resource?: Record<string, unknown> | Record<string, unknown>[],\n ): unknown {\n if (!resource) return undefined;\n const single = !Array.isArray(resource);\n const list = single ? [resource as Record<string, unknown>] : resource;\n const nodes: Record<string, unknown>[] = [];\n for (const wrapper of list) {\n const spec = SPEC_BY_TYPE[wrapper.type as string];\n if (!spec) continue;\n const inner = (wrapper[spec.key] ?? {}) as Record<string, unknown>;\n const { [spec.valueField]: value, ...rest } = inner;\n const built = buildResource(spec)(undefined, { value, ...rest });\n if (built) nodes.push(built);\n }\n if (nodes.length === 0) return undefined;\n return single ? nodes[0] : nodes;\n }\n\n /**\n * Build a resource wrapper from a bare ResourceDataJson (bpg-compatible).\n * `data` may also be a plain string (used as the url/src/body value).\n */\n resourceFromResourceDataJson(\n context: unknown,\n type: string,\n data?: Record<string, unknown> | string,\n ): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const spec = SPEC_BY_TYPE[type];\n if (!spec) return undefined;\n const asString = typeof data === \"string\" ? data : undefined;\n const obj = typeof data === \"object\" ? data : {};\n const { url, src, body, ...rest } = obj as {\n url?: unknown;\n src?: unknown;\n body?: unknown;\n [k: string]: unknown;\n };\n const value = url ?? src ?? body ?? asString;\n return buildResource(spec)(context, { value, ...rest });\n }\n imageResource: ResourceMethod = buildResource(RESOURCE_SPECS.imageResource);\n imageLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.imageLinkResource);\n audioResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioResource);\n audioEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioEmbedResource);\n audioLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioLinkResource);\n videoResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoResource);\n videoEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoEmbedResource);\n videoLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoLinkResource);\n stillImageFilmEmbedResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.stillImageFilmEmbedResource,\n );\n stillImageFilmLinkResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.stillImageFilmLinkResource,\n );\n articleResource: ResourceMethod = buildResource(RESOURCE_SPECS.articleResource);\n documentResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentResource);\n documentEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentEmbedResource);\n documentLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentLinkResource);\n documentDownloadResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.documentDownloadResource,\n );\n appLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.appLinkResource);\n websiteLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.websiteLinkResource);\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible enum objects and option interfaces (vendored from\n// bitmark-parser-generator v5.31.1, superenum EnumType<> replaced with the\n// equivalent value-union derivation). Exposed ONLY via the `legacy`\n// namespace / subpath — never re-exported at the package root.\n\n/** @internal */\ntype EnumType<T> = T[keyof T];\n\n/** Input type enumeration */\nexport const Input = {\n /** Input is as a string */\n string: \"string\",\n /** Input is as a file path */\n file: \"file\",\n} as const;\nexport type InputType = EnumType<typeof Input>;\n\n/** Output type enumeration */\nexport const Output = {\n /** Output bitmark string */\n bitmark: \"bitmark\",\n /** Output JSON as a plain JS object, or a file */\n json: \"json\",\n /** Output AST as a plain JS object, or a file */\n ast: \"ast\",\n /** Output plain text as a string, or a file */\n text: \"text\",\n} as const;\nexport type OutputType = EnumType<typeof Output>;\n\n/** Input format enumeration */\nexport const InputFormat = {\n bitmark: \"bitmark\",\n bitmarkText: \"bitmarkText\",\n plainText: \"plainText\",\n html: \"html\",\n} as const;\nexport type InputFormatType = EnumType<typeof InputFormat>;\n\nexport const BitmarkVersion = {\n v2: 2,\n v3: 3,\n} as const;\nexport type BitmarkVersionType = EnumType<typeof BitmarkVersion>;\n\nexport const CardSetVersion = {\n v1: 1,\n v2: 2,\n} as const;\nexport type CardSetVersionType = EnumType<typeof CardSetVersion>;\n\nexport const BitmarkParserType = {\n peggy: \"peggy\",\n} as const;\nexport type BitmarkParserTypeType = EnumType<typeof BitmarkParserType>;\n\nexport const InfoType = {\n list: \"list\",\n deprecated: \"deprecated\",\n all: \"all\",\n bit: \"bit\",\n} as const;\nexport type InfoTypeType = EnumType<typeof InfoType>;\n\nexport const InfoFormat = {\n text: \"text\",\n json: \"json\",\n pojo: \"pojo\",\n} as const;\nexport type InfoFormatType = EnumType<typeof InfoFormat>;\n\nexport const BodyTextFormat = {\n plainText: \"text\",\n latex: \"latex\",\n json: \"json\",\n xml: \"xml\",\n bitmarkPlusPlus: \"bitmark++\",\n} as const;\nexport type BodyTextFormatType = EnumType<typeof BodyTextFormat>;\n\nexport const TextLocation = {\n tag: \"tag\",\n body: \"body\",\n} as const;\nexport type TextLocationType = EnumType<typeof TextLocation>;\n\n/** Options for the output file (Node only) */\nexport interface FileOptions {\n /** Append to a file if true, otherwise overwrite */\n append?: boolean;\n /** Character encoding, defaults to 'utf8' */\n encoding?: string;\n}\n\n// Strict option policy, surfaced at BUILD time (bpg declared these wider):\n// options this facade cannot honour are narrowed to their supported value(s)\n// — truthy-throws booleans to `false`, value-gated enums to the supported\n// literal — so TS consumers get a type error instead of only the runtime\n// LegacyUnsupportedError. The runtime validation stays (JS callers, or TS\n// with the type ignored, still get the loud error).\n\n/** Options for bitmark generation */\nexport interface BitmarkOptions {\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n explicitTextFormat?: false;\n prettifyJson?: boolean | number;\n /** bitmark v3 only — card set version `1` throws `LegacyUnsupportedError` at runtime. */\n cardSetVersion?: typeof CardSetVersion.v2;\n spacesAroundValues?: number | boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n debugGenerationInline?: false;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n noBreakscaping?: false;\n}\n\n/** Options for JSON generation */\nexport interface JsonOptions {\n enableWarnings?: boolean | number;\n prettify?: boolean | number;\n stringify?: boolean;\n /** bitmark v3 only — `true` throws `LegacyUnsupportedError` at runtime. */\n textAsPlainText?: false;\n /**\n * Exclude unknown properties from the JSON output (default: `false` —\n * unknown properties are included, as bpg). The parser's warning text\n * references the new API's inverse flag (`includeUnknownProperties`).\n */\n excludeUnknownProperties?: boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n debugGenerationInline?: false;\n}\n\n/** Options for bitmark text JSON generation */\nexport interface TextJsonOptions {\n prettify?: boolean | number;\n}\n\n/** Info options for the parser */\nexport interface InfoOptions {\n type?: InfoTypeType;\n bit?: string;\n outputFormat?: InfoFormatType;\n prettify?: boolean | number;\n}\n\n/** Conversion options for bitmark / JSON conversion */\nexport interface ConvertOptions {\n /** bitmark v3 only — version `2` throws `LegacyUnsupportedError` at runtime. */\n bitmarkVersion?: typeof BitmarkVersion.v3;\n bitmarkParserType?: BitmarkParserTypeType;\n inputFormat?: InputType;\n outputFormat?: OutputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Prettify options for bitmark / JSON prettify / validate */\nexport interface UpgradeOptions {\n /** bitmark v3 only — version `2` throws `LegacyUnsupportedError` at runtime. */\n bitmarkVersion?: typeof BitmarkVersion.v3;\n bitmarkParserType?: BitmarkParserTypeType;\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Conversion options for bitmark text / JSON conversion */\nexport interface ConvertTextOptions {\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n jsonOptions?: TextJsonOptions;\n}\n\n/** Create AST options */\nexport interface CreateAstOptions {\n inputFormat?: InputType;\n}\n\nexport interface ExtractPlainTextOptions {\n inputFormat?: InputFormatType;\n}\n\n/** Options for convertHtmlTable */\nexport interface ConvertHtmlTableOptions {\n inputFormat?: InputFormatType;\n outputFormat?: OutputType | \"html\";\n tableFormat?: string;\n keepUnknownTags?: boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n noBreakscaping?: false;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Breakscape options */\nexport interface BreakscapeOptions {\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n}\n\n/** Unbreakscape options */\nexport interface UnbreakscapeOptions {\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n}\n","// @zen-component: LEGACY-Facade\n// Remaining bpg enum exports: TextMarkType / TextNodeType (vendored values),\n// BitType (built lazily from the config-driven core — never a hardcoded bit\n// list), and throwing proxies for enums tied to unsupported internals.\n\nimport { unsupportedMember } from \"./errors.js\";\nimport { getLegacyWasm } from \"./runtime.js\";\n\n/** Vendored from bpg v5.31.1 model/enum/TextMarkType.ts. */\nexport const TextMarkType = {\n bold: \"bold\",\n light: \"light\",\n italic: \"italic\",\n highlight: \"highlight\",\n highlightOrange: \"highlightOrange\",\n highlightYellow: \"highlightYellow\",\n highlightGreen: \"highlightGreen\",\n highlightBlue: \"highlightBlue\",\n highlightPurple: \"highlightPurple\",\n highlightPink: \"highlightPink\",\n highlightBrown: \"highlightBrown\",\n highlightBlack: \"highlightBlack\",\n highlightWhite: \"highlightWhite\",\n highlightGray: \"highlightGray\",\n strike: \"strike\",\n subscript: \"subscript\",\n superscript: \"superscript\",\n ins: \"ins\",\n del: \"del\",\n underline: \"underline\",\n doubleUnderline: \"doubleUnderline\",\n circle: \"circle\",\n languageEmRed: \"languageEmRed\",\n languageEmOrange: \"languageEmOrange\",\n languageEmYellow: \"languageEmYellow\",\n languageEmGreen: \"languageEmGreen\",\n languageEmBlue: \"languageEmBlue\",\n languageEmPurple: \"languageEmPurple\",\n languageEmPink: \"languageEmPink\",\n languageEmBrown: \"languageEmBrown\",\n languageEmBlack: \"languageEmBlack\",\n languageEmWhite: \"languageEmWhite\",\n languageEmGray: \"languageEmGray\",\n languageEm: \"languageEm\",\n userUnderline: \"userUnderline\",\n userDoubleUnderline: \"userDoubleUnderline\",\n userStrike: \"userStrike\",\n userCircle: \"userCircle\",\n userHighlight: \"userHighlight\",\n notranslate: \"notranslate\",\n link: \"link\",\n ref: \"ref\",\n xref: \"xref\",\n extref: \"extref\",\n footnote: \"footnote\",\n footnoteStar: \"footnote*\",\n symbol: \"symbol\",\n var: \"var\",\n code: \"code\",\n timer: \"timer\",\n duration: \"duration\",\n color: \"color\",\n colorPicker: \"colorPicker\",\n comment: \"comment\",\n} as const;\n\n/** Vendored from bpg v5.31.1 model/enum/TextNodeType.ts. */\nexport const TextNodeType = {\n text: \"text\",\n hardBreak: \"hardBreak\",\n paragraph: \"paragraph\",\n heading: \"heading\",\n section: \"section\",\n noBulletList: \"noBulletList\",\n bulletList: \"bulletList\",\n orderedList: \"orderedList\",\n orderedListRoman: \"orderedListRoman\",\n orderedListRomanLower: \"orderedListRomanLower\",\n letteredList: \"letteredList\",\n letteredListLower: \"letteredListLower\",\n taskList: \"taskList\",\n listItem: \"listItem\",\n taskItem: \"taskItem\",\n image: \"image\",\n imageInline: \"imageInline\",\n codeBlock: \"codeBlock\",\n latex: \"latex\",\n gap: \"gap\",\n select: \"select\",\n highlight: \"highlight\",\n mark: \"mark\",\n} as const;\n\n/** bpg key derivation: kebab-case bit name → camelCase enum key. */\nfunction bitNameToKey(name: string): string {\n return name.replace(/-([a-z0-9])/gu, (_, c: string) => c.toUpperCase());\n}\n\nlet bitTypeCache: Record<string, string> | undefined;\n\nfunction loadBitTypes(): Record<string, string> {\n if (!bitTypeCache) {\n const wasm = getLegacyWasm();\n const all = JSON.parse(wasm.info(\"all\", \"json\", \"\", false, 2)) as { name: string }[];\n const map: Record<string, string> = { _standard: \"_standard\" };\n for (const { name } of all) {\n map[bitNameToKey(name)] = name;\n }\n bitTypeCache = map;\n }\n return bitTypeCache;\n}\n\n/**\n * bpg-compatible `BitType` enum object, built lazily from the core's\n * config (`info`) rather than a hardcoded list. Keys are the camelCase of\n * the bit names, exactly as bpg derives them.\n */\nexport const BitType: Record<string, string> = new Proxy(\n {},\n {\n get: (_t, prop) => (typeof prop === \"string\" ? loadBitTypes()[prop] : undefined),\n has: (_t, prop) => typeof prop === \"string\" && prop in loadBitTypes(),\n ownKeys: () => Reflect.ownKeys(loadBitTypes()),\n getOwnPropertyDescriptor: (_t, prop) =>\n typeof prop === \"string\" && prop in loadBitTypes()\n ? { value: loadBitTypes()[prop], enumerable: true, configurable: true, writable: false }\n : undefined,\n },\n);\n\n/** Loud F-2 stand-in for enums tied to unsupported bpg internals. */\nfunction unsupportedEnum(name: string, reason: string): Record<string, string> {\n return new Proxy(\n {},\n {\n get: (_t, prop) => {\n if (prop === Symbol.toPrimitive || prop === \"toString\" || prop === Symbol.toStringTag) {\n return () => `[unsupported ${name}]`;\n }\n return unsupportedMember(name, reason);\n },\n has: () => unsupportedMember(name, reason),\n ownKeys: () => unsupportedMember(name, reason),\n },\n );\n}\n\n/** bpg `NodeType` — names bpg's internal AST nodes; the legacy AST is bit JSON. */\nexport const NodeType = unsupportedEnum(\n \"NodeType\",\n \"it names bpg's internal AST nodes; the legacy AST is bit JSON (see createAst)\",\n);\n\n/** bpg `BoundingBoxIndex` — bpg-internal utility. */\nexport const BoundingBoxIndex = unsupportedEnum(\n \"BoundingBoxIndex\",\n \"bpg-internal bounding-box utility\",\n);\n","// @zen-component: LEGACY-Facade\n// Throwing stubs for bpg exports the legacy facade deliberately does not\n// implement (PLAN-126 F-2: exist, but fail loudly and deterministically —\n// never silent no-ops). These are internals of bpg's TS implementation\n// (its AST walker, generators, parsers, writers), which have no equivalent\n// over the WASM core.\n\nimport { unsupportedMember } from \"./errors.js\";\n\nfunction stubClass(name: string, reason: string): new (...args: unknown[]) => never {\n return class {\n constructor() {\n unsupportedMember(name, reason);\n }\n } as unknown as new (...args: unknown[]) => never;\n}\n\nconst WALKER_REASON =\n \"the legacy AST is bit JSON, not bpg's internal node model; walking it with bpg NodeType names would silently misbehave\";\nconst INTERNAL_REASON = \"internal class of bpg's TS implementation\";\n\n/** bpg `Ast` walker — unsupported (PLAN-126 decision Q-7). */\nexport const Ast = stubClass(\"Ast\", WALKER_REASON);\n\nexport const BitmarkGenerator = stubClass(\"BitmarkGenerator\", INTERNAL_REASON);\nexport const BitmarkStringGenerator = stubClass(\"BitmarkStringGenerator\", INTERNAL_REASON);\nexport const BitmarkFileGenerator = stubClass(\"BitmarkFileGenerator\", INTERNAL_REASON);\nexport const JsonGenerator = stubClass(\"JsonGenerator\", INTERNAL_REASON);\nexport const JsonStringGenerator = stubClass(\"JsonStringGenerator\", INTERNAL_REASON);\nexport const JsonFileGenerator = stubClass(\"JsonFileGenerator\", INTERNAL_REASON);\nexport const HtmlTableGenerator = stubClass(\"HtmlTableGenerator\", INTERNAL_REASON);\nexport const HtmlTableParser = stubClass(\"HtmlTableParser\", INTERNAL_REASON);\nexport const BitmarkParser = stubClass(\"BitmarkParser\", INTERNAL_REASON);\nexport const JsonParser = stubClass(\"JsonParser\", INTERNAL_REASON);\nexport const StringWriter = stubClass(\"StringWriter\", INTERNAL_REASON);\nexport const FileWriter = stubClass(\"FileWriter\", INTERNAL_REASON);\nexport const StreamWriter = stubClass(\"StreamWriter\", INTERNAL_REASON);\n","// @zen-component: WASM-TSBindings\n\nimport type { AnyBit } from \"./generated/bit-types.js\";\n\n/**\n * Output mode for JSON serialization.\n *\n * - `\"optimized\"` — omit keys whose values match their natural defaults.\n * - `\"full\"` — include all keys enumerated from the bitmark configuration.\n */\nexport type OutputMode = \"optimized\" | \"full\";\n\n/**\n * Lexer stage selector.\n *\n * - `\"lex\"` — combined lexer, text output (default).\n * - `\"lex-json\"` — combined lexer, JSON array output.\n */\nexport type LexStage = \"lex\" | \"lex-json\";\n\n/** Options for the {@link lex} function. */\nexport interface LexOptions {\n /** Selects the lexer pipeline stage (default: `\"lex\"`). */\n stage?: LexStage;\n}\n\n/** Options for the typed conversion pair ({@link bitmarkToObjects} /\n * {@link objectsToBitmark}). */\nexport interface ParseOptions {\n /** JSON output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /**\n * Include unknown properties in the bit JSON (default: `false`). Applies\n * to {@link bitmarkToObjects} only (parsing); ignored by\n * {@link objectsToBitmark} — unknown properties are never converted back\n * to bitmark. See {@link ConvertOptions.includeUnknownProperties}.\n */\n includeUnknownProperties?: boolean;\n}\n\n/**\n * Input format selector (adds auto-detection).\n *\n * `\"auto\"` sniffs bitmark-vs-JSON from the content; `\"bitmark\"` / `\"json\"` are\n * explicit; any config mapping id (e.g. `\"html\"`, `\"xml\"`) selects a markup\n * input that is reversed to the AST. The `(string & {})` arm admits those\n * config-driven mapping ids while keeping literal autocompletion.\n */\nexport type InputFormat = \"auto\" | \"bitmark\" | \"json\" | (string & {});\n\n/** Concrete output format. `\"text\"` is lossy plain-text extraction and is\n * output-only (it cannot be used as an input format). */\nexport type OutputFormat = \"bitmark\" | \"json\" | \"text\";\n\n/** Options for the {@link convert} function. */\nexport interface ConvertOptions {\n /** Input format (default: `\"auto\"`). */\n inputFormat?: InputFormat;\n /** Output format (default: `\"auto\"` — the opposite of the input). */\n outputFormat?: OutputFormat | \"auto\";\n /** JSON output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /** Include validation warnings in `parser.warnings` output (default: `false`). */\n warnings?: boolean;\n /** Output text as plain text — debug mode (default: `false`). */\n plainText?: boolean;\n /**\n * Prettify the JSON being emitted (default: `false`). For JSON output this\n * is the whole document; for bitmark output it is the embedded JSON bodies\n * of `json`-format bits (cosmetic — they re-parse to the same value).\n */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n /**\n * Bitmark → JSON only: include unknown properties in the bit JSON\n * (default: `false`). An unknown property (`[@key:value]` the bit's\n * config cannot resolve, at the bit body/footer — never inside cards or\n * consumed by a chain) is appended after all real keys as an array of\n * strings (`[@u]` with no value → `true`); a key colliding with a\n * configured key is `_`-prefixed. Unknown properties are never converted\n * back to bitmark, and each occurrence still warns.\n */\n includeUnknownProperties?: boolean;\n /**\n * Replace the converted output with a human-readable MAPPING REPORT of\n * what each input construct mapped to — including inputs that are NOT\n * mapped (default: `false`). Composite conversions (e.g. xml → json)\n * report every leg, one section after the other.\n */\n mappingReport?: boolean;\n}\n\n/** Options for the {@link canonicalize} function (the single same-format\n * re-emit surface; `mode` covers what the removed optimize/fullize did). */\nexport interface CanonicalizeOptions {\n /**\n * Input format (default: `\"auto\"`). The output is re-emitted in this same\n * format — e.g. `\"html\"` in, html out. `\"auto\"` sniffs bitmark vs JSON.\n */\n inputFormat?: InputFormat;\n /** Output mode (default: `\"optimized\"`; `\"full\"` emits all keys). */\n mode?: OutputMode;\n /**\n * Prettify the JSON being emitted (default: `false`) — the whole document\n * for JSON input, the embedded JSON bodies of `json`-format bits for\n * bitmark input.\n */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n}\n\n/** A patch operation. */\nexport type PatchOp = \"set\" | \"create\" | \"delete\" | \"append\";\n\n/**\n * A patch entry. Either the verbose form `{ path, op, value? }` or the\n * shorthand single-key object `{ \"<path>\": value }` (which means `set`).\n *\n * `path` addresses the bit JSON directly (e.g. `id`,\n * `cards[2].question.instruction`, `id[-1]`). To modify bitmark, convert to\n * JSON, patch, then convert back — `transform` does this when the output\n * format is bitmark.\n */\nexport type PatchEntry =\n | { path: string; op: PatchOp; value?: unknown }\n | Record<string, unknown>;\n\n// ── typed patch values (PLAN-128 §3.7) ──────────────────────────────────\n// The value type is resolved from the caller's literal path against `AnyBit`,\n// segment by segment — no enumeration of the path space, so compile cost is\n// per-call-site and bounded by the literal's length. Unresolvable segments and\n// dynamic (non-literal) paths degrade to `unknown`.\n\n/** @internal Peel `[n]` indexes off the front of `S`, unwrapping one array level each. */\ntype ApplyIndexes<T, S extends string> = S extends `[${string}]${infer Rest}`\n ? ApplyIndexes<T extends readonly (infer E)[] ? E : unknown, Rest>\n : T;\n\n/** @internal Resolve one dot-separated segment (`key`, `key[n]…`, or bare index). */\ntype Seg<T, S extends string> = S extends `${infer K}[${infer Rest}`\n ? ApplyIndexes<K extends \"\" ? T : K extends keyof T ? T[K] : unknown, `[${Rest}`>\n : S extends keyof T\n ? T[S]\n : S extends `${number}` | `-${number}`\n ? T extends readonly (infer E)[]\n ? E\n : unknown\n : unknown;\n\n/**\n * The type at patch path `P` within `T` (paths as in {@link PatchEntry}:\n * dot-separated keys with `[n]` indexes, negative-from-end allowed).\n */\nexport type PathValue<T, P extends string> = string extends P\n ? unknown\n : P extends `${infer S}.${infer Rest}`\n ? PathValue<NonNullable<Seg<T, S>>, Rest>\n : Seg<T, P>;\n\n/**\n * Build a {@link PatchEntry} with the `value` typed from the literal `path`,\n * resolved against {@link AnyBit}.\n *\n * For `append`, the value is typed as an *element* of the array at the path.\n *\n * @example\n * patchEntry(\"instruction\", \"set\", [{ type: \"paragraph\", content: [] }]);\n * patchEntry(\"id\", \"append\", \"1234\");\n * patchEntry(\"cards[0].question\", \"delete\");\n */\nexport type PatchValueFor<P extends string, O extends PatchOp> = O extends \"append\"\n ? NonNullable<PathValue<AnyBit, P>> extends readonly (infer E)[]\n ? E\n : PathValue<AnyBit, P>\n : PathValue<AnyBit, P>;\n\nexport function patchEntry<const P extends string, const O extends PatchOp>(\n path: P,\n op: O,\n value?: PatchValueFor<P, O>,\n): PatchEntry {\n return value === undefined ? { path, op } : { path, op, value };\n}\n\n/** One bit's source slice within a bitmark document (from {@link splitBits}). */\nexport interface BitSlice {\n index: number;\n byteStart: number;\n byteEnd: number;\n source: string;\n}\n\n/**\n * What a {@link PreHook} / {@link PostHook} sees for one bit, in its source\n * format. `index` is the bit's 0-based position; `total` is the bit count.\n */\nexport type BitView =\n | { format: \"bitmark\"; index: number; total: number; source: string }\n | { format: \"json\"; index: number; total: number; bit: AnyBit };\n\n/**\n * What a {@link PreHook} may return for a bit. All fields are optional; an\n * empty result (or `void`) makes the hook a pure observer.\n */\nexport interface PreHookResult {\n /** Patches to apply to this bit, after any static `patch`. */\n patches?: PatchEntry[];\n /** Override the output format for this bit only. */\n outputFormat?: OutputFormat;\n /** Drop the bit from the output entirely. */\n drop?: boolean;\n}\n\n/** Pre-processing hook: inspect a bit, optionally return modifications. */\nexport type PreHook = (view: BitView) => PreHookResult | void;\n\n/** Post-processing hook: observe a bit's input view and rendered output. */\nexport type PostHook = (view: BitView, output: string) => void;\n\n/** Options for the {@link transform} function. */\nexport interface TransformOptions {\n /** Input format (default: `\"auto\"`). */\n inputFormat?: InputFormat;\n /** Output format (default: `\"json\"`). */\n outputFormat?: OutputFormat;\n /** Output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /** A static patch applied to every bit (array of entries, or a JSON string). */\n patch?: PatchEntry[] | string;\n /**\n * Per-bit pre-hook, run on the calling thread. Returns patches (applied\n * after the static `patch`), an output-format override, or `drop`. Providing\n * a `preHook` or `postHook` switches `transform` to the per-bit path; with\n * neither, the whole document is transformed in a single pass.\n */\n preHook?: PreHook;\n /** Per-bit post-hook, run on the calling thread after each bit is rendered. */\n postHook?: PostHook;\n /**\n * Worker-thread count for {@link transformParallel} (Node only; default `4`).\n * Ignored by the synchronous {@link transform}.\n */\n workers?: number;\n /** Prettify the emitted JSON (default: `false`) — for bitmark output, the\n * embedded JSON bodies of `json`-format bits. */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n}\n\n/** Text format for breakscape / unbreakscape operations. */\nexport type TextFormat = \"bitmark++\" | \"plainText\";\n\n/** Text location for breakscape / unbreakscape operations. */\nexport type TextLocation = \"body\" | \"tag\";\n\n/** Options for the {@link breakscapeText} and {@link unbreakscapeText} functions. */\nexport interface BreakscapeOptions {\n /** Text format (default: `\"bitmark++\"`). */\n format?: TextFormat;\n /** Text location (default: `\"body\"`). */\n location?: TextLocation;\n}\n\n/** Info query type for the {@link info} function. */\nexport type InfoType = \"list\" | \"bit\" | \"all\" | \"deprecated\";\n\n/** Output format for the {@link info} function. */\nexport type InfoFormat = \"text\" | \"json\";\n\n/** Options for the {@link info} function. */\nexport interface InfoOptions {\n /** Info query type (default: `\"list\"`). */\n infoType?: InfoType;\n /** Output format (default: `\"text\"`). */\n format?: InfoFormat;\n /** Bit name — required when `infoType` is `\"bit\"`. */\n bit?: string;\n /** Whether to pretty-print JSON output (default: `false`). */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ADV9D,yBAA8B;;;AEEvB,IAAM,eAAe;AAAA,EAC1B,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,WAAW;AAAA,EACX,eAAe;AACjB;;;ACwCO,SAAS,QAAQ,GAAoB;AAC1C,SAAO,EAAE,WAAW,QAAQ;AAC9B;AAOO,SAAS,YAAY,GAAoB;AAC9C,QAAM,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AAC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U;AACjC,QAAM,WAAW,QAAQ,YAAY;AACrC,SAAO,KAAK,gBAAgB,OAAO,QAAQ,QAAQ;AACrD;AASO,SAAS,iBAAiB,OAAe,UAA6B,CAAC,GAAW;AACvF,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,WAAW,QAAQ,YAAY;AACrC,SAAO,KAAK,kBAAkB,OAAO,QAAQ,QAAQ;AACvD;AAQO,SAAS,KAAK,UAAuB,CAAC,GAAW;AACtD,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,MAAM,QAAQ,OAAO;AAC3B,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,SAAS,QAAQ,UAAU;AACjC,SAAO,KAAK,KAAK,UAAU,QAAQ,KAAK,QAAQ,MAAM;AACxD;","names":["wasm","out","wasm","path","wasm","wasm","wasm","wasm","info","wasm","out","wasm","path","require"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/tsup/assets/cjs_shims.js","../src/generated/package_info.ts","../src/core/hooked-transform.ts","../src/core/parallel.ts","../src/node/pool.ts","../src/node/transform-parallel.ts","../src/node/legacy-init.ts","../src/legacy/runtime.ts","../src/legacy/index.ts","../src/legacy/errors.ts","../src/legacy/translate.ts","../src/legacy/pseudo-ast.ts","../src/legacy/generated/resource-collection-keys.ts","../src/legacy/builder.ts","../src/legacy/bpg-class.ts","../src/legacy/resource-builder.ts","../src/legacy/options.ts","../src/legacy/enums-extra.ts","../src/legacy/stubs.ts","../src/types.ts"],"sourcesContent":["// @zen-component: WASM-TSBindings\n\nimport { createRequire } from \"node:module\";\nimport { PACKAGE_INFO } from \"./generated/package_info.js\";\nimport { runHookedTransform, type HookedWasm } from \"./core/hooked-transform.js\";\nimport { runParallelTransform } from \"./node/transform-parallel.js\";\nimport type { LexOptions, ParseOptions, ConvertOptions, BreakscapeOptions, InfoOptions, CanonicalizeOptions, TransformOptions, BitSlice } from \"./types.js\";\nimport type { AnyBit, Bit, BitEntry } from \"./generated/bit-types.js\";\nconst require = createRequire(import.meta.url);\nconst wasm = require(\"../wasm/bitmark_wasm.js\") as typeof import(\"../wasm/bitmark_wasm.js\");\n\n// Legacy (bpg-compatible) API — namespaced, never merged into the root surface\nimport { initLegacyNode } from \"./node/legacy-init.js\";\ninitLegacyNode(wasm);\nexport * as legacy from \"./legacy/index.js\";\n\nexport type { LexOptions, LexStage, ParseOptions, ConvertOptions, OutputMode, BreakscapeOptions, TextFormat, TextLocation, InfoOptions, InfoType, InfoFormat, InputFormat, OutputFormat, CanonicalizeOptions, TransformOptions, PatchOp, PatchEntry, PathValue, PatchValueFor, BitSlice, BitView, PreHook, PostHook, PreHookResult } from \"./types.js\";\nexport { patchEntry } from \"./types.js\";\n\n// Generated types for the parser's JSON (from bitmark.json via schemagen, PLAN-128)\nexport type * from \"./generated/bit-types.js\";\n\n/**\n * Get the version of the @gmb/bitmark-parser library.\n *\n * @returns Version string (e.g. \"3.0.0\").\n */\nexport function version(): string {\n return PACKAGE_INFO.version;\n}\n\n/**\n * Lex bitmark input text, returning one line per token.\n *\n * @param input - The bitmark source text.\n * @param options - Lex options (e.g. `{ stage: \"lex\" }`).\n * @returns Token dump string (one token per line).\n */\nexport function lex(input: string, options: LexOptions = {}): string {\n return wasm.lex(input, options.stage ?? \"lex\");\n}\n\n/**\n * Parse bitmark into typed bit entries.\n *\n * The typed (object) counterpart of\n * `convert(input, { inputFormat: \"bitmark\", outputFormat: \"json\" })`:\n * returns the entries as objects instead of a JSON string. **Bitmark input\n * only** — the format is pinned, no auto-detection.\n *\n * @example\n * const entries = bitmarkToObjects(\"[.article]\\nHello **world**\");\n * const bit = entries[0].bit;\n * if (bit.type === \"article\") console.log(bit.body);\n *\n * @throws If the core reports a conversion error.\n */\nexport function bitmarkToObjects(input: string, options: ParseOptions = {}): BitEntry[] {\n const out = wasm.convert(\n input,\n \"bitmark\",\n \"json\",\n options.mode ?? \"optimized\",\n false,\n 2,\n 1,\n options.includeUnknownProperties ?? false,\n false,\n );\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return JSON.parse(out) as BitEntry[];\n}\n\n/**\n * Compose bitmark text from typed bits or entries.\n *\n * The typed (object) counterpart of\n * `convert(json, { inputFormat: \"json\", outputFormat: \"bitmark\" })` — typed\n * objects are JSON by construction, so the format is pinned, no\n * auto-detection. Bare bits are auto-wrapped into entries; the config-driven\n * composer normalizes, defaults and validates on ingest — construct bits as\n * plain typed literals (no builder needed).\n *\n * @example\n * const bitmark = objectsToBitmark([{ type: \"article\", body: \"Hello\" }]);\n *\n * @throws If the core reports a compose error.\n */\nexport function objectsToBitmark(bits: readonly (Bit | AnyBit | BitEntry)[], options: ParseOptions = {}): string {\n const entries = bits.map((b) =>\n b !== null && typeof b === \"object\" && \"bit\" in b && typeof (b as BitEntry).bit === \"object\"\n ? b\n : { bit: b },\n );\n const out = wasm.convert(\n JSON.stringify(entries),\n \"json\",\n \"bitmark\",\n options.mode ?? \"optimized\",\n false,\n 2,\n 1,\n false,\n false,\n );\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return out;\n}\n\n/**\n * Convert between bitmark, JSON, and the mapped markup formats (html/xml/…) —\n * the single string-based conversion surface.\n *\n * Performance: `inputFormat` defaults to `\"auto\"`, which detects the format\n * by scanning the input for a bitmark bit header — for non-bitmark input\n * that is a full pass over the whole input before parsing starts, and the\n * detection is heuristic (markup formats are never auto-detected). **If you\n * know the input format, set `inputFormat` explicitly.** For typed objects\n * use {@link bitmarkToObjects} / {@link objectsToBitmark}, which pin their\n * formats.\n *\n * @param input - Bitmark, JSON, or mapped-format input text.\n * @param options - Convert options (e.g. `{ inputFormat: \"bitmark\", mode: \"full\" }`).\n * @returns Converted output string. For bitmark input, this is a JSON string\n * array of structured parsed entries (`bit`, `parser`, `bitmark`).\n */\nexport function convert(input: string, options: ConvertOptions = {}): string {\n return wasm.convert(\n input,\n options.inputFormat ?? \"auto\",\n options.outputFormat ?? \"auto\",\n options.mode ?? \"optimized\",\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n options.includeUnknownProperties ?? false,\n options.mappingReport ?? false,\n );\n}\n\n/**\n * Re-emit input in its own format in canonical form — the single same-format\n * surface (the former `optimize`/`fullize`/`expand` were pure mode pins of\n * this function and were removed).\n *\n * @param input - Input text (bitmark, JSON, or a markup format such as html/xml).\n * @param options - `mode`: `\"optimized\"` (default — omit natural defaults) or\n * `\"full\"` (emit all keys). `inputFormat` selects the format (default:\n * `\"auto\"`; prefer explicit — see {@link convert}); the output is\n * re-emitted in that same format.\n */\nexport function canonicalize(input: string, options: CanonicalizeOptions = {}): string {\n return wasm.canonicalize(\n input,\n options.inputFormat ?? \"auto\",\n options.mode ?? \"optimized\",\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n );\n}\n\n/**\n * Count the bits in `input`, auto-detecting bitmark vs JSON (heuristic —\n * a full input scan when the input is not bitmark; see {@link convert}).\n *\n * @throws If the input cannot be parsed.\n */\nexport function countBits(input: string): number {\n const out = wasm.count_bits(input);\n if (out.startsWith(\"error:\")) throw new Error(out);\n return Number.parseInt(out, 10);\n}\n\n/**\n * Split a bitmark document into per-bit source slices.\n *\n * @returns Array of `{ index, byteStart, byteEnd, source }`.\n */\nexport function splitBits(input: string): BitSlice[] {\n return JSON.parse(wasm.split_bits(input)) as BitSlice[];\n}\n\n/**\n * Transform a document bit-by-bit: apply an optional static `patch` and/or\n * per-bit `preHook`/`postHook`, then re-emit.\n *\n * With neither hook, the whole document is transformed in a single WASM pass\n * (the fast path). When a `preHook` or `postHook` is supplied, `transform`\n * drives the bits one at a time on the calling thread — the hook inspects each\n * bit, may return patches / an output-format override / `drop`, and only data\n * crosses into WASM. The patch may be an array of entries or a JSON string.\n *\n * `options.inputFormat` defaults to `\"auto\"`; prefer an explicit format when\n * known — see {@link convert}.\n *\n * @returns The transformed document, or an `error:`-prefixed string on failure.\n */\nexport function transform(input: string, options: TransformOptions = {}): string {\n if (options.preHook || options.postHook) {\n return runHookedTransform(wasm as unknown as HookedWasm, input, options);\n }\n const patchJson =\n options.patch === undefined\n ? \"\"\n : typeof options.patch === \"string\"\n ? options.patch\n : JSON.stringify(options.patch);\n return wasm.transform(\n input,\n options.inputFormat ?? \"auto\",\n options.outputFormat ?? \"json\",\n options.mode ?? \"optimized\",\n patchJson,\n options.pretty ?? false,\n options.indent ?? 2,\n options.spacesAroundValues ?? 1,\n );\n}\n\n/**\n * Parallel counterpart of {@link transform} (Node only). Fans the per-bit WASM\n * compute across a `worker_threads` pool (`options.workers`, default `4`),\n * while `preHook`/`postHook` still run on the calling thread. Output is\n * identical to {@link transform}; this trades startup cost for throughput on\n * large documents.\n *\n * @returns A Promise of the transformed document, or an `error:`-prefixed\n * string on failure.\n */\nexport function transformParallel(input: string, options: TransformOptions = {}): Promise<string> {\n return runParallelTransform(wasm as unknown as HookedWasm, input, options);\n}\n\n/**\n * Breakscape text (escape bitmark special characters).\n *\n * @param input - The text to breakscape.\n * @param options - Breakscape options (e.g. `{ format: \"plainText\", location: \"tag\" }`).\n * @returns Breakscaped text.\n */\nexport function breakscapeText(input: string, options: BreakscapeOptions = {}): string {\n const format = options.format ?? \"bitmark++\";\n const location = options.location ?? \"body\";\n return wasm.breakscape_text(input, format, location);\n}\n\n/**\n * Unbreakscape text (unescape bitmark special characters).\n *\n * @param input - The text to unbreakscape.\n * @param options - Unbreakscape options (e.g. `{ format: \"plainText\", location: \"tag\" }`).\n * @returns Unbreakscaped text.\n */\nexport function unbreakscapeText(input: string, options: BreakscapeOptions = {}): string {\n const format = options.format ?? \"bitmark++\";\n const location = options.location ?? \"body\";\n return wasm.unbreakscape_text(input, format, location);\n}\n\n/**\n * Query information about supported bit types.\n *\n * @param options - Info options (e.g. `{ infoType: \"bit\", format: \"json\", bit: \"cloze\" }`).\n * @returns Information string.\n */\nexport function info(options: InfoOptions = {}): string {\n const infoType = options.infoType ?? \"list\";\n const format = options.format ?? \"text\";\n const bit = options.bit ?? \"\";\n const pretty = options.pretty ?? false;\n const indent = options.indent ?? 2;\n const includeDeprecated = options.includeDeprecated ?? false;\n const onlyDeprecated = options.onlyDeprecated ?? false;\n const full = options.full ?? false;\n return wasm.info(infoType, format, bit, pretty, indent, includeDeprecated, onlyDeprecated, full);\n}\n\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// This file is automatically generated. DO NOT EDIT.\n\n/* eslint-disable */\n\nexport const PACKAGE_INFO = {\n \"name\": \"@gmb/bitmark-parser\",\n \"version\": \"6.9.0\",\n \"author\": \"Get More Brain Ltd <info@getmorebrain.com>\",\n \"license\": \"ISC\",\n \"description\": \"A parser for bitmark text, powered by WebAssembly.\"\n};\n","// @zen-component: TS-HookedTransform\n\nimport type { BitView, OutputFormat, PatchEntry, TransformOptions } from \"../types.js\";\n\n/**\n * The minimal WASM surface the per-bit hook driver needs. Both the Node and\n * browser entry points satisfy this with their loaded module.\n */\nexport interface HookedWasm {\n is_bitmark(input: string): boolean;\n split_bits(input: string): string;\n split_json_bits(input: string): string;\n prettify(json: string, indent: number): string;\n transform(\n input: string,\n inputFormat: string,\n outputFormat: string,\n mode: string,\n patchJson: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n ): string;\n}\n\n/** A single bit's compute job: data only, safe to ship to a worker thread. */\nexport interface BitJob {\n index: number;\n source: string;\n inputFormat: \"bitmark\" | \"json\";\n outputFormat: OutputFormat;\n mode: string;\n patchJson: string;\n spacesAroundValues: number;\n}\n\n/**\n * The result of running `preHook` over a document's bits: the compute `jobs`\n * for the bits that survived (in document order) and the matching `views`\n * (so `postHook` can be called per surviving bit), plus the document-level\n * recombination settings.\n */\nexport interface TransformPlan {\n jobs: BitJob[];\n views: BitView[];\n output: OutputFormat;\n pretty: boolean;\n indent: number;\n}\n\nexport function isError(s: string): boolean {\n return s.startsWith(\"error:\");\n}\n\n/**\n * Normalise a thrown value to an `error:`-prefixed string, without\n * double-prefixing a message that already carries the prefix (split helpers\n * surface WASM `error:` strings as thrown `Error`s).\n */\nexport function errorString(e: unknown): string {\n const m = e instanceof Error ? e.message : String(e);\n return m.startsWith(\"error:\") ? m : `error: ${m}`;\n}\n\n/** Strip the outer `[ … ]` of a compact one-element JSON array. */\nexport function stripArray(doc: string): string {\n const t = doc.trim();\n return t.startsWith(\"[\") && t.endsWith(\"]\") ? t.slice(1, -1) : doc;\n}\n\nfunction normalisePatch(patch: TransformOptions[\"patch\"]): PatchEntry[] {\n if (patch === undefined) return [];\n if (typeof patch === \"string\") {\n const trimmed = patch.trim();\n return trimmed === \"\" ? [] : (JSON.parse(trimmed) as PatchEntry[]);\n }\n return patch;\n}\n\nfunction buildUnits(\n wasm: HookedWasm,\n input: string,\n inputIsBitmark: boolean,\n): { view: BitView; source: string }[] {\n if (inputIsBitmark) {\n const out = wasm.split_bits(input);\n if (isError(out)) throw new Error(out);\n const slices = JSON.parse(out) as { index: number; source: string }[];\n return slices.map((s) => ({\n view: { format: \"bitmark\", index: s.index, total: slices.length, source: s.source },\n source: s.source,\n }));\n }\n const out = wasm.split_json_bits(input);\n if (isError(out)) throw new Error(out);\n const envelopes = JSON.parse(out) as { bit?: import(\"../generated/bit-types.js\").AnyBit }[];\n return envelopes.map((env, index) => ({\n view: { format: \"json\", index, total: envelopes.length, bit: env.bit ?? {} },\n // Per-bit transform consumes a one-bit JSON document.\n source: JSON.stringify([env]),\n }));\n}\n\n/**\n * Split the document and run `preHook` (on the calling thread) for each bit,\n * producing the surviving compute jobs + their views. This is the main-thread\n * half shared by the sync and worker-pool drivers — only the resulting\n * data-only {@link BitJob}s ever cross to a worker.\n */\nexport function planTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): TransformPlan {\n const mode = options.mode ?? \"optimized\";\n const output: OutputFormat = options.outputFormat ?? \"json\";\n const spacesAroundValues = options.spacesAroundValues ?? 1;\n const indent = options.indent ?? 2;\n const pretty = options.pretty ?? false;\n\n const sel = options.inputFormat ?? \"auto\";\n const inputIsBitmark = sel === \"bitmark\" || (sel !== \"json\" && wasm.is_bitmark(input));\n const inputFormat = inputIsBitmark ? \"bitmark\" : \"json\";\n\n const staticPatch = normalisePatch(options.patch);\n const units = buildUnits(wasm, input, inputIsBitmark);\n const total = units.length;\n\n const jobs: BitJob[] = [];\n const views: BitView[] = [];\n for (let index = 0; index < total; index++) {\n const { view, source } = units[index];\n view.index = index;\n view.total = total;\n\n const result = options.preHook ? options.preHook(view) || {} : {};\n if (result.drop) continue;\n\n const patches = result.patches ? [...staticPatch, ...result.patches] : staticPatch;\n jobs.push({\n index,\n source,\n inputFormat,\n outputFormat: result.outputFormat ?? output,\n mode,\n patchJson: JSON.stringify(patches),\n spacesAroundValues,\n });\n views.push(view);\n }\n return { jobs, views, output, pretty, indent };\n}\n\n/**\n * Compute one bit's rendered element synchronously via WASM. The per-bit\n * element is always compact JSON (the document is prettified once on\n * recombination). Returns an `error:`-prefixed string on failure.\n */\nexport function computeBit(wasm: HookedWasm, job: BitJob): string {\n const out = wasm.transform(\n job.source,\n job.inputFormat,\n job.outputFormat,\n job.mode,\n job.patchJson,\n false,\n 2,\n job.spacesAroundValues,\n );\n if (isError(out)) return out;\n return job.outputFormat === \"json\" ? stripArray(out) : out;\n}\n\n/** Recombine per-bit elements into the final document, in document order. */\nexport function recombine(\n wasm: HookedWasm,\n elements: string[],\n output: OutputFormat,\n pretty: boolean,\n indent: number,\n): string {\n // Bitmark and plain-text bits both join with newlines; only JSON wraps as an\n // array. (`text` is output-only, lossy plain-text extraction.)\n if (output === \"bitmark\" || output === \"text\") return elements.join(\"\\n\");\n const arr = `[${elements.join(\",\")}]`;\n return pretty ? wasm.prettify(arr, indent) : arr;\n}\n\n/**\n * Per-bit transform driver (synchronous, in-process): split the document, run\n * `preHook` for each bit on the calling thread, apply the static patch + any\n * hook patches, re-emit the bit, run `postHook`, then recombine in document\n * order.\n *\n * Hooks run synchronously on the calling thread; only data crosses into WASM.\n * Used when a `preHook`/`postHook` is supplied; the hookless path stays a\n * single `wasm.transform` call. Returns the document, or an `error:`-prefixed\n * string on failure.\n */\nexport function runHookedTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): string {\n let plan: TransformPlan;\n try {\n plan = planTransform(wasm, input, options);\n } catch (e) {\n return errorString(e);\n }\n\n const rendered: string[] = [];\n for (let i = 0; i < plan.jobs.length; i++) {\n const element = computeBit(wasm, plan.jobs[i]);\n if (isError(element)) return element;\n options.postHook?.(plan.views[i], element);\n rendered.push(element);\n }\n return recombine(wasm, rendered, plan.output, plan.pretty, plan.indent);\n}\n","// @zen-component: TS-ParallelOrchestrator\n\nimport type { TransformOptions } from \"../types.js\";\nimport { type BitJob, errorString, type HookedWasm, isError, planTransform, recombine } from \"./hooked-transform.js\";\n\n/**\n * A platform pool: compute `jobs` across up to `workers` workers, returning the\n * rendered element per job in submission order. Node and browser supply their\n * own (worker_threads / Worker); the orchestration around it is shared.\n */\nexport type RunJobs = (jobs: BitJob[], workers: number) => Promise<string[]>;\n\n/**\n * Shared parallel transform orchestration. The main-thread half — split +\n * `preHook` + recombine + `postHook` — is identical to the sync driver; only\n * the data-only per-bit jobs cross to `runJobs` (the platform pool). Closures\n * (`preHook`/`postHook`) never leave the calling thread.\n *\n * Returns the document, or an `error:`-prefixed string on failure.\n */\nexport async function orchestrateParallel(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n runJobs: RunJobs,\n): Promise<string> {\n let plan;\n try {\n plan = planTransform(wasm, input, options);\n } catch (e) {\n return errorString(e);\n }\n\n let elements: string[];\n try {\n elements = await runJobs(plan.jobs, options.workers ?? 4);\n } catch (e) {\n return errorString(e);\n }\n\n for (let i = 0; i < elements.length; i++) {\n if (isError(elements[i])) return elements[i];\n options.postHook?.(plan.views[i], elements[i]);\n }\n return recombine(wasm, elements, plan.output, plan.pretty, plan.indent);\n}\n","// @zen-component: TS-WorkerPool\n//\n// A fixed-size Node worker_threads pool that computes per-bit transform jobs in\n// parallel. Jobs are dispatched to idle workers; results are matched by id and\n// returned in submission order. The pool is short-lived (created per\n// transformParallel call) and terminated when all jobs settle.\n\nimport { fileURLToPath } from \"node:url\";\nimport { Worker } from \"node:worker_threads\";\nimport type { BitJob } from \"../core/hooked-transform.js\";\n\ninterface JobResult {\n ok: boolean;\n element?: string;\n error?: string;\n}\n\n// The worker entry is emitted as a sibling CJS file in dist/ (see tsup config),\n// so a CJS-format worker runs regardless of how the package itself was loaded.\nfunction workerPath(): string {\n return fileURLToPath(new URL(\"./worker-entry.cjs\", import.meta.url));\n}\n\n/**\n * Run `jobs` across up to `workers` worker threads, returning the rendered\n * element for each job in the **same order** as `jobs`. Rejects on the first\n * worker error or job error.\n */\nexport function runJobsParallel(jobs: BitJob[], workers: number): Promise<string[]> {\n if (jobs.length === 0) return Promise.resolve([]);\n const poolSize = Math.max(1, Math.min(workers, jobs.length));\n const path = workerPath();\n\n return new Promise<string[]>((resolve, reject) => {\n const results = new Array<string>(jobs.length);\n let next = 0;\n let settled = 0;\n let done = false;\n const pool: Worker[] = [];\n\n const shutdown = () => {\n for (const w of pool) void w.terminate();\n };\n const fail = (err: Error) => {\n if (done) return;\n done = true;\n shutdown();\n reject(err);\n };\n\n const dispatch = (w: Worker) => {\n if (done) return;\n if (next >= jobs.length) return; // no more work for this worker\n const id = next++;\n w.postMessage({ id, job: jobs[id] });\n };\n\n for (let i = 0; i < poolSize; i++) {\n const w = new Worker(path);\n pool.push(w);\n w.on(\"message\", (res: JobResult & { id: number }) => {\n if (done) return;\n if (!res.ok) {\n fail(new Error(res.error ?? \"worker job failed\"));\n return;\n }\n results[res.id] = res.element as string;\n settled++;\n if (settled === jobs.length) {\n done = true;\n shutdown();\n resolve(results);\n return;\n }\n dispatch(w);\n });\n w.on(\"error\", fail);\n w.on(\"exit\", (code) => {\n if (!done && code !== 0) fail(new Error(`worker exited with code ${code}`));\n });\n }\n\n // Prime each worker with one job.\n for (const w of pool) dispatch(w);\n });\n}\n","// @zen-component: TS-TransformParallel\n//\n// Node-only parallel transform: the main-thread half (split + preHook +\n// recombine + postHook) is shared with the synchronous driver and the browser\n// pool via orchestrateParallel; only the per-bit WASM compute is fanned out\n// across a worker_threads pool.\n\nimport { orchestrateParallel } from \"../core/parallel.js\";\nimport type { HookedWasm } from \"../core/hooked-transform.js\";\nimport type { TransformOptions } from \"../types.js\";\nimport { runJobsParallel } from \"./pool.js\";\n\n/**\n * Parallel counterpart of `transform` on Node. `preHook`/`postHook` run on the\n * calling thread; only data-only jobs cross to the worker_threads pool.\n */\nexport function runParallelTransform(\n wasm: HookedWasm,\n input: string,\n options: TransformOptions,\n): Promise<string> {\n return orchestrateParallel(wasm, input, options, runJobsParallel);\n}\n","// @zen-component: LEGACY-Facade\n// Node platform wiring for the legacy facade: provides the WASM module and\n// real file I/O (PLAN-126 F-5). The browser entry provides WASM only.\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { setLegacyFileIo, setLegacyWasm, type LegacyWasm } from \"../legacy/runtime.js\";\n\nexport function initLegacyNode(wasm: LegacyWasm): void {\n setLegacyWasm(wasm);\n setLegacyFileIo({\n existsSync: (p) => fs.existsSync(p),\n readFileSync: (p, encoding) => fs.readFileSync(p, { encoding: encoding as BufferEncoding }),\n writeFile: (p, data, opts) => {\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, data, {\n encoding: (opts.encoding ?? \"utf8\") as BufferEncoding,\n flag: opts.append ? \"a\" : \"w\",\n });\n },\n });\n}\n","// @zen-component: LEGACY-Facade\n// Platform injection for the legacy facade. The Node and browser entries\n// provide the WASM module (and, on Node, file I/O) before exposing the\n// `legacy` namespace — the facade itself stays platform-free.\n\n/** The subset of the WASM surface the legacy facade drives. */\nexport interface LegacyWasm {\n convert(\n input: string,\n inputFormat: string,\n outputFormat: string,\n mode: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n includeUnknownProperties: boolean,\n mappingReport: boolean,\n ): string;\n canonicalize(\n input: string,\n inputFormat: string,\n mode: string,\n pretty: boolean,\n indent: number,\n spacesAroundValues: number,\n ): string;\n breakscape_text(input: string, format: string, location: string): string;\n unbreakscape_text(input: string, format: string, location: string): string;\n info(\n infoType: string,\n format: string,\n bit: string,\n pretty: boolean,\n indent: number,\n includeDeprecated: boolean,\n onlyDeprecated: boolean,\n full: boolean,\n ): string;\n is_bitmark(input: string): boolean;\n prettify(json: string, indent: number): string;\n convert_text(input: string, direction: string, format: string, location: string): string;\n}\n\nlet wasmModule: LegacyWasm | undefined;\n\nexport function setLegacyWasm(wasm: LegacyWasm): void {\n wasmModule = wasm;\n}\n\nexport function getLegacyWasm(): LegacyWasm {\n if (!wasmModule) {\n throw new Error(\n \"legacy API not initialised: the WASM module has not been provided (browser consumers must call init() first)\",\n );\n }\n return wasmModule;\n}\n\n/** Node file I/O, injected by the Node entry only (PLAN-126 F-5). */\nexport interface LegacyFileIo {\n existsSync(path: string): boolean;\n readFileSync(path: string, encoding: string): string;\n /** Write (or append) `data`, creating parent directories as needed. */\n writeFile(path: string, data: string, opts: { append?: boolean; encoding?: string }): void;\n}\n\nlet fileIo: LegacyFileIo | undefined;\n\nexport function setLegacyFileIo(io: LegacyFileIo): void {\n fileIo = io;\n}\n\n/** Returns undefined in the browser (no file I/O). */\nexport function getLegacyFileIo(): LegacyFileIo | undefined {\n return fileIo;\n}\n","// @zen-component: LEGACY-Facade\n// The `legacy` namespace: a bpg-compatible (bitmark-parser-generator\n// v5.31.1) programmatic interface over the WASM core (PLAN-126).\n//\n// Everything here is exposed ONLY via `legacy.*` / the\n// `@gmb/bitmark-parser/legacy` subpath — nothing is re-exported at the\n// package root (reserved for the modern API and its future generated types).\n\nexport { BitmarkParserGenerator, bitmarkTextParse } from \"./bpg-class.js\";\nexport { Builder, type BuildBitOptions } from \"./builder.js\";\nexport { ResourceBuilder, type ResourceMethod } from \"./resource-builder.js\";\nexport { LegacyUnsupportedError } from \"./errors.js\";\nexport { isPseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\n\n// Enum objects + option interfaces (vendored shapes)\nexport * from \"./options.js\";\nexport { BitType, BoundingBoxIndex, NodeType, TextMarkType, TextNodeType } from \"./enums-extra.js\";\n\n// Unsupported bpg internals — present but throwing (PLAN-126 F-2)\nexport {\n Ast,\n BitmarkFileGenerator,\n BitmarkGenerator,\n BitmarkParser,\n BitmarkStringGenerator,\n FileWriter,\n HtmlTableGenerator,\n HtmlTableParser,\n JsonFileGenerator,\n JsonGenerator,\n JsonParser,\n JsonStringGenerator,\n StreamWriter,\n StringWriter,\n} from \"./stubs.js\";\n\n// Vendored bpg JSON model / text-node types (type-only)\nexport type * from \"./vendor/BitJson.js\";\nexport type * from \"./vendor/BitWrapperJson.js\";\nexport type * from \"./vendor/BodyBitJson.js\";\nexport type * from \"./vendor/ParserJson.js\";\nexport type * from \"./vendor/ResourceJson.js\";\nexport type * from \"./vendor/TextNodes.js\";\n// bpg parity: bpg additionally exported JsonText under the alias `Text`\n// (bitmark-parser-generator src/index.ts: `JsonText as Text`).\nexport type { JsonText as Text } from \"./vendor/TextNodes.js\";\nexport type {\n ParserError,\n ParserInfo,\n ParserLocation,\n BitTypeType,\n TextFormatType,\n ResourceTypeType,\n TextMarkTypeType,\n TextNodeTypeType,\n} from \"./vendor/enums.js\";\n","// @zen-component: LEGACY-Facade\n\n/** Error thrown for bpg API members / options the legacy facade does not support. */\nexport class LegacyUnsupportedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LegacyUnsupportedError\";\n }\n}\n\n/** Throw for a bpg API member that is not supported (PLAN-126 F-2). */\nexport function unsupportedMember(member: string, reason?: string): never {\n throw new LegacyUnsupportedError(\n `'${member}' is not supported by the @gmb/bitmark-parser legacy API` + (reason ? `: ${reason}` : \"\"),\n );\n}\n\n/** Throw for an option that cannot be honoured (PLAN-126 F-9: never silently ignore). */\nexport function unsupportedOption(option: string, reason?: string): never {\n throw new LegacyUnsupportedError(\n `Option '${option}' is not supported by the @gmb/bitmark-parser legacy API` +\n (reason ? `: ${reason}` : \"\"),\n );\n}\n","// @zen-component: LEGACY-Facade\n// Central bpg-option → core-parameter translation table (PLAN-126 F-4/F-9).\n// Strict policy: options that map are honoured; options we cannot honour\n// throw a LegacyUnsupportedError naming the option. Sole exception:\n// `bitmarkParserType` is accepted and ignored — bpg v5.31.1 itself hardcodes\n// the peggy parser and ignores the option.\n\nimport { unsupportedOption } from \"./errors.js\";\nimport type { BitmarkOptions, JsonOptions } from \"./options.js\";\n\nconst V3_ONLY = \"bitmark v2 output is not supported (this parser is bitmark v3 only)\";\n\nexport function validateVersionOptions(opts: {\n bitmarkVersion?: number;\n bitmarkParserType?: string;\n}): void {\n if (opts.bitmarkVersion === 2) unsupportedOption(\"bitmarkVersion: 2\", V3_ONLY);\n // bitmarkParserType: accepted + ignored (documented exception).\n}\n\nexport function validateBitmarkOptions(o: BitmarkOptions): void {\n // The option TYPES are narrowed to the supported values (build-time\n // errors for TS consumers), but JS callers can still pass anything —\n // keep validating the runtime values (hence the widening casts).\n // Booleans error only when set truthy (false === bpg default behaviour).\n if (o.explicitTextFormat) unsupportedOption(\"bitmarkOptions.explicitTextFormat\");\n // prettifyJson: honoured — maps to the core's pretty/indent for bitmark\n // output (embedded JSON bodies of json-format bits); see prettyIndent().\n if ((o.cardSetVersion as number | undefined) === 1) {\n unsupportedOption(\"bitmarkOptions.cardSetVersion: 1\", V3_ONLY);\n }\n if (o.debugGenerationInline) unsupportedOption(\"bitmarkOptions.debugGenerationInline\");\n if (o.noBreakscaping) unsupportedOption(\"bitmarkOptions.noBreakscaping\");\n}\n\nexport function validateJsonOptions(o: JsonOptions): void {\n if (o.textAsPlainText) unsupportedOption(\"jsonOptions.textAsPlainText\", V3_ONLY);\n // excludeUnknownProperties: honoured — maps to the core's inverse\n // `includeUnknownProperties` flag (bpg default: include; see bpg-class).\n if (o.debugGenerationInline) unsupportedOption(\"jsonOptions.debugGenerationInline\");\n // enableWarnings: accepted — parser warnings are always carried in the\n // output envelope by this parser, so both values are honoured trivially.\n}\n\n/**\n * bpg `prettify?: boolean | number` → core (pretty, indent).\n *\n * Also used for `bitmarkOptions.prettifyJson` (identical bpg semantics:\n * true → indent 2, positive number → that indent, else off) — for bitmark\n * output the core's pretty/indent prettify the embedded JSON bodies of\n * json-format bits, which is exactly what bpg's prettifyJson did.\n */\nexport function prettyIndent(prettify: boolean | number | undefined): {\n pretty: boolean;\n indent: number;\n} {\n if (prettify === true) return { pretty: true, indent: 2 };\n if (typeof prettify === \"number\" && prettify > 0) return { pretty: true, indent: prettify };\n return { pretty: false, indent: 2 };\n}\n\n/** bpg `spacesAroundValues?: number | boolean` → core spaces count (cap 10, as bpg). */\nexport function spacesAround(v: number | boolean | undefined): number {\n if (v === undefined || v === true) return 1;\n if (v === false) return 0;\n return Math.max(0, Math.min(10, v));\n}\n\n/**\n * bpg text format value → core breakscape format.\n * bpg maps `latex`/`json`/`xml` as aliases of plain text, and defaults\n * anything else (including absent) to bitmark text (`bitmark++`).\n */\nexport function mapTextFormat(f: string | undefined): \"bitmark++\" | \"plainText\" {\n switch (f) {\n case \"text\":\n case \"latex\":\n case \"json\":\n case \"xml\":\n return \"plainText\";\n default:\n return \"bitmark++\";\n }\n}\n","// @zen-component: LEGACY-Facade\n// The legacy \"AST\" is bit JSON (PLAN-126 §3.1): an envelope of the parser's\n// wrapper entries (`{ bit, parser?, bitmark? }`), tagged with a\n// non-enumerable marker so it can be recognised without surviving\n// JSON.stringify. It round-trips through `convert`, but is NOT bpg's\n// internal TS AST node model (no `cardNode` / `BodyPart[]` structure).\n\nexport const PSEUDO_AST_MARKER = Symbol.for(\"@gmb/bitmark-parser/legacy-pseudo-ast\");\n\nexport interface LegacyPseudoAst {\n bits: unknown[];\n}\n\nexport function makePseudoAst(bits: unknown[]): LegacyPseudoAst {\n const ast: LegacyPseudoAst = { bits };\n Object.defineProperty(ast, PSEUDO_AST_MARKER, { value: true, enumerable: false });\n return ast;\n}\n\nexport function isPseudoAst(v: unknown): v is LegacyPseudoAst {\n return (\n v !== null &&\n typeof v === \"object\" &&\n (PSEUDO_AST_MARKER in v || Array.isArray((v as LegacyPseudoAst).bits))\n );\n}\n","// GENERATED FILE — do not edit.\n// Emitted by scripts/gen-legacy-resource-keys.mjs from\n// resources/bitmark-configurator/bitmark.json. Regenerate via `npm run init`.\n//\n// Every bit whose config maps a repeatable resource tag group onto a single\n// JSON collection key. The legacy `Builder.buildBit` routes bpg's\n// `resources` input onto this key (bpg's JsonGenerator special-cased the\n// same family by bit type; here it is derived from config).\n\n/** A bit's resource-collection mapping: target JSON key + accepted resource type. */\nexport interface ResourceCollection {\n key: string;\n resourceType: string;\n}\n\nexport const RESOURCE_COLLECTION_KEYS: Readonly<Record<string, ResourceCollection>> = {\n \"extractor-image\": { key: \"images\", resourceType: \"image\" },\n \"extractor-image-collapsible\": { key: \"images\", resourceType: \"image\" },\n \"images-logo-grave\": { key: \"logos\", resourceType: \"image\" },\n \"prototype-images\": { key: \"images\", resourceType: \"image\" },\n};\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `Builder` (PLAN-126 §3.1): the legacy AST is bit JSON, so\n// building a bit is a data *mapping* (bpg buildBit data → bit JSON keys)\n// followed by one WASM json→json normalization pass — the config-driven core\n// performs the defaulting/coercion/validation that bpg's ~4.2k-line builder\n// does in TS. No parsing logic lives here.\n\nimport { getLegacyWasm } from \"./runtime.js\";\nimport { makePseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\nimport { RESOURCE_COLLECTION_KEYS } from \"./generated/resource-collection-keys.js\";\nimport type { ParserError, ParserInfo } from \"./vendor/enums.js\";\n\n/** Carries bpg `data.parser` (wrapper-level metadata) invisibly on the built bit. */\nexport const BUILT_BIT_PARSER = Symbol.for(\"@gmb/bitmark-parser/legacy-built-bit-parser\");\n\n/**\n * bpg buildBit data keys whose bit-JSON key differs. Everything else in the\n * flat data object maps by identity (the data fields are already the bpg\n * JSON model types) and unknown keys pass through untouched (PLAN-126 F-6).\n */\nconst DATA_KEY_TO_JSON_KEY: Record<string, string> = {\n bitType: \"type\",\n textFormat: \"format\",\n flashcards: \"cards\",\n markConfig: \"marks\",\n};\n\n/** bpg deprecated text-format value accepted by buildBit. */\nconst DEPRECATED_TEXT_FORMATS: Record<string, string> = {\n \"bitmark--\": \"bitmark++\",\n \"bitmark+\": \"bitmark++\",\n};\n\n/**\n * Config `bodyFormat` → bpg TextFormat value. When the caller omits\n * `textFormat`, bpg defaults to the bit config's `textFormatDefault`\n * (bpg Builder.bit), which is derived from the config `bodyFormat` — NOT\n * to bitmark text. E.g. `extractor-information` (bodyFormat: json) built\n * without an explicit `textFormat` must keep its JSON body verbatim.\n */\nconst CONFIG_BODY_FORMAT_TO_TEXT_FORMAT: Record<string, string> = {\n bitmark: \"bitmark++\",\n text: \"text\",\n json: \"json\",\n latex: \"latex\",\n xml: \"xml\",\n};\n\n/** Top-level bit JSON fields typed JsonText (tag location) in bpg. */\nconst TAG_TEXT_KEYS = [\n \"title\",\n \"subtitle\",\n \"item\",\n \"lead\",\n \"pageNumber\",\n \"marginNumber\",\n \"hint\",\n \"instruction\",\n \"caption\",\n] as const;\n\nexport interface BuildBitOptions {\n cardSet?: {\n sideNo: number;\n variantNo: number;\n };\n}\n\nexport class Builder {\n /**\n * Build bitmark AST envelope (bpg-compatible `buildBitmark`).\n */\n buildBitmark(data: { bits?: unknown[]; errors?: ParserError[] }): LegacyPseudoAst {\n const ast = makePseudoAst(data.bits ?? []);\n if (data.errors !== undefined) {\n (ast as LegacyPseudoAst & { errors?: ParserError[] }).errors = data.errors;\n }\n return ast;\n }\n\n /**\n * Build a bit (bpg-compatible `buildBit`).\n *\n * Accepts the full bpg data shape (flat, ~250 optional fields, values in\n * the JSON model types). Returns the normalized bit JSON. Throws\n * `No config found for bit: X` for unknown bit types, as bpg does.\n *\n * NOTE (documented divergences from bpg):\n * - the return value is bit JSON, not bpg's internal AST node model;\n * - `resourceType` (an inference hint in bpg) is not carried into the\n * JSON — the attached `resource` object is authoritative.\n *\n * `resources` follows bpg's JsonGenerator routing: on a bit whose config\n * maps a repeatable resource tag group onto a collection key (e.g.\n * `images` / `logos` — see the generated RESOURCE_COLLECTION_KEYS), the\n * matching-type entries land under that key; on every other bit the first\n * entry becomes the canonical single `resource` (as bpg: \"if there is\n * more than one resource, use the first one\").\n */\n buildBit(data: Record<string, unknown>, _options?: BuildBitOptions): Record<string, unknown> {\n const wasm = getLegacyWasm();\n const src = { ...data };\n\n const bitType = src.bitType as string | undefined;\n const bitConfig = this.getBitConfig(bitType);\n\n // --- divergent keys ---\n const bit: Record<string, unknown> = {};\n bit.type = bitType;\n if (src.isCommented) {\n bit.type = \"_comment\";\n bit.originalType = bitType;\n }\n delete src.bitType;\n delete src.isCommented;\n\n const textFormat = src.textFormat as string | undefined;\n if (textFormat !== undefined) {\n bit.format = DEPRECATED_TEXT_FORMATS[textFormat] ?? textFormat;\n delete src.textFormat;\n } else {\n // bpg parity: `textFormat ?? bitConfig.textFormatDefault` — the\n // config-driven default, so e.g. JSON-bodied bits don't get their\n // body mangled by the bitmark text parser (see parseStringTexts).\n bit.format = CONFIG_BODY_FORMAT_TO_TEXT_FORMAT[bitConfig.bodyFormat ?? \"\"] ?? \"bitmark++\";\n }\n\n // resourceType is an inference hint only (see doc comment)\n delete src.resourceType;\n\n // body: accept bpg's Partial<Body> node ({ body: <JsonText> }) or a bare JsonText\n const body = src.body as { body?: unknown } | unknown;\n if (body !== undefined && body !== null && typeof body === \"object\" && \"body\" in (body as object)) {\n bit.body = (body as { body?: unknown }).body;\n delete src.body;\n }\n\n // example / __isDefaultExample → isExample + example (bpg toExample semantics)\n if (src.example !== undefined) {\n bit.isExample = true;\n bit.example = src.example;\n delete src.example;\n delete src.__isDefaultExample;\n } else if (src.__isDefaultExample) {\n bit.isExample = true;\n delete src.__isDefaultExample;\n }\n\n // resources → the bit's resource-collection key (config-derived), else\n // the canonical single `resource` — bpg's JsonGenerator routing.\n const resources = src.resources;\n if (resources !== undefined && bitType !== undefined) {\n const list = Array.isArray(resources) ? resources : [resources];\n const collection = RESOURCE_COLLECTION_KEYS[bitType];\n if (collection) {\n // bpg keeps only the entries of the collection's resource type.\n bit[collection.key] = list.filter(\n (r) =>\n r !== null &&\n typeof r === \"object\" &&\n (r as { type?: unknown }).type === collection.resourceType,\n );\n } else if (list.length >= 1) {\n bit.resource = list[0];\n }\n delete src.resources;\n }\n\n // parser metadata lives on the wrapper, not in the bit JSON\n const parser = src.parser as ParserInfo | undefined;\n delete src.parser;\n\n // extraProperties spread into the bit JSON top level (bpg semantics)\n const extraProperties = src.extraProperties as Record<string, unknown> | undefined;\n delete src.extraProperties;\n\n // --- renamed + identity + unknown keys (pass through, PLAN-126 F-6) ---\n for (const [key, value] of Object.entries(src)) {\n if (value === undefined) continue;\n bit[DATA_KEY_TO_JSON_KEY[key] ?? key] = value;\n }\n if (extraProperties) {\n for (const [key, value] of Object.entries(extraProperties)) {\n if (!(key in bit)) bit[key] = value;\n }\n }\n\n // --- bpg parity: string JsonText values are parsed bitmark text ---\n this.parseStringTexts(bit);\n\n // --- normalization pass: the config-driven core defaults/coerces/validates ---\n const out = wasm.convert(JSON.stringify([{ bit }]), \"json\", \"json\", \"optimized\", false, 2, 1, false, false);\n if (out.startsWith(\"error:\")) {\n throw new Error(out.slice(\"error:\".length).trim());\n }\n const entries = JSON.parse(out) as { bit: Record<string, unknown> }[];\n const built = entries[0]?.bit ?? bit;\n\n // F-6: keys the core doesn't know are dropped by the normalize pass —\n // re-attach them so nothing is lost silently. Values matching bpg's own\n // \"unset optional\" strip set (false / \"\" / [] / null) stay stripped,\n // mirroring bpg's removeUnwantedProperties.\n for (const [key, value] of Object.entries(bit)) {\n if (key in built) continue;\n if (\n value === false ||\n value === \"\" ||\n value === null ||\n (Array.isArray(value) && value.length === 0)\n ) {\n continue;\n }\n built[key] = value;\n }\n if (parser !== undefined) {\n Object.defineProperty(built, BUILT_BIT_PARSER, { value: parser, enumerable: false });\n }\n return built;\n }\n\n /**\n * Build a highlight body bit (bpg-compatible `buildHighlight`).\n * Shapes the HighlightJson body-bit; unset optionals are omitted.\n */\n buildHighlight(\n _context: unknown,\n data: Record<string, unknown> | undefined,\n ): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const src = { ...data };\n // bpg: data may arrive nested under 'attrs' (when coming from JSON)\n const attrs = src.attrs as Record<string, unknown> | undefined;\n if (attrs) Object.assign(src, attrs);\n\n const texts = Array.isArray(src.texts)\n ? (src.texts as Record<string, unknown>[]).filter((t) => t != null).map((t) => ({\n text: t.text ?? \"\",\n isCorrect: t.isCorrect ?? false,\n isHighlighted: t.isHighlighted ?? false,\n ...stripUndefined(t, [\"text\", \"isCorrect\", \"isHighlighted\"]),\n }))\n : [];\n\n const node: Record<string, unknown> = {\n type: \"highlight\",\n texts,\n prefix: src.prefix ?? \"\",\n postfix: src.postfix ?? \"\",\n ...stripUndefined(src, [\"type\", \"texts\", \"prefix\", \"postfix\", \"attrs\"]),\n attrs: {},\n };\n return node;\n }\n\n /**\n * bpg's builder parses string-valued JsonText fields as bitmark text\n * (inline marks become TextAst marks); the composer would otherwise treat\n * them as literal text. Converts top-level JsonText fields in place.\n * Nested (card-content) strings are left literal — documented divergence.\n *\n * A string body is dispatched on the bit's resolved text format, as bpg's\n * buildBody: bitmark text is parsed to TextAst, `json` is JSON.parsed\n * (unparseable → null), and plain-text formats (text/latex/xml) stay\n * verbatim. Tag texts are always bitmark text, independent of body format\n * (bpg TextParser.toAst ignores format; only location matters).\n */\n private parseStringTexts(bit: Record<string, unknown>): void {\n const wasm = getLegacyWasm();\n const toAst = (s: string, location: \"body\" | \"tag\"): unknown => {\n if (s === \"\") return s;\n const out = wasm.convert_text(s, \"textToAst\", \"bitmark++\", location);\n try {\n return JSON.parse(out) as unknown;\n } catch {\n return s;\n }\n };\n\n const format = bit.format as string | undefined;\n const bitmarkBody = format === undefined || format === \"bitmark++\" || format === \"bitmark+\";\n if (typeof bit.body === \"string\") {\n if (format === \"json\") {\n // bpg handleJsonBody: parse legacy string bodies; null on failure\n try {\n bit.body = JSON.parse(bit.body) as unknown;\n } catch {\n bit.body = null;\n }\n } else if (bitmarkBody) {\n bit.body = toAst(bit.body, \"body\");\n }\n // plain-text formats (text/latex/xml): body stays a verbatim string\n }\n for (const key of TAG_TEXT_KEYS) {\n const v = bit[key];\n if (typeof v === \"string\") bit[key] = toAst(v, \"tag\");\n }\n }\n\n /**\n * Look up the bit's config (`wasm.info`); throws bpg's exact\n * unknown-bit-type error (`Config.getBitConfig` parity).\n */\n private getBitConfig(bitType: string | undefined): { bodyFormat?: string } {\n const wasm = getLegacyWasm();\n if (bitType !== undefined) {\n try {\n const info = JSON.parse(wasm.info(\"bit\", \"json\", bitType, false, 2, false, false, true)) as {\n error?: string;\n body?: { format?: string };\n };\n // PLAN-149 restructured the info JSON: bodyFormat now lives at\n // `body.format`; adapt to the legacy flat shape callers expect.\n if (info.error === undefined) return { bodyFormat: info.body?.format };\n } catch {\n // fall through to the not-found error\n }\n }\n throw new Error(`No config found for bit: ${bitType}`);\n }\n}\n\nfunction stripUndefined(\n src: Record<string, unknown>,\n exclude: string[],\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(src)) {\n if (v !== undefined && !exclude.includes(k)) out[k] = v;\n }\n return out;\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `BitmarkParserGenerator` class — a thin synchronous wrapper\n// over the WASM core (PLAN-126). Behavioural parity is at the call boundary:\n// same method names, option keys and return shapes as bpg v5.31.1.\n\nimport { PACKAGE_INFO } from \"../generated/package_info.js\";\nimport { unsupportedMember, unsupportedOption } from \"./errors.js\";\nimport { getLegacyFileIo, getLegacyWasm } from \"./runtime.js\";\nimport {\n mapTextFormat,\n prettyIndent,\n spacesAround,\n validateBitmarkOptions,\n validateJsonOptions,\n validateVersionOptions,\n} from \"./translate.js\";\nimport type {\n BreakscapeOptions,\n ConvertHtmlTableOptions,\n ConvertOptions,\n ConvertTextOptions,\n CreateAstOptions,\n ExtractPlainTextOptions,\n FileOptions,\n InfoOptions,\n UnbreakscapeOptions,\n UpgradeOptions,\n} from \"./options.js\";\nimport { makePseudoAst, type LegacyPseudoAst } from \"./pseudo-ast.js\";\nimport { BUILT_BIT_PARSER } from \"./builder.js\";\n\n/** Classified input for the convert/upgrade pipeline (PLAN-126 F-10). */\ninterface ResolvedInput {\n /** JSON-wrapper-array string (json/ast input) or bitmark source (bitmark input). */\n source: string;\n isBitmark: boolean;\n}\n\nexport class BitmarkParserGenerator {\n /**\n * Get the version of the library.\n *\n * Reports the @gmb/bitmark-parser version (not a bpg version string).\n */\n public version(): string {\n return PACKAGE_INFO.version;\n }\n\n /**\n * Convert bitmark from bitmark to JSON, or JSON to bitmark (bpg-compatible).\n *\n * Input detection order matches bpg: AST → JSON → assume bitmark.\n * Default output: bitmark input → json; json/ast input → bitmark.\n */\n public convert(input: string | unknown, options?: ConvertOptions): string | unknown | void {\n const opts: ConvertOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateVersionOptions(opts);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n\n const outputFormat = opts.outputFormat ?? (isBitmark ? \"json\" : \"bitmark\");\n const coreFormat = outputFormat === \"ast\" ? \"json\" : outputFormat;\n // bpg parity: `jsonOptions.prettify` governs JSON output only;\n // `bitmarkOptions.prettifyJson` governs bitmark output (it prettifies the\n // embedded JSON bodies of json-format bits — same boolean|number shape).\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const emit =\n coreFormat === \"bitmark\" ? prettyIndent(bitmarkOptions.prettifyJson) : { pretty, indent };\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n // bpg parity: unknown properties are included in JSON output unless\n // `jsonOptions.excludeUnknownProperties` is set (the core flag is the\n // inverse and only affects the bitmark → JSON direction).\n const includeUnknown = !jsonOptions.excludeUnknownProperties;\n\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", coreFormat, \"optimized\", emit.pretty, emit.indent, spaces, includeUnknown, false);\n this.throwOnError(out);\n\n // Shape the result per output format (bpg-compatible return shapes)\n if (outputFormat === \"bitmark\" || outputFormat === \"text\") {\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n if (outputFormat === \"json\") {\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n // outputFormat === \"ast\": bit-JSON pseudo-AST (PLAN-126 §3.1)\n const ast = makePseudoAst(JSON.parse(out) as unknown[]);\n if (opts.outputFile) {\n return this.deliver(JSON.stringify(ast), opts.outputFile, opts.fileOptions);\n }\n return ast;\n }\n\n /**\n * Upgrade (prettify / canonicalize) bitmark or JSON to the latest version\n * of itself (bpg-compatible `upgrade`).\n */\n public upgrade(input: string | unknown, options?: UpgradeOptions): string | unknown | void {\n const opts: UpgradeOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateVersionOptions(opts);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n // Same routing as convert(): bitmark in → bitmark out, so prettifyJson\n // applies; JSON in → JSON out, so jsonOptions.prettify applies.\n const { pretty, indent } = prettyIndent(\n isBitmark ? bitmarkOptions.prettifyJson : jsonOptions.prettify,\n );\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n\n const out = wasm.canonicalize(source, isBitmark ? \"bitmark\" : \"json\", \"optimized\", pretty, indent, spaces);\n this.throwOnError(out);\n\n if (isBitmark) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n\n /**\n * Get information about the bitmark language (bpg-compatible `info`).\n */\n public info(options?: InfoOptions): unknown {\n const opts: InfoOptions = Object.assign({}, options);\n const wasm = getLegacyWasm();\n const type = opts.type ?? \"list\";\n const format = opts.outputFormat ?? \"text\";\n const { pretty, indent } = prettyIndent(opts.prettify);\n\n const coreFormat = format === \"pojo\" ? \"json\" : format;\n // full=true: the legacy facade keeps the rich info shape (bpg parity).\n const out = wasm.info(type, coreFormat, opts.bit ?? \"\", pretty, indent, false, false, true);\n this.throwOnError(out);\n if (format === \"pojo\") return JSON.parse(out) as unknown;\n return out;\n }\n\n /** Not supported: bpg-internal development tool. */\n public generateConfig(_options?: unknown): void {\n unsupportedMember(\"BitmarkParserGenerator.generateConfig\", \"bpg-internal development tool\");\n }\n\n /**\n * Convert between HTML tables and bitmark tables (bpg-compatible\n * `convertHtmlTable`).\n *\n * Backed by the core's schema-driven html mapping: HTML input has each\n * `<table>` wrapped in the core's `<bitmark-bit>` envelope and parsed;\n * bits input is emitted as html and the `<table>` fragments extracted\n * (the envelope stripped). The markup *inside* `<table>` follows this\n * parser's html mapping, which may differ from bpg's in detail.\n */\n public convertHtmlTable(\n input: string | unknown,\n options?: ConvertHtmlTableOptions,\n ): string | unknown | void {\n const opts: ConvertHtmlTableOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n const bitmarkOptions = Object.assign({}, opts.bitmarkOptions);\n validateBitmarkOptions(bitmarkOptions);\n validateJsonOptions(jsonOptions);\n if (opts.keepUnknownTags) unsupportedOption(\"keepUnknownTags\");\n if (opts.noBreakscaping) unsupportedOption(\"noBreakscaping\");\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n\n const inStr = typeof input === \"string\" ? this.maybeReadFile(input, undefined) : \"\";\n const isHtmlInput =\n opts.inputFormat === \"html\" ||\n (opts.inputFormat === undefined && typeof input === \"string\" && /<table[\\s>]/iu.test(inStr));\n\n if (!isHtmlInput) {\n // bits (bitmark / JSON / AST) → HTML `<table>` fragments\n const { source, isBitmark } = this.resolveInput(input, undefined);\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"html\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return this.deliver(extractHtmlTables(out).join(\"\\n\"), opts.outputFile, opts.fileOptions);\n }\n\n // HTML input: wrap each <table> in the core's bit envelope and parse\n const bitType = opts.tableFormat === \"table\" ? \"table\" : \"table-extended\";\n const wrapped = extractHtmlTables(inStr)\n .map((t) => `<bitmark-bit data-type=\"${bitType}\" data-format=\"bitmark++\">${t}</bitmark-bit>`)\n .join(\"\");\n const outputFormat = opts.outputFormat ?? \"bitmark\";\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const spaces = spacesAround(bitmarkOptions.spacesAroundValues);\n\n if (outputFormat === \"html\") {\n const out = wasm.convert(wrapped, \"html\", \"html\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return this.deliver(extractHtmlTables(out).join(\"\\n\"), opts.outputFile, opts.fileOptions);\n }\n const coreFormat = outputFormat === \"ast\" ? \"json\" : outputFormat;\n const out = wasm.convert(wrapped, \"html\", coreFormat, \"optimized\", pretty, indent, spaces, false, false);\n this.throwOnError(out);\n if (outputFormat === \"bitmark\" || outputFormat === \"text\") {\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n if (outputFormat === \"json\") {\n if (opts.outputFile) return this.deliver(out, opts.outputFile, opts.fileOptions);\n if (pretty || jsonOptions.stringify) return out;\n return JSON.parse(out) as unknown;\n }\n const ast = makePseudoAst(JSON.parse(out) as unknown[]);\n if (opts.outputFile) return this.deliver(JSON.stringify(ast), opts.outputFile, opts.fileOptions);\n return ast;\n }\n\n /**\n * Create a bit-JSON pseudo-AST from bitmark or JSON input (PLAN-126 §3.1).\n *\n * NOTE: the returned structure is the bit JSON (wrapper entries), not\n * bpg's internal TS AST node model. It round-trips through `convert` but\n * is not walkable with bpg's `Ast`/`NodeType`.\n */\n public createAst(input: unknown, options?: CreateAstOptions): LegacyPseudoAst {\n const opts: CreateAstOptions = Object.assign({}, options);\n const wasm = getLegacyWasm();\n const { source, isBitmark } = this.resolveInput(input, opts.inputFormat);\n // bpg's AST carries extraProperties unconditionally (createAst has no\n // jsonOptions), so unknown properties are always included here.\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"json\", \"optimized\", false, 2, 1, true, false);\n this.throwOnError(out);\n return makePseudoAst(JSON.parse(out) as unknown[]);\n }\n\n /**\n * Breakscape text (bpg-compatible `breakscapeText`).\n */\n public breakscapeText(input: string, options?: BreakscapeOptions): string | void {\n if (!input) return input;\n const opts: BreakscapeOptions = Object.assign({}, options);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n const inStr = this.maybeReadFile(input, opts.inputFormat);\n const res = wasm.breakscape_text(inStr, mapTextFormat(opts.textFormat), opts.textLocation ?? \"body\");\n return this.deliver(res, opts.outputFile, opts.fileOptions);\n }\n\n /**\n * Unbreakscape text (bpg-compatible `unbreakscapeText`).\n */\n public unbreakscapeText(input: string, options?: UnbreakscapeOptions): string | void {\n if (!input) return input;\n const opts: UnbreakscapeOptions = Object.assign({}, options);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n const inStr = this.maybeReadFile(input, opts.inputFormat);\n const res = wasm.unbreakscape_text(inStr, mapTextFormat(opts.textFormat), opts.textLocation ?? \"body\");\n return this.deliver(res, opts.outputFile, opts.fileOptions);\n }\n\n /**\n * Convert bitmark text ↔ text AST (bpg-compatible `convertText`).\n *\n * Direction is auto-detected: TextAst (JSON) input generates bitmark\n * text; anything else parses as bitmark text and returns the TextAst\n * (plain JS object; a string when `jsonOptions.prettify` is set).\n */\n public convertText(input: string | unknown, options?: ConvertTextOptions): string | unknown | void {\n const opts: ConvertTextOptions = Object.assign({}, options);\n const jsonOptions = Object.assign({}, opts.jsonOptions);\n this.checkBrowserFileWrite(opts.outputFile);\n const wasm = getLegacyWasm();\n\n const isBitmarkText = opts.textFormat === undefined || mapTextFormat(opts.textFormat) === \"bitmark++\";\n const textLocation = opts.textLocation ?? \"body\";\n\n let inStr: string;\n let ast: unknown[] | undefined;\n if (typeof input === \"string\") {\n inStr = this.maybeReadFile(input, opts.inputFormat);\n ast = this.parseTextAstString(inStr);\n } else {\n inStr = JSON.stringify(input);\n ast = Array.isArray(input) ? input : undefined;\n }\n\n if (ast !== undefined) {\n // TextAst → text (reverse honours the location; a plain-text format\n // generates plain text, i.e. marks are dropped — bpg parity)\n const out = isBitmarkText\n ? wasm.convert_text(JSON.stringify(ast), \"astToText\", \"bitmark++\", textLocation)\n : wasm.convert_text(JSON.stringify(ast), \"astToPlainText\", \"plainText\", textLocation);\n this.throwOnError(out);\n return this.deliver(out, opts.outputFile, opts.fileOptions);\n }\n\n // text → TextAst (bpg parses forward at body location)\n const out = wasm.convert_text(inStr, \"textToAst\", isBitmarkText ? \"bitmark++\" : \"plainText\", \"body\");\n this.throwOnError(out);\n const { pretty, indent } = prettyIndent(jsonOptions.prettify);\n const outStr = pretty ? wasm.prettify(out, indent) : out;\n if (opts.outputFile) return this.deliver(outStr, opts.outputFile, opts.fileOptions);\n if (pretty) return outStr;\n return JSON.parse(out) as unknown;\n }\n\n /**\n * Convert a text AST to plain text (bpg-compatible `textAstToPlainText`).\n */\n public textAstToPlainText(textAst: unknown, _options?: ExtractPlainTextOptions): string {\n const wasm = getLegacyWasm();\n const out = wasm.convert_text(\n typeof textAst === \"string\" ? textAst : JSON.stringify(textAst),\n \"astToPlainText\",\n \"bitmark++\",\n \"body\",\n );\n this.throwOnError(out);\n return out;\n }\n\n /**\n * Extract plain text from bitmark or bitmark JSON (bpg-compatible).\n */\n public extractPlainText(input: string | unknown, options?: ExtractPlainTextOptions): string {\n const inputFormat = options?.inputFormat;\n const wasm = getLegacyWasm();\n if (inputFormat === \"plainText\") {\n return typeof input === \"string\" ? String(input) : \"\";\n }\n if (inputFormat === \"bitmarkText\") {\n const ast = wasm.convert_text(String(input), \"textToAst\", \"bitmark++\", \"body\");\n const out = wasm.convert_text(ast, \"astToPlainText\", \"bitmark++\", \"body\");\n this.throwOnError(out);\n return out;\n }\n if (typeof input === \"string\" && this.parseTextAstString(input) === undefined && !wasm.is_bitmark(input)) {\n // Neither JSON nor bitmark: bpg falls through to bitmark text\n const looksJson = ((): boolean => {\n try {\n JSON.parse(input);\n return true;\n } catch {\n return false;\n }\n })();\n if (!looksJson) {\n return this.extractPlainText(input, { inputFormat: \"bitmarkText\" });\n }\n }\n const { source, isBitmark } = this.resolveInput(input, undefined);\n const out = wasm.convert(source, isBitmark ? \"bitmark\" : \"json\", \"text\", \"optimized\", false, 2, 1, false, false);\n this.throwOnError(out);\n return out;\n }\n\n /** If `s` parses as a TextAst JSON array, return it. */\n private parseTextAstString(s: string): unknown[] | undefined {\n const t = s.trim();\n if (!t.startsWith(\"[\")) return undefined;\n try {\n const v = JSON.parse(t) as unknown;\n if (Array.isArray(v) && v.every((n) => n !== null && typeof n === \"object\" && \"type\" in n)) {\n return v;\n }\n } catch {\n // not JSON\n }\n return undefined;\n }\n\n // ------------------------------------------------------------------\n // Internal helpers\n // ------------------------------------------------------------------\n\n /**\n * Resolve bpg input (string | file path | JSON value | pseudo-AST) to a\n * source string for the WASM core, classified per bpg's detection order:\n * AST → JSON → assume bitmark (PLAN-126 F-10).\n */\n protected resolveInput(input: unknown, inputFormat: string | undefined): ResolvedInput {\n if (typeof input !== \"string\") {\n // Parsed JSON / pseudo-AST value.\n const entries = this.jsonEntries(input);\n return {\n source: JSON.stringify(entries ? entries.map((b) => this.toWrapperEntry(b)) : input),\n isBitmark: false,\n };\n }\n const inStr = this.maybeReadFile(input, inputFormat);\n const wasm = getLegacyWasm();\n if (wasm.is_bitmark(inStr)) return { source: inStr, isBitmark: true };\n // JSON-ish: normalise loose shapes (AST envelope, single wrapper, bare bit)\n try {\n const parsed = JSON.parse(inStr) as unknown;\n const entries = this.jsonEntries(parsed);\n if (entries) {\n return {\n source: JSON.stringify(entries.map((b) => this.toWrapperEntry(b))),\n isBitmark: false,\n };\n }\n } catch {\n // is_bitmark said \"not bitmark\" but it is not JSON either —\n // fall through and let the core's own detection handle it (bpg\n // behaviour: assume bitmark).\n return { source: inStr, isBitmark: true };\n }\n return { source: inStr, isBitmark: false };\n }\n\n /**\n * Normalise the JSON shapes bpg accepts to a bits/entries array:\n * wrapper array, `{ bits: [...] }` AST envelope, single `{ bit: ... }`\n * wrapper, or a bare bit object (`{ type: ... }`).\n */\n private jsonEntries(v: unknown): unknown[] | undefined {\n if (Array.isArray(v)) return v;\n if (v !== null && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (Array.isArray(o.bits)) return o.bits;\n if (\"bit\" in o) return [o];\n if (typeof o.type === \"string\") return [{ bit: o }];\n }\n return undefined;\n }\n\n /**\n * Normalise a pseudo-AST bits entry to a `{ bit, parser? }` wrapper.\n * `Builder.buildBit` returns bare bit JSON (with any parser metadata\n * attached under a non-enumerable symbol); parsed forward output is\n * already wrapper-shaped.\n */\n private toWrapperEntry(entry: unknown): unknown {\n if (entry !== null && typeof entry === \"object\" && \"bit\" in (entry as object)) return entry;\n const wrapper: { bit: unknown; parser?: unknown } = { bit: entry };\n const parser = (entry as Record<symbol, unknown> | null)?.[BUILT_BIT_PARSER];\n if (parser !== undefined) wrapper.parser = parser;\n return wrapper;\n }\n\n /** bpg parity: read `input` as a file when it names one (Node only). */\n protected maybeReadFile(input: string, inputFormat: string | undefined): string {\n if (inputFormat === \"string\") return input;\n const io = getLegacyFileIo();\n if (!io) return input;\n try {\n if (io.existsSync(input)) return io.readFileSync(input, \"utf8\");\n } catch {\n // treat as literal input\n }\n return input;\n }\n\n /** bpg parity: writing a file is impossible in the browser. */\n protected checkBrowserFileWrite(outputFile: string | undefined): void {\n if (outputFile && !getLegacyFileIo()) {\n throw new Error(\"Cannot write to file in browser environment\");\n }\n }\n\n /** Return `data`, or write it to `outputFile` (returning void), as bpg does. */\n protected deliver(data: string, outputFile?: string, fileOptions?: FileOptions): string | void {\n if (!outputFile) return data;\n const io = getLegacyFileIo();\n if (!io) throw new Error(\"Cannot write to file in browser environment\");\n io.writeFile(outputFile, data, {\n append: fileOptions?.append,\n encoding: fileOptions?.encoding ?? \"utf8\",\n });\n }\n\n /** The core reports failures as `error:`-prefixed strings; bpg throws. */\n protected throwOnError(out: string): void {\n if (out.startsWith(\"error:\")) {\n throw new Error(out.slice(\"error:\".length).trim());\n }\n }\n}\n\n/**\n * Extract every top-level `<table>…</table>` fragment from `html`\n * (case-insensitive, nesting-safe). Pure string scanning — no HTML parsing.\n */\nfunction extractHtmlTables(html: string): string[] {\n const tables: string[] = [];\n const lower = html.toLowerCase();\n let i = 0;\n for (;;) {\n const start = lower.indexOf(\"<table\", i);\n if (start === -1) break;\n let depth = 0;\n let j = start;\n let end = -1;\n while (j < html.length) {\n const open = lower.indexOf(\"<table\", j);\n const close = lower.indexOf(\"</table\", j);\n if (close === -1) break;\n if (open !== -1 && open < close) {\n depth++;\n j = open + \"<table\".length;\n } else {\n depth--;\n const closeEnd = lower.indexOf(\">\", close);\n j = closeEnd === -1 ? html.length : closeEnd + 1;\n if (depth === 0) {\n end = j;\n break;\n }\n }\n }\n if (end === -1) break;\n tables.push(html.slice(start, end));\n i = end;\n }\n return tables;\n}\n\n/**\n * Direct bitmark text parser (bpg-compatible `bitmarkTextParse`):\n * bitmark text → TextAst array.\n */\nexport function bitmarkTextParse(text: string): unknown[] {\n const out = getLegacyWasm().convert_text(text, \"textToAst\", \"bitmark++\", \"body\");\n if (out.startsWith(\"error:\")) throw new Error(out.slice(\"error:\".length).trim());\n return JSON.parse(out) as unknown[];\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible `ResourceBuilder` (PLAN-126 §3.1): each method shapes the\n// `{ type, <family>: { ... } }` ResourceJson wrapper from bpg's flat data.\n// One generic table-driven implementation — per-bit-type defaulting and\n// URL-derived cosmetics are left to the config-driven core, which normalizes\n// the resource when the bit containing it is converted.\n\ninterface ResourceSpec {\n /** ResourceJson discriminator (`type`). */\n type: string;\n /** Family key holding the resource data object. */\n key: string;\n /** JSON field that bpg's `data.value` maps to. */\n valueField: \"src\" | \"url\" | \"body\";\n}\n\nconst RESOURCE_SPECS = {\n imageResource: { type: \"image\", key: \"image\", valueField: \"src\" },\n imageLinkResource: { type: \"image-link\", key: \"imageLink\", valueField: \"url\" },\n audioResource: { type: \"audio\", key: \"audio\", valueField: \"src\" },\n audioEmbedResource: { type: \"audio-embed\", key: \"audioEmbed\", valueField: \"src\" },\n audioLinkResource: { type: \"audio-link\", key: \"audioLink\", valueField: \"url\" },\n videoResource: { type: \"video\", key: \"video\", valueField: \"src\" },\n videoEmbedResource: { type: \"video-embed\", key: \"videoEmbed\", valueField: \"url\" },\n videoLinkResource: { type: \"video-link\", key: \"videoLink\", valueField: \"url\" },\n stillImageFilmEmbedResource: {\n type: \"still-image-film-embed\",\n key: \"stillImageFilmEmbed\",\n valueField: \"url\",\n },\n stillImageFilmLinkResource: {\n type: \"still-image-film-link\",\n key: \"stillImageFilmLink\",\n valueField: \"url\",\n },\n articleResource: { type: \"article\", key: \"article\", valueField: \"body\" },\n documentResource: { type: \"document\", key: \"document\", valueField: \"url\" },\n documentEmbedResource: { type: \"document-embed\", key: \"documentEmbed\", valueField: \"url\" },\n documentLinkResource: { type: \"document-link\", key: \"documentLink\", valueField: \"url\" },\n documentDownloadResource: {\n type: \"document-download\",\n key: \"documentDownload\",\n valueField: \"url\",\n },\n appLinkResource: { type: \"app-link\", key: \"appLink\", valueField: \"url\" },\n websiteLinkResource: { type: \"website-link\", key: \"websiteLink\", valueField: \"url\" },\n} as const satisfies Record<string, ResourceSpec>;\n\nexport type ResourceMethod = (\n context: unknown,\n data: Record<string, unknown> | undefined,\n __typeAlias?: string,\n) => Record<string, unknown> | undefined;\n\nfunction buildResource(spec: ResourceSpec): ResourceMethod {\n return (_context, data, _typeAlias) => {\n if (!data) return undefined;\n const { value, ...rest } = data;\n const inner: Record<string, unknown> = { [spec.valueField]: value ?? \"\" };\n for (const [k, v] of Object.entries(rest)) {\n if (v !== undefined) inner[k] = v;\n }\n return { type: spec.type, [spec.key]: inner };\n };\n}\n\n/** Resource `type` string → spec (for the generic wrapper/data entry points). */\nconst SPEC_BY_TYPE: Record<string, ResourceSpec> = Object.fromEntries(\n Object.values(RESOURCE_SPECS).map((s) => [s.type, s]),\n);\n\n/** bpg-compatible ResourceBuilder: 17 `<family>Resource(context, data)` methods\n * plus the generic `resourceFromResourceJson` / `resourceFromResourceDataJson`. */\nexport class ResourceBuilder {\n /**\n * Normalise existing ResourceJson wrapper(s) (bpg-compatible).\n * Unknown resource types are dropped (bpg parity: it skips invalid types).\n */\n resourceFromResourceJson(\n _context: unknown,\n resource?: Record<string, unknown> | Record<string, unknown>[],\n ): unknown {\n if (!resource) return undefined;\n const single = !Array.isArray(resource);\n const list = single ? [resource as Record<string, unknown>] : resource;\n const nodes: Record<string, unknown>[] = [];\n for (const wrapper of list) {\n const spec = SPEC_BY_TYPE[wrapper.type as string];\n if (!spec) continue;\n const inner = (wrapper[spec.key] ?? {}) as Record<string, unknown>;\n const { [spec.valueField]: value, ...rest } = inner;\n const built = buildResource(spec)(undefined, { value, ...rest });\n if (built) nodes.push(built);\n }\n if (nodes.length === 0) return undefined;\n return single ? nodes[0] : nodes;\n }\n\n /**\n * Build a resource wrapper from a bare ResourceDataJson (bpg-compatible).\n * `data` may also be a plain string (used as the url/src/body value).\n */\n resourceFromResourceDataJson(\n context: unknown,\n type: string,\n data?: Record<string, unknown> | string,\n ): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const spec = SPEC_BY_TYPE[type];\n if (!spec) return undefined;\n const asString = typeof data === \"string\" ? data : undefined;\n const obj = typeof data === \"object\" ? data : {};\n const { url, src, body, ...rest } = obj as {\n url?: unknown;\n src?: unknown;\n body?: unknown;\n [k: string]: unknown;\n };\n const value = url ?? src ?? body ?? asString;\n return buildResource(spec)(context, { value, ...rest });\n }\n imageResource: ResourceMethod = buildResource(RESOURCE_SPECS.imageResource);\n imageLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.imageLinkResource);\n audioResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioResource);\n audioEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioEmbedResource);\n audioLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.audioLinkResource);\n videoResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoResource);\n videoEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoEmbedResource);\n videoLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.videoLinkResource);\n stillImageFilmEmbedResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.stillImageFilmEmbedResource,\n );\n stillImageFilmLinkResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.stillImageFilmLinkResource,\n );\n articleResource: ResourceMethod = buildResource(RESOURCE_SPECS.articleResource);\n documentResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentResource);\n documentEmbedResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentEmbedResource);\n documentLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.documentLinkResource);\n documentDownloadResource: ResourceMethod = buildResource(\n RESOURCE_SPECS.documentDownloadResource,\n );\n appLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.appLinkResource);\n websiteLinkResource: ResourceMethod = buildResource(RESOURCE_SPECS.websiteLinkResource);\n}\n","// @zen-component: LEGACY-Facade\n// bpg-compatible enum objects and option interfaces (vendored from\n// bitmark-parser-generator v5.31.1, superenum EnumType<> replaced with the\n// equivalent value-union derivation). Exposed ONLY via the `legacy`\n// namespace / subpath — never re-exported at the package root.\n\n/** @internal */\ntype EnumType<T> = T[keyof T];\n\n/** Input type enumeration */\nexport const Input = {\n /** Input is as a string */\n string: \"string\",\n /** Input is as a file path */\n file: \"file\",\n} as const;\nexport type InputType = EnumType<typeof Input>;\n\n/** Output type enumeration */\nexport const Output = {\n /** Output bitmark string */\n bitmark: \"bitmark\",\n /** Output JSON as a plain JS object, or a file */\n json: \"json\",\n /** Output AST as a plain JS object, or a file */\n ast: \"ast\",\n /** Output plain text as a string, or a file */\n text: \"text\",\n} as const;\nexport type OutputType = EnumType<typeof Output>;\n\n/** Input format enumeration */\nexport const InputFormat = {\n bitmark: \"bitmark\",\n bitmarkText: \"bitmarkText\",\n plainText: \"plainText\",\n html: \"html\",\n} as const;\nexport type InputFormatType = EnumType<typeof InputFormat>;\n\nexport const BitmarkVersion = {\n v2: 2,\n v3: 3,\n} as const;\nexport type BitmarkVersionType = EnumType<typeof BitmarkVersion>;\n\nexport const CardSetVersion = {\n v1: 1,\n v2: 2,\n} as const;\nexport type CardSetVersionType = EnumType<typeof CardSetVersion>;\n\nexport const BitmarkParserType = {\n peggy: \"peggy\",\n} as const;\nexport type BitmarkParserTypeType = EnumType<typeof BitmarkParserType>;\n\nexport const InfoType = {\n list: \"list\",\n deprecated: \"deprecated\",\n all: \"all\",\n bit: \"bit\",\n} as const;\nexport type InfoTypeType = EnumType<typeof InfoType>;\n\nexport const InfoFormat = {\n text: \"text\",\n json: \"json\",\n pojo: \"pojo\",\n} as const;\nexport type InfoFormatType = EnumType<typeof InfoFormat>;\n\nexport const BodyTextFormat = {\n plainText: \"text\",\n latex: \"latex\",\n json: \"json\",\n xml: \"xml\",\n bitmarkPlusPlus: \"bitmark++\",\n} as const;\nexport type BodyTextFormatType = EnumType<typeof BodyTextFormat>;\n\nexport const TextLocation = {\n tag: \"tag\",\n body: \"body\",\n} as const;\nexport type TextLocationType = EnumType<typeof TextLocation>;\n\n/** Options for the output file (Node only) */\nexport interface FileOptions {\n /** Append to a file if true, otherwise overwrite */\n append?: boolean;\n /** Character encoding, defaults to 'utf8' */\n encoding?: string;\n}\n\n// Strict option policy, surfaced at BUILD time (bpg declared these wider):\n// options this facade cannot honour are narrowed to their supported value(s)\n// — truthy-throws booleans to `false`, value-gated enums to the supported\n// literal — so TS consumers get a type error instead of only the runtime\n// LegacyUnsupportedError. The runtime validation stays (JS callers, or TS\n// with the type ignored, still get the loud error).\n\n/** Options for bitmark generation */\nexport interface BitmarkOptions {\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n explicitTextFormat?: false;\n prettifyJson?: boolean | number;\n /** bitmark v3 only — card set version `1` throws `LegacyUnsupportedError` at runtime. */\n cardSetVersion?: typeof CardSetVersion.v2;\n spacesAroundValues?: number | boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n debugGenerationInline?: false;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n noBreakscaping?: false;\n}\n\n/** Options for JSON generation */\nexport interface JsonOptions {\n enableWarnings?: boolean | number;\n prettify?: boolean | number;\n stringify?: boolean;\n /** bitmark v3 only — `true` throws `LegacyUnsupportedError` at runtime. */\n textAsPlainText?: false;\n /**\n * Exclude unknown properties from the JSON output (default: `false` —\n * unknown properties are included, as bpg). The parser's warning text\n * references the new API's inverse flag (`includeUnknownProperties`).\n */\n excludeUnknownProperties?: boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n debugGenerationInline?: false;\n}\n\n/** Options for bitmark text JSON generation */\nexport interface TextJsonOptions {\n prettify?: boolean | number;\n}\n\n/** Info options for the parser */\nexport interface InfoOptions {\n type?: InfoTypeType;\n bit?: string;\n outputFormat?: InfoFormatType;\n prettify?: boolean | number;\n}\n\n/** Conversion options for bitmark / JSON conversion */\nexport interface ConvertOptions {\n /** bitmark v3 only — version `2` throws `LegacyUnsupportedError` at runtime. */\n bitmarkVersion?: typeof BitmarkVersion.v3;\n bitmarkParserType?: BitmarkParserTypeType;\n inputFormat?: InputType;\n outputFormat?: OutputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Prettify options for bitmark / JSON prettify / validate */\nexport interface UpgradeOptions {\n /** bitmark v3 only — version `2` throws `LegacyUnsupportedError` at runtime. */\n bitmarkVersion?: typeof BitmarkVersion.v3;\n bitmarkParserType?: BitmarkParserTypeType;\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Conversion options for bitmark text / JSON conversion */\nexport interface ConvertTextOptions {\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n jsonOptions?: TextJsonOptions;\n}\n\n/** Create AST options */\nexport interface CreateAstOptions {\n inputFormat?: InputType;\n}\n\nexport interface ExtractPlainTextOptions {\n inputFormat?: InputFormatType;\n}\n\n/** Options for convertHtmlTable */\nexport interface ConvertHtmlTableOptions {\n inputFormat?: InputFormatType;\n outputFormat?: OutputType | \"html\";\n tableFormat?: string;\n keepUnknownTags?: boolean;\n /** Not supported — `true` throws `LegacyUnsupportedError` at runtime. */\n noBreakscaping?: false;\n outputFile?: string;\n fileOptions?: FileOptions;\n bitmarkOptions?: BitmarkOptions;\n jsonOptions?: JsonOptions;\n}\n\n/** Breakscape options */\nexport interface BreakscapeOptions {\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n}\n\n/** Unbreakscape options */\nexport interface UnbreakscapeOptions {\n inputFormat?: InputType;\n outputFile?: string;\n fileOptions?: FileOptions;\n textFormat?: BodyTextFormatType;\n textLocation?: TextLocationType;\n}\n","// @zen-component: LEGACY-Facade\n// Remaining bpg enum exports: TextMarkType / TextNodeType (vendored values),\n// BitType (built lazily from the config-driven core — never a hardcoded bit\n// list), and throwing proxies for enums tied to unsupported internals.\n\nimport { unsupportedMember } from \"./errors.js\";\nimport { getLegacyWasm } from \"./runtime.js\";\n\n/** Vendored from bpg v5.31.1 model/enum/TextMarkType.ts. */\nexport const TextMarkType = {\n bold: \"bold\",\n light: \"light\",\n italic: \"italic\",\n highlight: \"highlight\",\n highlightOrange: \"highlightOrange\",\n highlightYellow: \"highlightYellow\",\n highlightGreen: \"highlightGreen\",\n highlightBlue: \"highlightBlue\",\n highlightPurple: \"highlightPurple\",\n highlightPink: \"highlightPink\",\n highlightBrown: \"highlightBrown\",\n highlightBlack: \"highlightBlack\",\n highlightWhite: \"highlightWhite\",\n highlightGray: \"highlightGray\",\n strike: \"strike\",\n subscript: \"subscript\",\n superscript: \"superscript\",\n ins: \"ins\",\n del: \"del\",\n underline: \"underline\",\n doubleUnderline: \"doubleUnderline\",\n circle: \"circle\",\n languageEmRed: \"languageEmRed\",\n languageEmOrange: \"languageEmOrange\",\n languageEmYellow: \"languageEmYellow\",\n languageEmGreen: \"languageEmGreen\",\n languageEmBlue: \"languageEmBlue\",\n languageEmPurple: \"languageEmPurple\",\n languageEmPink: \"languageEmPink\",\n languageEmBrown: \"languageEmBrown\",\n languageEmBlack: \"languageEmBlack\",\n languageEmWhite: \"languageEmWhite\",\n languageEmGray: \"languageEmGray\",\n languageEm: \"languageEm\",\n userUnderline: \"userUnderline\",\n userDoubleUnderline: \"userDoubleUnderline\",\n userStrike: \"userStrike\",\n userCircle: \"userCircle\",\n userHighlight: \"userHighlight\",\n notranslate: \"notranslate\",\n link: \"link\",\n ref: \"ref\",\n xref: \"xref\",\n extref: \"extref\",\n footnote: \"footnote\",\n footnoteStar: \"footnote*\",\n symbol: \"symbol\",\n var: \"var\",\n code: \"code\",\n timer: \"timer\",\n duration: \"duration\",\n color: \"color\",\n colorPicker: \"colorPicker\",\n comment: \"comment\",\n} as const;\n\n/** Vendored from bpg v5.31.1 model/enum/TextNodeType.ts. */\nexport const TextNodeType = {\n text: \"text\",\n hardBreak: \"hardBreak\",\n paragraph: \"paragraph\",\n heading: \"heading\",\n section: \"section\",\n noBulletList: \"noBulletList\",\n bulletList: \"bulletList\",\n orderedList: \"orderedList\",\n orderedListRoman: \"orderedListRoman\",\n orderedListRomanLower: \"orderedListRomanLower\",\n letteredList: \"letteredList\",\n letteredListLower: \"letteredListLower\",\n taskList: \"taskList\",\n listItem: \"listItem\",\n taskItem: \"taskItem\",\n image: \"image\",\n imageInline: \"imageInline\",\n codeBlock: \"codeBlock\",\n latex: \"latex\",\n gap: \"gap\",\n select: \"select\",\n highlight: \"highlight\",\n mark: \"mark\",\n} as const;\n\n/** bpg key derivation: kebab-case bit name → camelCase enum key. */\nfunction bitNameToKey(name: string): string {\n return name.replace(/-([a-z0-9])/gu, (_, c: string) => c.toUpperCase());\n}\n\nlet bitTypeCache: Record<string, string> | undefined;\n\nfunction loadBitTypes(): Record<string, string> {\n if (!bitTypeCache) {\n const wasm = getLegacyWasm();\n // includeDeprecated: bpg's BitType enum carries the deprecated bit\n // types too (PLAN-149 hides them from listings by default).\n const all = JSON.parse(wasm.info(\"all\", \"json\", \"\", false, 2, true, false, false)) as {\n name: string;\n }[];\n const map: Record<string, string> = { _standard: \"_standard\" };\n for (const { name } of all) {\n map[bitNameToKey(name)] = name;\n }\n bitTypeCache = map;\n }\n return bitTypeCache;\n}\n\n/**\n * bpg-compatible `BitType` enum object, built lazily from the core's\n * config (`info`) rather than a hardcoded list. Keys are the camelCase of\n * the bit names, exactly as bpg derives them.\n */\nexport const BitType: Record<string, string> = new Proxy(\n {},\n {\n get: (_t, prop) => (typeof prop === \"string\" ? loadBitTypes()[prop] : undefined),\n has: (_t, prop) => typeof prop === \"string\" && prop in loadBitTypes(),\n ownKeys: () => Reflect.ownKeys(loadBitTypes()),\n getOwnPropertyDescriptor: (_t, prop) =>\n typeof prop === \"string\" && prop in loadBitTypes()\n ? { value: loadBitTypes()[prop], enumerable: true, configurable: true, writable: false }\n : undefined,\n },\n);\n\n/** Loud F-2 stand-in for enums tied to unsupported bpg internals. */\nfunction unsupportedEnum(name: string, reason: string): Record<string, string> {\n return new Proxy(\n {},\n {\n get: (_t, prop) => {\n if (prop === Symbol.toPrimitive || prop === \"toString\" || prop === Symbol.toStringTag) {\n return () => `[unsupported ${name}]`;\n }\n return unsupportedMember(name, reason);\n },\n has: () => unsupportedMember(name, reason),\n ownKeys: () => unsupportedMember(name, reason),\n },\n );\n}\n\n/** bpg `NodeType` — names bpg's internal AST nodes; the legacy AST is bit JSON. */\nexport const NodeType = unsupportedEnum(\n \"NodeType\",\n \"it names bpg's internal AST nodes; the legacy AST is bit JSON (see createAst)\",\n);\n\n/** bpg `BoundingBoxIndex` — bpg-internal utility. */\nexport const BoundingBoxIndex = unsupportedEnum(\n \"BoundingBoxIndex\",\n \"bpg-internal bounding-box utility\",\n);\n","// @zen-component: LEGACY-Facade\n// Throwing stubs for bpg exports the legacy facade deliberately does not\n// implement (PLAN-126 F-2: exist, but fail loudly and deterministically —\n// never silent no-ops). These are internals of bpg's TS implementation\n// (its AST walker, generators, parsers, writers), which have no equivalent\n// over the WASM core.\n\nimport { unsupportedMember } from \"./errors.js\";\n\nfunction stubClass(name: string, reason: string): new (...args: unknown[]) => never {\n return class {\n constructor() {\n unsupportedMember(name, reason);\n }\n } as unknown as new (...args: unknown[]) => never;\n}\n\nconst WALKER_REASON =\n \"the legacy AST is bit JSON, not bpg's internal node model; walking it with bpg NodeType names would silently misbehave\";\nconst INTERNAL_REASON = \"internal class of bpg's TS implementation\";\n\n/** bpg `Ast` walker — unsupported (PLAN-126 decision Q-7). */\nexport const Ast = stubClass(\"Ast\", WALKER_REASON);\n\nexport const BitmarkGenerator = stubClass(\"BitmarkGenerator\", INTERNAL_REASON);\nexport const BitmarkStringGenerator = stubClass(\"BitmarkStringGenerator\", INTERNAL_REASON);\nexport const BitmarkFileGenerator = stubClass(\"BitmarkFileGenerator\", INTERNAL_REASON);\nexport const JsonGenerator = stubClass(\"JsonGenerator\", INTERNAL_REASON);\nexport const JsonStringGenerator = stubClass(\"JsonStringGenerator\", INTERNAL_REASON);\nexport const JsonFileGenerator = stubClass(\"JsonFileGenerator\", INTERNAL_REASON);\nexport const HtmlTableGenerator = stubClass(\"HtmlTableGenerator\", INTERNAL_REASON);\nexport const HtmlTableParser = stubClass(\"HtmlTableParser\", INTERNAL_REASON);\nexport const BitmarkParser = stubClass(\"BitmarkParser\", INTERNAL_REASON);\nexport const JsonParser = stubClass(\"JsonParser\", INTERNAL_REASON);\nexport const StringWriter = stubClass(\"StringWriter\", INTERNAL_REASON);\nexport const FileWriter = stubClass(\"FileWriter\", INTERNAL_REASON);\nexport const StreamWriter = stubClass(\"StreamWriter\", INTERNAL_REASON);\n","// @zen-component: WASM-TSBindings\n\nimport type { AnyBit } from \"./generated/bit-types.js\";\n\n/**\n * Output mode for JSON serialization.\n *\n * - `\"optimized\"` — omit keys whose values match their natural defaults.\n * - `\"full\"` — include all keys enumerated from the bitmark configuration.\n */\nexport type OutputMode = \"optimized\" | \"full\";\n\n/**\n * Lexer stage selector.\n *\n * - `\"lex\"` — combined lexer, text output (default).\n * - `\"lex-json\"` — combined lexer, JSON array output.\n */\nexport type LexStage = \"lex\" | \"lex-json\";\n\n/** Options for the {@link lex} function. */\nexport interface LexOptions {\n /** Selects the lexer pipeline stage (default: `\"lex\"`). */\n stage?: LexStage;\n}\n\n/** Options for the typed conversion pair ({@link bitmarkToObjects} /\n * {@link objectsToBitmark}). */\nexport interface ParseOptions {\n /** JSON output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /**\n * Include unknown properties in the bit JSON (default: `false`). Applies\n * to {@link bitmarkToObjects} only (parsing); ignored by\n * {@link objectsToBitmark} — unknown properties are never converted back\n * to bitmark. See {@link ConvertOptions.includeUnknownProperties}.\n */\n includeUnknownProperties?: boolean;\n}\n\n/**\n * Input format selector (adds auto-detection).\n *\n * `\"auto\"` sniffs bitmark-vs-JSON from the content; `\"bitmark\"` / `\"json\"` are\n * explicit; any config mapping id (e.g. `\"html\"`, `\"xml\"`) selects a markup\n * input that is reversed to the AST. The `(string & {})` arm admits those\n * config-driven mapping ids while keeping literal autocompletion.\n */\nexport type InputFormat = \"auto\" | \"bitmark\" | \"json\" | (string & {});\n\n/** Concrete output format. `\"text\"` is lossy plain-text extraction and is\n * output-only (it cannot be used as an input format). */\nexport type OutputFormat = \"bitmark\" | \"json\" | \"text\";\n\n/** Options for the {@link convert} function. */\nexport interface ConvertOptions {\n /** Input format (default: `\"auto\"`). */\n inputFormat?: InputFormat;\n /** Output format (default: `\"auto\"` — the opposite of the input). */\n outputFormat?: OutputFormat | \"auto\";\n /** JSON output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /** Include validation warnings in `parser.warnings` output (default: `false`). */\n warnings?: boolean;\n /** Output text as plain text — debug mode (default: `false`). */\n plainText?: boolean;\n /**\n * Prettify the JSON being emitted (default: `false`). For JSON output this\n * is the whole document; for bitmark output it is the embedded JSON bodies\n * of `json`-format bits (cosmetic — they re-parse to the same value).\n */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n /**\n * Bitmark → JSON only: include unknown properties in the bit JSON\n * (default: `false`). An unknown property (`[@key:value]` the bit's\n * config cannot resolve, at the bit body/footer — never inside cards or\n * consumed by a chain) is appended after all real keys as an array of\n * strings (`[@u]` with no value → `true`); a key colliding with a\n * configured key is `_`-prefixed. Unknown properties are never converted\n * back to bitmark, and each occurrence still warns.\n */\n includeUnknownProperties?: boolean;\n /**\n * Replace the converted output with a human-readable MAPPING REPORT of\n * what each input construct mapped to — including inputs that are NOT\n * mapped (default: `false`). Composite conversions (e.g. xml → json)\n * report every leg, one section after the other.\n */\n mappingReport?: boolean;\n}\n\n/** Options for the {@link canonicalize} function (the single same-format\n * re-emit surface; `mode` covers what the removed optimize/fullize did). */\nexport interface CanonicalizeOptions {\n /**\n * Input format (default: `\"auto\"`). The output is re-emitted in this same\n * format — e.g. `\"html\"` in, html out. `\"auto\"` sniffs bitmark vs JSON.\n */\n inputFormat?: InputFormat;\n /** Output mode (default: `\"optimized\"`; `\"full\"` emits all keys). */\n mode?: OutputMode;\n /**\n * Prettify the JSON being emitted (default: `false`) — the whole document\n * for JSON input, the embedded JSON bodies of `json`-format bits for\n * bitmark input.\n */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n}\n\n/** A patch operation. */\nexport type PatchOp = \"set\" | \"create\" | \"delete\" | \"append\";\n\n/**\n * A patch entry. Either the verbose form `{ path, op, value? }` or the\n * shorthand single-key object `{ \"<path>\": value }` (which means `set`).\n *\n * `path` addresses the bit JSON directly (e.g. `id`,\n * `cards[2].question.instruction`, `id[-1]`). To modify bitmark, convert to\n * JSON, patch, then convert back — `transform` does this when the output\n * format is bitmark.\n */\nexport type PatchEntry =\n | { path: string; op: PatchOp; value?: unknown }\n | Record<string, unknown>;\n\n// ── typed patch values (PLAN-128 §3.7) ──────────────────────────────────\n// The value type is resolved from the caller's literal path against `AnyBit`,\n// segment by segment — no enumeration of the path space, so compile cost is\n// per-call-site and bounded by the literal's length. Unresolvable segments and\n// dynamic (non-literal) paths degrade to `unknown`.\n\n/** @internal Peel `[n]` indexes off the front of `S`, unwrapping one array level each. */\ntype ApplyIndexes<T, S extends string> = S extends `[${string}]${infer Rest}`\n ? ApplyIndexes<T extends readonly (infer E)[] ? E : unknown, Rest>\n : T;\n\n/** @internal Resolve one dot-separated segment (`key`, `key[n]…`, or bare index). */\ntype Seg<T, S extends string> = S extends `${infer K}[${infer Rest}`\n ? ApplyIndexes<K extends \"\" ? T : K extends keyof T ? T[K] : unknown, `[${Rest}`>\n : S extends keyof T\n ? T[S]\n : S extends `${number}` | `-${number}`\n ? T extends readonly (infer E)[]\n ? E\n : unknown\n : unknown;\n\n/**\n * The type at patch path `P` within `T` (paths as in {@link PatchEntry}:\n * dot-separated keys with `[n]` indexes, negative-from-end allowed).\n */\nexport type PathValue<T, P extends string> = string extends P\n ? unknown\n : P extends `${infer S}.${infer Rest}`\n ? PathValue<NonNullable<Seg<T, S>>, Rest>\n : Seg<T, P>;\n\n/**\n * Build a {@link PatchEntry} with the `value` typed from the literal `path`,\n * resolved against {@link AnyBit}.\n *\n * For `append`, the value is typed as an *element* of the array at the path.\n *\n * @example\n * patchEntry(\"instruction\", \"set\", [{ type: \"paragraph\", content: [] }]);\n * patchEntry(\"id\", \"append\", \"1234\");\n * patchEntry(\"cards[0].question\", \"delete\");\n */\nexport type PatchValueFor<P extends string, O extends PatchOp> = O extends \"append\"\n ? NonNullable<PathValue<AnyBit, P>> extends readonly (infer E)[]\n ? E\n : PathValue<AnyBit, P>\n : PathValue<AnyBit, P>;\n\nexport function patchEntry<const P extends string, const O extends PatchOp>(\n path: P,\n op: O,\n value?: PatchValueFor<P, O>,\n): PatchEntry {\n return value === undefined ? { path, op } : { path, op, value };\n}\n\n/** One bit's source slice within a bitmark document (from {@link splitBits}). */\nexport interface BitSlice {\n index: number;\n byteStart: number;\n byteEnd: number;\n source: string;\n}\n\n/**\n * What a {@link PreHook} / {@link PostHook} sees for one bit, in its source\n * format. `index` is the bit's 0-based position; `total` is the bit count.\n */\nexport type BitView =\n | { format: \"bitmark\"; index: number; total: number; source: string }\n | { format: \"json\"; index: number; total: number; bit: AnyBit };\n\n/**\n * What a {@link PreHook} may return for a bit. All fields are optional; an\n * empty result (or `void`) makes the hook a pure observer.\n */\nexport interface PreHookResult {\n /** Patches to apply to this bit, after any static `patch`. */\n patches?: PatchEntry[];\n /** Override the output format for this bit only. */\n outputFormat?: OutputFormat;\n /** Drop the bit from the output entirely. */\n drop?: boolean;\n}\n\n/** Pre-processing hook: inspect a bit, optionally return modifications. */\nexport type PreHook = (view: BitView) => PreHookResult | void;\n\n/** Post-processing hook: observe a bit's input view and rendered output. */\nexport type PostHook = (view: BitView, output: string) => void;\n\n/** Options for the {@link transform} function. */\nexport interface TransformOptions {\n /** Input format (default: `\"auto\"`). */\n inputFormat?: InputFormat;\n /** Output format (default: `\"json\"`). */\n outputFormat?: OutputFormat;\n /** Output mode (default: `\"optimized\"`). */\n mode?: OutputMode;\n /** A static patch applied to every bit (array of entries, or a JSON string). */\n patch?: PatchEntry[] | string;\n /**\n * Per-bit pre-hook, run on the calling thread. Returns patches (applied\n * after the static `patch`), an output-format override, or `drop`. Providing\n * a `preHook` or `postHook` switches `transform` to the per-bit path; with\n * neither, the whole document is transformed in a single pass.\n */\n preHook?: PreHook;\n /** Per-bit post-hook, run on the calling thread after each bit is rendered. */\n postHook?: PostHook;\n /**\n * Worker-thread count for {@link transformParallel} (Node only; default `4`).\n * Ignored by the synchronous {@link transform}.\n */\n workers?: number;\n /** Prettify the emitted JSON (default: `false`) — for bitmark output, the\n * embedded JSON bodies of `json`-format bits. */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Spaces around tag values in bitmark output, `0..=10` (default: `1`). */\n spacesAroundValues?: number;\n}\n\n/** Text format for breakscape / unbreakscape operations. */\nexport type TextFormat = \"bitmark++\" | \"plainText\";\n\n/** Text location for breakscape / unbreakscape operations. */\nexport type TextLocation = \"body\" | \"tag\";\n\n/** Options for the {@link breakscapeText} and {@link unbreakscapeText} functions. */\nexport interface BreakscapeOptions {\n /** Text format (default: `\"bitmark++\"`). */\n format?: TextFormat;\n /** Text location (default: `\"body\"`). */\n location?: TextLocation;\n}\n\n/** Info query type for the {@link info} function. */\nexport type InfoType = \"list\" | \"bit\" | \"all\" | \"deprecated\";\n\n/** Output format for the {@link info} function. */\nexport type InfoFormat = \"text\" | \"json\";\n\n/** Options for the {@link info} function. */\nexport interface InfoOptions {\n /** Info query type (default: `\"list\"`). */\n infoType?: InfoType;\n /** Output format (default: `\"text\"`). */\n format?: InfoFormat;\n /** Bit name — required when `infoType` is `\"bit\"`. */\n bit?: string;\n /** Whether to pretty-print JSON output (default: `false`). */\n pretty?: boolean;\n /** Indent size for pretty-printing (default: `2`). */\n indent?: number;\n /** Include deprecated bits in `list`/`all` output (default: `false`). */\n includeDeprecated?: boolean;\n /** Restrict `list`/`all` output to deprecated bits only (default: `false`;\n * wins over `includeDeprecated`). */\n onlyDeprecated?: boolean;\n /** Full detail for `\"bit\"`/`\"all\"`: provenance, keys, card structure\n * (default `false` = compact one-line-per-tag view). */\n full?: boolean;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ADV9D,yBAA8B;;;AEEvB,IAAM,eAAe;AAAA,EAC1B,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,WAAW;AAAA,EACX,eAAe;AACjB;;;ACwCO,SAAS,QAAQ,GAAoB;AAC1C,SAAO,EAAE,WAAW,QAAQ;AAC9B;AAOO,SAAS,YAAY,GAAoB;AAC9C,QAAM,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AACnD,SAAO,EAAE,WAAW,QAAQ,IAAI,IAAI,UAAU,CAAC;AACjD;AAGO,SAAS,WAAW,KAAqB;AAC9C,QAAM,IAAI,IAAI,KAAK;AACnB,SAAO,EAAE,WAAW,GAAG,KAAK,EAAE,SAAS,GAAG,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI;AACjE;AAEA,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