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, 23:30 UTC
fix(web): Word previews no longer cut ordinary documents short (#32040)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
yaacovcorcos committed
Nov 11, 2026 at 21:44 UTC
787c59c802ff58274b06a2cdfb1a369bf7c04571
3 files changed
+224
-40
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+23
-17
@@ -482,6 +482,7 @@ describe("bounded binary previews", () => {
482
});
483
});
484
import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";
485
+import { WORD_LIMITS } from "./officeArchive";
486
487
describe("large text preview recovery", () => {
488
it("retains the workspace viewer across URL renewals and reloads revisions and manual refreshes", async () => {
@@ -1190,7 +1191,7 @@ it.each([
1191
: scenario === "runs"
1192
? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
1193
: scenario === "tables"
1193
- ? "<w:tbl/>".repeat(50_001)
1194
+ ? "<w:tbl/>".repeat(2 * WORD_LIMITS.bodyElements)
1195
: scenario === "XML bytes"
1196
? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
1197
: "<w:p/>";
@@ -1203,7 +1204,7 @@ it.each([
1204
if (scenario === "auxiliary XML" || scenario === "renamed XML")
1205
archive.file(
1206
scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
1206
- `<w:footnotes>${"<w:p/>".repeat(50_001)}</w:footnotes>`,
1207
+ `<w:footnotes>${"<w:p/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</w:footnotes>`,
1208
);
1209
const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1210
const src = URL.createObjectURL(file);
@@ -1254,8 +1255,8 @@ it.each([
1255
);
1256
}
1257
expect(markup.length).toBeLessThan(body.length);
1257
- expect(markup.length).toBeLessThanOrEqual(3 * 1024 * 1024);
1258
- expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(100_000);
1258
+ expect(markup.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
1259
+ expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(WORD_LIMITS.bodyTags);
1260
}
1261
} finally {
1262
worker.terminate();
@@ -1286,15 +1287,15 @@ it.each([
1287
);
1288
archive.file(
1289
"word/_rels/document.xml.rels",
1289
- `<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(50_001) : ""}</Relationships>`,
1290
+ `<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>`,
1291
);
1292
archive.file(
1293
path,
1294
scenario === "relationship bytes"
1294
- ? `<styles>${"x".repeat(1024 * 1024)}</styles>`
1295
+ ? `<styles>${"x".repeat(WORD_LIMITS.auxiliaryPartBytes)}</styles>`
1296
: scenario === "deep XML"
1297
? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
1297
- : `<styles>${"<style/>".repeat(50_001)}</styles>`,
1298
+ : `<styles>${"<style/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</styles>`,
1299
);
1300
const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
1301
const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
@@ -1348,11 +1349,12 @@ async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
1349
'<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
1350
);
1351
const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
1351
- // Each copy of the 2,000-paragraph payload costs 8,000 markup units, so 20
1352
- // references (or pages) exceed the 100,000-unit expansion budget.
1352
+ // Each copy of the 2,000-paragraph payload costs 6,000 markup units, so enough
1353
+ // references (or pages) exceed the expansion budget.
1354
+ const copies = Math.ceil(WORD_LIMITS.expandedMarkup / 6_000) + 1;
1355
archive.file(
1356
"word/document.xml",
1355
- `<w:document xmlns:w="${ns}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${text("body retained")}${Array.from({ length: 20 }, () => `<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>`,
1357
+ `<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>`,
1358
);
1359
archive.file(
1360
"word/_rels/document.xml.rels",
@@ -1360,23 +1362,25 @@ async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
1362
);
1363
const xml =
1364
role === "style chain" || role === "style count" || role === "style visits"
1363
- ? `<w:styles xmlns:w="${ns}">${Array.from({ length: role === "style count" ? 3_000 : 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>`
1365
+ ? `<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>`
1366
: role === "styles"
1367
? `<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>`
1368
: role.includes("numbering")
1367
- ? `<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: 100 }, (_, i) => `<w:num w:numId="${i}"><w:abstractNumId w:val="1"/></w:num>`).join("")}</w:numbering>`
1369
+ ? `<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>`
1370
: role === "header" || role === "footer"
1371
? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
1372
: `<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}>`;
1373
archive.file("word/media/aux.xml", xml);
1374
if (role === "note roots") {
1375
+ // Each note's XML repeats the 32 KB root, which the expansion budget charges twice.
1376
+ const notes = Math.ceil(WORD_LIMITS.expandedBytes / 64_000) + 1;
1377
archive.file(
1378
"word/document.xml",
1375
- `<w:document xmlns:w="${ns}"><w:body>${text("body retained")}${Array.from({ length: 200 }, (_, id) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`).join("")}</w:body></w:document>`,
1379
+ `<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>`,
1380
);
1381
archive.file(
1382
"word/media/aux.xml",
1379
- `<w:footnotes xmlns:w="${ns}" padding="${"x".repeat(32_000)}">${Array.from({ length: 200 }, (_, id) => `<w:footnote w:id="${id}">${text("omitted payload")}</w:footnote>`).join("")}</w:footnotes>`,
1383
+ `<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>`,
1384
);
1385
}
1386
return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
@@ -1401,7 +1405,7 @@ it.each(EXPANDED_WORD_ROLES)(
1405
(sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
1406
0,
1407
),
1404
- ).toBeLessThan(4 * 1024 * 1024);
1408
+ ).toBeLessThan(WORD_LIMITS.expandedBytes + 4 * 1024 * 1024);
1409
const bounded = await JSZip.loadAsync(prepared.bytes);
1410
const markup = await bounded.file("word/document.xml")!.async("string");
1411
expect(markup).toContain("body retained");
@@ -1622,7 +1626,8 @@ it.each([false, true])(
1626
},
1627
);
1628
1625
-it.each([1, 145])(
1629
+// A body just over the read limit once each paragraph repeats its text this often.
1630
+it.each([1, Math.ceil(WORD_LIMITS.bodyBytes / 5_000 / 4)])(
1631
"counts shared Word settings once with %s text repetitions",
1632
async (repetitions) => {
1633
const { default: JSZip } = await import("jszip");
@@ -1658,7 +1663,8 @@ it.each([1, 145])(
1663
const document = await bounded.file("word/document.xml")!.async("string");
1664
const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
1665
expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
1661
- expect(document.length + retainedSettings.length).toBeLessThanOrEqual(3 * 1024 * 1024);
1666
+ expect(document.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
1667
+ expect(retainedSettings).toBe(settings);
1668
} finally {
1669
worker.terminate();
1670
}
apps/web/src/components/files/officeArchive.test.ts
new
+136
@@ -0,0 +1,136 @@
1
+import JSZip from "jszip";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { prepareOffice } from "./officeArchive";
5
+
6
+const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
7
+const V = 'xmlns:v="urn:schemas-microsoft-com:vml"';
8
+const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
9
+const relationship = (type: string, target: string) =>
10
+ `<Relationship Id="${type}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`;
11
+const paragraph = (text: string, properties = "") =>
12
+ `<w:p>${properties}<w:r><w:t xml:space="preserve">${text}</w:t></w:r></w:p>`;
13
+
14
+async function wordFile(
15
+ body: string,
16
+ parts: Partial<Record<"styles" | "numbering" | "header" | "footer" | "footnotes", string>> = {},
17
+ section = "",
18
+) {
19
+ const zip = new JSZip();
20
+ zip.file(
21
+ "[Content_Types].xml",
22
+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`,
23
+ );
24
+ zip.file(
25
+ "_rels/.rels",
26
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship("officeDocument", "word/document.xml")}</Relationships>`,
27
+ );
28
+ zip.file(
29
+ "word/_rels/document.xml.rels",
30
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${Object.keys(
31
+ parts,
32
+ )
33
+ .map((part) => relationship(part, `${part}.xml`))
34
+ .join("")}</Relationships>`,
35
+ );
36
+ for (const [part, xml] of Object.entries(parts)) zip.file(`word/${part}.xml`, xml);
37
+ zip.file(
38
+ "word/document.xml",
39
+ `<w:document ${W} ${V} ${R}><w:body>${body}<w:sectPr>${section}<w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>`,
40
+ );
41
+ return zip.generateAsync({ type: "arraybuffer" });
42
+}
43
+
44
+async function prepared(bytes: ArrayBuffer) {
45
+ const result = await prepareOffice(bytes, "docx");
46
+ const zip = await JSZip.loadAsync(result.bytes);
47
+ return { truncated: result.truncated, part: (path: string) => zip.file(path)?.async("string") };
48
+}
49
+
50
+// regression: the budgets sized for a main-thread renderer cut ordinary documents short.
51
+describe("Word preview limits", () => {
52
+ it("keeps a document whose table follows a long one", async () => {
53
+ const rows = Array.from(
54
+ { length: 500 },
55
+ (_, row) =>
56
+ `<w:tr>${Array.from({ length: 5 }, (_, cell) => `<w:tc>${paragraph(`r${row}c${cell}`)}</w:tc>`).join("")}</w:tr>`,
57
+ ).join("");
58
+ const result = await prepared(
59
+ await wordFile(`<w:tbl>${rows}</w:tbl>${paragraph("After the table")}`),
60
+ );
61
+ expect(result.truncated).toBe(false);
62
+ expect(await result.part("word/document.xml")).toContain("After the table");
63
+ });
64
+
65
+ it("keeps the list and style definitions of a long document", async () => {
66
+ const levels = Array.from(
67
+ { length: 9 },
68
+ (_, level) =>
69
+ `<w:lvl w:ilvl="${level}"><w:numFmt w:val="decimal"/><w:lvlText w:val="%${level + 1}."/></w:lvl>`,
70
+ ).join("");
71
+ const numbering = `<w:numbering ${W}>${Array.from({ length: 60 }, (_, list) => `<w:abstractNum w:abstractNumId="${list}">${levels}</w:abstractNum>`).join("")}${Array.from({ length: 60 }, (_, list) => `<w:num w:numId="${list + 1}"><w:abstractNumId w:val="${list}"/></w:num>`).join("")}</w:numbering>`;
72
+ const styles = `<w:styles ${W}>${Array.from(
73
+ { length: 1_500 },
74
+ (_, style) =>
75
+ `<w:style w:type="paragraph" w:styleId="S${style}">${style % 10 ? `<w:basedOn w:val="S${style - 1}"/>` : ""}<w:pPr><w:spacing w:after="${style}"/></w:pPr><w:rPr><w:sz w:val="22"/></w:rPr></w:style>`,
76
+ ).join("")}</w:styles>`;
77
+ const result = await prepared(
78
+ await wordFile(
79
+ Array.from({ length: 6_000 }, (_, index) =>
80
+ paragraph(
81
+ `Item ${index}`,
82
+ `<w:pPr><w:pStyle w:val="S${index % 1_500}"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="${(index % 60) + 1}"/></w:numPr></w:pPr>`,
83
+ ),
84
+ ).join(""),
85
+ { styles, numbering },
86
+ ),
87
+ );
88
+ expect(result.truncated).toBe(false);
89
+ expect(await result.part("word/numbering.xml")).toBe(numbering);
90
+ expect(await result.part("word/styles.xml")).toBe(styles);
91
+ expect(await result.part("word/document.xml")).toContain("Item 5999");
92
+ });
93
+
94
+ const text = "x".repeat(140_000);
95
+ it.each([
96
+ ["on its own", `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`],
97
+ [
98
+ "after an empty paragraph in a text box",
99
+ `<w:p><w:r><w:pict><v:shape><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape></w:pict></w:r><w:r><w:t>${text}</w:t></w:r></w:p>`,
100
+ ],
101
+ ["written as CDATA", `<w:p><w:r><w:t><![CDATA[${text}]]></w:t></w:r></w:p>`],
102
+ ])("stops before a paragraph too long to lay out %s", async (_, long) => {
103
+ const result = await prepared(
104
+ await wordFile(paragraph("Kept") + long + paragraph("Not reached")),
105
+ );
106
+ expect(result.truncated).toBe(true);
107
+ const document = await result.part("word/document.xml");
108
+ expect(document).toContain("Kept");
109
+ expect(document).not.toContain("Not reached");
110
+ });
111
+
112
+ it("counts only the text a paragraph lays out", async () => {
113
+ const formatted = `<w:p>${" ".repeat(140_000)}<w:r><w:instrText>${"x".repeat(140_000)}</w:instrText></w:r><w:r><w:t>${"x".repeat(40_000)}</w:t></w:r></w:p>`;
114
+ const result = await prepared(await wordFile(formatted + paragraph("After")));
115
+ expect(result.truncated).toBe(false);
116
+ expect(await result.part("word/document.xml")).toContain("After");
117
+ });
118
+
119
+ it("keeps a long header", async () => {
120
+ const header = `<w:hdr ${W}>${Array.from({ length: 3_000 }, (_, line) => paragraph(`Header line ${line}`)).join("")}</w:hdr>`;
121
+ const footer = `<w:ftr ${W}>${paragraph("Footer")}</w:ftr>`;
122
+ const footnotes = `<w:footnotes ${W}><w:footnote w:id="1">${paragraph("Note")}</w:footnote></w:footnotes>`;
123
+ const result = await prepared(
124
+ await wordFile(
125
+ `<w:p><w:r><w:t>Body</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>`,
126
+ { header, footer, footnotes },
127
+ `<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>`,
128
+ ),
129
+ );
130
+ expect(result.truncated).toBe(false);
131
+ expect(await result.part("word/header.xml")).toBe(header);
132
+ expect(await result.part("word/footer.xml")).toBe(footer);
133
+ expect(await result.part("word/footnotes.xml")).toBe(footnotes);
134
+ expect(await result.part("word/document.xml")).toContain("Body");
135
+ });
136
+});
apps/web/src/components/files/officeArchive.ts
+65
-23
@@ -10,6 +10,31 @@ import {
10
type OfficeWorkerRequest,
11
} from "./officePreviewProtocol";
12
13
+// Word limits, measured against the @betteroffice/docx engine, which lays out in its own worker.
14
+export const WORD_LIMITS = {
15
+ /** document.xml read and kept, about 700 pages of prose; the engine opens it in about 1 s. */
16
+ bodyBytes: 4 * 1024 * 1024,
17
+ bodyElements: 50_000,
18
+ bodyTags: 1_000_000,
19
+ /** A table is laid out in one go: 100,000 tags is a 4,000-row table, about 2 s. */
20
+ elementTags: 100_000,
21
+ /** Line breaking grows with the square of a paragraph's text: 40K characters take about 2 s. */
22
+ paragraphText: 128 * 1024,
23
+ styles: 8_192,
24
+ styleBytes: 16 * 1024 * 1024,
25
+ styleUnits: 400_000,
26
+ styleVisits: 131_072,
27
+ stylePropertyVisits: 2_000_000,
28
+ numberingReferences: 20_000,
29
+ numberingBytes: 32 * 1024 * 1024,
30
+ numberingMarkup: 400_000,
31
+ auxiliaryPartBytes: 8 * 1024 * 1024,
32
+ auxiliaryMarkup: 1_000_000,
33
+ /** Body, styles, lists and notes, with headers and footers counted once per page. */
34
+ expandedBytes: 64 * 1024 * 1024,
35
+ expandedMarkup: 4_000_000,
36
+};
37
+
38
function xmlParser() {
39
const parser = new SaxesParser({ xmlns: true });
40
parser.on("doctype", () => {
@@ -143,27 +168,41 @@ function wordDocuments(
168
let elementTags = 0;
169
let batchTags = 0;
170
let elements = 0;
171
+ // The text each open paragraph lays out (its w:t runs); a nested paragraph counts apart.
172
+ const paragraphText: number[] = [];
173
+ let inText = false;
174
let truncated = incomplete;
175
const limit = Symbol("Word preview limit");
176
+ const countText = (text: string) => {
177
+ if (!inText || paragraphText.length === 0) return;
178
+ const length = paragraphText.at(-1)! + text.length;
179
+ if (length > WORD_LIMITS.paragraphText) throw limit;
180
+ paragraphText[paragraphText.length - 1] = length;
181
+ };
182
+ parser.on("text", countText);
183
+ parser.on("cdata", countText);
184
parser.on("opentag", (tag) => {
185
names.push(tag.name);
186
+ if (prefix && tag.local === "p") paragraphText.push(0);
187
+ if (tag.local === "t") inText = true;
188
if (names.length === 2 && tag.local === "body") {
189
prefix = xml.slice(0, parser.position).replace(/\/>$/, ">");
190
suffix = `</${tag.name}></${names[0]}>`;
191
boundary = batchStart = parser.position;
192
} else if (prefix && names.length > 2) {
155
- if (names.length === 3 && ++elements > 5_000) throw limit;
193
+ if (names.length === 3 && ++elements > WORD_LIMITS.bodyElements) throw limit;
194
tags++;
195
elementTags++;
196
batchTags++;
159
- if (tags > 100_000 || elementTags > 2_000 || parser.position - boundary > 128 * 1024)
160
- throw limit;
197
+ if (tags > WORD_LIMITS.bodyTags || elementTags > WORD_LIMITS.elementTags) throw limit;
198
}
199
if (names.length > 64) throw limit;
200
});
201
parser.on("closetag", (tag) => {
202
+ if (prefix && tag.local === "p") paragraphText.pop();
203
+ if (tag.local === "t") inText = false;
204
if (prefix && names.length === 3 && tag.local !== "sectPr") {
166
- if (parser.position - prefix.length > 3 * 1024 * 1024) throw limit;
205
+ if (parser.position - prefix.length > WORD_LIMITS.bodyBytes) throw limit;
206
boundary = parser.position;
207
elementTags = 0;
208
if (batchTags >= 500) {
@@ -177,7 +216,6 @@ function wordDocuments(
216
try {
217
for (let offset = 0; offset < xml.length; offset += 16 * 1024) {
218
parser.write(xml.slice(offset, offset + 16 * 1024));
180
- if (prefix && parser.position - boundary > 128 * 1024) throw limit;
219
}
220
if (!incomplete) parser.close();
221
} catch (cause) {
@@ -195,7 +233,7 @@ function wordDocuments(
233
const document = prefix + batch.content + (section?.xml ?? "") + suffix;
234
length += batch.content.length;
235
markup += batch.content.match(/<(?![!?/])/g)?.length ?? 0;
198
- if (length > 3 * 1024 * 1024 || markup > 100_000) {
236
+ if (length > WORD_LIMITS.bodyBytes || markup > WORD_LIMITS.bodyTags) {
237
truncated = true;
238
break;
239
}
@@ -617,9 +655,6 @@ function wordPartTypes() {
655
656
// Bound inherited style and numbering expansion before the engine loads it.
657
// Picture bullets can duplicate embedded images, so omit those definitions.
620
-const WORD_STYLE_MAX_BYTES = 1024 * 1024;
621
-const WORD_STYLE_MAX_UNITS = 20_000;
622
-
658
function wordXmlCost(xml: string, roles: Set<string> | undefined) {
659
const parser = xmlParser();
660
let depth = 0;
@@ -648,7 +683,7 @@ function wordXmlCost(xml: string, roles: Set<string> | undefined) {
683
Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
684
names.push(tag.local === "tblStylePr" ? `${tag.local}:${attr("type")}` : tag.local);
685
if (roles?.has("styles") && (tag.local === "style" || tag.local === "docDefaults")) {
651
- if (++styleCount > 1_024 || attr("styleId").length > 256) throw limit;
686
+ if (++styleCount > WORD_LIMITS.styles || attr("styleId").length > 256) throw limit;
687
style = { id: attr("styleId"), properties: new Map(), base: "", linked: "" };
688
}
689
if (style) {
@@ -659,7 +694,7 @@ function wordXmlCost(xml: string, roles: Set<string> | undefined) {
694
const size = new TextEncoder().encode(
695
xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
696
).length;
662
- if (++ownUnits > WORD_STYLE_MAX_UNITS) throw limit;
697
+ if (++ownUnits > WORD_LIMITS.styleUnits) throw limit;
698
style.properties.set(key, size);
699
}
700
}
@@ -671,7 +706,7 @@ function wordXmlCost(xml: string, roles: Set<string> | undefined) {
706
markup: markup - 1,
707
};
708
if (tag.local === "num") {
674
- if (references.length >= 2_000) throw limit;
709
+ if (references.length >= WORD_LIMITS.numberingReferences) throw limit;
710
reference = { id: "", selector: attr("numId").length + 32 };
711
references.push(reference);
712
}
@@ -731,16 +766,16 @@ function wordXmlCost(xml: string, roles: Set<string> | undefined) {
766
]) {
767
const seen = new Set<string>();
768
for (let node = root; node; node = node.parent) {
734
- if (++visited > 8_192) return exceeded;
769
+ if (++visited > WORD_LIMITS.styleVisits) return exceeded;
770
for (const [key, size] of node.properties) {
736
- if (++propertyVisits > 100_000) return exceeded;
771
+ if (++propertyVisits > WORD_LIMITS.stylePropertyVisits) return exceeded;
772
if (seen.has(key)) continue;
773
// Latent styles never enter properties. Charge each own property
774
// once per resolved style, including linked and default selectors.
775
const copies = id ? 1 : 2;
776
bytes += (size * 2 + id.length + 32) * copies;
777
expandedMarkup += copies;
743
- if (bytes > WORD_STYLE_MAX_BYTES || expandedMarkup > WORD_STYLE_MAX_UNITS)
778
+ if (bytes > WORD_LIMITS.styleBytes || expandedMarkup > WORD_LIMITS.styleUnits)
779
return exceeded;
780
seen.add(key);
781
}
@@ -756,7 +791,8 @@ function wordXmlCost(xml: string, roles: Set<string> | undefined) {
791
if (!cost) continue;
792
bytes += cost.bytes * 2 + cost.markup * ref.selector;
793
markup += cost.markup;
759
- if (bytes > 128 * 1024 || markup > 2_000) return exceeded;
794
+ if (bytes > WORD_LIMITS.numberingBytes || markup > WORD_LIMITS.numberingMarkup)
795
+ return exceeded;
796
}
797
}
798
return { bytes, markup, pictures };
@@ -851,7 +887,7 @@ async function wordExpansion(
887
let expanded = memo.get(key);
888
if (!expanded) {
889
expandedXmlBytes += node.xml.length * 2;
854
- if (expandedXmlBytes > 3 * 1024 * 1024) {
890
+ if (expandedXmlBytes > WORD_LIMITS.expandedBytes) {
891
cost.bytes = Infinity;
892
break;
893
}
@@ -901,7 +937,9 @@ async function wordExpansion(
937
markup += cost.markup;
938
}
939
const overBudget =
904
- bytes > 3 * 1024 * 1024 || markup > 100_000 || media > OFFICE_PREVIEW_MAX_BYTES;
940
+ bytes > WORD_LIMITS.expandedBytes ||
941
+ markup > WORD_LIMITS.expandedMarkup ||
942
+ media > OFFICE_PREVIEW_MAX_BYTES;
943
const truncated = (used.size > 0 && overBudget) || bytes === Infinity;
944
const omitted = new Set([...optional].filter((path) => truncated || !used.has(path)));
945
for (const path of omitted) archive.remove(path);
@@ -1014,7 +1052,10 @@ export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type:
1052
// stay small before the engine parses it.
1053
if (input.kind === "docx" && !document && !media) {
1054
for (const byte of chunk) if (byte === 0x3c) wordAuxiliaryMarkup++;
1017
- if (length > 1024 * 1024 || wordAuxiliaryMarkup > 50_000) {
1055
+ if (
1056
+ length > WORD_LIMITS.auxiliaryPartBytes ||
1057
+ wordAuxiliaryMarkup > WORD_LIMITS.auxiliaryMarkup
1058
+ ) {
1059
stream.pause();
1060
reject(
1061
new Error("Preview limited: this Word document has too much auxiliary markup."),
@@ -1058,8 +1099,9 @@ export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type:
1099
if (
1100
(roles?.has("numbering") && cost.pictures) ||
1101
(roles?.has("styles") &&
1061
- (cost.bytes > WORD_STYLE_MAX_BYTES || cost.markup > WORD_STYLE_MAX_UNITS)) ||
1062
- (roles?.has("numbering") && (cost.bytes > 128 * 1024 || cost.markup > 2_000))
1102
+ (cost.bytes > WORD_LIMITS.styleBytes || cost.markup > WORD_LIMITS.styleUnits)) ||
1103
+ (roles?.has("numbering") &&
1104
+ (cost.bytes > WORD_LIMITS.numberingBytes || cost.markup > WORD_LIMITS.numberingMarkup))
1105
) {
1106
wordInputTruncated = true;
1107
continue;
@@ -1098,8 +1140,8 @@ export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type:
1140
const images = extra.media;
1141
const batchImages = new Set(extra.images);
1142
if (
1101
- bytes + cost.bytes > 3 * 1024 * 1024 ||
1102
- markup + cost.markup > 100_000 ||
1143
+ bytes + cost.bytes > WORD_LIMITS.expandedBytes ||
1144
+ markup + cost.markup > WORD_LIMITS.expandedMarkup ||
1145
mediaBytes + images > OFFICE_PREVIEW_MAX_BYTES
1146
)
1147
break;