Files
AFFiNE/packages/frontend/hosts/web/scripts/verify-preview-workers-e2e.mjs
T
DarkSky 2144304032 perf(preview): keep PDF documents open in the worker by docId
The preview workers now use a linear-memory ABI with four exports:
`memory`, `prepare(len)`, `invoke()` and `output_ptr()`. The host writes
each request into worker memory in one copy and copies each response out in
one copy. The old ABI called an export for every 4 bytes in each direction.

Rust gives out only the addresses of its own buffers, so the crate keeps
`forbid(unsafe_code)`. Buffers larger than 1 MiB go back to the allocator
after each request.

The PDF worker keeps each parsed document under a `docId` that the host
assigns. The frames are `PDF_OPEN`, `PDF_RENDER` and `PDF_CLOSE`.

The bytes of a document go to the worker once per open, not once per page.
Page pixels come back as a compact RGBA buffer that the worker transfers.

The playground bridge has one session table in `wasm_pdf_state.rs`. It
opens at most 8 documents or 256 MiB of source bytes.

To make room, the table closes least recently used idle documents, but only
when that makes the new document fit. Empty documents and documents larger
than 256 MiB never go to the worker.

The table closes a document when the view clears the last scope that used
it, also when no page request claimed it yet. A reopen that fails after a
worker restart keeps the known page count.

The table restarts the worker before the IDs run out.

The bridge no longer keeps 16 copies of PDF bytes.

Each worker event listener ignores events from a replaced worker, so a late
error of an old worker cannot stop the new one. A crash answers each sent
request once, so the count of unanswered requests stays exact.

`pdf-client.js` uses the same protocol and keeps its public methods. It
keeps the same open budget and waits for room before it sends an open.

New bytes for a known `docKey` now open a new document and drop the old
page count and pages. Before, the client returned the old page count.

Four snapshot IDs of the PDF viewer and the attachment toolbar use
`format_args!`, so the production bundle has no copy of their prefixes. The
prefix gate now checks 14 prefixes.
2026-12-01 18:55:10 +09:00

658 lines
21 KiB
JavaScript

