Files
docx/scripts/compare-layout.ts
DolanandClaude Opus 5.5 2e07d2d688 perf: make the browser bundle 29 KB smaller, zipping with fflate and hashing with docx's own SHA-1 and SHA-256 (#3834) (#3836)
* build(deps): add fflate, to zip and unzip packages in place of JSZip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* perf: hash with docx's own SHA-1 and SHA-256, in place of hash.js

hash.js was about 6.5 KB of a browser bundle, minified and gzipped, as its whole library is bundled for the two hashes
docx uses: SHA-1 for the names of media files (`hashedId`) and SHA-256 for the password that protects a document. It
hasn't had a release since 2018, and brought `inherits` and `minimalistic-assert` with it. The platforms' own hashes
can't replace it, as browsers only hash asynchronously and documents are written synchronously.

The hashes are the same: they match FIPS 180-4's examples and node:crypto, and the password hash Word accepts is
unchanged. They are also faster: hashing a 5 MB image takes about half the time, and a password's 100,000 rounds about
130 ms rather than 155 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* perf: zip and unzip with fflate, in place of JSZip

JSZip was about 30 KB of a browser bundle, minified and gzipped, as its prebuilt browser file brings its own copy of
pako and more. fflate's zipSync and unzipSync, the only parts docx needs, are about 6 KB. Together with the hashes, the
bundle of a page that packs a document goes from 123 KB to 94 KB.

Nothing changes for users:
- Packer and patchDocument give each output type as JSZip gave it, including "string" and "binarystring" as a
  character for each byte, a Blob with the .docx or .docm MIME type, and the same errors for "nodebuffer" without
  Buffer, a Blob without Blob, and "text", which JSZip never gave.
- patchDocument and patchDetector still take a JSZip instance, which is read through its generateAsync, so the types
  no longer import jszip. They also still take the other forms JSZip read: a string with a character for each byte, an
  array of bytes, a Blob, an ArrayBuffer and bytes from another realm.
- A part's text keeps a byte order mark at its start, as it did.
- Packer.toStream still compiles synchronously, so it throws as before, and gives the document a turn of the event
  loop later.

Zipping is now synchronous, and faster: packing a document with 5,000 paragraphs and 5 MB of images takes 83 ms
rather than 182 ms.

The zip files no longer have folder entries, which JSZip added for each folder. Word doesn't write them, and nothing
reads them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* test: test the packer and the patcher's zip reading without JSZip

These specs mocked JSZip or read the JSZip instance the compiler returned. They now build real zip files and read
what the Packer and the patcher give, so they test the zipping too:
- loadZip reads every form a template can be given in, a JSZip instance through its generateAsync, and leaves out
  folders
- Packer.toStream throws when the document can't be written, and gives it even to a listener added after an await
- toBlob, toArrayBuffer and toStream give real zip files, rather than what a mocked compiler gave

The counts of the files in a package no longer include the folder entries JSZip added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* test: test zipping, unzipping and each output type of a zip file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* chore: read and write .docx files in the scripts with fflate, in place of JSZip

