The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 22:15 UTC
ci: split web tests over two runners so every run finishes sooner (#34554)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 11, 2026 at 13:54 UTC
fcc25c8bb283ae89a2c852b6760fce15d78b1dac
4 files changed
+1121
-1047
.github/workflows/ci.yml
+27
-3
@@ -355,16 +355,22 @@ jobs:
355
356
# The web suite is the largest outside the server. In the shared Test job it
357
# started last and ran alone for about 40s after everything else finished.
358
- # release.yml mirrors this test, test_web, and test_server split.
358
+ # Browser tests are bound by the Vite server transforming modules for each
359
+ # file, not by Chromium, so a second runner (and Vite server) halves the job
360
+ # that gated every run. release.yml mirrors this test, test_web, and test_server split.
361
test_web:
362
permissions:
363
contents: read
364
id-token: write
363
- name: Test Web
365
+ name: Test Web ${{ matrix.shard }}
366
needs: changes
367
if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }}
368
runs-on: blacksmith-8vcpu-ubuntu-2404
369
timeout-minutes: 10
370
+ strategy:
371
+ fail-fast: false
372
+ matrix:
373
+ shard: [1, 2]
374
steps:
375
- name: Checkout
376
uses: actions/checkout@v6
@@ -406,7 +412,7 @@ jobs:
412
fi
413
414
- name: Test
409
- run: vp run --filter @t3tools/web test
415
+ run: vp run --filter @t3tools/web test --shard ${{ matrix.shard }}/${{ strategy.job-total }}
416
417
# apps/server sets `fileParallelism: false`, so its test files run strictly
418
# one at a time. Sharding spreads them over separate runners instead of
@@ -481,6 +487,17 @@ jobs:
487
node apps/server/node_modules/playwright-core/cli.js install-deps chromium
488
fi
489
490
+ # Each server test file runs in its own Vitest process, and a fresh install starts
491
+ # Vitest's content-keyed module cache empty, so every file re-transformed its imports.
492
+ # Only pushes to main save it, so pull requests never evict each other's entries.
493
+ - name: Restore Vitest module cache
494
+ if: steps.changes.outputs.test_server != 'false'
495
+ uses: actions/cache/restore@v6
496
+ with:
497
+ path: node_modules/.vitest-cache
498
+ key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
499
+ restore-keys: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-
500
+
501
- name: Test
502
if: steps.changes.outputs.test_server != 'false'
503
env:
@@ -491,6 +508,13 @@ jobs:
508
--uncached apps/server/integration/transferBudgetV2.integration.test.ts
509
--verify-hits 1 apps/server
510
511
+ - name: Save Vitest module cache
512
+ if: github.event_name == 'push' && steps.changes.outputs.test_server != 'false'
513
+ uses: actions/cache/save@v6
514
+ with:
515
+ path: node_modules/.vitest-cache
516
+ key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
517
+
518
# integration/transferBudgetV2.integration.test.ts writes the report; exactly one shard
519
# produces these files. Gating the upload on their presence keeps a
520
# single `thread-transfer-results` artifact per run, which is the name
.github/workflows/release.yml
+7
-2
@@ -300,11 +300,15 @@ jobs:
300
# Web browser tests time out when they share a runner with the other package
301
# suites: Chromium gets too little CPU and diff workers miss their 10s start budget.
302
test_web:
303
- name: Release web tests
303
+ name: Release web tests ${{ matrix.shard }}
304
needs: [preflight]
305
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
306
runs-on: blacksmith-8vcpu-ubuntu-2404
307
timeout-minutes: 10
308
+ strategy:
309
+ fail-fast: false
310
+ matrix:
311
+ shard: [1, 2]
312
steps:
313
- name: Checkout
314
uses: actions/checkout@v6
@@ -344,10 +348,11 @@ jobs:
348
fi
349
350
- name: Test
347
- run: vp run --filter @t3tools/web test
351
+ run: vp run --filter @t3tools/web test --shard ${{ matrix.shard }}/${{ strategy.job-total }}
352
353
# Browser tests run source modules; this boots the production chunk graph.
354
- name: Boot the built web client
355
+ if: matrix.shard == 1
356
run: |
357
vp run --filter @t3tools/web build
358
node apps/web/scripts/verify-built-boot.ts
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+1
-1042
@@ -78,6 +78,7 @@ import { decodeImagePreview } from "./decodeImagePreview";
78
import type { BinaryWorkerResult } from "./binaryPreviewProtocol";
79
import type { TextPreviewResult } from "./largeTextProtocol";
80
import type { ReactElement } from "react";
81
+import type { OfficeWorkerResult } from "./officePreviewProtocol";
82
83
// Real worker imports and WASM initialization can exceed waitFor's default second
84
// when the full browser project runs concurrently on CI.
@@ -481,8 +482,6 @@ describe("bounded binary previews", () => {
482
}
483
});
484
});
484
-import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";
485
-import { WORD_LIMITS } from "./officeArchive";
485
486
describe("large text preview recovery", () => {
487
it("retains the workspace viewer across URL renewals and reloads revisions and manual refreshes", async () => {
@@ -921,1046 +920,6 @@ describe("large text preview recovery", () => {
920
await vi.waitFor(() => expect(load).toHaveBeenCalledWith(0));
921
});
922
});
924
-it.each(["<w:body/>", "<w:body></w:body>"])(
925
- "opens an empty Word document with %s",
926
- async (body) => {
927
- const { default: JSZip } = await import("jszip");
928
- const { prepareOffice } = await import("./officeArchive");
929
- const archive = new JSZip().file(
930
- "word/document.xml",
931
- `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:document>`,
932
- );
933
- const prepared = await prepareOffice(
934
- await archive.generateAsync({ type: "arraybuffer" }),
935
- "docx",
936
- );
937
- const result = await JSZip.loadAsync(prepared.bytes);
938
- const xml = new DOMParser().parseFromString(
939
- await result.file("word/document.xml")!.async("string"),
940
- "application/xml",
941
- );
942
- expect(xml.querySelector("parsererror")).toBeNull();
943
- expect(
944
- xml.getElementsByTagNameNS(
945
- "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
946
- "body",
947
- ),
948
- ).toHaveLength(1);
949
- },
950
-);
951
-
952
-it.each([false, true])(
953
- "rejects excessive archive entries before JSZip (directories: %s)",
954
- async (directories) => {
955
- const { default: JSZip } = await import("jszip");
956
- const { prepareOffice } = await import("./officeArchive");
957
- const archive = new JSZip();
958
- for (let i = 0; i < 4096; i++)
959
- archive.file(`entry-${i}${directories ? "/" : ".txt"}`, "", { dir: directories });
960
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
961
- const load = vi.spyOn(JSZip, "loadAsync");
962
- try {
963
- await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
964
- expect(load).not.toHaveBeenCalled();
965
- // The actual central-directory records must also be bounded if EOCD lies.
966
- const view = new DataView(bytes);
967
- view.setUint16(bytes.byteLength - 22 + 8, 1, true);
968
- view.setUint16(bytes.byteLength - 22 + 10, 1, true);
969
- await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
970
- expect(load).not.toHaveBeenCalled();
971
- } finally {
972
- load.mockRestore();
973
- }
974
- },
975
-);
976
-
977
-it("rejects oversized embedded images before decoding pixels and retains ordinary images", async () => {
978
- const { officeImageBitmap } = await import("./office/image-bitmap");
979
- const canvas = new OffscreenCanvas(2, 3);
980
- canvas.getContext("2d");
981
- const blob = await canvas.convertToBlob({ type: "image/png" });
982
- const bytes = await blob.arrayBuffer();
983
- new DataView(bytes).setUint32(16, 12000);
984
- new DataView(bytes).setUint32(20, 12000);
985
- const decode = vi.spyOn(globalThis, "createImageBitmap");
986
- try {
987
- await expect(officeImageBitmap(new Blob([bytes]))).rejects.toThrow("pixel limit");
988
- expect(decode).not.toHaveBeenCalled();
989
- const bitmap = await officeImageBitmap(blob);
990
- expect([bitmap.width, bitmap.height]).toEqual([2, 3]);
991
- bitmap.close();
992
- } finally {
993
- decode.mockRestore();
994
- }
995
-});
996
-
997
-it.each(["utf-16le", "utf-16be", "windows-1252"])(
998
- "preserves %s Office XML and safe hyperlink targets",
999
- async (encoding) => {
1000
- const { default: JSZip } = await import("jszip");
1001
- const { prepareOffice } = await import("./officeArchive");
1002
- const archive = new JSZip();
1003
- const encode = (text: string) => {
1004
- const xml = `<?xml version="1.0" encoding="${encoding}"?>${text}`;
1005
- if (encoding === "windows-1252") return Uint8Array.from(xml, (char) => char.charCodeAt(0));
1006
- const bytes = new Uint8Array(2 + xml.length * 2);
1007
- const view = new DataView(bytes.buffer);
1008
- const little = encoding === "utf-16le";
1009
- view.setUint16(0, 0xfeff, little);
1010
- for (let i = 0; i < xml.length; i++) view.setUint16(2 + i * 2, xml.charCodeAt(i), little);
1011
- return bytes;
1012
- };
1013
- archive.file(
1014
- "word/document.xml",
1015
- encode(
1016
- '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>café</w:t></w:r></w:p></w:body></w:document>',
1017
- ),
1018
- );
1019
- archive.file(
1020
- "word/_rels/document.xml.rels",
1021
- encode(
1022
- `<Relationships>${["https://example.com/page", "http://example.com", "mailto:maria@example.com", "javascript:alert(1)", "file:///tmp/private"].map((target, i) => `<Relationship Id="r${i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" TargetMode="External" Target="${target}"/>`).join("")}</Relationships>`,
1023
- ),
1024
- );
1025
- const prepared = await prepareOffice(
1026
- await archive.generateAsync({ type: "arraybuffer" }),
1027
- "docx",
1028
- );
1029
- const result = await JSZip.loadAsync(prepared.bytes);
1030
- expect(await result.file("word/document.xml")!.async("string")).toContain("café");
1031
- const links = await result.file("word/_rels/document.xml.rels")!.async("string");
1032
- expect(links).toContain('encoding="UTF-8"');
1033
- expect(links).toContain("https://example.com/page");
1034
- expect(links).toContain("http://example.com");
1035
- expect(links).toContain("mailto:maria@example.com");
1036
- expect(links).not.toContain("javascript:");
1037
- expect(links).not.toContain("file:");
1038
- },
1039
-);
1040
-
1041
-it.each([
1042
- ["", "worksheets/./sheet1.xml", false, false],
1043
- ["x:", "../xl/worksheets/sheet1.xml", false, false],
1044
- ["", "/xl/worksheets/sheet1.xml", true, false],
1045
- ["", "worksheets/sheet1.xml", false, true],
1046
- ["", "worksheets/sheet1.xml", true, true],
1047
-])(
1048
- "preserves %sworksheet metadata with relationship target %s",
1049
- async (prefix, target, empty, localPrefix) => {
1050
- const { default: JSZip } = await import("jszip");
1051
- const archive = new JSZip();
1052
- const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
1053
- archive.file(
1054
- "xl/workbook.xml",
1055
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Chart" sheetId="2" r:id="c"/><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
1056
- );
1057
- archive.file(
1058
- "xl/_rels/workbook.xml.rels",
1059
- `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/><Relationship Id="c" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet1.xml"/></Relationships>`,
1060
- );
1061
- archive.file(
1062
- "xl/worksheets/sheet1.xml",
1063
- `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}sheetViews><${prefix}sheetView showGridLines="0"/></${prefix}sheetViews><${prefix}sheetFormatPr defaultColWidth="30"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
1064
- .replace(
1065
- /<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g,
1066
- prefix ? "<$1$2></$1>" : "$&",
1067
- )
1068
- .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
1069
- .replace(/<(\/?)sheetData\b/g, (tag, closing: string) =>
1070
- localPrefix ? `<${closing}x:sheetData${closing ? "" : ` xmlns:x="${ns}"`}` : tag,
1071
- )
1072
- .replace(/="([^"]*)"/g, (attribute, value: string) =>
1073
- prefix || empty
1074
- ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
1075
- : attribute,
1076
- ),
1077
- );
1078
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
1079
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1080
- type: "module",
1081
- });
1082
- try {
1083
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1084
- worker.addEventListener(
1085
- "message",
1086
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1087
- { once: true },
1088
- );
1089
- worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
1090
- });
1091
- expect(result.type).toBe("xlsx");
1092
- if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
1093
- // The engine counts the chart sheet before it.
1094
- expect(result.view?.hiddenGridlines).toEqual([1]);
1095
- const bounded = await JSZip.loadAsync(result.bytes);
1096
- const sheet = new DOMParser().parseFromString(
1097
- await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
1098
- "application/xml",
1099
- );
1100
- expect(sheet.querySelector("parsererror")).toBeNull();
1101
- const row = sheet.getElementsByTagNameNS(ns, "row")[0];
1102
- if (empty) expect(row).toBeUndefined();
1103
- else {
1104
- expect(row!.getAttribute("ht")).toBe("42");
1105
- expect(row!.getAttribute("hidden")).toBe("1");
1106
- expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
1107
- expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
1108
- }
1109
- expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
1110
- expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
1111
- const columns = [...sheet.getElementsByTagNameNS(ns, "col")].map((column) =>
1112
- ["min", "max", "width"].map((name) => column.getAttribute(name)),
1113
- );
1114
- // The engine ignores `defaultColWidth`, so the columns it sizes are spelled out.
1115
- expect(columns).toEqual([
1116
- [String(OFFICE_PREVIEW_MAX_COLUMNS - 1), String(OFFICE_PREVIEW_MAX_COLUMNS), "20"],
1117
- // Hidden columns keep their span past the limit, so they stay hidden.
1118
- [String(OFFICE_PREVIEW_MAX_COLUMNS + 1), String(OFFICE_PREVIEW_MAX_COLUMNS + 30), null],
1119
- ["1", String(OFFICE_PREVIEW_MAX_COLUMNS - 2), "30"],
1120
- ]);
1121
- } finally {
1122
- worker.terminate();
1123
- }
1124
- },
1125
-);
1126
-
1127
-it("reports the final slide at maximum scroll after page visibility changes", async () => {
1128
- const { OfficePages } = await import("./office/OfficePages");
1129
- const changed = vi.fn();
1130
- const container = document.createElement("div");
1131
- container.style.cssText = "display:flex;flex-direction:column;width:400px;height:400px";
1132
- await using screen = await render(
1133
- <OfficePages
1134
- pages={Array.from({ length: 6 }, () => ({ width: 400, height: 240 }))}
1135
- label="Slide"
1136
- paint={async () => undefined}
1137
- onPageChange={changed}
1138
- onError={(error) => {
1139
- throw error;
1140
- }}
1141
- />,
1142
- { container },
1143
- );
1144
- const scroller = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
1145
- await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight));
1146
- await act(() => {
1147
- scroller.scrollTop = scroller.scrollHeight;
1148
- });
1149
- await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(5));
1150
- await act(() => {
1151
- scroller.scrollTop = 10;
1152
- });
1153
- await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(0));
1154
-});
1155
-
1156
-it("preserves merged text across tile clears", async () => {
1157
- const { paintFrame } = await import("./office/sheet-frame");
1158
- const canvas = new OffscreenCanvas(400, 80);
1159
- const context = canvas.getContext("2d")!;
1160
- paintFrame(
1161
- context,
1162
- {
1163
- viewport: { x: 0, y: 0, width: 400, height: 80 },
1164
- list: { width: 400, height: 80, commands: [] },
1165
- tiles: [
1166
- {
1167
- x: 0,
1168
- y: 0,
1169
- clipX: 0,
1170
- clipY: 0,
1171
- list: {
1172
- width: 208,
1173
- height: 80,
1174
- commands: [
1175
- {
1176
- op: "text",
1177
- x: 2,
1178
- y: 40,
1179
- text: "MMMMMMMMMMMMMMMMMMMMMMMM",
1180
- fontSize: 20,
1181
- color: "#000",
1182
- clip: { x: 0, y: 0, w: 400, h: 80 },
1183
- },
1184
- ],
1185
- },
1186
- },
1187
- { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },
1188
- ],
1189
- },
1190
- { ratio: 1, origin: { x: 0, y: 0 } },
1191
- );
1192
- const pixels = context.getImageData(240, 15, 100, 35).data;
1193
- expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
1194
-});
1195
-
1196
-it.each([
1197
- "paragraphs",
1198
- "runs",
1199
- "tables",
1200
- "auxiliary XML",
1201
- "XML bytes",
1202
- "renamed XML",
1203
- "section after prefix",
1204
- "oversized section",
1205
-])("bounds excessive Word %s before rendering DOM", async (scenario) => {
1206
- const { default: JSZip } = await import("jszip");
1207
- const archive = new JSZip();
1208
- const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)
1209
- ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)
1210
- : scenario === "runs"
1211
- ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
1212
- : scenario === "tables"
1213
- ? "<w:tbl/>".repeat(2 * WORD_LIMITS.bodyElements)
1214
- : scenario === "XML bytes"
1215
- ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
1216
- : "<w:p/>";
1217
- const section =
1218
- '<w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:left="1440" w:bottom="1440" w:right="1440"/></w:sectPr>';
1219
- archive.file(
1220
- "word/document.xml",
1221
- `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}${scenario === "section after prefix" ? '<w:p xmlns:s="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:pPr><s:sectPr><s:pgSz s:w="11906" s:h="16838"/></s:sectPr></w:pPr></w:p>' : ""}${scenario === "oversized section" ? `<w:sectPr>${"<w:cols/>".repeat(2_001)}</w:sectPr>` : section}</w:body></w:document>`,
1222
- );
1223
- if (scenario === "auxiliary XML" || scenario === "renamed XML")
1224
- archive.file(
1225
- scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
1226
- `<w:footnotes>${"<w:p/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</w:footnotes>`,
1227
- );
1228
- const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1229
- const src = URL.createObjectURL(file);
1230
- try {
1231
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1232
- type: "module",
1233
- });
1234
- try {
1235
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1236
- worker.addEventListener(
1237
- "message",
1238
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1239
- { once: true },
1240
- );
1241
- void file
1242
- .arrayBuffer()
1243
- .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));
1244
- });
1245
- if (
1246
- scenario === "auxiliary XML" ||
1247
- scenario === "renamed XML" ||
1248
- scenario === "oversized section"
1249
- ) {
1250
- expect(result).toMatchObject({
1251
- type: "error",
1252
- message: expect.stringContaining("Preview limited"),
1253
- });
1254
- } else {
1255
- expect(result.type).toBe("docx");
1256
- if (result.type !== "docx") throw new Error("Expected a Word prefix");
1257
- expect(result.truncated).toBe(true);
1258
- const bounded = await JSZip.loadAsync(result.bytes);
1259
- const markup = await bounded.file("word/document.xml")!.async("string");
1260
- {
1261
- const xml = markup;
1262
- const document = new DOMParser().parseFromString(xml, "application/xml");
1263
- expect(document.querySelector("parsererror")).toBeNull();
1264
- const bodies = document.getElementsByTagNameNS("*", "body");
1265
- expect(bodies).toHaveLength(1);
1266
- const section = bodies[0]!.lastElementChild!;
1267
- expect(section.localName).toBe("sectPr");
1268
- const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;
1269
- expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(
1270
- scenario === "section after prefix" ? "11906" : "16838",
1271
- );
1272
- expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(
1273
- scenario === "section after prefix" ? null : "landscape",
1274
- );
1275
- }
1276
- expect(markup.length).toBeLessThan(body.length);
1277
- expect(markup.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
1278
- expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(WORD_LIMITS.bodyTags);
1279
- }
1280
- } finally {
1281
- worker.terminate();
1282
- }
1283
- } finally {
1284
- URL.revokeObjectURL(src);
1285
- }
1286
-});
1287
-
1288
-it.each([
1289
- "relationship markup",
1290
- "relationship bytes",
1291
- "content type",
1292
- "metadata type",
1293
- "deep XML",
1294
- "query path",
1295
-])("bounds XML hidden in media by %s", async (scenario) => {
1296
- const { default: JSZip } = await import("jszip");
1297
- const archive = new JSZip();
1298
- const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;
1299
- archive.file(
1300
- "word/document.xml",
1301
- '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',
1302
- );
1303
- archive.file(
1304
- "[Content_Types].xml",
1305
- `<Types><Override PartName="/${path}" ContentType="${scenario === "content type" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" : "image/png"}"/>${scenario === "metadata type" ? '<Default Extension="rels" ContentType="image/png"/>' : ""}</Types>`,
1306
- );
1307
- archive.file(
1308
- "word/_rels/document.xml.rels",
1309
- `<Relationships>${scenario === "content type" ? "" : `<Relationship Id="style" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="${path.slice(5)}"/>`}${scenario === "metadata type" ? "<unused/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1) : ""}</Relationships>`,
1310
- );
1311
- archive.file(
1312
- path,
1313
- scenario === "relationship bytes"
1314
- ? `<styles>${"x".repeat(WORD_LIMITS.auxiliaryPartBytes)}</styles>`
1315
- : scenario === "deep XML"
1316
- ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
1317
- : `<styles>${"<style/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</styles>`,
1318
- );
1319
- const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
1320
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1321
- type: "module",
1322
- });
1323
- try {
1324
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1325
- worker.addEventListener(
1326
- "message",
1327
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1328
- { once: true },
1329
- );
1330
- worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
1331
- });
1332
- expect(result).toMatchObject({
1333
- type: "error",
1334
- message: expect.stringContaining("Preview limited"),
1335
- });
1336
- } finally {
1337
- worker.terminate();
1338
- }
1339
-});
1340
-
1341
-const EXPANDED_WORD_ROLES = [
1342
- "footnotes",
1343
- "note roots",
1344
- "endnotes",
1345
- "header",
1346
- "footer",
1347
- "comments",
1348
- "styles",
1349
- "style chain",
1350
- "style count",
1351
- "style visits",
1352
- "numbering",
1353
- "picture numbering",
1354
-] as const;
1355
-
1356
-async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
1357
- const archive = new JSZip();
1358
- const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1359
- const type = role.startsWith("style")
1360
- ? "styles"
1361
- : role === "picture numbering"
1362
- ? "numbering"
1363
- : role === "note roots"
1364
- ? "footnotes"
1365
- : role;
1366
- archive.file(
1367
- "_rels/.rels",
1368
- '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
1369
- );
1370
- const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
1371
- // Each copy of the 2,000-paragraph payload costs 6,000 markup units, so enough
1372
- // references (or pages) exceed the expansion budget.
1373
- const copies = Math.ceil(WORD_LIMITS.expandedMarkup / 6_000) + 1;
1374
- archive.file(
1375
- "word/document.xml",
1376
- `<w:document xmlns:w="${ns}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${text("body retained")}${Array.from({ length: copies }, () => `<w:p><w:r><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/><w:br w:type="page"/></w:r></w:p>`).join("")}<w:sectPr><w:headerReference w:type="default" r:id="aux"/><w:footerReference w:type="default" r:id="aux"/></w:sectPr></w:body></w:document>`,
1377
- );
1378
- archive.file(
1379
- "word/_rels/document.xml.rels",
1380
- `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,
1381
- );
1382
- const xml =
1383
- role === "style chain" || role === "style count" || role === "style visits"
1384
- ? `<w:styles xmlns:w="${ns}">${Array.from({ length: role === "style count" ? WORD_LIMITS.styles + 1 : role === "style visits" ? Math.ceil(WORD_LIMITS.styleVisits / 30) + 1 : 1_000 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${i ? `<w:basedOn w:val="s${role === "style visits" && i >= 30 ? 29 : i - 1}"/>` : ""}<w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
1385
- : role === "styles"
1386
- ? `<w:styles xmlns:w="${ns}">${Array.from({ length: 100 }, (_, i) => `<w:style w:styleId="${"s".repeat(2_000)}${i}" w:type="paragraph"><w:basedOn w:val="s0"/><w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
1387
- : role.includes("numbering")
1388
- ? `<w:numbering xmlns:w="${ns}">${role === "picture numbering" ? '<w:numPicBullet w:numPicBulletId="1"/>' : ""}<w:abstractNum w:abstractNumId="1">${Array.from({ length: 9 }, (_, i) => `<w:lvl w:ilvl="${i}"><w:lvlText w:val="%1."/></w:lvl>`).join("")}</w:abstractNum>${Array.from({ length: WORD_LIMITS.numberingReferences + 1 }, (_, i) => `<w:num w:numId="${i}"><w:abstractNumId w:val="1"/></w:num>`).join("")}</w:numbering>`
1389
- : role === "header" || role === "footer"
1390
- ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
1391
- : `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1">${text("omitted payload").repeat(2_000)}</w:${role.slice(0, -1)}></w:${role}>`;
1392
- archive.file("word/media/aux.xml", xml);
1393
- if (role === "note roots") {
1394
- // Each note's XML repeats the 32 KB root, which the expansion budget charges twice.
1395
- const notes = Math.ceil(WORD_LIMITS.expandedBytes / 64_000) + 1;
1396
- archive.file(
1397
- "word/document.xml",
1398
- `<w:document xmlns:w="${ns}"><w:body>${text("body retained")}${Array.from({ length: notes }, (_, id) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`).join("")}</w:body></w:document>`,
1399
- );
1400
- archive.file(
1401
- "word/media/aux.xml",
1402
- `<w:footnotes xmlns:w="${ns}" padding="${"x".repeat(32_000)}">${Array.from({ length: notes }, (_, id) => `<w:footnote w:id="${id}">${text("omitted payload")}</w:footnote>`).join("")}</w:footnotes>`,
1403
- );
1404
- }
1405
- return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1406
-}
1407
-
1408
-// Rendering starts a Word engine worker per case, which compiles about 30 MB of WebAssembly and
1409
-// took 10-17 s per test on loaded CI runners. Omission and retention are prepareOffice decisions,
1410
-// so they are checked there.
1411
-it.each(EXPANDED_WORD_ROLES)(
1412
- "keeps the body and omits expanded %s from the prepared document",
1413
- async (role) => {
1414
- const file = await expandedWordFixture(role);
1415
- const { SaxesParser } = await import("saxes");
1416
- const { prepareOffice } = await import("./officeArchive");
1417
- const parse = vi.spyOn(SaxesParser.prototype, "write");
1418
- try {
1419
- const prepared = await prepareOffice(await file.arrayBuffer(), "docx");
1420
- expect(prepared.truncated).toBe(true);
1421
- if (role === "note roots")
1422
- expect(
1423
- parse.mock.calls.reduce(
1424
- (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
1425
- 0,
1426
- ),
1427
- ).toBeLessThan(WORD_LIMITS.expandedBytes + 4 * 1024 * 1024);
1428
- const bounded = await JSZip.loadAsync(prepared.bytes);
1429
- const markup = await bounded.file("word/document.xml")!.async("string");
1430
- expect(markup).toContain("body retained");
1431
- expect(bounded.file("word/media/aux.xml")).toBeNull();
1432
- // A dangling header or footer reference makes the engine reject the whole body.
1433
- expect(markup).not.toMatch(/<w:(header|footer)Reference/);
1434
- for (const entry of Object.values(bounded.files))
1435
- if (!entry.dir) expect(await entry.async("string")).not.toContain("omitted payload");
1436
- } finally {
1437
- parse.mockRestore();
1438
- }
1439
- },
1440
-);
1441
-
1442
-it.each([
1443
- "ordinary parts",
1444
- "unused parts",
1445
- "independent styles",
1446
- "inherited styles",
1447
- "python-docx package",
1448
- "default template styles",
1449
- "binary package properties",
1450
-])("retains Word %s without a limit warning", async (scenario) => {
1451
- const { default: JSZip } = await import("jszip");
1452
- const archive = new JSZip();
1453
- const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1454
- const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
1455
- const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
1456
- archive.file(
1457
- "_rels/.rels",
1458
- `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,
1459
- );
1460
- if (scenario === "python-docx package" || scenario === "binary package properties") {
1461
- const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
1462
- archive.file(
1463
- "_rels/.rels",
1464
- `<Relationships xmlns="${packageRelationships}"><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/><Relationship Id="thumbnail" Type="${packageRelationships}/metadata/thumbnail" Target="docProps/thumbnail.jpeg"/><Relationship Id="core" Type="${packageRelationships}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="app" Type="${r}/extended-properties" Target="docProps/app.xml"/><Relationship Id="custom" Type="${r}/custom-properties" Target="docProps/custom.xml"/><Relationship Id="signature" Type="${packageRelationships}/digital-signature/origin" Target="_xmlsignatures/origin.sigs"/></Relationships>`,
1465
- );
1466
- archive.file(
1467
- "[Content_Types].xml",
1468
- '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/></Types>',
1469
- );
1470
- archive.file(
1471
- "docProps/thumbnail.jpeg",
1472
- new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),
1473
- );
1474
- archive.file("_xmlsignatures/origin.sigs", new Uint8Array());
1475
- for (const part of ["core", "app", "custom"])
1476
- archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');
1477
- if (scenario === "binary package properties") {
1478
- const roles = [
1479
- `${packageRelationships}/metadata/core-properties`,
1480
- `${r}/extended-properties`,
1481
- `${packageRelationships}/metadata/custom-properties`,
1482
- `${packageRelationships}/digital-signature/signature`,
1483
- ];
1484
- archive.file(
1485
- "_rels/.rels",
1486
- `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/>${roles.map((role, i) => `<Relationship Id="metadata${i}" Type="${role}" Target="docProps/metadata${i}.dat"/>`).join("")}</Relationships>`,
1487
- );
1488
- for (const i of roles.keys())
1489
- archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));
1490
- }
1491
- }
1492
- const ordinary = scenario === "ordinary parts";
1493
- archive.file(
1494
- "word/document.xml",
1495
- `<w:document xmlns:w="${ns}" xmlns:r="${r}"><w:body>${text("ordinary body")}<w:p><w:pPr><w:pStyle w:val="s19"/></w:pPr><w:r><w:t>styled body</w:t>${ordinary ? '<w:footnoteReference w:id="1"/><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/>' : ""}</w:r></w:p><w:sectPr>${ordinary ? '<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>' : ""}</w:sectPr></w:body></w:document>`,
1496
- );
1497
- archive.file(
1498
- "word/_rels/document.xml.rels",
1499
- `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,
1500
- );
1501
- for (const [role, root] of [
1502
- ["header", "hdr"],
1503
- ["footer", "ftr"],
1504
- ])
1505
- archive.file(
1506
- `word/${role}.xml`,
1507
- `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,
1508
- );
1509
- for (const role of ["footnotes", "endnotes", "comments"])
1510
- archive.file(
1511
- `word/${role}.xml`,
1512
- `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1" w:author="reviewer" w:date="2026-10-01T00:00:00Z">${text(`${role} retained`)}</w:${role.slice(0, -1)}></w:${role}>`,
1513
- );
1514
- archive.file(
1515
- "word/fontTable.xml",
1516
- `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,
1517
- );
1518
- archive.file(
1519
- "word/styles.xml",
1520
- `<w:styles xmlns:w="${ns}"><w:docDefaults/><w:style w:type="paragraph" w:styleId="base"><w:rPr><w:b/></w:rPr></w:style>${Array.from({ length: 20 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${scenario === "inherited styles" ? '<w:basedOn w:val="base"/>' : ""}<w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}</w:styles>`,
1521
- );
1522
- if (scenario === "default template styles") {
1523
- const heading =
1524
- '<w:style w:type="paragraph" w:styleId="s19"><w:basedOn w:val="Normal"/><w:link w:val="HeadingChar"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="123456"/></w:rPr></w:style>';
1525
- const conditions = [
1526
- "wholeTable",
1527
- "firstRow",
1528
- "lastRow",
1529
- "firstCol",
1530
- "lastCol",
1531
- "band1Horz",
1532
- "band2Horz",
1533
- "band1Vert",
1534
- "band2Vert",
1535
- ];
1536
- archive.file(
1537
- "word/styles.xml",
1538
- `<w:styles xmlns:w="${ns}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:latentStyles>${Array.from({ length: 276 }, (_, i) => `<w:lsdException w:name="latent ${i}" w:semiHidden="0" w:uiPriority="99"/>`).join("")}</w:latentStyles><w:style w:type="paragraph" w:styleId="Normal"/><w:style w:type="character" w:styleId="HeadingChar"><w:rPr><w:b/></w:rPr></w:style>${heading}${Array.from({ length: 61 }, (_, i) => `<w:style w:type="paragraph" w:styleId="p${i}"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}${Array.from({ length: 100 }, (_, i) => `<w:style w:type="table" w:styleId="Table${i}">${i ? '<w:basedOn w:val="Table0"/>' : ""}<w:tblPr><w:tblCellMar><w:top w:w="0"/><w:left w:w="108"/><w:bottom w:w="0"/><w:right w:w="108"/></w:tblCellMar></w:tblPr>${conditions.map((type) => `<w:tblStylePr w:type="${type}"><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:b/><w:color w:val="123456"/></w:rPr><w:tcPr><w:shd w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>`).join("")}</w:style>`).join("")}</w:styles>`,
1539
- );
1540
- archive.file(
1541
- "word/_rels/document.xml.rels",
1542
- (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(
1543
- "</Relationships>",
1544
- `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,
1545
- ),
1546
- );
1547
- archive.file(
1548
- "word/numbering.xml",
1549
- `<w:numbering xmlns:w="${ns}">${Array.from({ length: 9 }, (_, i) => `<w:abstractNum w:abstractNumId="${i}"><w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:tabs><w:tab w:val="num" w:pos="720"/></w:tabs><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="${i + 1}"><w:abstractNumId w:val="${i}"/></w:num>`).join("")}</w:numbering>`,
1550
- );
1551
- const document = await archive.file("word/document.xml")!.async("string");
1552
- archive.file(
1553
- "word/document.xml",
1554
- document.replace(
1555
- "<w:sectPr>",
1556
- '<w:tbl><w:tblPr><w:tblStyle w:val="Table99"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>styled cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:sectPr>',
1557
- ),
1558
- );
1559
- }
1560
- const { prepareOffice } = await import("./officeArchive");
1561
- const prepared = await prepareOffice(
1562
- await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }),
1563
- "docx",
1564
- );
1565
- expect(prepared.truncated).toBe(false);
1566
- const bounded = await JSZip.loadAsync(prepared.bytes);
1567
- const markup = await bounded.file("word/document.xml")!.async("string");
1568
- expect(markup).toContain("ordinary body");
1569
- expect(markup).toContain("styled body");
1570
- expect(bounded.file("word/styles.xml")).not.toBeNull();
1571
- if (scenario === "default template styles") {
1572
- expect(markup).toContain("styled cell");
1573
- expect(await bounded.file("word/styles.xml")!.async("string")).toContain('w:styleId="Table99"');
1574
- }
1575
- if (ordinary) {
1576
- expect(markup).toMatch(/<w:headerReference/);
1577
- expect(markup).toMatch(/<w:footerReference/);
1578
- for (const role of ["header", "footer", "footnotes", "endnotes", "comments"])
1579
- expect(await bounded.file(`word/${role}.xml`)!.async("string")).toContain(`${role} retained`);
1580
- }
1581
-});
1582
-
1583
-it.each([false, true])(
1584
- "bounds shared-string text including CDATA %s per cell and across sheets in the worker",
1585
- async (cdata) => {
1586
- const { default: JSZip } = await import("jszip");
1587
- const archive = new JSZip();
1588
- archive.file(
1589
- "xl/workbook.xml",
1590
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="one" sheetId="1" r:id="s"/><sheet name="two" sheetId="2" r:id="s"/></sheets></workbook>',
1591
- );
1592
- archive.file(
1593
- "xl/_rels/workbook.xml.rels",
1594
- '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
1595
- );
1596
- const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";
1597
- archive.file(
1598
- "xl/_rels/workbook.xml.rels",
1599
- (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(
1600
- "</Relationships>",
1601
- `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,
1602
- ),
1603
- );
1604
- const content = "x".repeat(32_767);
1605
- archive.file(
1606
- `xl/${sharedPath}`,
1607
- `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,
1608
- );
1609
- archive.file(
1610
- "xl/worksheets/sheet1.xml",
1611
- `<worksheet><sheetData>${Array.from({ length: 500 }, (_, i) => `<row r="${i + 1}">${Array.from({ length: 50 }, (_, j) => `<c r="${j < 26 ? String.fromCharCode(65 + j) : "A" + String.fromCharCode(65 + j - 26)}${i + 1}" t="s"><v>${cdata ? "<![CDATA[0]]>" : "0"}</v></c>`).join("")}</row>`).join("")}</sheetData></worksheet>`.replace(
1612
- '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',
1613
- `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,
1614
- ),
1615
- );
1616
- const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1617
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1618
- type: "module",
1619
- });
1620
- try {
1621
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1622
- worker.addEventListener(
1623
- "message",
1624
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1625
- { once: true },
1626
- );
1627
- void file
1628
- .arrayBuffer()
1629
- .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));
1630
- });
1631
- expect(result.type).toBe("xlsx");
1632
- if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
1633
- const bounded = await JSZip.loadAsync(result.bytes);
1634
- const sheet = new DOMParser().parseFromString(
1635
- await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
1636
- "application/xml",
1637
- );
1638
- const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");
1639
- expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);
1640
- expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);
1641
- expect(result.truncated).toBe(true);
1642
- } finally {
1643
- worker.terminate();
1644
- }
1645
- },
1646
-);
1647
-
1648
-// A body just over the read limit once each paragraph repeats its text this often.
1649
-it.each([1, Math.ceil(WORD_LIMITS.bodyBytes / 5_000 / 4)])(
1650
- "counts shared Word settings once with %s text repetitions",
1651
- async (repetitions) => {
1652
- const { default: JSZip } = await import("jszip");
1653
- const archive = new JSZip();
1654
- const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1655
- archive.file(
1656
- "word/document.xml",
1657
- `<w:document xmlns:w="${ns}"><w:body>${`<w:p><w:r><w:t>${"body".repeat(repetitions)}</w:t></w:r></w:p>`.repeat(5_000)}</w:body></w:document>`,
1658
- );
1659
- archive.file(
1660
- "word/_rels/document.xml.rels",
1661
- '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',
1662
- );
1663
- const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;
1664
- archive.file("word/settings.xml", settings);
1665
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
1666
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1667
- type: "module",
1668
- });
1669
- try {
1670
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1671
- worker.addEventListener(
1672
- "message",
1673
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1674
- { once: true },
1675
- );
1676
- worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
1677
- });
1678
- expect(result.type).toBe("docx");
1679
- if (result.type !== "docx") throw new Error("Expected a Word prefix");
1680
- expect(result.truncated).toBe(repetitions > 1);
1681
- const bounded = await JSZip.loadAsync(result.bytes);
1682
- const document = await bounded.file("word/document.xml")!.async("string");
1683
- const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
1684
- expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
1685
- expect(document.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
1686
- expect(retainedSettings).toBe(settings);
1687
- } finally {
1688
- worker.terminate();
1689
- }
1690
- },
1691
-);
1692
-
1693
-it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(
1694
- "bounds Word image expansion for %s",
1695
- async (scenario) => {
1696
- const { default: JSZip } = await import("jszip");
1697
- const archive = new JSZip();
1698
- archive.file(
1699
- "[Content_Types].xml",
1700
- '<Types><Default Extension="png" ContentType="image/png"/></Types>',
1701
- );
1702
- archive.file(
1703
- "word/_rels/document.xml.rels",
1704
- `<Relationships><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${scenario === "XML relationship alias" ? "styles" : "image"}" Target="media/payload.png"/>${scenario === "duplicate relationship ID" ? '<Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/tiny.png"/>' : ""}</Relationships>`,
1705
- );
1706
- archive.file(
1707
- "word/media/payload.png",
1708
- scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),
1709
- );
1710
- if (scenario === "duplicate relationship ID")
1711
- archive.file("word/media/tiny.png", new Uint8Array(1));
1712
- archive.file(
1713
- "word/document.xml",
1714
- `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p>${'<w:r><a:blip r:embed="image"/></w:r>'.repeat(7)}</w:p></w:body></w:document>`,
1715
- );
1716
- const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
1717
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1718
- type: "module",
1719
- });
1720
- try {
1721
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1722
- worker.addEventListener(
1723
- "message",
1724
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1725
- { once: true },
1726
- );
1727
- worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
1728
- });
1729
- expect(result).toMatchObject({
1730
- type: "error",
1731
- message: expect.stringContaining("expanded markup"),
1732
- });
1733
- } finally {
1734
- worker.terminate();
1735
- }
1736
- },
1737
-);
1738
-
1739
-it.each(["XFD200", "XFD300", "XFD1048576", "AX500", "AZ9999999"])(
1740
- "bounds spreadsheet cells at %s before padding",
1741
- async (ref) => {
1742
- const { default: JSZip } = await import("jszip");
1743
- const archive = new JSZip();
1744
- archive.file(
1745
- "xl/workbook.xml",
1746
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',
1747
- );
1748
- // A nonstandard relationship target must get the same bounds.
1749
- archive.file(
1750
- "xl/_rels/workbook.xml.rels",
1751
- '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',
1752
- );
1753
- archive.file(
1754
- "xl/custom.xml",
1755
- `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}">${ref === "XFD300" ? `<c r="${ref}" s="1"/>` : `<c r="${ref}"><v>9</v></c>`}</row></sheetData></worksheet>`,
1756
- );
1757
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
1758
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1759
- type: "module",
1760
- });
1761
- try {
1762
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1763
- worker.addEventListener(
1764
- "message",
1765
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1766
- { once: true },
1767
- );
1768
- worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
1769
- });
1770
- if (ref === "AZ9999999" || ref === "XFD1048576") {
1771
- expect(result).toMatchObject({
1772
- type: "error",
1773
- message: expect.stringContaining(ref === "AZ9999999" ? "invalid" : "preview limit"),
1774
- });
1775
- } else {
1776
- expect(result.type).toBe("xlsx");
1777
- if (result.type !== "xlsx") throw new Error("Expected workbook values");
1778
- const bounded = await JSZip.loadAsync(result.bytes);
1779
- const sheet = new DOMParser().parseFromString(
1780
- await bounded.file("xl/custom.xml")!.async("string"),
1781
- "application/xml",
1782
- );
1783
- expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
1784
- expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
1785
- expect(result.truncated).toBe(ref === "XFD200" || ref === "XFD300");
1786
- if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
1787
- else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
1788
- }
1789
- } finally {
1790
- worker.terminate();
1791
- }
1792
- },
1793
-);
1794
-
1795
-it.each(['<u val="double"/>', '<u val="double"></u>'])(
1796
- "shows workbook formats and underline %s",
1797
- async (underline) => {
1798
- const { default: JSZip } = await import("jszip");
1799
- const archive = new JSZip();
1800
- archive.file(
1801
- "xl/workbook.xml",
1802
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Styles" sheetId="1" r:id="rId1"/></sheets></workbook>',
1803
- );
1804
- archive.file(
1805
- "xl/_rels/workbook.xml.rels",
1806
- '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
1807
- );
1808
- archive.file(
1809
- "xl/styles.xml",
1810
- `<styleSheet><numFmts count="4"><numFmt numFmtId="164" formatCode="0.000"/><numFmt numFmtId="65535" formatCode="0.0000"/><numFmt numFmtId="007" formatCode=""¥"#,##0.00"/><numFmt numFmtId="82" formatCode="[$-010409]dd-mmm-yyyy"/></numFmts><fonts count="2"><font><sz val="11"/></font><font>${underline}<sz val="11"/></font></fonts><cellXfs count="4"><xf numFmtId="0" fontId="0"/><xf numFmtId="7" fontId="0"/><xf numFmtId="82" fontId="0"/><xf numFmtId="0" fontId="1"/></cellXfs></styleSheet>`,
1811
- );
1812
- archive.file(
1813
- "xl/worksheets/sheet1.xml",
1814
- '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>100</v></c><c r="B1" s="2"><v>44986</v></c><c r="C1" s="3" t="inlineStr"><is><t>Total</t></is></c></row></sheetData></worksheet>',
1815
- );
1816
- const { prepareOffice } = await import("./officeArchive");
1817
- const prepared = await prepareOffice(
1818
- await archive.generateAsync({ type: "arraybuffer" }),
1819
- "xlsx",
1820
- );
1821
- const styles = await (
1822
- await JSZip.loadAsync(prepared.bytes)
1823
- )
1824
- .file("xl/styles.xml")!
1825
- .async("string");
1826
- expect(styles).toContain("<font><u/>");
1827
- const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), {
1828
- type: "module",
1829
- });
1830
- try {
1831
- const { createWorkerClient } = await import("./office/worker-rpc");
1832
- const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1833
- const bytes = prepared.bytes;
1834
- await client.call("open", { bytes, view: prepared.view! }, { transfer: [bytes] });
1835
- const cells = await client.call("cells", {
1836
- sheet: 0,
1837
- range: { top: 0, bottom: 0, left: 0, right: 1 },
1838
- });
1839
- // Ids under 164 that a workbook defines keep its formats, not Excel's built-in ones.
1840
- expect(cells[0]).toEqual(["¥100.00", "01-Mar-2023"]);
1841
- } finally {
1842
- worker.terminate();
1843
- }
1844
- archive.file("xl/styles.xml", "<styleSheet><numFmts/><numFmts/></styleSheet>");
1845
- await expect(
1846
- prepareOffice(await archive.generateAsync({ type: "arraybuffer" }), "xlsx"),
1847
- ).rejects.toThrow("duplicate stylesheet blocks");
1848
- },
1849
-);
1850
-
1851
-it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
1852
- const { default: JSZip } = await import("jszip");
1853
- const archive = new JSZip();
1854
- archive.file(
1855
- "xl/workbook.xml",
1856
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',
1857
- );
1858
- archive.file(
1859
- "xl/_rels/workbook.xml.rels",
1860
- '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
1861
- );
1862
- archive.file(
1863
- "xl/styles.xml",
1864
- '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',
1865
- );
1866
- archive.file(
1867
- "xl/worksheets/sheet1.xml",
1868
- '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',
1869
- );
1870
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
1871
- const workerModule = new URL(
1872
- "./office/spreadsheet.worker.ts?worker_file&type=module",
1873
- import.meta.url,
1874
- ).href;
1875
- // Give the worker a west-of-UTC default while preserving explicit format options.
1876
- const bootstrap = URL.createObjectURL(
1877
- new Blob(
1878
- [
1879
- `
1880
- const NativeURL = URL;
1881
- globalThis.URL = class extends NativeURL {
1882
- constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }
1883
- };
1884
- const format = Date.prototype.toLocaleDateString;
1885
- Date.prototype.toLocaleDateString = function(locale, options) {
1886
- return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });
1887
- };
1888
- await import(${JSON.stringify(workerModule)});
1889
- postMessage({ type: "ready" });
1890
- `,
1891
- ],
1892
- { type: "text/javascript" },
1893
- ),
1894
- );
1895
- const worker = new Worker(bootstrap, { type: "module" });
1896
- try {
1897
- await new Promise<void>((resolve, reject) => {
1898
- worker.addEventListener(
1899
- "message",
1900
- (event) => {
1901
- if (event.data.type === "ready") resolve();
1902
- },
1903
- { once: true },
1904
- );
1905
- worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });
1906
- });
1907
- const { createWorkerClient } = await import("./office/worker-rpc");
1908
- const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1909
- await client.call(
1910
- "open",
1911
- {
1912
- bytes,
1913
- view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
1914
- },
1915
- { transfer: [bytes] },
1916
- );
1917
- const cells = await client.call("cells", {
1918
- sheet: 0,
1919
- range: { top: 0, bottom: 0, left: 0, right: 0 },
1920
- });
1921
- expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);
1922
- } finally {
1923
- worker.terminate();
1924
- URL.revokeObjectURL(bootstrap);
1925
- }
1926
-});
1927
-
1928
-it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async (pages) => {
1929
- const { default: JSZip } = await import("jszip");
1930
- const archive = new JSZip();
1931
- const paragraph = (text: string) =>
1932
- `<w:p><w:pPr><w:spacing w:after="120"/><w:jc w:val="left"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Calibri"/><w:sz w:val="22"/></w:rPr><w:t>${text}</w:t></w:r></w:p>`;
1933
- archive.file(
1934
- "word/document.xml",
1935
- `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${Array.from({ length: pages }, (_, page) => paragraph(`page ${page + 1}`) + `<w:tbl>${Array.from({ length: 10 }, () => `<w:tr>${Array.from({ length: 5 }, () => `<w:tc><w:tcPr><w:tcW w:w="1800"/></w:tcPr>${paragraph("report entry")}</w:tc>`).join("")}</w:tr>`).join("")}</w:tbl>`).join("")}</w:body></w:document>`,
1936
- );
1937
- archive.file(
1938
- "_rels/.rels",
1939
- '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
1940
- );
1941
- archive.file(
1942
- "[Content_Types].xml",
1943
- '<Types><Default Extension="png" ContentType="image/png"/></Types>',
1944
- );
1945
- // Binary media must not consume the document's markup budget.
1946
- archive.file("word/media/image.png", new Uint8Array(2_500_000));
1947
- const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1948
- await using screen = await render(
1949
- <AttachmentFilePreview
1950
- name="report.docx"
1951
- mimeType="application/octet-stream"
1952
- file={file}
1953
- sizeBytes={file.size}
1954
- />,
1955
- );
1956
- // The first Office preview in the file loads the lazy viewer chain and the preparation worker.
1957
- await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1958
- timeout: 10_000,
1959
- });
1960
- expect(screen.container.textContent).not.toContain("Preview limited");
1961
- expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1962
-});
1963
-
923
describe("standalone Mermaid previews", () => {
924
it.each([
925
'A@{ "img": "//attacker.invalid/pixel.png" }',
apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx
new
+1086
@@ -0,0 +1,1086 @@
1
+import { act, render } from "../../../test/render";
2
+import { expect, it, vi } from "vite-plus/test";
3
+import "~/index.css";
4
+
5
+const { refresh, assetUrlState } = vi.hoisted(() => ({
6
+ refresh: vi.fn<() => Promise<string | null>>(),
7
+ assetUrlState: vi.fn<() => import("~/assets/assetUrls").AssetUrlState>(),
8
+}));
9
+
10
+vi.mock(import("~/assets/assetUrls"), async (original) => ({
11
+ ...(await original()),
12
+ useAssetUrlRefresh: () => refresh,
13
+ useAssetUrlState: assetUrlState,
14
+}));
15
+// The real source view highlights through a worker pool; the text it receives is what matters here.
16
+// Never load the original: its highlighter graph can outlast waitFor on a cold CI browser.
17
+vi.mock(import("./ReadOnlySourcePreview"), () => ({
18
+ default: ({ text, wordWrap }: { text: string; wordWrap?: boolean }) => (
19
+ <pre data-word-wrap={String(wordWrap)}>{text}</pre>
20
+ ),
21
+}));
22
+
23
+// The Word engine compiles about 30 MB of WebAssembly in a fresh worker per document, which took
24
+// 10-17 s per test on loaded CI runners. These tests cover fetching, preparation and remounts, so
25
+// the stand-in shows the prepared body's text instead of laying it out.
26
+vi.mock(import("./office/WordDocument"), async () => {
27
+ const { use } = await import("react");
28
+ const { default: Zip } = await import("jszip");
29
+ const texts = new WeakMap<ArrayBuffer, Promise<string>>();
30
+ const read = (bytes: ArrayBuffer) =>
31
+ Zip.loadAsync(bytes)
32
+ .then((zip) => zip.file("word/document.xml")!.async("string"))
33
+ .then((xml) => xml.replace(/<[^>]+>/g, " "));
34
+ return {
35
+ default: ({ bytes }: { bytes: ArrayBuffer }) => {
36
+ let text = texts.get(bytes);
37
+ if (!text) texts.set(bytes, (text = read(bytes)));
38
+ return <pre>{use(text)}</pre>;
39
+ },
40
+ };
41
+});
42
+
43
+import { AttachmentFilePreview } from "./AttachmentFilePreview";
44
+import JSZip from "jszip";
45
+import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";
46
+import { WORD_LIMITS } from "./officeArchive";
47
+
48
+it.each(["<w:body/>", "<w:body></w:body>"])(
49
+ "opens an empty Word document with %s",
50
+ async (body) => {
51
+ const { default: JSZip } = await import("jszip");
52
+ const { prepareOffice } = await import("./officeArchive");
53
+ const archive = new JSZip().file(
54
+ "word/document.xml",
55
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:document>`,
56
+ );
57
+ const prepared = await prepareOffice(
58
+ await archive.generateAsync({ type: "arraybuffer" }),
59
+ "docx",
60
+ );
61
+ const result = await JSZip.loadAsync(prepared.bytes);
62
+ const xml = new DOMParser().parseFromString(
63
+ await result.file("word/document.xml")!.async("string"),
64
+ "application/xml",
65
+ );
66
+ expect(xml.querySelector("parsererror")).toBeNull();
67
+ expect(
68
+ xml.getElementsByTagNameNS(
69
+ "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
70
+ "body",
71
+ ),
72
+ ).toHaveLength(1);
73
+ },
74
+);
75
+
76
+it.each([false, true])(
77
+ "rejects excessive archive entries before JSZip (directories: %s)",
78
+ async (directories) => {
79
+ const { default: JSZip } = await import("jszip");
80
+ const { prepareOffice } = await import("./officeArchive");
81
+ const archive = new JSZip();
82
+ for (let i = 0; i < 4096; i++)
83
+ archive.file(`entry-${i}${directories ? "/" : ".txt"}`, "", { dir: directories });
84
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
85
+ const load = vi.spyOn(JSZip, "loadAsync");
86
+ try {
87
+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
88
+ expect(load).not.toHaveBeenCalled();
89
+ // The actual central-directory records must also be bounded if EOCD lies.
90
+ const view = new DataView(bytes);
91
+ view.setUint16(bytes.byteLength - 22 + 8, 1, true);
92
+ view.setUint16(bytes.byteLength - 22 + 10, 1, true);
93
+ await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
94
+ expect(load).not.toHaveBeenCalled();
95
+ } finally {
96
+ load.mockRestore();
97
+ }
98
+ },
99
+);
100
+
101
+it("rejects oversized embedded images before decoding pixels and retains ordinary images", async () => {
102
+ const { officeImageBitmap } = await import("./office/image-bitmap");
103
+ const canvas = new OffscreenCanvas(2, 3);
104
+ canvas.getContext("2d");
105
+ const blob = await canvas.convertToBlob({ type: "image/png" });
106
+ const bytes = await blob.arrayBuffer();
107
+ new DataView(bytes).setUint32(16, 12000);
108
+ new DataView(bytes).setUint32(20, 12000);
109
+ const decode = vi.spyOn(globalThis, "createImageBitmap");
110
+ try {
111
+ await expect(officeImageBitmap(new Blob([bytes]))).rejects.toThrow("pixel limit");
112
+ expect(decode).not.toHaveBeenCalled();
113
+ const bitmap = await officeImageBitmap(blob);
114
+ expect([bitmap.width, bitmap.height]).toEqual([2, 3]);
115
+ bitmap.close();
116
+ } finally {
117
+ decode.mockRestore();
118
+ }
119
+});
120
+
121
+it.each(["utf-16le", "utf-16be", "windows-1252"])(
122
+ "preserves %s Office XML and safe hyperlink targets",
123
+ async (encoding) => {
124
+ const { default: JSZip } = await import("jszip");
125
+ const { prepareOffice } = await import("./officeArchive");
126
+ const archive = new JSZip();
127
+ const encode = (text: string) => {
128
+ const xml = `<?xml version="1.0" encoding="${encoding}"?>${text}`;
129
+ if (encoding === "windows-1252") return Uint8Array.from(xml, (char) => char.charCodeAt(0));
130
+ const bytes = new Uint8Array(2 + xml.length * 2);
131
+ const view = new DataView(bytes.buffer);
132
+ const little = encoding === "utf-16le";
133
+ view.setUint16(0, 0xfeff, little);
134
+ for (let i = 0; i < xml.length; i++) view.setUint16(2 + i * 2, xml.charCodeAt(i), little);
135
+ return bytes;
136
+ };
137
+ archive.file(
138
+ "word/document.xml",
139
+ encode(
140
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>café</w:t></w:r></w:p></w:body></w:document>',
141
+ ),
142
+ );
143
+ archive.file(
144
+ "word/_rels/document.xml.rels",
145
+ encode(
146
+ `<Relationships>${["https://example.com/page", "http://example.com", "mailto:maria@example.com", "javascript:alert(1)", "file:///tmp/private"].map((target, i) => `<Relationship Id="r${i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" TargetMode="External" Target="${target}"/>`).join("")}</Relationships>`,
147
+ ),
148
+ );
149
+ const prepared = await prepareOffice(
150
+ await archive.generateAsync({ type: "arraybuffer" }),
151
+ "docx",
152
+ );
153
+ const result = await JSZip.loadAsync(prepared.bytes);
154
+ expect(await result.file("word/document.xml")!.async("string")).toContain("café");
155
+ const links = await result.file("word/_rels/document.xml.rels")!.async("string");
156
+ expect(links).toContain('encoding="UTF-8"');
157
+ expect(links).toContain("https://example.com/page");
158
+ expect(links).toContain("http://example.com");
159
+ expect(links).toContain("mailto:maria@example.com");
160
+ expect(links).not.toContain("javascript:");
161
+ expect(links).not.toContain("file:");
162
+ },
163
+);
164
+
165
+it.each([
166
+ ["", "worksheets/./sheet1.xml", false, false],
167
+ ["x:", "../xl/worksheets/sheet1.xml", false, false],
168
+ ["", "/xl/worksheets/sheet1.xml", true, false],
169
+ ["", "worksheets/sheet1.xml", false, true],
170
+ ["", "worksheets/sheet1.xml", true, true],
171
+])(
172
+ "preserves %sworksheet metadata with relationship target %s",
173
+ async (prefix, target, empty, localPrefix) => {
174
+ const { default: JSZip } = await import("jszip");
175
+ const archive = new JSZip();
176
+ const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
177
+ archive.file(
178
+ "xl/workbook.xml",
179
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Chart" sheetId="2" r:id="c"/><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
180
+ );
181
+ archive.file(
182
+ "xl/_rels/workbook.xml.rels",
183
+ `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/><Relationship Id="c" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet1.xml"/></Relationships>`,
184
+ );
185
+ archive.file(
186
+ "xl/worksheets/sheet1.xml",
187
+ `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}sheetViews><${prefix}sheetView showGridLines="0"/></${prefix}sheetViews><${prefix}sheetFormatPr defaultColWidth="30"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
188
+ .replace(
189
+ /<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g,
190
+ prefix ? "<$1$2></$1>" : "$&",
191
+ )
192
+ .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
193
+ .replace(/<(\/?)sheetData\b/g, (tag, closing: string) =>
194
+ localPrefix ? `<${closing}x:sheetData${closing ? "" : ` xmlns:x="${ns}"`}` : tag,
195
+ )
196
+ .replace(/="([^"]*)"/g, (attribute, value: string) =>
197
+ prefix || empty
198
+ ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
199
+ : attribute,
200
+ ),
201
+ );
202
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
203
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
204
+ type: "module",
205
+ });
206
+ try {
207
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
208
+ worker.addEventListener(
209
+ "message",
210
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
211
+ { once: true },
212
+ );
213
+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
214
+ });
215
+ expect(result.type).toBe("xlsx");
216
+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
217
+ // The engine counts the chart sheet before it.
218
+ expect(result.view?.hiddenGridlines).toEqual([1]);
219
+ const bounded = await JSZip.loadAsync(result.bytes);
220
+ const sheet = new DOMParser().parseFromString(
221
+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
222
+ "application/xml",
223
+ );
224
+ expect(sheet.querySelector("parsererror")).toBeNull();
225
+ const row = sheet.getElementsByTagNameNS(ns, "row")[0];
226
+ if (empty) expect(row).toBeUndefined();
227
+ else {
228
+ expect(row!.getAttribute("ht")).toBe("42");
229
+ expect(row!.getAttribute("hidden")).toBe("1");
230
+ expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
231
+ expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
232
+ }
233
+ expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
234
+ expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
235
+ const columns = [...sheet.getElementsByTagNameNS(ns, "col")].map((column) =>
236
+ ["min", "max", "width"].map((name) => column.getAttribute(name)),
237
+ );
238
+ // The engine ignores `defaultColWidth`, so the columns it sizes are spelled out.
239
+ expect(columns).toEqual([
240
+ [String(OFFICE_PREVIEW_MAX_COLUMNS - 1), String(OFFICE_PREVIEW_MAX_COLUMNS), "20"],
241
+ // Hidden columns keep their span past the limit, so they stay hidden.
242
+ [String(OFFICE_PREVIEW_MAX_COLUMNS + 1), String(OFFICE_PREVIEW_MAX_COLUMNS + 30), null],
243
+ ["1", String(OFFICE_PREVIEW_MAX_COLUMNS - 2), "30"],
244
+ ]);
245
+ } finally {
246
+ worker.terminate();
247
+ }
248
+ },
249
+);
250
+
251
+it("reports the final slide at maximum scroll after page visibility changes", async () => {
252
+ const { OfficePages } = await import("./office/OfficePages");
253
+ const changed = vi.fn();
254
+ const container = document.createElement("div");
255
+ container.style.cssText = "display:flex;flex-direction:column;width:400px;height:400px";
256
+ await using screen = await render(
257
+ <OfficePages
258
+ pages={Array.from({ length: 6 }, () => ({ width: 400, height: 240 }))}
259
+ label="Slide"
260
+ paint={async () => undefined}
261
+ onPageChange={changed}
262
+ onError={(error) => {
263
+ throw error;
264
+ }}
265
+ />,
266
+ { container },
267
+ );
268
+ const scroller = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
269
+ await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight));
270
+ await act(() => {
271
+ scroller.scrollTop = scroller.scrollHeight;
272
+ });
273
+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(5));
274
+ await act(() => {
275
+ scroller.scrollTop = 10;
276
+ });
277
+ await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(0));
278
+});
279
+
280
+it("preserves merged text across tile clears", async () => {
281
+ const { paintFrame } = await import("./office/sheet-frame");
282
+ const canvas = new OffscreenCanvas(400, 80);
283
+ const context = canvas.getContext("2d")!;
284
+ paintFrame(
285
+ context,
286
+ {
287
+ viewport: { x: 0, y: 0, width: 400, height: 80 },
288
+ list: { width: 400, height: 80, commands: [] },
289
+ tiles: [
290
+ {
291
+ x: 0,
292
+ y: 0,
293
+ clipX: 0,
294
+ clipY: 0,
295
+ list: {
296
+ width: 208,
297
+ height: 80,
298
+ commands: [
299
+ {
300
+ op: "text",
301
+ x: 2,
302
+ y: 40,
303
+ text: "MMMMMMMMMMMMMMMMMMMMMMMM",
304
+ fontSize: 20,
305
+ color: "#000",
306
+ clip: { x: 0, y: 0, w: 400, h: 80 },
307
+ },
308
+ ],
309
+ },
310
+ },
311
+ { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },
312
+ ],
313
+ },
314
+ { ratio: 1, origin: { x: 0, y: 0 } },
315
+ );
316
+ const pixels = context.getImageData(240, 15, 100, 35).data;
317
+ expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
318
+});
319
+
320
+it.each([
321
+ "paragraphs",
322
+ "runs",
323
+ "tables",
324
+ "auxiliary XML",
325
+ "XML bytes",
326
+ "renamed XML",
327
+ "section after prefix",
328
+ "oversized section",
329
+])("bounds excessive Word %s before rendering DOM", async (scenario) => {
330
+ const { default: JSZip } = await import("jszip");
331
+ const archive = new JSZip();
332
+ const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)
333
+ ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)
334
+ : scenario === "runs"
335
+ ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
336
+ : scenario === "tables"
337
+ ? "<w:tbl/>".repeat(2 * WORD_LIMITS.bodyElements)
338
+ : scenario === "XML bytes"
339
+ ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
340
+ : "<w:p/>";
341
+ const section =
342
+ '<w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:left="1440" w:bottom="1440" w:right="1440"/></w:sectPr>';
343
+ archive.file(
344
+ "word/document.xml",
345
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}${scenario === "section after prefix" ? '<w:p xmlns:s="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:pPr><s:sectPr><s:pgSz s:w="11906" s:h="16838"/></s:sectPr></w:pPr></w:p>' : ""}${scenario === "oversized section" ? `<w:sectPr>${"<w:cols/>".repeat(2_001)}</w:sectPr>` : section}</w:body></w:document>`,
346
+ );
347
+ if (scenario === "auxiliary XML" || scenario === "renamed XML")
348
+ archive.file(
349
+ scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
350
+ `<w:footnotes>${"<w:p/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</w:footnotes>`,
351
+ );
352
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
353
+ const src = URL.createObjectURL(file);
354
+ try {
355
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
356
+ type: "module",
357
+ });
358
+ try {
359
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
360
+ worker.addEventListener(
361
+ "message",
362
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
363
+ { once: true },
364
+ );
365
+ void file
366
+ .arrayBuffer()
367
+ .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));
368
+ });
369
+ if (
370
+ scenario === "auxiliary XML" ||
371
+ scenario === "renamed XML" ||
372
+ scenario === "oversized section"
373
+ ) {
374
+ expect(result).toMatchObject({
375
+ type: "error",
376
+ message: expect.stringContaining("Preview limited"),
377
+ });
378
+ } else {
379
+ expect(result.type).toBe("docx");
380
+ if (result.type !== "docx") throw new Error("Expected a Word prefix");
381
+ expect(result.truncated).toBe(true);
382
+ const bounded = await JSZip.loadAsync(result.bytes);
383
+ const markup = await bounded.file("word/document.xml")!.async("string");
384
+ {
385
+ const xml = markup;
386
+ const document = new DOMParser().parseFromString(xml, "application/xml");
387
+ expect(document.querySelector("parsererror")).toBeNull();
388
+ const bodies = document.getElementsByTagNameNS("*", "body");
389
+ expect(bodies).toHaveLength(1);
390
+ const section = bodies[0]!.lastElementChild!;
391
+ expect(section.localName).toBe("sectPr");
392
+ const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;
393
+ expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(
394
+ scenario === "section after prefix" ? "11906" : "16838",
395
+ );
396
+ expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(
397
+ scenario === "section after prefix" ? null : "landscape",
398
+ );
399
+ }
400
+ expect(markup.length).toBeLessThan(body.length);
401
+ expect(markup.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
402
+ expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(WORD_LIMITS.bodyTags);
403
+ }
404
+ } finally {
405
+ worker.terminate();
406
+ }
407
+ } finally {
408
+ URL.revokeObjectURL(src);
409
+ }
410
+});
411
+
412
+it.each([
413
+ "relationship markup",
414
+ "relationship bytes",
415
+ "content type",
416
+ "metadata type",
417
+ "deep XML",
418
+ "query path",
419
+])("bounds XML hidden in media by %s", async (scenario) => {
420
+ const { default: JSZip } = await import("jszip");
421
+ const archive = new JSZip();
422
+ const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;
423
+ archive.file(
424
+ "word/document.xml",
425
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',
426
+ );
427
+ archive.file(
428
+ "[Content_Types].xml",
429
+ `<Types><Override PartName="/${path}" ContentType="${scenario === "content type" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" : "image/png"}"/>${scenario === "metadata type" ? '<Default Extension="rels" ContentType="image/png"/>' : ""}</Types>`,
430
+ );
431
+ archive.file(
432
+ "word/_rels/document.xml.rels",
433
+ `<Relationships>${scenario === "content type" ? "" : `<Relationship Id="style" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="${path.slice(5)}"/>`}${scenario === "metadata type" ? "<unused/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1) : ""}</Relationships>`,
434
+ );
435
+ archive.file(
436
+ path,
437
+ scenario === "relationship bytes"
438
+ ? `<styles>${"x".repeat(WORD_LIMITS.auxiliaryPartBytes)}</styles>`
439
+ : scenario === "deep XML"
440
+ ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
441
+ : `<styles>${"<style/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</styles>`,
442
+ );
443
+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
444
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
445
+ type: "module",
446
+ });
447
+ try {
448
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
449
+ worker.addEventListener(
450
+ "message",
451
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
452
+ { once: true },
453
+ );
454
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
455
+ });
456
+ expect(result).toMatchObject({
457
+ type: "error",
458
+ message: expect.stringContaining("Preview limited"),
459
+ });
460
+ } finally {
461
+ worker.terminate();
462
+ }
463
+});
464
+
465
+const EXPANDED_WORD_ROLES = [
466
+ "footnotes",
467
+ "note roots",
468
+ "endnotes",
469
+ "header",
470
+ "footer",
471
+ "comments",
472
+ "styles",
473
+ "style chain",
474
+ "style count",
475
+ "style visits",
476
+ "numbering",
477
+ "picture numbering",
478
+] as const;
479
+
480
+async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
481
+ const archive = new JSZip();
482
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
483
+ const type = role.startsWith("style")
484
+ ? "styles"
485
+ : role === "picture numbering"
486
+ ? "numbering"
487
+ : role === "note roots"
488
+ ? "footnotes"
489
+ : role;
490
+ archive.file(
491
+ "_rels/.rels",
492
+ '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
493
+ );
494
+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
495
+ // Each copy of the 2,000-paragraph payload costs 6,000 markup units, so enough
496
+ // references (or pages) exceed the expansion budget.
497
+ const copies = Math.ceil(WORD_LIMITS.expandedMarkup / 6_000) + 1;
498
+ archive.file(
499
+ "word/document.xml",
500
+ `<w:document xmlns:w="${ns}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${text("body retained")}${Array.from({ length: copies }, () => `<w:p><w:r><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/><w:br w:type="page"/></w:r></w:p>`).join("")}<w:sectPr><w:headerReference w:type="default" r:id="aux"/><w:footerReference w:type="default" r:id="aux"/></w:sectPr></w:body></w:document>`,
501
+ );
502
+ archive.file(
503
+ "word/_rels/document.xml.rels",
504
+ `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,
505
+ );
506
+ const xml =
507
+ role === "style chain" || role === "style count" || role === "style visits"
508
+ ? `<w:styles xmlns:w="${ns}">${Array.from({ length: role === "style count" ? WORD_LIMITS.styles + 1 : role === "style visits" ? Math.ceil(WORD_LIMITS.styleVisits / 30) + 1 : 1_000 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${i ? `<w:basedOn w:val="s${role === "style visits" && i >= 30 ? 29 : i - 1}"/>` : ""}<w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
509
+ : role === "styles"
510
+ ? `<w:styles xmlns:w="${ns}">${Array.from({ length: 100 }, (_, i) => `<w:style w:styleId="${"s".repeat(2_000)}${i}" w:type="paragraph"><w:basedOn w:val="s0"/><w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
511
+ : role.includes("numbering")
512
+ ? `<w:numbering xmlns:w="${ns}">${role === "picture numbering" ? '<w:numPicBullet w:numPicBulletId="1"/>' : ""}<w:abstractNum w:abstractNumId="1">${Array.from({ length: 9 }, (_, i) => `<w:lvl w:ilvl="${i}"><w:lvlText w:val="%1."/></w:lvl>`).join("")}</w:abstractNum>${Array.from({ length: WORD_LIMITS.numberingReferences + 1 }, (_, i) => `<w:num w:numId="${i}"><w:abstractNumId w:val="1"/></w:num>`).join("")}</w:numbering>`
513
+ : role === "header" || role === "footer"
514
+ ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
515
+ : `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1">${text("omitted payload").repeat(2_000)}</w:${role.slice(0, -1)}></w:${role}>`;
516
+ archive.file("word/media/aux.xml", xml);
517
+ if (role === "note roots") {
518
+ // Each note's XML repeats the 32 KB root, which the expansion budget charges twice.
519
+ const notes = Math.ceil(WORD_LIMITS.expandedBytes / 64_000) + 1;
520
+ archive.file(
521
+ "word/document.xml",
522
+ `<w:document xmlns:w="${ns}"><w:body>${text("body retained")}${Array.from({ length: notes }, (_, id) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`).join("")}</w:body></w:document>`,
523
+ );
524
+ archive.file(
525
+ "word/media/aux.xml",
526
+ `<w:footnotes xmlns:w="${ns}" padding="${"x".repeat(32_000)}">${Array.from({ length: notes }, (_, id) => `<w:footnote w:id="${id}">${text("omitted payload")}</w:footnote>`).join("")}</w:footnotes>`,
527
+ );
528
+ }
529
+ return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
530
+}
531
+
532
+// Rendering starts a Word engine worker per case, which compiles about 30 MB of WebAssembly and
533
+// took 10-17 s per test on loaded CI runners. Omission and retention are prepareOffice decisions,
534
+// so they are checked there.
535
+it.each(EXPANDED_WORD_ROLES)(
536
+ "keeps the body and omits expanded %s from the prepared document",
537
+ async (role) => {
538
+ const file = await expandedWordFixture(role);
539
+ const { SaxesParser } = await import("saxes");
540
+ const { prepareOffice } = await import("./officeArchive");
541
+ const parse = vi.spyOn(SaxesParser.prototype, "write");
542
+ try {
543
+ const prepared = await prepareOffice(await file.arrayBuffer(), "docx");
544
+ expect(prepared.truncated).toBe(true);
545
+ if (role === "note roots")
546
+ expect(
547
+ parse.mock.calls.reduce(
548
+ (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
549
+ 0,
550
+ ),
551
+ ).toBeLessThan(WORD_LIMITS.expandedBytes + 4 * 1024 * 1024);
552
+ const bounded = await JSZip.loadAsync(prepared.bytes);
553
+ const markup = await bounded.file("word/document.xml")!.async("string");
554
+ expect(markup).toContain("body retained");
555
+ expect(bounded.file("word/media/aux.xml")).toBeNull();
556
+ // A dangling header or footer reference makes the engine reject the whole body.
557
+ expect(markup).not.toMatch(/<w:(header|footer)Reference/);
558
+ for (const entry of Object.values(bounded.files))
559
+ if (!entry.dir) expect(await entry.async("string")).not.toContain("omitted payload");
560
+ } finally {
561
+ parse.mockRestore();
562
+ }
563
+ },
564
+);
565
+
566
+it.each([
567
+ "ordinary parts",
568
+ "unused parts",
569
+ "independent styles",
570
+ "inherited styles",
571
+ "python-docx package",
572
+ "default template styles",
573
+ "binary package properties",
574
+])("retains Word %s without a limit warning", async (scenario) => {
575
+ const { default: JSZip } = await import("jszip");
576
+ const archive = new JSZip();
577
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
578
+ const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
579
+ const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
580
+ archive.file(
581
+ "_rels/.rels",
582
+ `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,
583
+ );
584
+ if (scenario === "python-docx package" || scenario === "binary package properties") {
585
+ const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
586
+ archive.file(
587
+ "_rels/.rels",
588
+ `<Relationships xmlns="${packageRelationships}"><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/><Relationship Id="thumbnail" Type="${packageRelationships}/metadata/thumbnail" Target="docProps/thumbnail.jpeg"/><Relationship Id="core" Type="${packageRelationships}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="app" Type="${r}/extended-properties" Target="docProps/app.xml"/><Relationship Id="custom" Type="${r}/custom-properties" Target="docProps/custom.xml"/><Relationship Id="signature" Type="${packageRelationships}/digital-signature/origin" Target="_xmlsignatures/origin.sigs"/></Relationships>`,
589
+ );
590
+ archive.file(
591
+ "[Content_Types].xml",
592
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/></Types>',
593
+ );
594
+ archive.file(
595
+ "docProps/thumbnail.jpeg",
596
+ new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),
597
+ );
598
+ archive.file("_xmlsignatures/origin.sigs", new Uint8Array());
599
+ for (const part of ["core", "app", "custom"])
600
+ archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');
601
+ if (scenario === "binary package properties") {
602
+ const roles = [
603
+ `${packageRelationships}/metadata/core-properties`,
604
+ `${r}/extended-properties`,
605
+ `${packageRelationships}/metadata/custom-properties`,
606
+ `${packageRelationships}/digital-signature/signature`,
607
+ ];
608
+ archive.file(
609
+ "_rels/.rels",
610
+ `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/>${roles.map((role, i) => `<Relationship Id="metadata${i}" Type="${role}" Target="docProps/metadata${i}.dat"/>`).join("")}</Relationships>`,
611
+ );
612
+ for (const i of roles.keys())
613
+ archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));
614
+ }
615
+ }
616
+ const ordinary = scenario === "ordinary parts";
617
+ archive.file(
618
+ "word/document.xml",
619
+ `<w:document xmlns:w="${ns}" xmlns:r="${r}"><w:body>${text("ordinary body")}<w:p><w:pPr><w:pStyle w:val="s19"/></w:pPr><w:r><w:t>styled body</w:t>${ordinary ? '<w:footnoteReference w:id="1"/><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/>' : ""}</w:r></w:p><w:sectPr>${ordinary ? '<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>' : ""}</w:sectPr></w:body></w:document>`,
620
+ );
621
+ archive.file(
622
+ "word/_rels/document.xml.rels",
623
+ `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,
624
+ );
625
+ for (const [role, root] of [
626
+ ["header", "hdr"],
627
+ ["footer", "ftr"],
628
+ ])
629
+ archive.file(
630
+ `word/${role}.xml`,
631
+ `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,
632
+ );
633
+ for (const role of ["footnotes", "endnotes", "comments"])
634
+ archive.file(
635
+ `word/${role}.xml`,
636
+ `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1" w:author="reviewer" w:date="2026-10-01T00:00:00Z">${text(`${role} retained`)}</w:${role.slice(0, -1)}></w:${role}>`,
637
+ );
638
+ archive.file(
639
+ "word/fontTable.xml",
640
+ `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,
641
+ );
642
+ archive.file(
643
+ "word/styles.xml",
644
+ `<w:styles xmlns:w="${ns}"><w:docDefaults/><w:style w:type="paragraph" w:styleId="base"><w:rPr><w:b/></w:rPr></w:style>${Array.from({ length: 20 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${scenario === "inherited styles" ? '<w:basedOn w:val="base"/>' : ""}<w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}</w:styles>`,
645
+ );
646
+ if (scenario === "default template styles") {
647
+ const heading =
648
+ '<w:style w:type="paragraph" w:styleId="s19"><w:basedOn w:val="Normal"/><w:link w:val="HeadingChar"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="123456"/></w:rPr></w:style>';
649
+ const conditions = [
650
+ "wholeTable",
651
+ "firstRow",
652
+ "lastRow",
653
+ "firstCol",
654
+ "lastCol",
655
+ "band1Horz",
656
+ "band2Horz",
657
+ "band1Vert",
658
+ "band2Vert",
659
+ ];
660
+ archive.file(
661
+ "word/styles.xml",
662
+ `<w:styles xmlns:w="${ns}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:latentStyles>${Array.from({ length: 276 }, (_, i) => `<w:lsdException w:name="latent ${i}" w:semiHidden="0" w:uiPriority="99"/>`).join("")}</w:latentStyles><w:style w:type="paragraph" w:styleId="Normal"/><w:style w:type="character" w:styleId="HeadingChar"><w:rPr><w:b/></w:rPr></w:style>${heading}${Array.from({ length: 61 }, (_, i) => `<w:style w:type="paragraph" w:styleId="p${i}"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}${Array.from({ length: 100 }, (_, i) => `<w:style w:type="table" w:styleId="Table${i}">${i ? '<w:basedOn w:val="Table0"/>' : ""}<w:tblPr><w:tblCellMar><w:top w:w="0"/><w:left w:w="108"/><w:bottom w:w="0"/><w:right w:w="108"/></w:tblCellMar></w:tblPr>${conditions.map((type) => `<w:tblStylePr w:type="${type}"><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:b/><w:color w:val="123456"/></w:rPr><w:tcPr><w:shd w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>`).join("")}</w:style>`).join("")}</w:styles>`,
663
+ );
664
+ archive.file(
665
+ "word/_rels/document.xml.rels",
666
+ (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(
667
+ "</Relationships>",
668
+ `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,
669
+ ),
670
+ );
671
+ archive.file(
672
+ "word/numbering.xml",
673
+ `<w:numbering xmlns:w="${ns}">${Array.from({ length: 9 }, (_, i) => `<w:abstractNum w:abstractNumId="${i}"><w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:tabs><w:tab w:val="num" w:pos="720"/></w:tabs><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="${i + 1}"><w:abstractNumId w:val="${i}"/></w:num>`).join("")}</w:numbering>`,
674
+ );
675
+ const document = await archive.file("word/document.xml")!.async("string");
676
+ archive.file(
677
+ "word/document.xml",
678
+ document.replace(
679
+ "<w:sectPr>",
680
+ '<w:tbl><w:tblPr><w:tblStyle w:val="Table99"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>styled cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:sectPr>',
681
+ ),
682
+ );
683
+ }
684
+ const { prepareOffice } = await import("./officeArchive");
685
+ const prepared = await prepareOffice(
686
+ await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }),
687
+ "docx",
688
+ );
689
+ expect(prepared.truncated).toBe(false);
690
+ const bounded = await JSZip.loadAsync(prepared.bytes);
691
+ const markup = await bounded.file("word/document.xml")!.async("string");
692
+ expect(markup).toContain("ordinary body");
693
+ expect(markup).toContain("styled body");
694
+ expect(bounded.file("word/styles.xml")).not.toBeNull();
695
+ if (scenario === "default template styles") {
696
+ expect(markup).toContain("styled cell");
697
+ expect(await bounded.file("word/styles.xml")!.async("string")).toContain('w:styleId="Table99"');
698
+ }
699
+ if (ordinary) {
700
+ expect(markup).toMatch(/<w:headerReference/);
701
+ expect(markup).toMatch(/<w:footerReference/);
702
+ for (const role of ["header", "footer", "footnotes", "endnotes", "comments"])
703
+ expect(await bounded.file(`word/${role}.xml`)!.async("string")).toContain(`${role} retained`);
704
+ }
705
+});
706
+
707
+it.each([false, true])(
708
+ "bounds shared-string text including CDATA %s per cell and across sheets in the worker",
709
+ async (cdata) => {
710
+ const { default: JSZip } = await import("jszip");
711
+ const archive = new JSZip();
712
+ archive.file(
713
+ "xl/workbook.xml",
714
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="one" sheetId="1" r:id="s"/><sheet name="two" sheetId="2" r:id="s"/></sheets></workbook>',
715
+ );
716
+ archive.file(
717
+ "xl/_rels/workbook.xml.rels",
718
+ '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
719
+ );
720
+ const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";
721
+ archive.file(
722
+ "xl/_rels/workbook.xml.rels",
723
+ (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(
724
+ "</Relationships>",
725
+ `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,
726
+ ),
727
+ );
728
+ const content = "x".repeat(32_767);
729
+ archive.file(
730
+ `xl/${sharedPath}`,
731
+ `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,
732
+ );
733
+ archive.file(
734
+ "xl/worksheets/sheet1.xml",
735
+ `<worksheet><sheetData>${Array.from({ length: 500 }, (_, i) => `<row r="${i + 1}">${Array.from({ length: 50 }, (_, j) => `<c r="${j < 26 ? String.fromCharCode(65 + j) : "A" + String.fromCharCode(65 + j - 26)}${i + 1}" t="s"><v>${cdata ? "<![CDATA[0]]>" : "0"}</v></c>`).join("")}</row>`).join("")}</sheetData></worksheet>`.replace(
736
+ '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',
737
+ `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,
738
+ ),
739
+ );
740
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
741
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
742
+ type: "module",
743
+ });
744
+ try {
745
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
746
+ worker.addEventListener(
747
+ "message",
748
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
749
+ { once: true },
750
+ );
751
+ void file
752
+ .arrayBuffer()
753
+ .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));
754
+ });
755
+ expect(result.type).toBe("xlsx");
756
+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
757
+ const bounded = await JSZip.loadAsync(result.bytes);
758
+ const sheet = new DOMParser().parseFromString(
759
+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
760
+ "application/xml",
761
+ );
762
+ const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");
763
+ expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);
764
+ expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);
765
+ expect(result.truncated).toBe(true);
766
+ } finally {
767
+ worker.terminate();
768
+ }
769
+ },
770
+);
771
+
772
+// A body just over the read limit once each paragraph repeats its text this often.
773
+it.each([1, Math.ceil(WORD_LIMITS.bodyBytes / 5_000 / 4)])(
774
+ "counts shared Word settings once with %s text repetitions",
775
+ async (repetitions) => {
776
+ const { default: JSZip } = await import("jszip");
777
+ const archive = new JSZip();
778
+ const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
779
+ archive.file(
780
+ "word/document.xml",
781
+ `<w:document xmlns:w="${ns}"><w:body>${`<w:p><w:r><w:t>${"body".repeat(repetitions)}</w:t></w:r></w:p>`.repeat(5_000)}</w:body></w:document>`,
782
+ );
783
+ archive.file(
784
+ "word/_rels/document.xml.rels",
785
+ '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',
786
+ );
787
+ const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;
788
+ archive.file("word/settings.xml", settings);
789
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
790
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
791
+ type: "module",
792
+ });
793
+ try {
794
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
795
+ worker.addEventListener(
796
+ "message",
797
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
798
+ { once: true },
799
+ );
800
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
801
+ });
802
+ expect(result.type).toBe("docx");
803
+ if (result.type !== "docx") throw new Error("Expected a Word prefix");
804
+ expect(result.truncated).toBe(repetitions > 1);
805
+ const bounded = await JSZip.loadAsync(result.bytes);
806
+ const document = await bounded.file("word/document.xml")!.async("string");
807
+ const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
808
+ expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
809
+ expect(document.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
810
+ expect(retainedSettings).toBe(settings);
811
+ } finally {
812
+ worker.terminate();
813
+ }
814
+ },
815
+);
816
+
817
+it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(
818
+ "bounds Word image expansion for %s",
819
+ async (scenario) => {
820
+ const { default: JSZip } = await import("jszip");
821
+ const archive = new JSZip();
822
+ archive.file(
823
+ "[Content_Types].xml",
824
+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',
825
+ );
826
+ archive.file(
827
+ "word/_rels/document.xml.rels",
828
+ `<Relationships><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${scenario === "XML relationship alias" ? "styles" : "image"}" Target="media/payload.png"/>${scenario === "duplicate relationship ID" ? '<Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/tiny.png"/>' : ""}</Relationships>`,
829
+ );
830
+ archive.file(
831
+ "word/media/payload.png",
832
+ scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),
833
+ );
834
+ if (scenario === "duplicate relationship ID")
835
+ archive.file("word/media/tiny.png", new Uint8Array(1));
836
+ archive.file(
837
+ "word/document.xml",
838
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p>${'<w:r><a:blip r:embed="image"/></w:r>'.repeat(7)}</w:p></w:body></w:document>`,
839
+ );
840
+ const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
841
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
842
+ type: "module",
843
+ });
844
+ try {
845
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
846
+ worker.addEventListener(
847
+ "message",
848
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
849
+ { once: true },
850
+ );
851
+ worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
852
+ });
853
+ expect(result).toMatchObject({
854
+ type: "error",
855
+ message: expect.stringContaining("expanded markup"),
856
+ });
857
+ } finally {
858
+ worker.terminate();
859
+ }
860
+ },
861
+);
862
+
863
+it.each(["XFD200", "XFD300", "XFD1048576", "AX500", "AZ9999999"])(
864
+ "bounds spreadsheet cells at %s before padding",
865
+ async (ref) => {
866
+ const { default: JSZip } = await import("jszip");
867
+ const archive = new JSZip();
868
+ archive.file(
869
+ "xl/workbook.xml",
870
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',
871
+ );
872
+ // A nonstandard relationship target must get the same bounds.
873
+ archive.file(
874
+ "xl/_rels/workbook.xml.rels",
875
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',
876
+ );
877
+ archive.file(
878
+ "xl/custom.xml",
879
+ `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}">${ref === "XFD300" ? `<c r="${ref}" s="1"/>` : `<c r="${ref}"><v>9</v></c>`}</row></sheetData></worksheet>`,
880
+ );
881
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
882
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
883
+ type: "module",
884
+ });
885
+ try {
886
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
887
+ worker.addEventListener(
888
+ "message",
889
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
890
+ { once: true },
891
+ );
892
+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
893
+ });
894
+ if (ref === "AZ9999999" || ref === "XFD1048576") {
895
+ expect(result).toMatchObject({
896
+ type: "error",
897
+ message: expect.stringContaining(ref === "AZ9999999" ? "invalid" : "preview limit"),
898
+ });
899
+ } else {
900
+ expect(result.type).toBe("xlsx");
901
+ if (result.type !== "xlsx") throw new Error("Expected workbook values");
902
+ const bounded = await JSZip.loadAsync(result.bytes);
903
+ const sheet = new DOMParser().parseFromString(
904
+ await bounded.file("xl/custom.xml")!.async("string"),
905
+ "application/xml",
906
+ );
907
+ expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
908
+ expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
909
+ expect(result.truncated).toBe(ref === "XFD200" || ref === "XFD300");
910
+ if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
911
+ else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
912
+ }
913
+ } finally {
914
+ worker.terminate();
915
+ }
916
+ },
917
+);
918
+
919
+it.each(['<u val="double"/>', '<u val="double"></u>'])(
920
+ "shows workbook formats and underline %s",
921
+ async (underline) => {
922
+ const { default: JSZip } = await import("jszip");
923
+ const archive = new JSZip();
924
+ archive.file(
925
+ "xl/workbook.xml",
926
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Styles" sheetId="1" r:id="rId1"/></sheets></workbook>',
927
+ );
928
+ archive.file(
929
+ "xl/_rels/workbook.xml.rels",
930
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
931
+ );
932
+ archive.file(
933
+ "xl/styles.xml",
934
+ `<styleSheet><numFmts count="4"><numFmt numFmtId="164" formatCode="0.000"/><numFmt numFmtId="65535" formatCode="0.0000"/><numFmt numFmtId="007" formatCode=""¥"#,##0.00"/><numFmt numFmtId="82" formatCode="[$-010409]dd-mmm-yyyy"/></numFmts><fonts count="2"><font><sz val="11"/></font><font>${underline}<sz val="11"/></font></fonts><cellXfs count="4"><xf numFmtId="0" fontId="0"/><xf numFmtId="7" fontId="0"/><xf numFmtId="82" fontId="0"/><xf numFmtId="0" fontId="1"/></cellXfs></styleSheet>`,
935
+ );
936
+ archive.file(
937
+ "xl/worksheets/sheet1.xml",
938
+ '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>100</v></c><c r="B1" s="2"><v>44986</v></c><c r="C1" s="3" t="inlineStr"><is><t>Total</t></is></c></row></sheetData></worksheet>',
939
+ );
940
+ const { prepareOffice } = await import("./officeArchive");
941
+ const prepared = await prepareOffice(
942
+ await archive.generateAsync({ type: "arraybuffer" }),
943
+ "xlsx",
944
+ );
945
+ const styles = await (
946
+ await JSZip.loadAsync(prepared.bytes)
947
+ )
948
+ .file("xl/styles.xml")!
949
+ .async("string");
950
+ expect(styles).toContain("<font><u/>");
951
+ const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), {
952
+ type: "module",
953
+ });
954
+ try {
955
+ const { createWorkerClient } = await import("./office/worker-rpc");
956
+ const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
957
+ const bytes = prepared.bytes;
958
+ await client.call("open", { bytes, view: prepared.view! }, { transfer: [bytes] });
959
+ const cells = await client.call("cells", {
960
+ sheet: 0,
961
+ range: { top: 0, bottom: 0, left: 0, right: 1 },
962
+ });
963
+ // Ids under 164 that a workbook defines keep its formats, not Excel's built-in ones.
964
+ expect(cells[0]).toEqual(["¥100.00", "01-Mar-2023"]);
965
+ } finally {
966
+ worker.terminate();
967
+ }
968
+ archive.file("xl/styles.xml", "<styleSheet><numFmts/><numFmts/></styleSheet>");
969
+ await expect(
970
+ prepareOffice(await archive.generateAsync({ type: "arraybuffer" }), "xlsx"),
971
+ ).rejects.toThrow("duplicate stylesheet blocks");
972
+ },
973
+);
974
+
975
+it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
976
+ const { default: JSZip } = await import("jszip");
977
+ const archive = new JSZip();
978
+ archive.file(
979
+ "xl/workbook.xml",
980
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',
981
+ );
982
+ archive.file(
983
+ "xl/_rels/workbook.xml.rels",
984
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
985
+ );
986
+ archive.file(
987
+ "xl/styles.xml",
988
+ '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',
989
+ );
990
+ archive.file(
991
+ "xl/worksheets/sheet1.xml",
992
+ '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',
993
+ );
994
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
995
+ const workerModule = new URL(
996
+ "./office/spreadsheet.worker.ts?worker_file&type=module",
997
+ import.meta.url,
998
+ ).href;
999
+ // Give the worker a west-of-UTC default while preserving explicit format options.
1000
+ const bootstrap = URL.createObjectURL(
1001
+ new Blob(
1002
+ [
1003
+ `
1004
+ const NativeURL = URL;
1005
+ globalThis.URL = class extends NativeURL {
1006
+ constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }
1007
+ };
1008
+ const format = Date.prototype.toLocaleDateString;
1009
+ Date.prototype.toLocaleDateString = function(locale, options) {
1010
+ return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });
1011
+ };
1012
+ await import(${JSON.stringify(workerModule)});
1013
+ postMessage({ type: "ready" });
1014
+ `,
1015
+ ],
1016
+ { type: "text/javascript" },
1017
+ ),
1018
+ );
1019
+ const worker = new Worker(bootstrap, { type: "module" });
1020
+ try {
1021
+ await new Promise<void>((resolve, reject) => {
1022
+ worker.addEventListener(
1023
+ "message",
1024
+ (event) => {
1025
+ if (event.data.type === "ready") resolve();
1026
+ },
1027
+ { once: true },
1028
+ );
1029
+ worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });
1030
+ });
1031
+ const { createWorkerClient } = await import("./office/worker-rpc");
1032
+ const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1033
+ await client.call(
1034
+ "open",
1035
+ {
1036
+ bytes,
1037
+ view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
1038
+ },
1039
+ { transfer: [bytes] },
1040
+ );
1041
+ const cells = await client.call("cells", {
1042
+ sheet: 0,
1043
+ range: { top: 0, bottom: 0, left: 0, right: 0 },
1044
+ });
1045
+ expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);
1046
+ } finally {
1047
+ worker.terminate();
1048
+ URL.revokeObjectURL(bootstrap);
1049
+ }
1050
+});
1051
+
1052
+it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async (pages) => {
1053
+ const { default: JSZip } = await import("jszip");
1054
+ const archive = new JSZip();
1055
+ const paragraph = (text: string) =>
1056
+ `<w:p><w:pPr><w:spacing w:after="120"/><w:jc w:val="left"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Calibri"/><w:sz w:val="22"/></w:rPr><w:t>${text}</w:t></w:r></w:p>`;
1057
+ archive.file(
1058
+ "word/document.xml",
1059
+ `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${Array.from({ length: pages }, (_, page) => paragraph(`page ${page + 1}`) + `<w:tbl>${Array.from({ length: 10 }, () => `<w:tr>${Array.from({ length: 5 }, () => `<w:tc><w:tcPr><w:tcW w:w="1800"/></w:tcPr>${paragraph("report entry")}</w:tc>`).join("")}</w:tr>`).join("")}</w:tbl>`).join("")}</w:body></w:document>`,
1060
+ );
1061
+ archive.file(
1062
+ "_rels/.rels",
1063
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
1064
+ );
1065
+ archive.file(
1066
+ "[Content_Types].xml",
1067
+ '<Types><Default Extension="png" ContentType="image/png"/></Types>',
1068
+ );
1069
+ // Binary media must not consume the document's markup budget.
1070
+ archive.file("word/media/image.png", new Uint8Array(2_500_000));
1071
+ const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1072
+ await using screen = await render(
1073
+ <AttachmentFilePreview
1074
+ name="report.docx"
1075
+ mimeType="application/octet-stream"
1076
+ file={file}
1077
+ sizeBytes={file.size}
1078
+ />,
1079
+ );
1080
+ // The first Office preview in the file loads the lazy viewer chain and the preparation worker.
1081
+ await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1082
+ timeout: 10_000,
1083
+ });
1084
+ expect(screen.container.textContent).not.toContain("Preview limited");
1085
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1086
+});