Files
docx/scripts/layout-probes/word-continued-endnotes.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

153 lines
8.7 KiB
TypeScript

/**
* Probes of how Word fills a page of endnotes after the first, below the continuation separator, where
* word-watertight-endnotes.ts left it open. There, 48 lines exactly 288 tall went below the continuation separator, whether
* it was a line of Calibri 11 or written exactly 1100 tall (EN1, EN2), and a line of 183 and 47 of 288 (EN3): as many as
* fit on the page without the separator, the last up to 134.55 past the margin. Two readings fit all three: the
* separator's room is left out, so lines go past the margin by up to its height, or a line goes on the page while its top
* is above the margin. These tell them apart, and say how tall Word makes the continuation separator, which was a line of
* Calibri 11 in EN2 though written 1100 tall, and in SC4 of word-watertight-sections.ts though written with 537 after.
*
* Calibri 11 on A4 with 1440 margins, so the page's text is 13958 twips tall. In each, a line refers to two endnotes. The
* first takes the rest of the first page, to 9.9 twips above the margin, with 45 lines and one exactly 451 twips tall, as
* in word-watertight-endnotes.ts, so the second starts the next page, below the continuation separator. Each line of the
* endnotes is exactly as tall as it says, and its text names its probe, as word-continued-endnotes.py reads them.
* Endnotes are at the end of a document, so each probe is a document of its own.
*
* CE1: 47 lines of 288, then one of 600, then 20 of 288. With the separator's room left out, the 600 doesn't fit
* (47 * 288 + 600 = 14136) and starts the next page. Going on while its top is above the margin, it is on the page:
* its top is 268.55 + 47 * 288 = 13804.55 down
* CE2: a line of 299, then 111 lines of 150 in Calibri 6. With the separator's room left out, 91 of the 150 fit
* (299 + 91 * 150 = 13949). Going on while its top is above the margin, 90: the 91st starts 109.55 past it
* CE3: as CE1 without the 600, the continuation separator in Calibri 20 (488.28 tall at single spacing). With its room
* left out, 48 lines of 288 fit, the last 354.28 past the margin. Going on while its top is above the margin, 47.
* Where the first line starts says whether the separator's size counts
* CE4: as CE3, both separators in Calibri 11 with 400 before: where the first endnote starts on the first page, and the
* second on the next, say whether the space before is kept
* CE5: the separator written exactly 1100 tall, and the continuation separator double spaced, with a first endnote of 5
* lines: where the endnotes start on each page says whether their line spacing is kept
*
* Word (word-continued-endnotes1.pdf to 5.pdf, Word 16 for Mac, read with word-continued-endnotes.py):
* CE1: the 600 starts the next page, below 47 lines: the separator's room is left out, and a line doesn't go on because
* its top is above the margin
* CE2: the line of 299 and 91 of 150 on the page, the last 259.55 past the margin
* CE3: 48 lines, from 268.55 down: the separator is a line of Calibri 11, and drawn where CE1's is, in 20 points too
* CE4: both separators a line tall, without their 400 before: the first endnote starts where it does in CE1
* CE5: the same, though the separator is written 1100 tall and the continuation separator double spaced
* So Word lays out both separators a line of the document's text tall, whatever their own formatting, and fills each page
* after the first with as many lines as fit on it without the continuation separator
*
* Usage: npm run run-ts -- scripts/layout-probes/word-continued-endnotes.ts, which writes
* build/word-probes/word-continued-endnotes1.docx to 5.
*/
// cspell:ignore bbox
import { mkdirSync, writeFileSync } from "node:fs";
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
import { Document, EndnoteReferenceRun, LineRuleType, Packer, Paragraph, TextRun } from "docx";
/** A line of an endnote, exactly this tall, in Calibri of this size in half points */
const noteLine = (text: string, height = 288, size = 22): Paragraph =>
new Paragraph({
style: "EndnoteText",
spacing: { line: height, lineRule: LineRuleType.EXACT },
children: [new TextRun({ text, size })],
});
const lines = (name: string, count: number, from = 1, height = 288, size = 22): Paragraph[] =>
Array.from({ length: count }, (_, i) => noteLine(`${name} note 2 line ${from + i}`, height, size));
/** The first endnote: 45 lines and one of 451, which end 9.9 above the margin below a line and the separator */
const fillsFirstPage = (name: string): Paragraph[] => [
...Array.from({ length: 45 }, (_, i) => noteLine(`${name} note 1 line ${i + 1}`)),
noteLine(`${name} note 1 line 46`, 451),
];
const probe = (name: string, first: readonly Paragraph[], second: readonly Paragraph[]): Document =>
new Document({
styles: {
default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { before: 0, after: 0, line: 240 } } } },
paragraphStyles: [
{ id: "EndnoteText", name: "endnote text", run: { size: 22 }, paragraph: { spacing: { before: 0, after: 0 } } },
],
},
endnotes: { 1: { children: [...first] }, 2: { children: [...second] } },
sections: [
{
children: [
new Paragraph({ children: [new TextRun(`${name} refs`), new EndnoteReferenceRun(1), new EndnoteReferenceRun(2)] }),
],
},
],
});
/** The paragraph properties of a separator as docx writes them, which `changed` replaces */
const SPACING = '<w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>';
const SEPARATOR = '<w:endnote w:type="separator" w:id="-1"><w:p>';
const CONTINUATION = '<w:endnote w:type="continuationSeparator" w:id="0"><w:p>';
/** Changes the endnotes' XML, failing when a change finds nothing to change */
const changed = (xml: string, from: string, to: string, name: string): string => {
if (!xml.includes(from)) {
throw new Error(`${name}: ${from} isn't in the endnotes`);
}
return xml.replace(from, to);
};
/** Gives a separator (`which`) other paragraph properties */
const separatorWith = (xml: string, which: string, properties: string, name: string): string =>
changed(xml, which + SPACING, which + properties, name);
const write = async (document: Document, name: string, change?: (endnotes: string) => string): Promise<void> => {
const zip = unzipSync(await Packer.toBuffer(document), { filter: ({ name }) => !name.endsWith("/") });
if (change) {
zip["word/endnotes.xml"] = strToU8(change(strFromU8(zip["word/endnotes.xml"])));
}
mkdirSync("build/word-probes", { recursive: true });
writeFileSync(`build/word-probes/${name}.docx`, zipSync(zip, { level: 6 }));
};
const main = async (): Promise<void> => {
await write(
probe("CE1", fillsFirstPage("CE1"), [...lines("CE1", 47), noteLine("CE1 note 2 tall line 48", 600), ...lines("CE1", 20, 49)]),
"word-continued-endnotes1",
);
await write(
probe("CE2", fillsFirstPage("CE2"), [noteLine("CE2 note 2 line 0", 299), ...lines("CE2", 111, 1, 150, 12)]),
"word-continued-endnotes2",
);
// CE3: the continuation separator's text and mark in Calibri 20
const size40 = '<w:rPr><w:sz w:val="40"/><w:szCs w:val="40"/></w:rPr>';
await write(probe("CE3", fillsFirstPage("CE3"), lines("CE3", 150)), "word-continued-endnotes3", (xml) =>
changed(
separatorWith(xml, CONTINUATION, `<w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/>${size40}</w:pPr>`, "CE3"),
"<w:r><w:continuationSeparator/></w:r>",
`<w:r>${size40}<w:continuationSeparator/></w:r>`,
"CE3",
),
);
// CE4: both separators with 400 before
const before400 = '<w:pPr><w:spacing w:before="400" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>';
await write(probe("CE4", fillsFirstPage("CE4"), lines("CE4", 150)), "word-continued-endnotes4", (xml) =>
separatorWith(separatorWith(xml, SEPARATOR, before400, "CE4"), CONTINUATION, before400, "CE4"),
);
// CE5: the separator exactly 1100 tall, the continuation separator double spaced
await write(
probe(
"CE5",
Array.from({ length: 5 }, (_, i) => noteLine(`CE5 note 1 line ${i + 1}`)),
lines("CE5", 150),
),
"word-continued-endnotes5",
(xml) =>
separatorWith(
separatorWith(xml, SEPARATOR, '<w:pPr><w:spacing w:after="0" w:line="1100" w:lineRule="exact"/></w:pPr>', "CE5"),
CONTINUATION,
'<w:pPr><w:spacing w:after="0" w:line="480" w:lineRule="auto"/></w:pPr>',
"CE5",
),
);
};
void main();