@office-open/docx 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ import { wt as SectionChild } from "../core-properties-B3ztqzLD.mjs";
2
+ import { OutputByType, OutputType } from "@office-open/core";
3
+ import { Buffer } from "\u0000polyfill-node.buffer";
4
+
5
+ //#region src/patch/from-docx.d.ts
6
+ type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob;
7
+ declare const PatchType: {
8
+ readonly DOCUMENT: "file";
9
+ readonly PARAGRAPH: "paragraph";
10
+ };
11
+ interface ParagraphPatch {
12
+ type: typeof PatchType.PARAGRAPH;
13
+ children: unknown[];
14
+ }
15
+ interface FilePatch {
16
+ type: typeof PatchType.DOCUMENT;
17
+ children: SectionChild[];
18
+ }
19
+ type IPatch = ParagraphPatch | FilePatch;
20
+ type PatchDocumentOutputType = OutputType;
21
+ interface PatchDocumentOptions<T extends PatchDocumentOutputType = PatchDocumentOutputType> {
22
+ outputType: T;
23
+ data: InputDataType;
24
+ patches: Readonly<Record<string, IPatch>>;
25
+ keepOriginalStyles?: boolean;
26
+ placeholderDelimiters?: Readonly<{
27
+ start: string;
28
+ end: string;
29
+ }>;
30
+ recursive?: boolean;
31
+ }
32
+ declare const patchDocument: <T extends PatchDocumentOutputType = PatchDocumentOutputType>({
33
+ outputType,
34
+ data,
35
+ patches,
36
+ keepOriginalStyles,
37
+ placeholderDelimiters,
38
+ recursive
39
+ }: PatchDocumentOptions<T>) => Promise<OutputByType[T]>;
40
+ //#endregion
41
+ //#region src/patch/patch-detector.d.ts
42
+ interface PatchDetectorOptions {
43
+ data: InputDataType;
44
+ }
45
+ declare const patchDetector: ({
46
+ data
47
+ }: PatchDetectorOptions) => Promise<string[]>;
48
+ //#endregion
49
+ export { IPatch, InputDataType, PatchDocumentOptions, PatchDocumentOutputType, PatchType, patchDetector, patchDocument };
50
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/patch/from-docx.ts","../../src/patch/patch-detector.ts"],"mappings":";;;;;KAgHY,aAAA,GAAgB,MAAA,uBAA6B,UAAA,GAAa,WAAA,GAAc,IAAA;AAAA,cAOvE,SAAA;EAAA,SAGH,QAAA;EAAA,SAAA,SAAA;AAAA;AAAA,UAEA,cAAA;EACR,IAAA,SAAa,SAAA,CAAU,SAAS;EAChC,QAAA;AAAA;AAAA,UAGQ,SAAA;EACR,IAAA,SAAa,SAAA,CAAU,QAAA;EACvB,QAAA,EAAU,YAAY;AAAA;AAAA,KAaZ,MAAA,GAAS,cAAA,GAAiB,SAAS;AAAA,KAEnC,uBAAA,GAA0B,UAAU;AAAA,UAE/B,oBAAA,WAA+B,uBAAA,GAA0B,uBAAA;EACxE,UAAA,EAAY,CAAA;EACZ,IAAA,EAAM,aAAA;EACN,OAAA,EAAS,QAAA,CAAS,MAAA,SAAe,MAAA;EACjC,kBAAA;EACA,qBAAA,GAAwB,QAAA;IACtB,KAAA;IACA,GAAA;EAAA;EAEF,SAAA;AAAA;AAAA,cAuBW,aAAA,aAAiC,uBAAA,GAA0B,uBAAA;EAAyB,UAAA;EAAA,IAAA;EAAA,OAAA;EAAA,kBAAA;EAAA,qBAAA;EAAA;AAAA,GAO9F,oBAAA,CAAqB,CAAA,MAAK,OAAA,CAAQ,YAAA,CAAa,CAAA;;;UC5KxC,oBAAA;EACR,IAAA,EAAM,aAAa;AAAA;AAAA,cA4BR,aAAA;EAAuB;AAAA,GAAU,oBAAA,KAAuB,OAAA"}
@@ -0,0 +1,272 @@
1
+ import { D as stringifyJsonChild, E as tableDesc, O as stringifyParagraphInline, at as Media, k as stringifyRunInline, w as DocumentAttributeNamespaces } from "../document-CWr8C_OX.mjs";
2
+ import { DOCX_NS, OoxmlMimeType, TargetModeType, appendContentType, appendRelationship, createReplacer, createTraverser, getNextRelationshipIndex, getReferencedMedia, replaceImagePlaceholders, strFromU8, toJson, toUint8Array, unzipSync, zipAndConvert } from "@office-open/core";
3
+ import { escapeXml, js2xml, xml2js } from "@office-open/xml";
4
+ //#region src/patch/from-docx.ts
5
+ /** Reusable TextEncoder (stateless, safe to share). */
6
+ const encoder = new TextEncoder();
7
+ /**
8
+ * Document patching module for modifying existing .docx files.
9
+ *
10
+ * Uses compile-path stringifiers (zero class instantiation) to serialize
11
+ * patch content — no Formatter, no XmlComponent instances.
12
+ *
13
+ * @module
14
+ */
15
+ /**
16
+ * Lightweight BodyContext adapter for patch serialization.
17
+ * Captures hyperlink and image relationships for post-processing.
18
+ */
19
+ function createPatchContext(file, hyperlinkSink) {
20
+ return {
21
+ fileData: file,
22
+ file,
23
+ viewWrapper: { relationships: {
24
+ addRelationship: (linkId, _type, target, _mode) => {
25
+ hyperlinkSink.push({
26
+ id: linkId,
27
+ link: target
28
+ });
29
+ },
30
+ relationshipCount: 0
31
+ } },
32
+ stringifyChild: () => "",
33
+ addRelationship: () => "",
34
+ addMedia: () => ""
35
+ };
36
+ }
37
+ const docxReplacer = createReplacer({
38
+ ns: DOCX_NS,
39
+ formatChild: (child) => {
40
+ let xmlStr;
41
+ if (typeof child === "string") xmlStr = `<w:r><w:t xml:space="preserve">${escapeXml(child)}</w:t></w:r>`;
42
+ else if (typeof child === "object" && child !== null) {
43
+ const obj = child;
44
+ if ("paragraph" in obj) xmlStr = stringifyParagraphInline(obj.paragraph, currentPatchCtx);
45
+ else if ("table" in obj) xmlStr = tableDesc.stringify(obj.table, currentPatchCtx) ?? "";
46
+ else {
47
+ const jr = stringifyJsonChild(child, currentPatchCtx);
48
+ if (jr !== void 0) xmlStr = Array.isArray(jr) ? jr.join("") : jr;
49
+ else xmlStr = stringifyRunInline(child, currentPatchCtx);
50
+ }
51
+ } else xmlStr = "<w:r/>";
52
+ return [xml2js(xmlStr, { captureSpacesBetweenElements: true }).elements[0]];
53
+ }
54
+ });
55
+ /** Current patch context — set per file in the main loop. */
56
+ let currentPatchCtx;
57
+ /**
58
+ * Patch type enumeration.
59
+ *
60
+ * @publicApi
61
+ */
62
+ const PatchType = {
63
+ DOCUMENT: "file",
64
+ PARAGRAPH: "paragraph"
65
+ };
66
+ const UTF16LE = new Uint8Array([255, 254]);
67
+ const UTF16BE = new Uint8Array([254, 255]);
68
+ const compareByteArrays = (a, b) => {
69
+ if (a.length !== b.length) return false;
70
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
71
+ return true;
72
+ };
73
+ /**
74
+ * Patches an existing .docx document by replacing placeholders with new content.
75
+ *
76
+ * @publicApi
77
+ */
78
+ const patchDocument = async ({ outputType, data, patches, keepOriginalStyles = true, placeholderDelimiters = {
79
+ end: "}}",
80
+ start: "{{"
81
+ }, recursive = true }) => {
82
+ const zipContent = unzipSync(toUint8Array(data));
83
+ const contexts = /* @__PURE__ */ new Map();
84
+ const media = new Media();
85
+ const file = { media };
86
+ const map = /* @__PURE__ */ new Map();
87
+ const imageRelationshipAdditions = [];
88
+ const hyperlinkRelationshipAdditions = [];
89
+ let hasMedia = false;
90
+ const binaryContentMap = /* @__PURE__ */ new Map();
91
+ for (const [key, value] of Object.entries(zipContent)) {
92
+ const startBytes = value.slice(0, 2);
93
+ if (compareByteArrays(startBytes, UTF16LE) || compareByteArrays(startBytes, UTF16BE)) {
94
+ binaryContentMap.set(key, value);
95
+ continue;
96
+ }
97
+ if (!key.endsWith(".xml") && !key.endsWith(".rels")) {
98
+ binaryContentMap.set(key, value);
99
+ continue;
100
+ }
101
+ const json = toJson(strFromU8(value));
102
+ if (key === "word/document.xml") {
103
+ const document = json.elements?.find((i) => i.name === "w:document");
104
+ if (document && document.attributes) {
105
+ for (const ns of [
106
+ "mc",
107
+ "wp",
108
+ "r",
109
+ "w15",
110
+ "m"
111
+ ]) document.attributes[`xmlns:${ns}`] = DocumentAttributeNamespaces[ns];
112
+ document.attributes["mc:Ignorable"] = `${document.attributes["mc:Ignorable"] || ""} w15`.trim();
113
+ }
114
+ }
115
+ if (key.startsWith("word/") && !key.endsWith(".xml.rels")) {
116
+ const hyperlinkSink = [];
117
+ const context = {
118
+ fileData: file,
119
+ file,
120
+ viewWrapper: { relationships: { addRelationship: (linkId, _, target, __) => {
121
+ hyperlinkRelationshipAdditions.push({
122
+ hyperlink: {
123
+ id: linkId,
124
+ link: target
125
+ },
126
+ key
127
+ });
128
+ } } },
129
+ stringifyChild: () => "",
130
+ addRelationship: () => "",
131
+ addMedia: () => ""
132
+ };
133
+ contexts.set(key, context);
134
+ if (!placeholderDelimiters?.start.trim() || !placeholderDelimiters?.end.trim()) throw new Error("Both start and end delimiters must be non-empty strings.");
135
+ const { start, end } = placeholderDelimiters;
136
+ currentPatchCtx = createPatchContext(file, hyperlinkSink);
137
+ for (const [patchKey, patchValue] of Object.entries(patches)) {
138
+ const patchText = `${start}${patchKey}${end}`;
139
+ while (true) {
140
+ const { didFindOccurrence } = docxReplacer({
141
+ context,
142
+ json,
143
+ keepOriginalStyles,
144
+ patch: patchValue,
145
+ patchText
146
+ });
147
+ if (!recursive || !didFindOccurrence) break;
148
+ }
149
+ }
150
+ for (const hl of hyperlinkSink) hyperlinkRelationshipAdditions.push({
151
+ hyperlink: {
152
+ id: hl.id,
153
+ link: hl.link
154
+ },
155
+ key
156
+ });
157
+ const mediaDatas = getReferencedMedia(JSON.stringify(json), media.array);
158
+ if (mediaDatas.length > 0) {
159
+ hasMedia = true;
160
+ imageRelationshipAdditions.push({
161
+ key,
162
+ mediaDatas
163
+ });
164
+ }
165
+ }
166
+ map.set(key, json);
167
+ }
168
+ for (const { key, mediaDatas } of imageRelationshipAdditions) {
169
+ const relationshipKey = `word/_rels/${key.split("/").pop()}.rels`;
170
+ const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();
171
+ map.set(relationshipKey, relationshipsJson);
172
+ const index = getNextRelationshipIndex(relationshipsJson);
173
+ const newJson = replaceImagePlaceholders(JSON.stringify(map.get(key)), mediaDatas, index, "plain");
174
+ map.set(key, JSON.parse(newJson));
175
+ for (let i = 0; i < mediaDatas.length; i++) {
176
+ const { fileName } = mediaDatas[i];
177
+ appendRelationship(relationshipsJson, index + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${fileName}`);
178
+ }
179
+ }
180
+ for (const { key, hyperlink } of hyperlinkRelationshipAdditions) {
181
+ const relationshipKey = `word/_rels/${key.split("/").pop()}.rels`;
182
+ const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();
183
+ map.set(relationshipKey, relationshipsJson);
184
+ appendRelationship(relationshipsJson, hyperlink.id, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", hyperlink.link, TargetModeType.EXTERNAL);
185
+ }
186
+ if (hasMedia) {
187
+ const contentTypesJson = map.get("[Content_Types].xml");
188
+ if (!contentTypesJson) throw new Error("Could not find content types file");
189
+ appendContentType(contentTypesJson, "image/png", "png");
190
+ appendContentType(contentTypesJson, "image/jpeg", "jpeg");
191
+ appendContentType(contentTypesJson, "image/jpeg", "jpg");
192
+ appendContentType(contentTypesJson, "image/bmp", "bmp");
193
+ appendContentType(contentTypesJson, "image/gif", "gif");
194
+ appendContentType(contentTypesJson, "image/svg+xml", "svg");
195
+ }
196
+ const files = {};
197
+ for (const [key, value] of map) files[key] = encoder.encode(js2xml(value));
198
+ for (const [key, value] of binaryContentMap) files[key] = value;
199
+ for (const { data: mediaData, fileName } of media.array) files[`word/media/${fileName}`] = mediaData instanceof Uint8Array ? mediaData : new Uint8Array(mediaData);
200
+ return await zipAndConvert(files, outputType, OoxmlMimeType.DOCX);
201
+ };
202
+ const createRelationshipFile = () => ({
203
+ declaration: { attributes: {
204
+ encoding: "UTF-8",
205
+ standalone: "yes",
206
+ version: "1.0"
207
+ } },
208
+ elements: [{
209
+ attributes: { xmlns: "http://schemas.openxmlformats.org/package/2006/relationships" },
210
+ elements: [],
211
+ name: "Relationships",
212
+ type: "element"
213
+ }]
214
+ });
215
+ //#endregion
216
+ //#region src/patch/patch-detector.ts
217
+ /**
218
+ * Patch detector for discovering placeholders in document templates.
219
+ *
220
+ * @module
221
+ */
222
+ /**
223
+ * Detects all placeholders present in a document template.
224
+ *
225
+ * Scans through all XML content in a .docx file to find placeholder text
226
+ * enclosed in delimiters (default: {{placeholder}}). This is useful for
227
+ * discovering what patches a template expects before performing replacement.
228
+ *
229
+ * @param options - Patch detector configuration
230
+ * @returns Array of placeholder keys found in the document
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * const placeholders = await patchDetector({ data: templateBuffer });
235
+ * // Returns: ["name", "date", "address"] if template contains {{name}}, {{date}}, {{address}}
236
+ *
237
+ * // Use detected placeholders to create patches
238
+ * const patches = {};
239
+ * for (const key of placeholders) {
240
+ * patches[key] = {
241
+ * type: PatchType.PARAGRAPH,
242
+ * children: [new TextRun(getUserData(key))],
243
+ * };
244
+ * });
245
+ * ```
246
+ */
247
+ const patchDetector = async ({ data }) => {
248
+ const zipContent = unzipSync(toUint8Array(data));
249
+ const patches = /* @__PURE__ */ new Set();
250
+ for (const [key, value] of Object.entries(zipContent)) {
251
+ if (!key.endsWith(".xml") && !key.endsWith(".rels")) continue;
252
+ if (key.startsWith("word/") && !key.endsWith(".xml.rels")) {
253
+ const json = toJson(strFromU8(value));
254
+ const { traverse } = createTraverser(DOCX_NS);
255
+ for (const p of traverse(json)) for (const patch of findPatchKeys(p.text)) patches.add(patch);
256
+ }
257
+ }
258
+ return [...patches];
259
+ };
260
+ /**
261
+ * Extracts placeholder keys from text using regex pattern.
262
+ *
263
+ * @param text - Text to search for placeholders
264
+ * @returns Array of placeholder keys (without delimiters)
265
+ */
266
+ const findPatchKeys = (text) => {
267
+ return text.match(/(?<=\{\{).+?(?=\}\})/gs) ?? [];
268
+ };
269
+ //#endregion
270
+ export { PatchType, patchDetector, patchDocument };
271
+
272
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/patch/from-docx.ts","../../src/patch/patch-detector.ts"],"sourcesContent":["import { TargetModeType } from \"@office-open/core\";\nimport {\n DOCX_NS,\n OoxmlMimeType,\n appendContentType,\n appendRelationship,\n createReplacer,\n getNextRelationshipIndex,\n getReferencedMedia,\n replaceImagePlaceholders,\n strFromU8,\n toJson,\n unzipSync,\n zipAndConvert,\n} from \"@office-open/core\";\nimport type { OutputByType, OutputType } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport { escapeXml, js2xml, xml2js } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { DocumentAttributeNamespaces } from \"@parts/document\";\nimport { stringifyJsonChild, stringifyParagraphInline, stringifyRunInline } from \"@parts/inline\";\nimport type { ParagraphChild } from \"@parts/inline\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type { RunOptions } from \"@parts/paragraph/run/run\";\nimport { tableDesc } from \"@parts/table/descriptor\";\nimport type { TableOptions } from \"@parts/table/table\";\nimport { Media } from \"@shared/media\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { BodyContext } from \"../context\";\nimport type { ViewWrapper } from \"../context\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\n/**\n * Document patching module for modifying existing .docx files.\n *\n * Uses compile-path stringifiers (zero class instantiation) to serialize\n * patch content — no Formatter, no XmlComponent instances.\n *\n * @module\n */\n\n// ── Patch content stringification ──\n\n/**\n * Lightweight BodyContext adapter for patch serialization.\n * Captures hyperlink and image relationships for post-processing.\n */\nfunction createPatchContext(\n file: { media: Media },\n hyperlinkSink: Array<{ id: string; link: string }>,\n): BodyContext {\n return {\n fileData: file as unknown as BodyContext[\"fileData\"],\n file: file as unknown as BodyContext[\"file\"],\n viewWrapper: {\n relationships: {\n addRelationship: (linkId: string, _type: string, target: string, _mode?: string) => {\n hyperlinkSink.push({ id: linkId, link: target });\n },\n relationshipCount: 0,\n },\n } as unknown as BodyContext[\"viewWrapper\"],\n stringifyChild: () => \"\",\n addRelationship: () => \"\",\n addMedia: () => \"\",\n };\n}\n\nconst docxReplacer = createReplacer({\n ns: DOCX_NS,\n formatChild: (child: unknown): Element[] => {\n let xmlStr: string;\n\n if (typeof child === \"string\") {\n // Plain string → simple run\n xmlStr = `<w:r><w:t xml:space=\"preserve\">${escapeXml(child)}</w:t></w:r>`;\n } else if (typeof child === \"object\" && child !== null) {\n const obj = child as Record<string, unknown>;\n // SectionChild level (paragraph / table) — for DOCUMENT patches\n if (\"paragraph\" in obj) {\n xmlStr = stringifyParagraphInline(obj.paragraph as ParagraphOptions, currentPatchCtx);\n } else if (\"table\" in obj) {\n xmlStr = tableDesc.stringify(obj.table as TableOptions, currentPatchCtx) ?? \"\";\n } else {\n // ParagraphChild level — for PARAGRAPH patches\n // Try compile-path JSON child dispatch first\n const jr = stringifyJsonChild(child as ParagraphChild, currentPatchCtx);\n if (jr !== undefined) {\n xmlStr = Array.isArray(jr) ? jr.join(\"\") : jr;\n } else {\n // RunOptions (plain objects with text/children/bold/etc.)\n xmlStr = stringifyRunInline(child as RunOptions, currentPatchCtx);\n }\n }\n } else {\n xmlStr = \"<w:r/>\";\n }\n\n const jsonObj = xml2js(xmlStr, { captureSpacesBetweenElements: true });\n return [jsonObj.elements![0]];\n },\n});\n\n/** Current patch context — set per file in the main loop. */\nlet currentPatchCtx: BodyContext;\n\n/**\n * Supported input data types for document patching.\n */\nexport type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob;\n\n/**\n * Patch type enumeration.\n *\n * @publicApi\n */\nexport const PatchType = {\n DOCUMENT: \"file\",\n PARAGRAPH: \"paragraph\",\n} as const;\n\ninterface ParagraphPatch {\n type: typeof PatchType.PARAGRAPH;\n children: unknown[];\n}\n\ninterface FilePatch {\n type: typeof PatchType.DOCUMENT;\n children: SectionChild[];\n}\n\ninterface ImageRelationshipAddition {\n key: string;\n mediaDatas: { fileName: string }[];\n}\n\ninterface HyperlinkRelationshipAddition {\n key: string;\n hyperlink: { id: string; link: string };\n}\n\nexport type IPatch = ParagraphPatch | FilePatch;\n\nexport type PatchDocumentOutputType = OutputType;\n\nexport interface PatchDocumentOptions<T extends PatchDocumentOutputType = PatchDocumentOutputType> {\n outputType: T;\n data: InputDataType;\n patches: Readonly<Record<string, IPatch>>;\n keepOriginalStyles?: boolean;\n placeholderDelimiters?: Readonly<{\n start: string;\n end: string;\n }>;\n recursive?: boolean;\n}\n\nconst UTF16LE = new Uint8Array([0xff, 0xfe]);\nconst UTF16BE = new Uint8Array([0xfe, 0xff]);\n\nconst compareByteArrays = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Patches an existing .docx document by replacing placeholders with new content.\n *\n * @publicApi\n */\nexport const patchDocument = async <T extends PatchDocumentOutputType = PatchDocumentOutputType>({\n outputType,\n data,\n patches,\n keepOriginalStyles = true,\n placeholderDelimiters = { end: \"}}\", start: \"{{\" } as const,\n recursive = true,\n}: PatchDocumentOptions<T>): Promise<OutputByType[T]> => {\n const zipContent = unzipSync(toUint8Array(data));\n const contexts = new Map<string, BodyContext>();\n const media = new Media();\n const file = { media } as BodyContext[\"file\"];\n\n const map = new Map<string, Element>();\n\n const imageRelationshipAdditions: ImageRelationshipAddition[] = [];\n const hyperlinkRelationshipAdditions: HyperlinkRelationshipAddition[] = [];\n let hasMedia = false;\n\n const binaryContentMap = new Map<string, Uint8Array>();\n\n for (const [key, value] of Object.entries(zipContent)) {\n const startBytes = value.slice(0, 2);\n if (compareByteArrays(startBytes, UTF16LE) || compareByteArrays(startBytes, UTF16BE)) {\n binaryContentMap.set(key, value);\n continue;\n }\n\n if (!key.endsWith(\".xml\") && !key.endsWith(\".rels\")) {\n binaryContentMap.set(key, value);\n continue;\n }\n\n const json = toJson(strFromU8(value));\n\n if (key === \"word/document.xml\") {\n const document = json.elements?.find((i) => i.name === \"w:document\");\n if (document && document.attributes) {\n for (const ns of [\"mc\", \"wp\", \"r\", \"w15\", \"m\"] as const) {\n document.attributes[`xmlns:${ns}`] = DocumentAttributeNamespaces[ns];\n }\n document.attributes[\"mc:Ignorable\"] =\n `${document.attributes[\"mc:Ignorable\"] || \"\"} w15`.trim();\n }\n }\n\n if (key.startsWith(\"word/\") && !key.endsWith(\".xml.rels\")) {\n const hyperlinkSink: Array<{ id: string; link: string }> = [];\n\n const context: BodyContext = {\n fileData: file,\n file,\n viewWrapper: {\n relationships: {\n addRelationship: (\n linkId: string,\n _: string,\n target: string,\n __: (typeof TargetModeType)[keyof typeof TargetModeType],\n ) => {\n hyperlinkRelationshipAdditions.push({\n hyperlink: {\n id: linkId,\n link: target,\n },\n key,\n });\n },\n },\n } as unknown as ViewWrapper,\n stringifyChild: () => \"\",\n addRelationship: () => \"\",\n addMedia: () => \"\",\n };\n contexts.set(key, context);\n\n if (!placeholderDelimiters?.start.trim() || !placeholderDelimiters?.end.trim()) {\n throw new Error(\"Both start and end delimiters must be non-empty strings.\");\n }\n\n const { start, end } = placeholderDelimiters;\n\n // Create compile-path context for stringifying patch children\n const patchCtx = createPatchContext(file, hyperlinkSink);\n currentPatchCtx = patchCtx;\n\n for (const [patchKey, patchValue] of Object.entries(patches)) {\n const patchText = `${start}${patchKey}${end}`;\n while (true) {\n const { didFindOccurrence } = docxReplacer({\n context,\n json,\n keepOriginalStyles,\n patch: patchValue,\n patchText,\n });\n if (!recursive || !didFindOccurrence) {\n break;\n }\n }\n }\n\n // Flush hyperlink relationships captured by the compile-path context\n for (const hl of hyperlinkSink) {\n hyperlinkRelationshipAdditions.push({\n hyperlink: { id: hl.id, link: hl.link },\n key,\n });\n }\n\n const mediaDatas = getReferencedMedia(JSON.stringify(json), media.array);\n if (mediaDatas.length > 0) {\n hasMedia = true;\n imageRelationshipAdditions.push({\n key,\n mediaDatas,\n });\n }\n }\n\n map.set(key, json);\n }\n\n for (const { key, mediaDatas } of imageRelationshipAdditions) {\n const relationshipKey = `word/_rels/${key.split(\"/\").pop()}.rels`;\n const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();\n map.set(relationshipKey, relationshipsJson);\n\n const index = getNextRelationshipIndex(relationshipsJson);\n const newJson = replaceImagePlaceholders(\n JSON.stringify(map.get(key)),\n mediaDatas,\n index,\n \"plain\",\n );\n map.set(key, JSON.parse(newJson) as Element);\n\n for (let i = 0; i < mediaDatas.length; i++) {\n const { fileName } = mediaDatas[i];\n appendRelationship(\n relationshipsJson,\n index + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${fileName}`,\n );\n }\n }\n\n for (const { key, hyperlink } of hyperlinkRelationshipAdditions) {\n const relationshipKey = `word/_rels/${key.split(\"/\").pop()}.rels`;\n\n const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();\n map.set(relationshipKey, relationshipsJson);\n\n appendRelationship(\n relationshipsJson,\n hyperlink.id,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n hyperlink.link,\n TargetModeType.EXTERNAL,\n );\n }\n\n if (hasMedia) {\n const contentTypesJson = map.get(\"[Content_Types].xml\");\n\n if (!contentTypesJson) {\n throw new Error(\"Could not find content types file\");\n }\n\n appendContentType(contentTypesJson, \"image/png\", \"png\");\n appendContentType(contentTypesJson, \"image/jpeg\", \"jpeg\");\n appendContentType(contentTypesJson, \"image/jpeg\", \"jpg\");\n appendContentType(contentTypesJson, \"image/bmp\", \"bmp\");\n appendContentType(contentTypesJson, \"image/gif\", \"gif\");\n appendContentType(contentTypesJson, \"image/svg+xml\", \"svg\");\n }\n\n const files: Record<string, Uint8Array> = {};\n\n for (const [key, value] of map) {\n files[key] = encoder.encode(js2xml(value));\n }\n\n for (const [key, value] of binaryContentMap) {\n files[key] = value;\n }\n\n for (const { data: mediaData, fileName } of media.array) {\n files[`word/media/${fileName}`] =\n mediaData instanceof Uint8Array ? mediaData : new Uint8Array(mediaData);\n }\n\n return await zipAndConvert(files, outputType, OoxmlMimeType.DOCX);\n};\n\nconst createRelationshipFile = (): Element => ({\n declaration: {\n attributes: {\n encoding: \"UTF-8\",\n standalone: \"yes\",\n version: \"1.0\",\n },\n },\n elements: [\n {\n attributes: {\n xmlns: \"http://schemas.openxmlformats.org/package/2006/relationships\",\n },\n elements: [],\n name: \"Relationships\",\n type: \"element\",\n },\n ],\n});\n","/**\n * Patch detector for discovering placeholders in document templates.\n *\n * @module\n */\nimport { DOCX_NS, createTraverser, strFromU8, toJson, unzipSync } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\n\nimport type { InputDataType } from \"./from-docx\";\n\n/**\n * Options for patch detection.\n *\n * @property data - The document template to scan for placeholders\n */\ninterface PatchDetectorOptions {\n data: InputDataType;\n}\n\n/**\n * Detects all placeholders present in a document template.\n *\n * Scans through all XML content in a .docx file to find placeholder text\n * enclosed in delimiters (default: {{placeholder}}). This is useful for\n * discovering what patches a template expects before performing replacement.\n *\n * @param options - Patch detector configuration\n * @returns Array of placeholder keys found in the document\n *\n * @example\n * ```typescript\n * const placeholders = await patchDetector({ data: templateBuffer });\n * // Returns: [\"name\", \"date\", \"address\"] if template contains {{name}}, {{date}}, {{address}}\n *\n * // Use detected placeholders to create patches\n * const patches = {};\n * for (const key of placeholders) {\n * patches[key] = {\n * type: PatchType.PARAGRAPH,\n * children: [new TextRun(getUserData(key))],\n * };\n * });\n * ```\n */\nexport const patchDetector = async ({ data }: PatchDetectorOptions): Promise<string[]> => {\n const zipContent = unzipSync(toUint8Array(data));\n const patches = new Set<string>();\n\n for (const [key, value] of Object.entries(zipContent)) {\n if (!key.endsWith(\".xml\") && !key.endsWith(\".rels\")) {\n continue;\n }\n if (key.startsWith(\"word/\") && !key.endsWith(\".xml.rels\")) {\n const json = toJson(strFromU8(value));\n const { traverse } = createTraverser(DOCX_NS);\n for (const p of traverse(json)) {\n for (const patch of findPatchKeys(p.text)) {\n patches.add(patch);\n }\n }\n }\n }\n return [...patches];\n};\n\n/**\n * Extracts placeholder keys from text using regex pattern.\n *\n * @param text - Text to search for placeholders\n * @returns Array of placeholder keys (without delimiters)\n */\nconst findPatchKeys = (text: string): string[] => {\n const pattern = /(?<=\\{\\{).+?(?=\\}\\})/gs;\n return text.match(pattern) ?? [];\n};\n"],"mappings":";;;;;AAiCA,MAAM,UAAU,IAAI,YAAY;;;;;;;;;;;;;AAiBhC,SAAS,mBACP,MACA,eACa;CACb,OAAO;EACL,UAAU;EACJ;EACN,aAAa,EACX,eAAe;GACb,kBAAkB,QAAgB,OAAe,QAAgB,UAAmB;IAClF,cAAc,KAAK;KAAE,IAAI;KAAQ,MAAM;IAAO,CAAC;GACjD;GACA,mBAAmB;EACrB,EACF;EACA,sBAAsB;EACtB,uBAAuB;EACvB,gBAAgB;CAClB;AACF;AAEA,MAAM,eAAe,eAAe;CAClC,IAAI;CACJ,cAAc,UAA8B;EAC1C,IAAI;EAEJ,IAAI,OAAO,UAAU,UAEnB,SAAS,kCAAkC,UAAU,KAAK,EAAE;OACvD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;GACtD,MAAM,MAAM;GAEZ,IAAI,eAAe,KACjB,SAAS,yBAAyB,IAAI,WAA+B,eAAe;QAC/E,IAAI,WAAW,KACpB,SAAS,UAAU,UAAU,IAAI,OAAuB,eAAe,KAAK;QACvE;IAGL,MAAM,KAAK,mBAAmB,OAAyB,eAAe;IACtE,IAAI,OAAO,KAAA,GACT,SAAS,MAAM,QAAQ,EAAE,IAAI,GAAG,KAAK,EAAE,IAAI;SAG3C,SAAS,mBAAmB,OAAqB,eAAe;GAEpE;EACF,OACE,SAAS;EAIX,OAAO,CADS,OAAO,QAAQ,EAAE,8BAA8B,KAAK,CACtD,EAAE,SAAU,EAAE;CAC9B;AACF,CAAC;;AAGD,IAAI;;;;;;AAYJ,MAAa,YAAY;CACvB,UAAU;CACV,WAAW;AACb;AAsCA,MAAM,UAAU,IAAI,WAAW,CAAC,KAAM,GAAI,CAAC;AAC3C,MAAM,UAAU,IAAI,WAAW,CAAC,KAAM,GAAI,CAAC;AAE3C,MAAM,qBAA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S;CAG1E,OAAO,MAAM,cAAc,OAAO,YAAY,cAAc,IAAI;AAClE;AAEA,MAAM,gCAAyC;CAC7C,aAAa,EACX,YAAY;EACV,UAAU;EACV,YAAY;EACZ,SAAS;CACX,EACF;CACA,UAAU,CACR;EACE,YAAY,EACV,OAAO,+DACT;EACA,UAAU,CAAC;EACX,MAAM;EACN,MAAM;CACR,CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9VA,MAAa,gBAAgB,OAAO,EAAE,WAAoD;CACxF,MAAM,aAAa,UAAU,aAAa,IAAI,CAAC;CAC/C,MAAM,0BAAU,IAAI,IAAY;CAEhC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAAG;EACrD,IAAI,CAAC,IAAI,SAAS,MAAM,KAAK,CAAC,IAAI,SAAS,OAAO,GAChD;EAEF,IAAI,IAAI,WAAW,OAAO,KAAK,CAAC,IAAI,SAAS,WAAW,GAAG;GACzD,MAAM,OAAO,OAAO,UAAU,KAAK,CAAC;GACpC,MAAM,EAAE,aAAa,gBAAgB,OAAO;GAC5C,KAAK,MAAM,KAAK,SAAS,IAAI,GAC3B,KAAK,MAAM,SAAS,cAAc,EAAE,IAAI,GACtC,QAAQ,IAAI,KAAK;EAGvB;CACF;CACA,OAAO,CAAC,GAAG,OAAO;AACpB;;;;;;;AAQA,MAAM,iBAAiB,SAA2B;CAEhD,OAAO,KAAK,MAAM,wBAAO,KAAK,CAAC;AACjC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@office-open/docx",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "Generate, parse, and patch .docx documents with a declarative TypeScript API",
5
5
  "keywords": [
6
6
  "clippy",
@@ -22,7 +22,7 @@
22
22
  "author": {
23
23
  "name": "Demo Macro",
24
24
  "email": "abc@imst.xyz",
25
- "url": "https://imst.xyz/"
25
+ "url": "https://www.demomacro.com/"
26
26
  },
27
27
  "repository": {
28
28
  "type": "git",
@@ -38,17 +38,30 @@
38
38
  ".": {
39
39
  "types": "./dist/index.d.mts",
40
40
  "import": "./dist/index.mjs"
41
+ },
42
+ "./generate": {
43
+ "types": "./dist/generate.d.mts",
44
+ "import": "./dist/generate.mjs"
45
+ },
46
+ "./parse": {
47
+ "types": "./dist/parse.d.mts",
48
+ "import": "./dist/parse.mjs"
49
+ },
50
+ "./patch": {
51
+ "types": "./dist/patch/index.d.mts",
52
+ "import": "./dist/patch/index.mjs"
41
53
  }
42
54
  },
43
55
  "dependencies": {
44
- "@office-open/core": "0.8.1",
45
- "@office-open/xml": "0.8.1"
56
+ "@office-open/core": "0.9.0",
57
+ "@office-open/xml": "0.9.0"
46
58
  },
47
59
  "scripts": {
48
60
  "dev": "basis build --stub",
49
61
  "build": "vp pack",
50
62
  "test": "vp test run",
51
63
  "check": "vp check --fix",
64
+ "bench": "vp test bench",
52
65
  "typedoc": "typedoc src/index.ts --tsconfig tsconfig.typedoc.json",
53
66
  "extract": "tsx scripts/extract-document.ts",
54
67
  "demos": "tsx scripts/run-all-demos.ts"
@@ -1,27 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __exportAll = (all, no_symbols) => {
7
- let target = {};
8
- for (var name in all) __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true
11
- });
12
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
13
- return target;
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
- key = keys[i];
18
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
19
- get: ((k) => from[k]).bind(null, key),
20
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
21
- });
22
- }
23
- return to;
24
- };
25
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
26
- //#endregion
27
- export { __reExport as n, __exportAll as t };