mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
@@ -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.
|
||||
|
||||
@@ -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 <T extends PatchDocumentOutputType = PatchDoc
|
||||
numbering = { config: [] },
|
||||
pageNumbers,
|
||||
}: PatchDocumentOptions<T>): Promise<OutputByType[T]> => {
|
||||
const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data);
|
||||
const zipContent = await loadZip(data);
|
||||
const contexts = new Map<string, IContext>();
|
||||
// Theme colors in patches are written with the hex color they come to in the document's theme
|
||||
const themeColors = await readThemeColors(zipContent);
|
||||
|
||||
@@ -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<Uint8Array> => {
|
||||
const zip = new JSZip();
|
||||
zip.file("word/document.xml", "<w:document/>");
|
||||
return zip.generateAsync({ type: "uint8array" });
|
||||
};
|
||||
|
||||
const documentXmlOf = async (data: InputDataType): Promise<string | undefined> =>
|
||||
(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("<w:document/>");
|
||||
});
|
||||
|
||||
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("<w:document/>");
|
||||
});
|
||||
|
||||
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("<w:document/>");
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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<Uint8Array> =>
|
||||
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<number>((length, chunk) => length + (typeof chunk === "number" ? 1 : chunk.length), 0),
|
||||
);
|
||||
chunks.reduce<number>((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<JSZip> => {
|
||||
if (data instanceof JSZip) {
|
||||
return data;
|
||||
}
|
||||
return JSZip.loadAsync(isStream(data) ? await readStream(data) : data);
|
||||
};
|
||||
@@ -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(/<w:t[^>]*>Ada<\/w:t>/);
|
||||
expect(xml).not.toContain("{{name}}");
|
||||
});
|
||||
|
||||
describe("with JSZip instance", () => {
|
||||
it("should accept a JSZip instance directly", async () => {
|
||||
const zip = new JSZip();
|
||||
|
||||
@@ -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<readonly string[]> => {
|
||||
const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data);
|
||||
const zipContent = await loadZip(data);
|
||||
const patches = new Set<string>();
|
||||
|
||||
for (const [key, value] of Object.entries(zipContent.files)) {
|
||||
|
||||
Reference in New Issue
Block a user