#!/usr/bin/env node
// @ts-check
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { Worker as NodeWorker } from 'node:worker_threads';
import { createWorkerLoader } from '../src/worker-loader.js';
const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const ASSETS_DIR = join(WEB_ROOT, 'assets');
/**
* Builds a PDF with one 300x200 page per fill operator. `padBytes` adds an
* unreferenced stream object of that size, so large inputs make the worker
* grow its linear memory.
*
* @param {string[]} pageFills
* @param {number} [padBytes=0]
* @returns {Uint8Array}
*/
function buildPdf(pageFills, padBytes = 0) {
const bodies = [
'<< /Type /Catalog /Pages 2 0 R >>',
`<< /Type /Pages /Kids [${pageFills.map((_, i) => `${3 + i * 2} 0 R`).join(' ')}] /Count ${pageFills.length} >>`,
];
for (const [i, fill] of pageFills.entries()) {
const stream = `${fill} 0 0 300 200 re f\n`;
bodies.push(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents ${4 + i * 2} 0 R >>`,
`<< /Length ${stream.length} >>\nstream\n${stream}endstream`
);
}
const chunks = [Buffer.from('%PDF-1.4\n', 'ascii')];
let length = chunks[0].length;
const offsets = [];
const push = buf => {
chunks.push(buf);
length += buf.length;
};
for (const [i, body] of bodies.entries()) {
offsets.push(length);
push(Buffer.from(`${i + 1} 0 obj\n${body}\nendobj\n`, 'ascii'));
}
if (padBytes > 0) {
offsets.push(length);
push(
Buffer.from(
`${bodies.length + 1} 0 obj\n<< /Length ${padBytes} >>\nstream\n`,
'ascii'
)
);
push(Buffer.alloc(padBytes, 0x20));
push(Buffer.from('\nendstream\nendobj\n', 'ascii'));
}
const xrefAt = length;
const size = offsets.length + 1;
push(
Buffer.from(
`xref\n0 ${size}\n0000000000 65535 f \n` +
offsets.map(o => `${String(o).padStart(10, '0')} 00000 n \n`).join('') +
`trailer\n<< /Size ${size} /Root 1 0 R >>\nstartxref\n${xrefAt}\n%%EOF\n`,
'ascii'
)
);
return new Uint8Array(Buffer.concat(chunks));
}
/**
* Serves only staged static files under `hosts/web/assets/`.
*
* @param {string | URL} url
*/
async function staticAssetsFetch(url) {
const parsed = new URL(String(url));
if (!parsed.pathname.startsWith('/assets/')) {
return {
ok: false,
status: 404,
arrayBuffer: async () => new ArrayBuffer(0),
};
}
const relPath = parsed.pathname.slice('/assets/'.length);
const filePath = join(ASSETS_DIR, relPath);
const buf = readFileSync(filePath);
return {
ok: true,
status: 200,
arrayBuffer: async () =>
buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
};
}
const indexHtml = readFileSync(join(WEB_ROOT, 'index.html'), 'utf8');
const manifestMatch = indexHtml.match(
/<script id="affine-build-manifest" type="application\/json">([\s\S]*?)<\/script>/
);
assert.ok(manifestMatch, 'index.html must contain #affine-build-manifest');
const manifest = JSON.parse(manifestMatch[1].trim());
/** @type {Map<string, Blob>} */
const blobSources = new Map();
let blobCounter = 0;
/** @type {NodeWorker[]} */
const activeWorkers = [];
const loader = createWorkerLoader(manifest, {
baseUrl: 'https://app.affine.pro/workspace/ws-1/doc-2',
fetchImpl: /** @type {typeof fetch} */ (
/** @type {unknown} */ (staticAssetsFetch)
),
createObjectURL(blob) {
const id = `blob:https://app.affine.pro/e2e-${++blobCounter}`;
blobSources.set(id, blob);
return id;
},
createWorker(blobUrl) {
const blob = blobSources.get(blobUrl);
assert.ok(blob, `missing blob for ${blobUrl}`);
const harnessScript = `
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parentPort, workerData } from 'node:worker_threads';
const listeners = new Set();
globalThis.addEventListener = (type, fn) => {
if (type === 'message') listeners.add(fn);
};
globalThis.removeEventListener = (type, fn) => {
if (type === 'message') listeners.delete(fn);
};
globalThis.dispatchEvent = event => {
for (const fn of listeners) fn(event);
return true;
};
globalThis.postMessage = (data, transfer) => parentPort.postMessage(data, transfer);
globalThis.fetch = async url => {
const parsed = new URL(String(url));
if (!parsed.pathname.startsWith('/assets/')) {
return { ok: false, status: 404, arrayBuffer: async () => new ArrayBuffer(0) };
}
const filePath = join(workerData.assetsDir, parsed.pathname.slice('/assets/'.length));
const buf = readFileSync(filePath);
return {
ok: true,
status: 200,
arrayBuffer: async () => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
};
};
parentPort.on('message', data => {
globalThis.dispatchEvent({ type: 'message', data, ports: [] });
});
const rewritten = workerData.bootstrapSource.replace(
/await import\\("https:\\/\\/app\\.affine\\.pro\\/src\\/workers\\/([^"?]+)(?:\\?[^"]*)?"\\)/g,
(_m, file) => 'await import(' + JSON.stringify(workerData.workersBaseUrl + file) + ')'
);
await import('data:text/javascript;base64,' + Buffer.from(rewritten).toString('base64'));
`;
const readyWorker = blob.text().then(bootstrapSource => {
const worker = new NodeWorker(harnessScript, {
eval: true,
workerData: {
bootstrapSource,
assetsDir: ASSETS_DIR,
workersBaseUrl: pathToFileURL(
join(WEB_ROOT, 'src/workers/')
).toString(),
},
});
activeWorkers.push(worker);
return worker;
});
return /** @type {unknown} */ ({
async rpc(payload, transfer = []) {
const w = await readyWorker;
return new Promise((resolveRpc, rejectRpc) => {
const onMsg = msg => {
if (msg && msg.id === payload.id) {
w.off('message', onMsg);
w.off('error', onErr);
resolveRpc(msg);
}
};
const onErr = err => {
w.off('message', onMsg);
rejectRpc(err);
};
w.on('message', onMsg);
w.once('error', onErr);
w.postMessage(payload, transfer);
});
},
});
},
});
try {
// 1. Verify all 4 worker assets and all manifest fonts resolve & load from static assets.
for (const kind of /** @type {const} */ ([
'mermaid',
'math',
'typst',
'pdf',
])) {
const assets = loader.resolveWorkerAssets(kind);
assert.ok(
assets.script.startsWith(
`https://app.affine.pro/src/workers/${kind}-worker.js`
),
`unexpected script URL for ${kind}: ${assets.script}`
);
assert.ok(
assets.wasm.startsWith(
`https://app.affine.pro/assets/${kind}-worker.dev-local.wasm`
),
`unexpected wasm URL for ${kind}: ${assets.wasm}`
);
}
/** @type {Record<string, Uint8Array>} */
const loadedFonts = {};
for (const fontKey of Object.keys(manifest.fonts)) {
const fontBuf = await loader.loadFont(fontKey);
assert.ok(
fontBuf.byteLength > 10_000,
`manifest font "${fontKey}" must load non-empty TTF bytes from static assets`
);
loadedFonts[fontKey] = new Uint8Array(fontBuf);
}
assert.ok(loadedFonts.latin && loadedFonts.mono);
// 2. Mermaid worker: Light vs Dark themes must produce distinct themed SVGs.
const mermaidWorker = /** @type {any} */ (loader.loadWorker('mermaid'));
const mermaidSrc = 'flowchart LR\n A[Start] --> B[End]';
const mermaidLight = await mermaidWorker.rpc({
id: 1,
source: mermaidSrc,
theme: 'light',
});
const mermaidDark = await mermaidWorker.rpc({
id: 2,
source: mermaidSrc,
theme: 'dark',
});
assert.equal(
mermaidLight.ok,
true,
`mermaid light failed: ${mermaidLight.error}`
);
assert.equal(
mermaidDark.ok,
true,
`mermaid dark failed: ${mermaidDark.error}`
);
assert.ok(mermaidLight.result.svg.includes('<svg'));
assert.ok(mermaidDark.result.svg.includes('<svg'));
assert.notEqual(
mermaidLight.result.svg,
mermaidDark.result.svg,
'Mermaid light and dark worker SVGs must differ'
);
assert.ok(
mermaidLight.result.svg.toLowerCase().includes('#eef2ff'),
'Mermaid light SVG must apply AFFiNE Light palette'
);
assert.ok(
mermaidDark.result.svg.toLowerCase().includes('#1e2433'),
'Mermaid dark SVG must apply AFFiNE Dark palette'
);
// 3. Math (RaTeX) worker: both SVG (`op` omitted) and premultiplied RGBA (`op: 'rgba'`).
const mathWorker = /** @type {any} */ (loader.loadWorker('math'));
const mathRes = await mathWorker.rpc({
id: 3,
latex: 'x^2 + y^2 = z^2',
});
assert.equal(mathRes.ok, true, `math worker failed: ${mathRes.error}`);
assert.ok(mathRes.result.svg.includes('<svg'));
const mathInlineRgba = await mathWorker.rpc({
id: 30,
op: 'rgba',
latex: String.raw`\frac{1}{2}`,
display: false,
fontSizePt: 14.72,
paddingPt: 1.5,
colorCss: '#121212',
scaleFactor: 2.0,
});
const mathDisplayRgba = await mathWorker.rpc({
id: 31,
op: 'rgba',
latex: String.raw`\frac{\sqrt{\pi}}{2}`,
display: true,
fontSizePt: 18.0,
paddingPt: 4.0,
colorCss: '#e6e6e6',
scaleFactor: 2.0,
});
assert.equal(
mathInlineRgba.ok,
true,
`math inline rgba failed: ${mathInlineRgba.error}`
);
assert.equal(
mathDisplayRgba.ok,
true,
`math display rgba failed: ${mathDisplayRgba.error}`
);
assert.ok(
mathDisplayRgba.result.ascentPt + mathDisplayRgba.result.descentPt >
mathInlineRgba.result.ascentPt + mathInlineRgba.result.descentPt + 8,
'Display 18pt fraction must be taller than Inline 14.72pt fraction'
);
const inlineTotalPt =
mathInlineRgba.result.ascentPt + mathInlineRgba.result.descentPt;
assert.ok(
Math.abs(mathInlineRgba.result.ascentPt / inlineTotalPt - 0.78) > 0.05,
`Inline fraction baseline must come from real KaTeX metrics, got ${mathInlineRgba.result.ascentPt}/${inlineTotalPt}`
);
// Premultiplied RGBA8 invariant (`R, G, B <= A`) + crisp >=250-alpha dark-mode fraction bar row.
const dPixels = mathDisplayRgba.result.rgba;
const dW = mathDisplayRgba.result.widthPx;
const dH = mathDisplayRgba.result.heightPx;
assert.equal(dPixels.byteLength, dW * dH * 4);
for (let i = 0; i < dPixels.byteLength; i += 4) {
const a = dPixels[i + 3];
assert.ok(
dPixels[i] <= a && dPixels[i + 1] <= a && dPixels[i + 2] <= a,
`math worker RGBA must be premultiplied (pixel ${i / 4}: rgba=${dPixels[i]},${dPixels[i + 1]},${dPixels[i + 2]},${a})`
);
}
let foundCrispBar = false;
for (let row = Math.floor(dH / 3); row < Math.floor((dH * 2) / 3); row += 1) {
let run = 0;
for (let col = 0; col < dW; col += 1) {
if (dPixels[(row * dW + col) * 4 + 3] >= 250) {
run += 1;
if (run >= Math.max(6, Math.floor(dW / 2))) {
foundCrispBar = true;
break;
}
} else {
run = 0;
}
}
if (foundCrispBar) break;
}
assert.ok(
foundCrispBar,
'Dark-mode math worker RGBA must have crisp >=250-alpha fraction bar'
);
// 4. Typst worker: register fonts fetched via `loader.loadFont` and compile document.
const typstWorker = /** @type {any} */ (loader.loadWorker('typst'));
const latinReg = await typstWorker.rpc({
id: 4,
op: 'register_font',
fontBytes: loadedFonts.latin,
});
const monoReg = await typstWorker.rpc({
id: 5,
op: 'register_font',
fontBytes: loadedFonts.mono,
});
assert.equal(
latinReg.ok,
true,
`typst latin register failed: ${latinReg.error}`
);
assert.equal(
monoReg.ok,
true,
`typst mono register failed: ${monoReg.error}`
);
assert.ok(latinReg.result.faceCount >= 1);
assert.ok(monoReg.result.faceCount >= 1);
const typstRes = await typstWorker.rpc({
id: 6,
source:
'#set page(width: auto, height: auto, margin: 8pt)\n' +
'#show math.equation: set text(font: "New Computer Modern Math")\n' +
'= Hello Static Font\n`mono`\n$ x = (-b plus.minus sqrt(b^2 - 4 a c)) / (2 a) $',
pageIndex: 0,
});
assert.equal(typstRes.ok, true, `typst worker failed: ${typstRes.error}`);
assert.equal(typstRes.result.pageCount, 1);
assert.ok(typstRes.result.svg.includes('<svg'));
assert.ok(
typstRes.result.svg.includes('<path') ||
typstRes.result.svg.includes('<use'),
'typst worker SVG must contain rendered glyph paths'
);
const typstPages =
'#set page(width: 120pt, height: 80pt)\nFirst\n#pagebreak()\nSecond';
const typstPage1 = await typstWorker.rpc({
id: 60,
source: typstPages,
pageIndex: 1,
});
const typstPage0 = await typstWorker.rpc({
id: 61,
source: typstPages,
pageIndex: 0,
});
assert.equal(typstPage1.ok, true, `typst page 1 failed: ${typstPage1.error}`);
assert.equal(typstPage1.result.pageCount, 2);
assert.ok(typstPage1.result.svg.includes('<svg'));
assert.notEqual(typstPage1.result.svg, typstPage0.result.svg);
const typstOutOfRange = await typstWorker.rpc({
id: 62,
source: typstPages,
pageIndex: 2,
});
assert.equal(typstOutOfRange.ok, false);
assert.match(typstOutOfRange.error, /out of range/);
// 5. PDF (Hayro) worker. Messages sent back to back before the worker has
// started run in arrival order, so an open, a render and a close need no
// round trip between them.
const pdfWorker = /** @type {any} */ (loader.loadWorker('pdf'));
const RED = '0.9 0.1 0.1 rg';
const BLUE = '0.1 0.2 0.9 rg';
const GREEN = '0.1 0.8 0.2 rg';
const twoPagePdf = buildPdf([RED, BLUE]);
const coldOpenBytes = twoPagePdf.slice();
const [coldOpen, coldRender, coldClose, renderAfterClose] = await Promise.all(
[
pdfWorker.rpc(
{ id: 70, op: 'pdf_open', docId: 1, pdfBytes: coldOpenBytes },
[coldOpenBytes.buffer]
),
pdfWorker.rpc({
id: 71,
op: 'pdf_render',
docId: 1,
pageIndex: 1,
scale: 1,
}),
pdfWorker.rpc({ id: 72, op: 'pdf_close', docId: 1 }),
pdfWorker.rpc({
id: 73,
op: 'pdf_render',
docId: 1,
pageIndex: 0,
scale: 1,
}),
]
);
assert.equal(
coldOpenBytes.byteLength,
0,
'the open message transfers its bytes'
);
assert.equal(coldOpen.ok, true, `pdf cold open failed: ${coldOpen.error}`);
assert.equal(coldOpen.result.pageCount, 2);
assert.equal(
coldRender.ok,
true,
`pdf cold render failed: ${coldRender.error}`
);
assert.equal(coldClose.ok, true, `pdf close failed: ${coldClose.error}`);
assert.equal(renderAfterClose.ok, false);
assert.match(renderAfterClose.error, /unknown pdf handle 1/);
/** @param {any} res */
const centerPixel = res => {
const off =
(Math.floor(res.heightPx / 2) * res.widthPx +
Math.floor(res.widthPx / 2)) *
4;
return [res.rgba[off], res.rgba[off + 1], res.rgba[off + 2]];
};
/**
* @param {string} label
* @param {any} msg
* @param {'r' | 'g' | 'b'} channel
*/
const assertFill = (label, msg, channel) => {
assert.equal(msg.ok, true, `${label} failed: ${msg.error}`);
const res = msg.result;
assert.ok(
res.rgba instanceof Uint8Array,
`${label} must return Uint8Array RGBA`
);
assert.equal(res.rgba.byteOffset, 0, `${label} RGBA must own its buffer`);
assert.equal(res.rgba.buffer.byteLength, res.widthPx * res.heightPx * 4);
const [r, g, b] = centerPixel(res);
const value = { r, g, b }[channel];
assert.ok(
value > 180 && value > Math.max(r, g, b) - 1,
`${label} center pixel mismatch: ${r},${g},${b}`
);
};
assertFill('pdf cold render page 1', coldRender, 'b');
// Two documents stay open together and their renders interleave. The
// second one is larger than 32 MiB, so opening it grows linear memory.
const bigPadBytes = 32 * 1024 * 1024;
const bigPdf = buildPdf([GREEN, RED, BLUE], bigPadBytes);
const docs = await Promise.all([
pdfWorker.rpc({ id: 80, op: 'pdf_open', docId: 2, pdfBytes: twoPagePdf }),
pdfWorker.rpc({ id: 81, op: 'pdf_open', docId: 3, pdfBytes: bigPdf }, [
bigPdf.buffer,
]),
]);
assert.deepEqual(
docs.map(msg => [msg.ok, msg.result?.pageCount]),
[
[true, 2],
[true, 3],
]
);
const interleaved = await Promise.all([
pdfWorker.rpc({
id: 82,
op: 'pdf_render',
docId: 3,
pageIndex: 0,
scale: 1,
}),
pdfWorker.rpc({
id: 83,
op: 'pdf_render',
docId: 2,
pageIndex: 0,
scale: 1,
}),
pdfWorker.rpc({
id: 84,
op: 'pdf_render',
docId: 3,
pageIndex: 2,
scale: 2,
}),
pdfWorker.rpc({
id: 85,
op: 'pdf_render',
docId: 2,
pageIndex: 1,
scale: 1,
}),
]);
assertFill('pdf big page 0', interleaved[0], 'g');
assertFill('pdf small page 0', interleaved[1], 'r');
assertFill('pdf big page 2', interleaved[2], 'b');
assertFill('pdf small page 1', interleaved[3], 'b');
assert.deepEqual(
[interleaved[2].result.widthPx, interleaved[2].result.heightPx],
[600, 400],
'scale 2 doubles the page size'
);
const redRes = interleaved[1];
const blueRes = interleaved[3];
const [redR, , redB] = centerPixel(redRes.result);
const [blueR, , blueB] = centerPixel(blueRes.result);
// Error frames keep their worker error text.
const errors = await Promise.all([
pdfWorker.rpc({ id: 90, op: 'pdf_open', docId: 2, pdfBytes: twoPagePdf }),
pdfWorker.rpc({
id: 91,
op: 'pdf_open',
docId: 4,
pdfBytes: new TextEncoder().encode('%PDF-1.4 not a pdf'),
}),
pdfWorker.rpc({
id: 92,
op: 'pdf_render',
docId: 2,
pageIndex: 9,
scale: 1,
}),
pdfWorker.rpc({
id: 93,
op: 'pdf_render',
docId: 99,
pageIndex: 0,
scale: 1,
}),
pdfWorker.rpc({ id: 94, pdfBytes: twoPagePdf, pageIndex: 0 }),
]);
assert.deepEqual(
errors.map(msg => msg.ok),
[false, false, false, false, false]
);
assert.match(errors[0].error, /pdf handle 2 is already loaded/);
assert.match(errors[3].error, /unknown pdf handle 99/);
assert.match(errors[4].error, /Unsupported pdf worker op/);
// The documents stay usable after the errors.
assertFill(
'pdf small page 0 after errors',
await pdfWorker.rpc({
id: 95,
op: 'pdf_render',
docId: 2,
pageIndex: 0,
scale: 1,
}),
'r'
);
// 6. Main playground Wasm bundle (`assets/pkg/playground.js`): real Yjs v1 extract + merge + corrupt fail.
const mainWasmJsUrl = loader.resolveMainWasmJsUrl();
assert.ok(
mainWasmJsUrl && mainWasmJsUrl.includes('/assets/pkg/playground.js'),
`unexpected mainWasmJsUrl: ${mainWasmJsUrl}`
);
const playgroundWasmBytes = readFileSync(
join(ASSETS_DIR, 'pkg', 'playground_bg.wasm')
);
const playgroundMod = await import(
pathToFileURL(join(ASSETS_DIR, 'pkg', 'playground.js')).toString()
);
playgroundMod.initSync({ module: playgroundWasmBytes });
const realYjsV1 = [
new Uint8Array([
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0,
7, 0, 105, 0, 1, 40, 0, 105, 1, 2, 105, 100, 1, 119, 2, 112, 49, 40, 0,
105, 1, 5, 116, 105, 116, 108, 101, 1, 119, 9, 76, 105, 118, 101, 32, 80,
97, 103, 101, 41, 1, 6, 115, 112, 97, 99, 101, 115, 2, 112, 49, 8, 111,
108, 100, 45, 103, 117, 105, 100, 118, 0, 41, 1, 8, 111, 116, 104, 101,
114, 77, 97, 112, 7, 102, 111, 114, 101, 105, 103, 110, 12, 102, 111, 114,
101, 105, 103, 110, 45, 103, 117, 105, 100, 118, 0, 0,
]),
new Uint8Array([
1, 1, 105, 6, 169, 105, 4, 9, 108, 105, 118, 101, 45, 103, 117, 105, 100,
118, 0, 1, 105, 1, 4, 1,
]),
];
assert.deepEqual(playgroundMod.extract_subdoc_ids(realYjsV1), ['live-guid']);
const mergedV1 = playgroundMod.merge_updates_v1(realYjsV1);
assert.ok(mergedV1 instanceof Uint8Array && mergedV1.byteLength > 0);
assert.deepEqual(playgroundMod.extract_subdoc_ids([mergedV1]), ['live-guid']);
const emptyMerged = playgroundMod.merge_updates_v1([]);
assert.deepEqual(Array.from(emptyMerged), [0, 0]);
assert.throws(
() =>
playgroundMod.extract_subdoc_ids([
new Uint8Array([0xff, 0xff, 0xff, 0x80]),
]),
/./
);
console.log(
`E2E 4-worker + main-wasm-crdt + static-font verification passed: fonts(${Object.keys(loadedFonts).join(',')}), playground_bg.wasm(${playgroundWasmBytes.byteLength}B, merged=${mergedV1.byteLength}B), mermaid(light=${mermaidLight.result.svg.length}B vs dark=${mermaidDark.result.svg.length}B), math(${mathRes.result.svg.length}B), typst(1p ${typstRes.result.svg.length}B, 2p), pdf(red R=${redR}/B=${redB}, blue R=${blueR}/B=${blueB}, ${redRes.result.rgba.byteLength}B RGBA, 32 MiB doc open)`
);
} finally {
await Promise.all(activeWorkers.map(w => w.terminate()));
}