From 3b4f7777cd961ed3c19572f6262d90cd74bd640b Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 17 Oct 2026 19:30:50 +0100 Subject: [PATCH] fix: patch a template read from a stream (#2321) (#3786) --- docs/usage/patcher.md | 2 + src/patcher/from-docx.ts | 8 ++-- src/patcher/load-zip.spec.ts | 58 ++++++++++++++++++++++++++++ src/patcher/load-zip.ts | 62 ++++++++++++++++++++++++++++++ src/patcher/patch-detector.spec.ts | 19 +++++++++ src/patcher/patch-detector.ts | 5 +-- 6 files changed, 148 insertions(+), 6 deletions(-) create mode 100644 src/patcher/load-zip.spec.ts create mode 100644 src/patcher/load-zip.ts diff --git a/docs/usage/patcher.md b/docs/usage/patcher.md index 0899524e5f..bf23dfdcd7 100644 --- a/docs/usage/patcher.md +++ b/docs/usage/patcher.md @@ -23,6 +23,8 @@ const doc = await patchDocument({ fs.writeFileSync("My Patched Document.docx", doc); ``` +`data` can be a `Buffer`, `Uint8Array`, `ArrayBuffer`, `Blob`, `JSZip` instance, or a Node.js stream such as `fs.createReadStream("My Document.docx")` or `Packer.toStream(doc)`. A stream can be read only once, so to pass the same template to both `patchDetector` and `patchDocument`, read it into a `Buffer` first. + ## Discover placeholders before building patches Use `patchDetector({ data })` to find the placeholder keys in a template before calling `patchDocument`. It returns distinct keys without the `{{` and `}}` delimiters. This is useful when templates differ: an expensive patch, such as downloading images, only needs to be built when its placeholder is present. diff --git a/src/patcher/from-docx.ts b/src/patcher/from-docx.ts index fcaaba1d65..54c9452c6b 100644 --- a/src/patcher/from-docx.ts +++ b/src/patcher/from-docx.ts @@ -7,6 +7,7 @@ * @module */ import JSZip from "jszip"; +import type { Stream } from "stream"; import { ImageReplacer } from "@export/packer/image-replacer"; import { xmlifyPackageParts } from "@export/packer/package-part-writer"; @@ -30,6 +31,7 @@ import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids"; import { appendContentType, appendContentTypeOverride } from "./content-types-manager"; import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids"; import { type DrawingPatch, patchDrawings, relationshipsPathOf } from "./drawing-patch"; +import { loadZip } from "./load-zip"; import { patchNotes } from "./notes"; import { patchNumbering } from "./numbering"; import { type TemplatePageNumberEstimator, fillTemplatePageNumbers } from "./page-numbers"; @@ -45,10 +47,10 @@ import { toJson } from "./util"; * Supported input data types for document patching. * * The patcher can accept documents in various formats including buffers, - * arrays, and streams. + * arrays, and streams, such as `fs.createReadStream`'s or `Packer.toStream`'s. */ // eslint-disable-next-line functional/prefer-readonly-type -export type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream | JSZip; +export type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream | Stream | JSZip; export { PatchType } from "./patch-type"; export { DrawingPatch } from "./drawing-patch"; @@ -315,7 +317,7 @@ export const patchDocument = async ): Promise => { - const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data); + const zipContent = await loadZip(data); const contexts = new Map(); // Theme colors in patches are written with the hex color they come to in the document's theme const themeColors = await readThemeColors(zipContent); diff --git a/src/patcher/load-zip.spec.ts b/src/patcher/load-zip.spec.ts new file mode 100644 index 0000000000..a0b4f41b24 --- /dev/null +++ b/src/patcher/load-zip.spec.ts @@ -0,0 +1,58 @@ +import JSZip from "jszip"; +import { Readable, Stream } from "stream"; +import { describe, expect, it } from "vitest"; + +import { Document, Packer, Paragraph } from "../index"; +import type { InputDataType } from "./from-docx"; +import { loadZip } from "./load-zip"; + +const zipBytes = (): Promise => { + const zip = new JSZip(); + zip.file("word/document.xml", ""); + return zip.generateAsync({ type: "uint8array" }); +}; + +const documentXmlOf = async (data: InputDataType): Promise => + (await loadZip(data)).file("word/document.xml")?.async("string"); + +describe("loadZip", () => { + it("returns a JSZip instance as it is", async () => { + const zip = new JSZip(); + + expect(await loadZip(zip)).toBe(zip); + }); + + it("opens a zip file from its bytes", async () => { + expect(await documentXmlOf(await zipBytes())).toBe(""); + }); + + it("opens a zip file from a stream that gives its bytes in chunks", async () => { + const bytes = await zipBytes(); + const stream = Readable.from([bytes.subarray(0, 10), bytes.subarray(10, 50), bytes.subarray(50)]); + + expect(await documentXmlOf(stream)).toBe(""); + }); + + it("opens a zip file from a stream that gives each byte as a number, as Readable.from of a Uint8Array does", async () => { + expect(await documentXmlOf(Readable.from(await zipBytes()))).toBe(""); + }); + + it("opens a zip file from a stream with no iterator, such as Packer.toStream's", async () => { + const stream = Packer.toStream(new Document({ sections: [{ children: [new Paragraph("Hello")] }] })); + + expect(Symbol.asyncIterator in stream).toBe(false); + expect(await documentXmlOf(stream)).toContain("Hello"); + }); + + it("rejects a stream that gives text, naming what it gave", async () => { + await expect(loadZip(Readable.from(["PK"]))).rejects.toThrow("A template stream must give bytes, but it gave a string"); + }); + + it("rejects with a stream's error", async () => { + const stream = new Stream(); + const zip = loadZip(stream); + stream.emit("error", new Error("The file could not be read")); + + await expect(zip).rejects.toThrow("The file could not be read"); + }); +}); diff --git a/src/patcher/load-zip.ts b/src/patcher/load-zip.ts new file mode 100644 index 0000000000..2ddcbc42e0 --- /dev/null +++ b/src/patcher/load-zip.ts @@ -0,0 +1,62 @@ +import JSZip from "jszip"; +import type { Stream } from "stream"; + +import type { InputDataType } from "./from-docx"; + +type TemplateStream = NodeJS.ReadableStream | Stream; + +const isStream = (data: InputDataType): data is TemplateStream => + typeof data === "object" && data !== null && "on" in data && typeof data.on === "function"; + +/** + * Reads a stream to its end, as JSZip cannot load a zip file from a stream. + * + * It listens for the stream's events, rather than iterating it, so that a stream with no iterator also works, such + * as `Packer.toStream`'s. A chunk is usually a run of bytes, but a stream made with `Readable.from` of a `Uint8Array` + * gives each byte as a number of its own. Those are kept as numbers, not wrapped in an array each. + */ +const readStream = (stream: TemplateStream): Promise => + new Promise((resolve, reject) => { + // eslint-disable-next-line functional/prefer-readonly-type + const chunks: (Uint8Array | number)[] = []; + stream.on("data", (chunk: unknown) => { + // Not `instanceof Uint8Array`, which is false for a Buffer or Uint8Array from another realm, such as a vm context's + if (ArrayBuffer.isView(chunk)) { + // eslint-disable-next-line functional/immutable-data + chunks.push(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)); + } else if (typeof chunk === "number") { + // eslint-disable-next-line functional/immutable-data + chunks.push(chunk); + } else { + reject( + new TypeError( + `A template stream must give bytes, but it gave a ${typeof chunk}. A stream with an encoding set gives text, so do not set one.`, + ), + ); + } + }); + stream.on("error", reject); + stream.on("end", () => { + const bytes = new Uint8Array( + chunks.reduce((length, chunk) => length + (typeof chunk === "number" ? 1 : chunk.length), 0), + ); + chunks.reduce((offset, chunk) => { + if (typeof chunk === "number") { + // eslint-disable-next-line functional/immutable-data + bytes[offset] = chunk; + return offset + 1; + } + bytes.set(chunk, offset); + return offset + chunk.length; + }, 0); + resolve(bytes); + }); + }); + +/** Opens the zip file of a template, from any of the forms `patchDocument` and `patchDetector` take it in */ +export const loadZip = async (data: InputDataType): Promise => { + if (data instanceof JSZip) { + return data; + } + return JSZip.loadAsync(isStream(data) ? await readStream(data) : data); +}; diff --git a/src/patcher/patch-detector.spec.ts b/src/patcher/patch-detector.spec.ts index 1396f226d6..0665fbe35a 100644 --- a/src/patcher/patch-detector.spec.ts +++ b/src/patcher/patch-detector.spec.ts @@ -1,4 +1,5 @@ import JSZip from "jszip"; +import { Readable } from "stream"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { Document, Packer, Paragraph, TextRun } from "../index"; @@ -420,6 +421,24 @@ describe("patch-detector", () => { }); }); + it("should detect and patch placeholders in a template read from a stream", async () => { + const data = await Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph("Hello {{name}}")] }] })); + // A stream such as fs.createReadStream gives a template in chunks, and can be read only once + const streamOf = (): Readable => Readable.from([data.subarray(0, 100), data.subarray(100)]); + + const keys = await patchDetector({ data: streamOf() }); + const output = await patchDocument({ + outputType: "nodebuffer", + data: streamOf(), + patches: { name: { type: PatchType.PARAGRAPH, children: [new TextRun("Ada")] } }, + }); + const xml = await (await JSZip.loadAsync(output)).file("word/document.xml")!.async("string"); + + expect(keys).toEqual(["name"]); + expect(xml).toMatch(/]*>Ada<\/w:t>/); + expect(xml).not.toContain("{{name}}"); + }); + describe("with JSZip instance", () => { it("should accept a JSZip instance directly", async () => { const zip = new JSZip(); diff --git a/src/patcher/patch-detector.ts b/src/patcher/patch-detector.ts index e48972e848..c1d1c5b7e0 100644 --- a/src/patcher/patch-detector.ts +++ b/src/patcher/patch-detector.ts @@ -3,10 +3,9 @@ * * @module */ -import JSZip from "jszip"; - import { altTextOf, findDrawings } from "./drawing-patch"; import type { InputDataType } from "./from-docx"; +import { loadZip } from "./load-zip"; import { traverse } from "./traverser"; import { toJson } from "./util"; @@ -47,7 +46,7 @@ type PatchDetectorOptions = { * ``` */ export const patchDetector = async ({ data }: PatchDetectorOptions): Promise => { - const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data); + const zipContent = await loadZip(data); const patches = new Set(); for (const [key, value] of Object.entries(zipContent.files)) {