docx is replacing JSZip with fflate (#3834), and jszip is leaving package.json, so the scripts that read documents
(compare-layout.ts, the layout probes' line checkers) and the probes that edit docx's output before writing it use
fflate's unzipSync and zipSync. They leave out folder entries when they unzip, as Word's own files have none, and zip
at level 6. The written documents have the same files in the same order, with the same contents, as before.

check-api.ts's comment no longer says the built declarations import jszip. Those of releases up to 9.14.0 still do,
and the import, which no longer resolves, is any there, which the check accepts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* fix: load Node's types from docx's declarations, which JSZip's used to load

The declarations use Node's types, such as Buffer and NodeJS.ReadableStream. They had them because they imported
JSZip's declarations, which reference Node's types. Without JSZip, a project that doesn't load every @types package,
such as one with `types` set, or TypeScript 6's default, would find no Buffer in docx's types, and docx's own optional
entries didn't build. The reference is kept in the built declarations with `preserve="true"`, as TypeScript otherwise
leaves it out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* test: read and make zip files with fflate in the specs of charts, embedded files, macros, shapes and the core, in place of JSZip

jszip is leaving docx's dependencies, so these specs read packed documents and make changed templates with the helpers
in tests/zip, which unzip and zip with fflate, as docx now does. Each test checks what it checked before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* test: read and make zip files with fflate in the specs of docx/html, docx/layout and the patcher, in place of JSZip

jszip is leaving docx's dependencies, as docx now zips and unzips with fflate, so these specs read packed documents
and make templates with the helpers in src/tests/zip.ts. Templates that were JSZip instances are now zip files' bytes,
and the specs read text and bytes from the unzipped files directly, so some helpers that only awaited JSZip are no
longer asynchronous.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* test: patch real zip files in patchDocument's spec, rather than mocking JSZip

JSZip is leaving the dependencies. The spec mocked JSZip.loadAsync and passed an empty Buffer as the template, so
patchDocument never unzipped anything. Each template is now a real zip file, made with the specs' zip helper, so the
tests exercise the unzipping too. The tests of a template opened with JSZip pass an object with generateAsync, which
is how a JSZip instance is read now.

The path keys of the templates are covered by one file-level naming-convention exception, in place of the comments on
each patch key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* build(deps): remove jszip, as nothing uses it now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* fix: refuse a zip file's entry of the wrong size before taking memory for it, and inflate only what patchDetector reads

fflate takes room for the size a zip file gives an entry before inflating it, so a template of a few hundred bytes
could make docx take 4 GB, which fails in a browser or a process with a memory limit. JSZip refused such an entry
("uncompressed data size mismatch"). An entry whose given size is more than DEFLATE can inflate its data to (1032
times) is now refused before fflate takes the room, and one that inflates to less than its given size after.

JSZip also inflated only the entries that were read, so patchDetector, which reads only the XML parts in word/, never
inflated a template's images or embedded files. unzipFiles and loadZip now take the paths to read, and patchDetector
gives them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

* fix: refuse a zip file whose entries claim more compressed data than the zip file holds, before taking memory for them

The size an entry inflates to was checked against its compressed size, but that is also read from the zip file, so an
entry could claim compressed data larger than the zip file and pass. The entries docx reads now have their compressed
sizes added up, and a total larger than the zip file is refused before fflate takes room for the entry. Together with
DEFLATE's ratio, that keeps the room taken to 1032 times the zip file's size, as a real zip bomb's is.

The tests damage the entry's data too, so only a refusal before inflating gives their error: without either check, each
fails with fflate's own error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 00:08:58 +01:00

351 lines
18 KiB
TypeScript

/**
* Compares the page numbers docx/layout wrote into the tables of contents of the documents scripts/compare-layout.sh
* made with the pages LibreOffice put their headings on, and Word, when PDFs of them saved from Word are there. Then it
* compares docx/layout with Word's own pages in documents saved from Word, through the .docx adapter.
*
* Usage: npm run run-ts -- scripts/compare-layout.ts [directory]
*
* The directory (default build/layout) has each document's .docx, and the text of LibreOffice's pages of it in a .txt,
* with the pages split by form feeds, as pdftotext writes them, and of Word's in a .word.txt. A heading is on the last
* page with a line of only its text, as its entry in the table of contents, before it, has its page number on the line
* too. Spaces and tabs count as one space, because pdftotext can write a tab, or a wide gap, as several. So the headings
* of the documents compared are each on a line of their own, and their pages are numbered from 1. It fails when a
* heading's page number isn't LibreOffice's or Word's, or is left blank, when the number of pages written into a NUMPAGES
* field isn't the number of pages of LibreOffice's or Word's PDF, and when there is no text of LibreOffice's pages of a
* document, as when it couldn't convert it.
*
* A document saved from Word, named after it with .word.docx, such as text-and-spacing.word.docx, has Word's own pages:
* Word writes a w:lastRenderedPageBreak where each page began when it last laid the document out. docx/layout lays out
* the document Word saved, read through the .docx adapter as patchDocument's templates are, and each bookmark a page
* reference refers to, such as each heading of a table of contents, is compared with the page Word put it on. It fails
* when one isn't on Word's page, and when the number of pages isn't Word's. A document whose marks don't have all of
* Word's pages (see wordPagesOf) isn't compared, and fails when it is one committed in scripts/layout-probes, which are
* there because their marks have them all.
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { type Unzipped, strFromU8, unzipSync } from "fflate";
import { type XmlElement as Element, parseXml } from "../src/util/xml";
import { estimatePageNumbers } from "../src/layout/estimate-page-numbers";
const directory = process.argv[2] ?? "build/layout";
/** The text of an element, with its tabs, leaving out field instructions */
const textOf = (element: Element): string => {
if (element.type === "text") {
return String(element.text);
}
if (element.name === "w:instrText") {
return "";
}
if (element.name === "w:tab" && element.type === "element") {
return "\t";
}
return (element.elements ?? []).map(textOf).join("");
};
/** Text with each run of spaces and tabs as one space, and none at either end */
const collapsed = (text: string): string => text.replace(/\s+/g, " ").trim();
const paragraphsIn = (element: Element): readonly Element[] =>
element.name === "w:p" ? [element] : (element.elements ?? []).flatMap(paragraphsIn);
/** The files in a .docx, by their paths, leaving out its folders */
const filesOf = (path: string): Unzipped => unzipSync(readFileSync(path), { filter: ({ name }) => !name.endsWith("/") });
/** Each entry of the document's tables of contents: its heading's text, and the page number written for it */
const entriesOf = (path: string): readonly { readonly title: string; readonly page: string }[] => {
const document = parseXml(strFromU8(filesOf(path)["word/document.xml"]));
return paragraphsIn(document)
.filter((paragraph) => JSON.stringify(paragraph).includes("PAGEREF _Toc"))
.map((paragraph) => {
// Leaving out the paragraph's properties, whose tab stops aren't tabs in its text
const text = (paragraph.elements ?? [])
.filter(({ name }) => name !== "w:pPr")
.map(textOf)
.join("");
const split = text.lastIndexOf("\t");
return { title: collapsed(text.slice(0, split)), page: text.slice(split + 1).trim() };
});
};
/** The results written into the NUMPAGES fields of the document's text, headers and footers */
const pageCountsOf = (path: string): readonly string[] => {
const files = filesOf(path);
const parts = Object.keys(files).filter((file) => /^word\/(document|header\d+|footer\d+)\.xml$/.test(file));
const results: string[] = [];
const fields: { instruction: string; result?: string }[] = [];
const read = (element: Element): void => {
const field = fields[fields.length - 1];
const type = element.name === "w:fldChar" ? element.attributes?.["w:fldCharType"] : undefined;
if (type === "begin") {
fields.push({ instruction: "" });
} else if (type === "separate" && field) {
field.result = "";
} else if (type === "end" && field) {
fields.pop();
if (/^\s*NUMPAGES\b/.test(field.instruction)) {
results.push(field.result ?? "");
}
} else if (element.name === "w:instrText" && field) {
field.instruction += textOf({ ...element, name: "w:t" });
} else if (element.name === "w:t" && field?.result !== undefined) {
field.result += textOf(element);
} else {
(element.elements ?? []).forEach(read);
}
};
for (const part of parts) {
read(parseXml(strFromU8(files[part])));
}
return results;
};
/** The first element of the name in an element, in document order */
const findElement = (element: Element, name: string): Element | undefined =>
element.name === name
? element
: (element.elements ?? []).reduce<Element | undefined>((found, child) => found ?? findElement(child, name), undefined);
/** The XML parts of a .docx, parsed as patchDocument parses them, by their paths */
const partsOf = (path: string): ReadonlyMap<string, Element> =>
new Map(
Object.entries(filesOf(path))
.filter(([file]) => file.endsWith(".xml") || file.endsWith(".rels"))
.map(([file, data]) => [file, parseXml(strFromU8(data), { keepWhitespaceText: true })] as const),
);
/**
* Word's pages of a document it saved, read from the w:lastRenderedPageBreak elements Word writes where each page began
* when it last laid the document out: the page each bookmark starts on, as of the first text after it, and the number
* of pages. Also each bookmark's paragraph's text, and the bookmarks page references refer to.
*
* Word's PDFs of the layout demos showed where it writes them, and where it doesn't:
*
* - a row that breaks across pages has one in each of its cells that goes on to the next page, which are one page
* - the row or paragraph just after a row that broke across pages starts with one, though it is on the same page
* - there is none for the blank page before a section that starts on an odd or even page, so one is added when the
* section would start on a page of the other kind, with pages counted from 1
* - there is none where a column break starts a page, in a table of contents, nor on the pages Word hadn't laid out yet
* when it saved the document, so the pages read are only Word's when there are as many of them as Word says the
* document has (`Pages` in docProps/app.xml)
*/
const wordPagesOf = (
document: Element,
): {
readonly pages: ReadonlyMap<string, number>;
readonly titles: ReadonlyMap<string, string>;
readonly referred: readonly string[];
readonly pageCount: number;
} => {
const pages = new Map<string, number>();
const titles = new Map<string, string>();
const referred = new Set<string>();
// How each section starts, from its properties at its end
const starts: string[] = [];
const findSections = (element: Element): void => {
if (element.name === "w:sectPr") {
starts.push(String(element.elements?.find(({ name }) => name === "w:type")?.attributes?.["w:val"] ?? "nextPage"));
}
(element.elements ?? []).forEach(findSections);
};
findSections(document);
let page = 1;
let section = 0;
let sectionStarted = false;
let waiting: string[] = [];
// Whether a row just broke across pages, so a mark before any text after it is on the same page
let afterBrokenRow = false;
// The row being read: whether it has had a mark, which is its page's, and text, and whether it broke across pages
let row: { counted: boolean; text: boolean; broke: boolean } | undefined;
const read = (element: Element, paragraph: Element | undefined): void => {
if (element.name === "w:lastRenderedPageBreak") {
if (afterBrokenRow) {
afterBrokenRow = false;
} else if (!row?.counted) {
page++;
row = row && { ...row, counted: true };
}
row = row && { ...row, broke: row.broke || row.text };
} else if (element.name === "w:bookmarkStart") {
const name = String(element.attributes?.["w:name"]);
waiting.push(name);
titles.set(name, collapsed(paragraph ? textOf(paragraph) : ""));
} else if (element.name === "w:instrText") {
const reference = /^\s*PAGEREF\s+("?)([^\s"\\]+)\1/i.exec(textOf({ ...element, name: "w:t" }));
if (reference) {
referred.add(reference[2]);
}
} else if ((element.name === "w:t" && textOf(element).length > 0) || element.name === "w:tab" || element.name === "w:drawing") {
const start = starts[section];
if (sectionStarted && ((start === "oddPage" && page % 2 === 0) || (start === "evenPage" && page % 2 === 1))) {
// The blank page before it
page++;
}
sectionStarted = false;
afterBrokenRow = false;
row = row && { ...row, text: true };
waiting.forEach((name) => pages.set(name, page));
waiting = [];
} else if (element.name === "w:tr" && !row) {
row = { counted: false, text: false, broke: false };
(element.elements ?? []).forEach((child) => read(child, paragraph));
afterBrokenRow = row.broke;
row = undefined;
} else {
(element.elements ?? []).forEach((child) => read(child, element.name === "w:p" ? element : paragraph));
// A paragraph whose properties have its section's ends the section
if (
element.name === "w:p" &&
element.elements?.find(({ name }) => name === "w:pPr")?.elements?.some(({ name }) => name === "w:sectPr")
) {
section++;
sectionStarted = true;
}
}
};
read(document, undefined);
return { pages, titles, referred: [...referred], pageCount: page };
};
/** The pages of a PDF's text, each as its lines, or undefined when there is no such file */
const pagesOf = (path: string): readonly (readonly string[])[] | undefined =>
existsSync(path)
? readFileSync(path, "utf8")
.split("\f")
.map((page) => page.split("\n").map(collapsed))
: undefined;
// What each document is compared with: LibreOffice's pages, and Word's when they are there (see scripts/compare-layout.sh)
const REFERENCES = [
{ name: "LibreOffice", suffix: ".txt" },
{ name: "Word", suffix: ".word.txt" },
] as const;
const counts = new Map(REFERENCES.map(({ name }) => [name, { compared: 0, matched: 0 }]));
const pageCounts = new Map(REFERENCES.map(({ name }) => [name, { compared: 0, matched: 0 }]));
// The documents LibreOffice didn't lay out, which aren't compared
const notLaidOut: string[] = [];
for (const name of readdirSync(directory)
.filter((file) => file.endsWith(".docx") && !file.endsWith(".word.docx"))
.sort()) {
const entries = entriesOf(join(directory, name));
const references = REFERENCES.flatMap((reference) => {
const pages = pagesOf(join(directory, name.replace(/\.docx$/, reference.suffix)));
return pages ? [{ ...reference, pages }] : [];
});
console.log(`\n${name}`);
if (!references.some((reference) => reference.name === "LibreOffice")) {
console.log(" FAIL LibreOffice didn't lay it out");
notLaidOut.push(name);
}
for (const { title, page } of entries) {
const results = references.map(({ name: reference, pages }) => {
const found = String(pages.findLastIndex((lines) => lines.includes(title)) + 1);
const count = counts.get(reference)!;
count.compared++;
count.matched += page === found ? 1 : 0;
return `${page === found ? " " : "*"}${reference} ${found === "0" ? "none" : found.padStart(4)}`;
});
const matches = results.every((result) => result.startsWith(" "));
console.log(
`${matches ? " ok " : " FAIL"} ${title.padEnd(50)} docx/layout ${(page || "blank").padStart(5)} ${results.join(" ")}`,
);
}
// pdftotext ends each page with a form feed
const written = [...new Set(pageCountsOf(join(directory, name)))];
if (written.length > 0) {
const results = references.map(({ name: reference, pages }) => {
const found = String(pages.length - 1);
const count = pageCounts.get(reference)!;
count.compared++;
count.matched += written.length === 1 && written[0] === found ? 1 : 0;
return `${written.length === 1 && written[0] === found ? " " : "*"}${reference} ${found.padStart(4)}`;
});
const matches = results.every((result) => result.startsWith(" "));
console.log(
`${matches ? " ok " : " FAIL"} ${"Number of pages (NUMPAGES)".padEnd(50)} docx/layout ${(written.join(", ") || "blank").padStart(5)} ${results.join(" ")}`,
);
}
}
// Documents saved from Word, laid out through the .docx adapter, and compared with the pages Word marked in them. Each has
// Word's own pages in it, so it stays a check of docx/layout when the demo it was saved from changes, as Word's PDF of
// the demo doesn't
const saved = { compared: 0, matched: 0 };
const savedPageCounts = { compared: 0, matched: 0 };
// The documents whose marks don't have all of Word's pages, which aren't compared, and those of them that are committed
const notMarked: string[] = [];
const notMarkedCommitted: string[] = [];
for (const name of readdirSync(directory)
.filter((file) => file.endsWith(".word.docx"))
.sort()) {
const parts = partsOf(join(directory, name));
const marked = wordPagesOf(parts.get("word/document.xml")!);
// The number of pages Word had laid out when it saved the document
const app = parts.get("docProps/app.xml");
const pagesElement = app && findElement(app, "Pages");
const laidOut = pagesElement ? Number(textOf(pagesElement)) : undefined;
if (laidOut !== marked.pageCount) {
// Those committed in scripts/layout-probes are there because their marks have all their pages, so one that doesn't
// is read wrong, and fails
const committed = existsSync(join("scripts", "layout-probes", name));
console.log(
`\n${name}, saved from Word: ${committed ? "FAIL, " : ""}its marks have ${marked.pageCount} of its ${laidOut ?? "unknown"} pages, so it isn't compared`,
);
notMarked.push(name);
notMarkedCommitted.push(...(committed ? [name] : []));
continue;
}
console.log(`\n${name}, saved from Word`);
const estimate = estimatePageNumbers({ parts });
for (const bookmark of marked.referred.filter((referredTo) => marked.pages.has(referredTo))) {
const page = estimate.bookmarks.get(bookmark) ?? "";
const found = String(marked.pages.get(bookmark));
saved.compared++;
saved.matched += page === found ? 1 : 0;
console.log(
`${page === found ? " ok " : " FAIL"} ${marked.titles.get(bookmark)!.slice(0, 50).padEnd(50)} docx/layout ${(page || "blank").padStart(5)} ${page === found ? " " : "*"}Word ${found.padStart(4)}`,
);
}
const counted = String(estimate.pageCount ?? "");
savedPageCounts.compared++;
savedPageCounts.matched += counted === String(laidOut) ? 1 : 0;
console.log(
`${counted === String(laidOut) ? " ok " : " FAIL"} ${"Number of pages".padEnd(50)} docx/layout ${(counted || "blank").padStart(5)} ${counted === String(laidOut) ? " " : "*"}Word ${String(laidOut).padStart(4)}`,
);
}
console.log("");
for (const [reference, { compared, matched }] of counts) {
if (compared > 0) {
console.log(`${matched} of ${compared} headings are on ${reference}'s page`);
}
}
for (const [reference, { compared, matched }] of pageCounts) {
if (compared > 0) {
console.log(`${matched} of ${compared} numbers of pages are ${reference}'s`);
}
}
if (saved.compared > 0) {
console.log(
`${saved.matched} of ${saved.compared} headings are on Word's page in the documents saved from Word, laid out through the .docx adapter`,
);
console.log(`${savedPageCounts.matched} of ${savedPageCounts.compared} numbers of pages are Word's in the documents saved from Word`);
}
if (notMarked.length > 0) {
console.log(`Word's marks don't have all the pages of ${notMarked.join(", ")}, which aren't compared`);
}
if (notLaidOut.length > 0) {
console.log(`LibreOffice didn't lay out ${notLaidOut.join(", ")}`);
}
process.exit(
notLaidOut.length === 0 &&
notMarkedCommitted.length === 0 &&
[...counts.values(), ...pageCounts.values(), saved, savedPageCounts].every(({ compared, matched }) => compared === matched)
? 0
: 1,
);