Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: run the docx text rewrites over one unpacked part map instead of rezipping the archive after each (#16329)

Daniel Han2677f9718421
diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.ts
index 6107e5de2e1..03d2f8249c5 100644
--- a/studio/frontend/src/features/chat/attachment-content.ts
+++ b/studio/frontend/src/features/chat/attachment-content.ts
@@ -734,6 +734,41 @@ export function repackDocxAttachmentArchive(
return zipSync(archive.entries, { level: 0 });
}
+type DocxPartSelect = (keep: (name: string, size: number) => boolean) => Record<string, Uint8Array>;
+
+function archiveParts(archive: Uint8Array): DocxPartSelect {
+ return (keep) => unzipSync(archive, { filter: (entry) => keep(entry.name, entry.originalSize) });
+}
+
+function rezipDocx(archive: Uint8Array, rewritten: Record<string, Uint8Array> | null): Uint8Array {
+ return rewritten ? zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 }) : archive;
+}
+
+// fflate takes the 4 bytes 20 before the end record as a zip64 locator; its own output puts the last offset or name there.
+const ZIP64_LOCATOR = "PK\u0006\u0007";
+const ZIP64_LOCATOR_OFFSET_FLOOR = 0x06000000;
+
+/** The entries when `unzipSync(zipSync(entries))` returns them unchanged, else null. */
+function repackedDocxParts(entries: Unzipped): Record<string, Uint8Array> | null {
+ if (Object.getPrototypeOf(entries) !== Object.prototype) return null;
+ const names = Object.keys(entries);
+ if (names.length >= 65535) return null;
+ let offset = 0;
+ for (const name of names) {
+ const encoded = strToU8(name);
+ offset += 30 + encoded.length + entries[name].length;
+ if (
+ encoded.length > 65535 ||
+ strFromU8(encoded) !== name ||
+ name.includes(ZIP64_LOCATOR) ||
+ offset >= ZIP64_LOCATOR_OFFSET_FLOOR
+ ) {
+ return null;
+ }
+ }
+ return entries;
+}
+
const WORDPROCESSINGML_NAMESPACES = new Set([
"http://schemas.openxmlformats.org/wordprocessingml/2006/main",
"http://purl.oclc.org/ooxml/wordprocessingml/main",
@@ -854,8 +889,12 @@ function docxMathText(element: Element, w: string): string {
/** Each equation becomes a plain run where it sits; extractRawText drops OMML. */
export function linearizeDocxMath(archive: Uint8Array): Uint8Array {
+ return rezipDocx(archive, linearizeDocxMathParts(archiveParts(archive)));
+}
+
+function linearizeDocxMathParts(select: DocxPartSelect): Record<string, Uint8Array> | null {
const rewritten: Record<string, Uint8Array> = {};
- const parts = unzipSync(archive, { filter: (entry) => entry.name.endsWith(".xml") });
+ const parts = select((name) => name.endsWith(".xml"));
for (const [name, bytes] of Object.entries(parts)) {
const xml = strFromU8(bytes);
if (!xml.includes("oMath")) continue;
@@ -889,16 +928,19 @@ export function linearizeDocxMath(archive: Uint8Array): Uint8Array {
visit(doc);
if (found) rewritten[name] = strToU8(new XMLSerializer().serializeToString(doc));
}
- if (!Object.keys(rewritten).length) return archive;
- return zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 });
+ return Object.keys(rewritten).length ? rewritten : null;
}
const W14_NAMESPACE = "http://schemas.microsoft.com/office/word/2010/wordml";
const DOCX_BREAK_OR_CHECKBOX_RE = /<(?:[\w.-]+:)?(?:br|cr|checkbox|checkBox)[\s/>]/;
export function writeDocxBreaksAndCheckboxes(archive: Uint8Array): Uint8Array {
+ return rezipDocx(archive, writeDocxBreakAndCheckboxParts(archiveParts(archive)));
+}
+
+function writeDocxBreakAndCheckboxParts(select: DocxPartSelect): Record<string, Uint8Array> | null {
const rewritten: Record<string, Uint8Array> = {};
- const parts = unzipSync(archive, { filter: (entry) => entry.name.endsWith(".xml") });
+ const parts = select((name) => name.endsWith(".xml"));
for (const [name, bytes] of Object.entries(parts)) {
const xml = strFromU8(bytes);
if (!DOCX_BREAK_OR_CHECKBOX_RE.test(xml)) continue;
@@ -944,15 +986,18 @@ export function writeDocxBreaksAndCheckboxes(archive: Uint8Array): Uint8Array {
for (const br of breaks) br.parentNode?.replaceChild(text("\n"), br);
if (boxes.length || breaks.length) rewritten[name] = strToU8(new XMLSerializer().serializeToString(doc));
}
- if (!Object.keys(rewritten).length) return archive;
- return zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 });
+ return Object.keys(rewritten).length ? rewritten : null;
}
const DOCX_TABLE_RE = /<(?:[\w.-]+:)?tbl[\s>]/;
export function writeDocxTableRows(archive: Uint8Array): Uint8Array {
+ return rezipDocx(archive, writeDocxTableRowParts(archiveParts(archive)));
+}
+
+function writeDocxTableRowParts(select: DocxPartSelect): Record<string, Uint8Array> | null {
const rewritten: Record<string, Uint8Array> = {};
- const parts = unzipSync(archive, { filter: (entry) => entry.name.endsWith(".xml") });
+ const parts = select((name) => name.endsWith(".xml"));
for (const [name, bytes] of Object.entries(parts)) {
const xml = strFromU8(bytes);
if (!DOCX_TABLE_RE.test(xml)) continue;
@@ -1027,8 +1072,7 @@ export function writeDocxTableRows(archive: Uint8Array): Uint8Array {
}
rewritten[name] = strToU8(new XMLSerializer().serializeToString(doc));
}
- if (!Object.keys(rewritten).length) return archive;
- return zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 });
+ return Object.keys(rewritten).length ? rewritten : null;
}
function listNumber(n: number, format: string | undefined): string {
@@ -1059,14 +1103,22 @@ function wordValue(node: Element | undefined, name: string): string | undefined
// Labels are an extra: a numbering part this cannot read leaves the text as Mammoth reads it.
export function writeDocxListNumbers(archive: Uint8Array): Uint8Array {
try {
- return injectDocxListNumbers(archive);
+ return rezipDocx(archive, injectDocxListNumbers(archiveParts(archive)));
} catch {
return archive;
}
}
-function injectDocxListNumbers(archive: Uint8Array): Uint8Array {
- const parts = unzipSync(archive, { filter: (entry) => /\.(?:xml|rels)$/.test(entry.name) });
+function writeDocxListNumberParts(select: DocxPartSelect): Record<string, Uint8Array> | null {
+ try {
+ return injectDocxListNumbers(select);
+ } catch {
+ return null;
+ }
+}
+
+function injectDocxListNumbers(select: DocxPartSelect): Record<string, Uint8Array> | null {
+ const parts = select((name) => /\.(?:xml|rels)$/.test(name));
const resolve = (targets: string[] | undefined, fallback: string) =>
targets?.find((path) => Object.hasOwn(parts, path)) ?? fallback;
const main = resolve(readDocxXmlTargets(parts[DOCX_PACKAGE_RELATIONSHIPS], "").get(DOCX_MAIN_DOCUMENT_TYPE), DOCX_MAIN_DOCUMENT_FALLBACK);
@@ -1082,7 +1134,7 @@ function injectDocxListNumbers(archive: Uint8Array): Uint8Array {
const related = (name: string) => parse(resolve(targets.get(`${DOCX_RELATIONSHIP_NAMESPACE}${name}`), `word/${name}.xml`));
const numbering = related("numbering");
const body = numbering && parse(main);
- if (!numbering || !body) return archive;
+ if (!numbering || !body) return null;
const byId = (parent: Element, ns: string, name: string, id: string) =>
new Map(childElements(parent, ns, name).map((node) => [node.getAttributeNS(ns, id) ?? "", node]));
@@ -1249,15 +1301,15 @@ function injectDocxListNumbers(archive: Uint8Array): Uint8Array {
for (const p of paragraphs) {
const pPr = childElements(p, w, "pPr")[0];
label(p, pPr);
- if (budget < 0) return archive;
+ if (budget < 0) return null;
// w15:restartNumberingAfterBreak
if (pPr && restartable.size && childElements(pPr, w, "sectPr").length) {
for (const id of restartable) counters.delete(id);
restartable.clear();
}
}
- if (!found) return archive;
- return zipSync({ ...unzipSync(archive), [main]: strToU8(new XMLSerializer().serializeToString(doc)) }, { level: 0 });
+ if (!found) return null;
+ return { [main]: strToU8(new XMLSerializer().serializeToString(doc)) };
}
const DOCX_NOTE_REFERENCE_RE =
@@ -1291,14 +1343,23 @@ function romanNumeral(n: number): string {
export function markDocxNotes(archive: Uint8Array): {
archive: Uint8Array;
label: (text: string) => string;
+} {
+ const { rewritten, label } = markDocxNoteParts(archiveParts(archive));
+ if (!rewritten) return { archive, label };
+ const entries: Record<string, Uint8Array> = unzipSync(archive);
+ for (const [name, bytes] of Object.entries(rewritten)) entries[name] = bytes;
+ return { archive: zipSync(entries, { level: 0 }), label };
+}
+
+function markDocxNoteParts(select: DocxPartSelect): {
+ rewritten: Record<string, Uint8Array> | null;
+ label: (text: string) => string;
} {
const names = new Set<string>();
const read = (name: string) =>
- unzipSync(archive, {
- filter: (entry) => {
- names.add(entry.name);
- return entry.name === name;
- },
+ select((entry) => {
+ names.add(entry);
+ return entry === name;
})[name];
const targetsOf = (path: string) =>
readDocxXmlTargets(
@@ -1348,7 +1409,7 @@ export function markDocxNotes(archive: Uint8Array): {
}
}
if (!kinds.footnote.bodies.size && !kinds.endnote.bodies.size) {
- return { archive, label: (text) => text };
+ return { rewritten: null, label: (text) => text };
}
const refs: { kind: keyof typeof kinds; id: string }[] = [];
@@ -1412,10 +1473,8 @@ export function markDocxNotes(archive: Uint8Array): {
}
return body + sections.join("\n\n");
};
- if (!refs.length) return { archive, label };
- const entries = unzipSync(archive);
- entries[main] = strToU8(markedXml);
- return { archive: zipSync(entries, { level: 0 }), label };
+ if (!refs.length) return { rewritten: null, label };
+ return { rewritten: { [main]: strToU8(markedXml) }, label };
}
const XML_TOKEN_RE =
@@ -1772,17 +1831,41 @@ export async function extractOfficeAttachmentText(
export async function extractDocxAttachmentText(file: File): Promise<string> {
assertDocumentAttachmentSize(file, "DOCX");
- const [{ mammoth, writeDocxSymbols }, buffer] = await Promise.all([
+ const [{ mammoth, writeDocxSymbolParts, writeDocxSymbols }, buffer] = await Promise.all([
import("./docx-reader"),
file.arrayBuffer(),
]);
- const repacked = repackDocxAttachmentArchive(
- file.name,
- new Uint8Array(buffer),
- );
- const marked = markDocxNotes(linearizeDocxMath(writeDocxSymbols(repacked, MAX_OPEN_DOCUMENT_XML_BYTES)));
+ const unpacked = unpackDocxEntries(file.name, new Uint8Array(buffer));
+ assertDocxPartSizes(file.name, unpacked);
+ let parts: Record<string, Uint8Array> | null = repackedDocxParts(unpacked.entries);
+ if (!parts) {
+ const repacked = zipSync(unpacked.entries, { level: 0 });
+ const marked = markDocxNotes(linearizeDocxMath(writeDocxSymbols(repacked, MAX_OPEN_DOCUMENT_XML_BYTES)));
+ const { value } = await mammoth.extractRawText({
+ arrayBuffer: toArrayBuffer(writeDocxTableRows(writeDocxBreaksAndCheckboxes(writeDocxListNumbers(marked.archive)))),
+ });
+ return marked.label(value);
+ }
+ // Each rewrite reads the parts the one before it left, as it would from the rezipped archive.
+ const select: DocxPartSelect = (keep) => {
+ const picked: Record<string, Uint8Array> = {};
+ for (const [name, bytes] of Object.entries(parts!)) {
+ if (keep(name, bytes.length)) picked[name] = bytes;
+ }
+ return picked;
+ };
+ const apply = (rewritten: Record<string, Uint8Array> | null) => {
+ if (rewritten) parts = { ...parts, ...rewritten };
+ };
+ apply(writeDocxSymbolParts(select, MAX_OPEN_DOCUMENT_XML_BYTES));
+ apply(linearizeDocxMathParts(select));
+ const marked = markDocxNoteParts(select);
+ apply(marked.rewritten);
+ apply(writeDocxListNumberParts(select));
+ apply(writeDocxBreakAndCheckboxParts(select));
+ apply(writeDocxTableRowParts(select));
const { value } = await mammoth.extractRawText({
- arrayBuffer: toArrayBuffer(writeDocxTableRows(writeDocxBreaksAndCheckboxes(writeDocxListNumbers(marked.archive)))),
+ arrayBuffer: toArrayBuffer(zipSync(parts, { level: 0 })),
});
return marked.label(value);
}
diff --git a/studio/frontend/src/features/chat/docx-reader.ts b/studio/frontend/src/features/chat/docx-reader.ts
index 2215c35e633..a051f324564 100644
--- a/studio/frontend/src/features/chat/docx-reader.ts
+++ b/studio/frontend/src/features/chat/docx-reader.ts
@@ -32,8 +32,19 @@ function docxSymbolText(element: Element, w: string): string {
/** Each w:sym becomes the text it shows, so the body, equation and note readers all see it.
* Parts are picked by size, not name: mammoth reaches them through relationships. */
export function writeDocxSymbols(archive: Uint8Array, maxPartBytes: number): Uint8Array {
+ const rewritten = writeDocxSymbolParts(
+ (keep) => unzipSync(archive, { filter: (entry) => keep(entry.name, entry.originalSize) }),
+ maxPartBytes,
+ );
+ return rewritten ? zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 }) : archive;
+}
+
+export function writeDocxSymbolParts(
+ select: (keep: (name: string, size: number) => boolean) => Record<string, Uint8Array>,
+ maxPartBytes: number,
+): Record<string, Uint8Array> | null {
const rewritten: Record<string, Uint8Array> = {};
- const parts = unzipSync(archive, { filter: (entry) => entry.originalSize <= maxPartBytes });
+ const parts = select((_name, size) => size <= maxPartBytes);
for (const [name, bytes] of Object.entries(parts)) {
const xml = strFromU8(bytes);
if (!xml.includes("sym")) continue;
@@ -50,6 +61,5 @@ export function writeDocxSymbols(archive: Uint8Array, maxPartBytes: number): Uin
}
if (symbols.length) rewritten[name] = strToU8(new XMLSerializer().serializeToString(doc));
}
- if (!Object.keys(rewritten).length) return archive;
- return zipSync({ ...unzipSync(archive), ...rewritten }, { level: 0 });
+ return Object.keys(rewritten).length ? rewritten : null;
}
diff --git a/studio/frontend/tests/docx-attachment-extract.test.ts b/studio/frontend/tests/docx-attachment-extract.test.ts
new file mode 100644
index 00000000000..3f9ec15a40f
--- /dev/null
+++ b/studio/frontend/tests/docx-attachment-extract.test.ts
@@ -0,0 +1,212 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { DOMParser as XmlDomParser, XMLSerializer as XmlSerializer } from "@xmldom/xmldom";
+import { strFromU8, strToU8, zipSync } from "fflate";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ extractDocxAttachmentText,
+ linearizeDocxMath,
+ markDocxNotes,
+ repackDocxAttachmentArchive,
+ writeDocxBreaksAndCheckboxes,
+ writeDocxListNumbers,
+ writeDocxTableRows,
+} = await import("../src/features/chat/attachment-content.ts");
+const { mammoth, writeDocxSymbols } = await import("../src/features/chat/docx-reader.ts");
+
+const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
+const M = 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"';
+const W14 = 'xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"';
+const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+
+function rels(entries: Array<[string, string]>): Uint8Array {
+ return strToU8(
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${entries
+ .map(([type, target], i) => `<Relationship Id="rId${i + 1}" Type="${REL}/${type}" Target="${target}"/>`)
+ .join("")}</Relationships>`,
+ );
+}
+
+const notes = (kind: string, ids: string[]) =>
+ strToU8(
+ `<w:${kind}s ${W} ${M}>${ids
+ .map(
+ (id) =>
+ `<w:${kind} w:id="${id}"><w:p><w:r><w:t>${kind} ${id} </w:t></w:r><m:oMath><m:r><m:t>y</m:t></m:r></m:oMath>` +
+ `<w:r><w:br/><w:sym w:font="Symbol" w:char="F062"/></w:r></w:p></w:${kind}>`,
+ )
+ .join("")}</w:${kind}s>`,
+ );
+
+// Every rewrite has something to do, and several read what an earlier one wrote.
+function everyRewrite(document = "word/document.xml"): Record<string, Uint8Array> {
+ return {
+ "[Content_Types].xml": strToU8("<Types/>"),
+ "_rels/.rels": rels([["officeDocument", document]]),
+ [document]: strToU8(
+ `<w:document ${W} ${M} ${W14}><w:body>` +
+ `<w:p><m:oMath><m:r><w:sym w:font="Symbol" w:char="F061"/><m:t>x</m:t></m:r></m:oMath><w:r><w:t>after math</w:t></w:r></w:p>` +
+ `<w:tbl><w:tr><w:tc><w:p><w:r><w:t>a</w:t><w:br/><w:t>b</w:t><w:footnoteReference w:id="1"/></w:r></w:p></w:tc>` +
+ `<w:tc><w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>item</w:t><w:tab/><w:t>tabbed</w:t></w:r></w:p></w:tc></w:tr></w:tbl>` +
+ `<w:sdt><w:sdtPr><w14:checkbox><w14:checked w14:val="1"/></w14:checkbox></w:sdtPr><w:sdtContent><w:p><w:r><w:t>box</w:t></w:r></w:p></w:sdtContent></w:sdt>` +
+ `<w:p><w:r><w:t>legacy</w:t><w:cr/><w:sym w:font="Wingdings" w:char="F0FC"/></w:r></w:p>` +
+ `<w:p><w:r><w:t>end</w:t><w:endnoteReference w:id="2"/></w:r></w:p></w:body></w:document>`,
+ ),
+ [`${document.replace(/[^/]*$/, "")}_rels/${document.split("/").pop()}.rels`]: rels([
+ ["footnotes", "footnotes.xml"],
+ ["endnotes", "endnotes.xml"],
+ ["numbering", "numbering.xml"],
+ ]),
+ [document.replace(/[^/]*$/, "footnotes.xml")]: notes("footnote", ["1", "3"]),
+ [document.replace(/[^/]*$/, "endnotes.xml")]: notes("endnote", ["2"]),
+ [document.replace(/[^/]*$/, "numbering.xml")]: strToU8(
+ `<w:numbering ${W}><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>` +
+ `<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>`,
+ ),
+ };
+}
+
+/** The archive-to-archive chain extractDocxAttachmentText ran before reading one map of parts. */
+async function chained(name: string, bytes: Uint8Array): Promise<string> {
+ const repacked = repackDocxAttachmentArchive(name, bytes);
+ const marked = markDocxNotes(linearizeDocxMath(writeDocxSymbols(repacked, 10 * 1024 * 1024)));
+ const archive = writeDocxTableRows(writeDocxBreaksAndCheckboxes(writeDocxListNumbers(marked.archive)));
+ const { value } = await mammoth.extractRawText({ buffer: Buffer.from(archive) } as never);
+ return marked.label(value);
+}
+
+async function withDocxGlobals<T>(run: () => Promise<T>): Promise<T> {
+ const globals = globalThis as { DOMParser?: unknown; XMLSerializer?: unknown };
+ const original = { DOMParser: globals.DOMParser, XMLSerializer: globals.XMLSerializer };
+ // The malformed fixtures would otherwise log every xmldom parse error.
+ globals.DOMParser = class extends XmlDomParser {
+ constructor() {
+ super({ errorHandler: () => undefined });
+ }
+ };
+ globals.XMLSerializer = XmlSerializer;
+ // mammoth's node build takes a buffer, not the browser build's arrayBuffer.
+ const extract = mammoth.extractRawText;
+ mammoth.extractRawText = ((input: { arrayBuffer?: ArrayBuffer }) =>
+ extract(input.arrayBuffer ? ({ buffer: Buffer.from(input.arrayBuffer) } as never) : (input as never))) as never;
+ try {
+ return await run();
+ } finally {
+ mammoth.extractRawText = extract;
+ Object.assign(globals, original);
+ }
+}
+
+async function assertSameAsChained(name: string, bytes: Uint8Array): Promise<string> {
+ const file = new File([new Uint8Array(bytes)], name);
+ const outcome = (promise: Promise<string>) =>
+ promise.then(
+ (text) => ({ text }),
+ (error: Error) => ({ error: `${error.constructor.name}: ${error.message}` }),
+ );
+ const [direct, chain] = [await outcome(extractDocxAttachmentText(file)), await outcome(chained(name, bytes))];
+ assert.deepEqual(direct, chain, name);
+ return "text" in direct ? direct.text : "";
+}
+
+/** "__proto__" cannot be a key in a zipSync input, so the name is patched into the bytes. */
+function withProtoPart(entries: Record<string, Uint8Array>, level: 0 | 6): Uint8Array {
+ const bytes = zipSync(entries, { level });
+ const from = strToU8("__PROTO__");
+ for (let i = 0; i + from.length <= bytes.length; i++) {
+ if (from.every((byte, j) => bytes[i + j] === byte)) bytes.set(strToU8("__proto__"), i);
+ }
+ return bytes;
+}
+
+/** fflate writes no zip64, so its 16-bit entry count wraps; a zip64 end record carries the full count. */
+function asZip64(bytes: Uint8Array, count: number): Uint8Array {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const end = bytes.length - 22;
+ const cdSize = view.getUint32(end + 12, true);
+ const cdOffset = view.getUint32(end + 16, true);
+ const record = new DataView(new ArrayBuffer(56 + 20));
+ record.setUint32(0, 0x06064b50, true);
+ record.setBigUint64(4, 44n, true);
+ record.setUint16(12, 45, true);
+ record.setUint16(14, 45, true);
+ record.setBigUint64(24, BigInt(count), true);
+ record.setBigUint64(32, BigInt(count), true);
+ record.setBigUint64(40, BigInt(cdSize), true);
+ record.setBigUint64(48, BigInt(cdOffset), true);
+ record.setUint32(56, 0x07064b50, true);
+ record.setBigUint64(64, BigInt(end), true);
+ record.setUint32(72, 1, true);
+ const out = new Uint8Array(bytes.length + 76);
+ out.set(bytes.subarray(0, end));
+ out.set(new Uint8Array(record.buffer), end);
+ out.set(bytes.subarray(end), end + 76);
+ new DataView(out.buffer).setUint16(end + 76 + 8, 0xffff, true);
+ new DataView(out.buffer).setUint16(end + 76 + 10, 0xffff, true);
+ return out;
+}
+
+test("extractDocxAttachmentText reads the same text as the per-rewrite archive chain", async () => {
+ await withDocxGlobals(async () => {
+ for (const level of [0, 6] as const) {
+ const text = await assertSameAsChained("all.docx", zipSync(everyRewrite(), { level }));
+ for (const piece of ["αx", "1. item", "\t", "a b[1]", "☒", "legacy\n✓", "end[i]", "Footnotes\n[1]", "Endnotes\n[i]"]) {
+ assert.ok(text.includes(piece), `${piece} in ${JSON.stringify(text)}`);
+ }
+ await assertSameAsChained("moved.docx", zipSync(everyRewrite("other/main.xml"), { level }));
+ }
+ });
+});
+
+test("extractDocxAttachmentText matches the chain on names the zip round trip changes", async () => {
+ await withDocxGlobals(async () => {
+ const base = everyRewrite();
+ const cases: Record<string, Uint8Array> = {
+ "proto.docx": withProtoPart({ ...base, __PROTO__: strToU8("<x/>") }, 0),
+ "proto-first.docx": withProtoPart({ __PROTO__: strToU8("<x/>"), ...base }, 6),
+ "proto-main.docx": withProtoPart(
+ { ...base, __PROTO__: base["word/document.xml"]!, "_rels/.rels": rels([["officeDocument", "/__PROTO__"]]) },
+ 0,
+ ),
+ "names.docx": zipSync({ ...base, "word/\ud800x.xml": strToU8(`<w:document ${W}><w:body><w:p><w:r><w:br/></w:r></w:p></w:body></w:document>`), "ünï.xml": strToU8("<a/>"), "1": strToU8("1") }),
+ "locator.docx": zipSync({ ...base, ["zzPK\u0006\u0007" + "z".repeat(24)]: strToU8("q") }),
+ };
+ for (const count of [65534, 65535, 70000]) {
+ const filler: Record<string, Uint8Array> = {};
+ for (let i = Object.keys(base).length; i < count; i++) filler[`c/${i}`] = new Uint8Array(0);
+ if (count <= 65535) cases[`many-${count}.docx`] = zipSync({ ...base, ...filler }, { level: 0 });
+ // Past the 16-bit count, a round trip keeps only the first count % 65536 entries.
+ else {
+ cases[`zip64-${count}.docx`] = asZip64(zipSync({ ...base, ...filler }, { level: 0 }), count);
+ cases[`zip64-late-${count}.docx`] = asZip64(zipSync({ ...filler, ...base }, { level: 0 }), count);
+ }
+ }
+ for (const [name, bytes] of Object.entries(cases)) await assertSameAsChained(name, bytes);
+ });
+});
+
+test("extractDocxAttachmentText keeps the chain's errors for unreadable archives", async () => {
+ await withDocxGlobals(async () => {
+ const good = zipSync(everyRewrite(), { level: 0 });
+ const broken = new Uint8Array(good);
+ broken.set(strToU8("not xml <<<"), strFromU8(broken, true).indexOf("<w:body>"));
+ for (const [name, bytes] of Object.entries({
+ "empty.docx": new Uint8Array(0),
+ "text.docx": strToU8("plain text, not a zip"),
+ "half.docx": good.subarray(0, good.length >> 1),
+ "no-body.docx": zipSync({ "[Content_Types].xml": strToU8("<Types/>") }),
+ "broken-xml.docx": zipSync({ ...everyRewrite(), "word/document.xml": strToU8(`<w:document ${W}><w:body><w:p><w:r><w:t>x</w:r></w:body>`) }),
+ "stored-broken.docx": broken,
+ })) {
+ await assertSameAsChained(name, bytes);
+ }
+ });
+});