@folijs/docx 0.0.0-stage → 0.4.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.
- package/CHANGELOG.md +56 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/export/content.d.ts +17 -0
- package/dist/export/content.d.ts.map +1 -0
- package/dist/export/content.js +165 -0
- package/dist/export/content.js.map +1 -0
- package/dist/export/index.d.ts +21 -0
- package/dist/export/index.d.ts.map +1 -0
- package/dist/export/index.js +360 -0
- package/dist/export/index.js.map +1 -0
- package/dist/export/parts.d.ts +24 -0
- package/dist/export/parts.d.ts.map +1 -0
- package/dist/export/parts.js +413 -0
- package/dist/export/parts.js.map +1 -0
- package/dist/export/properties.d.ts +39 -0
- package/dist/export/properties.d.ts.map +1 -0
- package/dist/export/properties.js +506 -0
- package/dist/export/properties.js.map +1 -0
- package/dist/export/xmlout.d.ts +63 -0
- package/dist/export/xmlout.d.ts.map +1 -0
- package/dist/export/xmlout.js +194 -0
- package/dist/export/xmlout.js.map +1 -0
- package/dist/import/content.d.ts +35 -0
- package/dist/import/content.d.ts.map +1 -0
- package/dist/import/content.js +370 -0
- package/dist/import/content.js.map +1 -0
- package/dist/import/index.d.ts +31 -0
- package/dist/import/index.d.ts.map +1 -0
- package/dist/import/index.js +106 -0
- package/dist/import/index.js.map +1 -0
- package/dist/import/ooxml.d.ts +39 -0
- package/dist/import/ooxml.d.ts.map +1 -0
- package/dist/import/ooxml.js +71 -0
- package/dist/import/ooxml.js.map +1 -0
- package/dist/import/parts.d.ts +35 -0
- package/dist/import/parts.d.ts.map +1 -0
- package/dist/import/parts.js +365 -0
- package/dist/import/parts.js.map +1 -0
- package/dist/import/properties.d.ts +50 -0
- package/dist/import/properties.d.ts.map +1 -0
- package/dist/import/properties.js +404 -0
- package/dist/import/properties.js.map +1 -0
- package/dist/import/report.d.ts +28 -0
- package/dist/import/report.d.ts.map +1 -0
- package/dist/import/report.js +42 -0
- package/dist/import/report.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/package.d.ts +70 -0
- package/dist/package.d.ts.map +1 -0
- package/dist/package.js +259 -0
- package/dist/package.js.map +1 -0
- package/dist/settings.d.ts +8 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +72 -0
- package/dist/settings.js.map +1 -0
- package/dist/xml.d.ts +79 -0
- package/dist/xml.d.ts.map +1 -0
- package/dist/xml.js +384 -0
- package/dist/xml.js.map +1 -0
- package/dist/zip.d.ts +66 -0
- package/dist/zip.d.ts.map +1 -0
- package/dist/zip.js +356 -0
- package/dist/zip.js.map +1 -0
- package/package.json +36 -3
- package/src/export/content.ts +229 -0
- package/src/export/index.ts +473 -0
- package/src/export/parts.ts +545 -0
- package/src/export/properties.ts +608 -0
- package/src/export/xmlout.ts +225 -0
- package/src/import/content.ts +413 -0
- package/src/import/index.ts +139 -0
- package/src/import/ooxml.ts +78 -0
- package/src/import/parts.ts +423 -0
- package/src/import/properties.ts +507 -0
- package/src/import/report.ts +64 -0
- package/src/index.ts +24 -0
- package/src/package.ts +328 -0
- package/src/settings.ts +75 -0
- package/src/xml.ts +443 -0
- package/src/zip.ts +401 -0
package/src/package.ts
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `.docx` as an Open Packaging Conventions package (ECMA-376 Part 2): its parts, their
|
|
3
|
+
* content types and the relationships between them. Read once; written back with every part it
|
|
4
|
+
* was not asked to replace copied from the original file byte for byte.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { type ParseXmlOptions, parseXml, type XmlDocument, type XmlElement } from "./xml.js";
|
|
8
|
+
import {
|
|
9
|
+
deflateEntry,
|
|
10
|
+
inflateEntry,
|
|
11
|
+
readZip,
|
|
12
|
+
writeZip,
|
|
13
|
+
type ZipEntry,
|
|
14
|
+
type ZipLimits,
|
|
15
|
+
} from "./zip.js";
|
|
16
|
+
|
|
17
|
+
export interface DocxPart {
|
|
18
|
+
/** The part name: `/word/document.xml`. */
|
|
19
|
+
readonly name: string;
|
|
20
|
+
/** Its content type from `[Content_Types].xml`; "" when the file declares none. */
|
|
21
|
+
readonly contentType: string;
|
|
22
|
+
/** The part's bytes, uncompressed. */
|
|
23
|
+
readonly data: Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Relationship {
|
|
27
|
+
readonly id: string;
|
|
28
|
+
/** The relationship type URI. */
|
|
29
|
+
readonly type: string;
|
|
30
|
+
/** As written in the relationships part. */
|
|
31
|
+
readonly target: string;
|
|
32
|
+
readonly external: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The part an internal target points to (resolved against its source), whether or not it
|
|
35
|
+
* exists; none for a target that is a full URI.
|
|
36
|
+
*/
|
|
37
|
+
readonly partName?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ReadPackageOptions extends ZipLimits, ParseXmlOptions {}
|
|
41
|
+
|
|
42
|
+
/** A file that is not a `.docx` package, or is damaged. */
|
|
43
|
+
export class DocxError extends Error {
|
|
44
|
+
override name = "DocxError";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const CONTENT_TYPES = "/[Content_Types].xml";
|
|
48
|
+
const OFFICE_DOCUMENT = /\/officeDocument$/;
|
|
49
|
+
/** Documents, templates, and their macro-enabled kinds (ECMA-376 and MS-OFFMACRO). */
|
|
50
|
+
const WORD_MAIN =
|
|
51
|
+
/^application\/vnd\.(openxmlformats-officedocument\.wordprocessingml\.(document|template)\.main\+xml|ms-word\.(document|template)\.macroEnabled(Template)?\.main\+xml)$/;
|
|
52
|
+
|
|
53
|
+
/** Reads a `.docx` (a package whose `officeDocument` is WordprocessingML). */
|
|
54
|
+
export async function readPackage(
|
|
55
|
+
bytes: Uint8Array,
|
|
56
|
+
options: ReadPackageOptions = {},
|
|
57
|
+
): Promise<DocxPackage> {
|
|
58
|
+
const entries = readZip(bytes, options);
|
|
59
|
+
// One entry at a time: memory holds the parts read so far, never several inflations at once.
|
|
60
|
+
const data: Uint8Array[] = [];
|
|
61
|
+
for (const entry of entries) data.push(await inflateEntry(entry));
|
|
62
|
+
return new DocxPackage(entries, data, options);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class DocxPackage {
|
|
66
|
+
/** Every part in the zip's order (`[Content_Types].xml` and folder entries are not parts). */
|
|
67
|
+
readonly parts: readonly DocxPart[];
|
|
68
|
+
/** The main document part: the target of the package's `officeDocument` relationship. */
|
|
69
|
+
readonly mainDocument: string;
|
|
70
|
+
readonly #entries: readonly ZipEntry[];
|
|
71
|
+
readonly #options: ParseXmlOptions;
|
|
72
|
+
readonly #byName = new Map<string, DocxPart>();
|
|
73
|
+
readonly #relationships = new Map<string, readonly Relationship[]>();
|
|
74
|
+
readonly #xml = new Map<string, XmlDocument>();
|
|
75
|
+
readonly #defaults: ReadonlyMap<string, string>;
|
|
76
|
+
readonly #overridden: ReadonlySet<string>;
|
|
77
|
+
readonly #contentTypesText: string;
|
|
78
|
+
|
|
79
|
+
/** @internal Use {@link readPackage}. */
|
|
80
|
+
constructor(entries: readonly ZipEntry[], data: readonly Uint8Array[], options: ParseXmlOptions) {
|
|
81
|
+
this.#entries = entries;
|
|
82
|
+
this.#options = options.maxDepth === undefined ? {} : { maxDepth: options.maxDepth };
|
|
83
|
+
const index = entries.findIndex((e) => key(partName(e.name)) === key(CONTENT_TYPES));
|
|
84
|
+
if (index === -1) throw new DocxError("Not a .docx: no [Content_Types].xml");
|
|
85
|
+
const typesXml = xml(data[index] as Uint8Array, CONTENT_TYPES, this.#options);
|
|
86
|
+
const types = contentTypes(typesXml.root);
|
|
87
|
+
this.#defaults = types.defaults;
|
|
88
|
+
this.#overridden = new Set(types.overrides.keys());
|
|
89
|
+
// Rewritten as UTF-8 when parts are added: the declaration says so.
|
|
90
|
+
this.#contentTypesText = typesXml.source.replace(
|
|
91
|
+
/^(<\?xml[^?]*?encoding=)(["'])[^"']*\2/,
|
|
92
|
+
"$1$2UTF-8$2",
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
const parts: DocxPart[] = [];
|
|
96
|
+
entries.forEach((entry, i) => {
|
|
97
|
+
if (i === index || entry.name.endsWith("/")) return;
|
|
98
|
+
const name = partName(entry.name);
|
|
99
|
+
const contentType =
|
|
100
|
+
types.overrides.get(key(name)) ?? types.defaults.get(extension(name)) ?? "";
|
|
101
|
+
const part = { name, contentType, data: data[i] as Uint8Array };
|
|
102
|
+
parts.push(part);
|
|
103
|
+
this.#byName.set(key(name), part);
|
|
104
|
+
});
|
|
105
|
+
this.parts = parts;
|
|
106
|
+
|
|
107
|
+
const main = this.relationships("/").find((r) => OFFICE_DOCUMENT.test(r.type) && !r.external);
|
|
108
|
+
const part = main?.partName ? this.part(main.partName) : undefined;
|
|
109
|
+
if (!part) throw new DocxError("Not a .docx: no main document part");
|
|
110
|
+
if (!WORD_MAIN.test(part.contentType)) {
|
|
111
|
+
throw new DocxError(`Not a .docx: the main part is ${part.contentType || "untyped"}`);
|
|
112
|
+
}
|
|
113
|
+
this.mainDocument = part.name;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The part named `name`, if any. Part names compare case-insensitively and percent-decoded. */
|
|
117
|
+
part(name: string): DocxPart | undefined {
|
|
118
|
+
return this.#byName.get(key(name));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The relationships whose source is the part `source` ("/" for the package itself). */
|
|
122
|
+
relationships(source: string): readonly Relationship[] {
|
|
123
|
+
const known = this.#relationships.get(key(source));
|
|
124
|
+
if (known) return known;
|
|
125
|
+
const relsName = relationshipsPart(source);
|
|
126
|
+
const part = this.part(relsName);
|
|
127
|
+
const list = part ? parseRelationships(this.xml(part.name).root, source, relsName) : [];
|
|
128
|
+
this.#relationships.set(key(source), list);
|
|
129
|
+
return list;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The part's text (UTF-8 or UTF-16 by its byte order mark), throwing on invalid bytes. */
|
|
133
|
+
text(name: string): string {
|
|
134
|
+
const part = this.part(name);
|
|
135
|
+
if (!part) throw new DocxError(`No part ${name}`);
|
|
136
|
+
// shortcut: the encoding and byte order mark are not reported; export (8.5) needs them to
|
|
137
|
+
// re-encode a part it rewrites that was not BOM-less UTF-8 (Word writes only that).
|
|
138
|
+
return text(part.data, part.name);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The part parsed as XML (once); every node keeps its offsets into the part's text. */
|
|
142
|
+
xml(name: string): XmlDocument {
|
|
143
|
+
const part = this.part(name);
|
|
144
|
+
if (!part) throw new DocxError(`No part ${name}`);
|
|
145
|
+
let doc = this.#xml.get(key(part.name));
|
|
146
|
+
if (!doc) {
|
|
147
|
+
doc = xml(part.data, part.name, this.#options);
|
|
148
|
+
this.#xml.set(key(part.name), doc);
|
|
149
|
+
}
|
|
150
|
+
return doc;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The package as a `.docx` file. Parts in `replace` (by part name) get the new bytes; parts in
|
|
155
|
+
* `add` are new (their content type declared in `[Content_Types].xml` unless its defaults
|
|
156
|
+
* already give it). Every other entry, `[Content_Types].xml` included when nothing is added,
|
|
157
|
+
* is copied from the original file as it was stored. Entries keep their order; added ones
|
|
158
|
+
* come last.
|
|
159
|
+
*/
|
|
160
|
+
async write(
|
|
161
|
+
replace: ReadonlyMap<string, Uint8Array> = new Map(),
|
|
162
|
+
add: readonly NewPart[] = [],
|
|
163
|
+
): Promise<Uint8Array> {
|
|
164
|
+
const pending = new Map<string, Uint8Array>();
|
|
165
|
+
for (const [name, data] of replace) {
|
|
166
|
+
const part = this.part(name);
|
|
167
|
+
if (!part) throw new DocxError(`No part ${name} to replace`);
|
|
168
|
+
pending.set(key(part.name), data);
|
|
169
|
+
}
|
|
170
|
+
const overrides: string[] = [];
|
|
171
|
+
for (const part of add) {
|
|
172
|
+
if (!part.name.startsWith("/") || part.name.endsWith("/"))
|
|
173
|
+
throw new DocxError(`Not a part name: ${part.name}`);
|
|
174
|
+
if (this.part(part.name) || add.filter((p) => key(p.name) === key(part.name)).length > 1) {
|
|
175
|
+
throw new DocxError(`Part ${part.name} already exists`);
|
|
176
|
+
}
|
|
177
|
+
// An Override already there (a stale one, for a part the zip lacks) is not repeated.
|
|
178
|
+
const declared = this.#overridden.has(key(part.name));
|
|
179
|
+
if (
|
|
180
|
+
part.contentType &&
|
|
181
|
+
!declared &&
|
|
182
|
+
this.#defaults.get(extension(part.name)) !== part.contentType
|
|
183
|
+
) {
|
|
184
|
+
overrides.push(
|
|
185
|
+
`<Override PartName="${escapeXml(part.name)}" ContentType="${escapeXml(part.contentType)}"/>`,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (overrides.length) {
|
|
190
|
+
const types = this.#contentTypesText;
|
|
191
|
+
const close = types.lastIndexOf("</");
|
|
192
|
+
pending.set(
|
|
193
|
+
key(CONTENT_TYPES),
|
|
194
|
+
new TextEncoder().encode(types.slice(0, close) + overrides.join("") + types.slice(close)),
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
const entries: ZipEntry[] = [];
|
|
198
|
+
for (const entry of this.#entries) {
|
|
199
|
+
const data = pending.get(key(partName(entry.name)));
|
|
200
|
+
entries.push(data ? await deflateEntry(entry.name, data, entry) : entry);
|
|
201
|
+
}
|
|
202
|
+
for (const part of add) entries.push(await deflateEntry(part.name.slice(1), part.data));
|
|
203
|
+
return writeZip(entries);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A part to add to a package. */
|
|
208
|
+
export interface NewPart {
|
|
209
|
+
/** `/word/numbering.xml`. */
|
|
210
|
+
readonly name: string;
|
|
211
|
+
readonly data: Uint8Array;
|
|
212
|
+
/** Declared unless the extension's default content type is already this one. */
|
|
213
|
+
readonly contentType?: string;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function escapeXml(value: string): string {
|
|
217
|
+
return value.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** `word/document.xml` (zip) → `/word/document.xml` (part name). */
|
|
221
|
+
function partName(entryName: string): string {
|
|
222
|
+
return `/${entryName}`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Part names are equivalent case-insensitively and with percent-encoding decoded (ECMA-376
|
|
227
|
+
* Part 2, 6.2.2). `decodeURI` leaves encoded delimiters (`%2F`) encoded: never a new segment.
|
|
228
|
+
*/
|
|
229
|
+
function key(name: string): string {
|
|
230
|
+
let decoded = name;
|
|
231
|
+
try {
|
|
232
|
+
decoded = decodeURI(name);
|
|
233
|
+
} catch {}
|
|
234
|
+
return decoded.toLowerCase();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function extension(name: string): string {
|
|
238
|
+
const slash = name.lastIndexOf("/");
|
|
239
|
+
const dot = name.lastIndexOf(".");
|
|
240
|
+
return dot > slash ? name.slice(dot + 1).toLowerCase() : "";
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function contentTypes(root: XmlElement): {
|
|
244
|
+
defaults: Map<string, string>;
|
|
245
|
+
overrides: Map<string, string>;
|
|
246
|
+
} {
|
|
247
|
+
const defaults = new Map<string, string>();
|
|
248
|
+
const overrides = new Map<string, string>();
|
|
249
|
+
if (root.local !== "Types") throw new DocxError("Not a .docx: [Content_Types].xml has no Types");
|
|
250
|
+
for (const child of root.children) {
|
|
251
|
+
if (child.kind !== "element") continue;
|
|
252
|
+
const type = attribute(child, "ContentType");
|
|
253
|
+
if (child.local === "Default") {
|
|
254
|
+
defaults.set((attribute(child, "Extension") ?? "").toLowerCase(), type ?? "");
|
|
255
|
+
} else if (child.local === "Override") {
|
|
256
|
+
overrides.set(key(attribute(child, "PartName") ?? ""), type ?? "");
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return { defaults, overrides };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** `/word/document.xml` → `/word/_rels/document.xml.rels`; `/` → `/_rels/.rels`. */
|
|
263
|
+
function relationshipsPart(source: string): string {
|
|
264
|
+
const slash = source.lastIndexOf("/");
|
|
265
|
+
return `${source.slice(0, slash)}/_rels/${source.slice(slash + 1)}.rels`;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function parseRelationships(root: XmlElement, source: string, relsName: string): Relationship[] {
|
|
269
|
+
if (root.local !== "Relationships") throw new DocxError(`${relsName} has no Relationships`);
|
|
270
|
+
const list: Relationship[] = [];
|
|
271
|
+
for (const child of root.children) {
|
|
272
|
+
if (child.kind !== "element" || child.local !== "Relationship") continue;
|
|
273
|
+
const id = attribute(child, "Id");
|
|
274
|
+
const type = attribute(child, "Type");
|
|
275
|
+
const target = attribute(child, "Target");
|
|
276
|
+
if (id === undefined || type === undefined || target === undefined) {
|
|
277
|
+
throw new DocxError(`${relsName}: a relationship without Id, Type or Target`);
|
|
278
|
+
}
|
|
279
|
+
const external = attribute(child, "TargetMode") === "External";
|
|
280
|
+
// A target with a scheme (`http:`, `file:`) is not a part, whatever its mode says.
|
|
281
|
+
const uri = /^[a-z][a-z0-9+.-]*:/i.test(target);
|
|
282
|
+
list.push(
|
|
283
|
+
external || uri
|
|
284
|
+
? { id, type, target, external }
|
|
285
|
+
: { id, type, target, external, partName: resolveTarget(source, target) },
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
return list;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** A relative target resolved against its source part's folder (RFC 3986 dot segments). */
|
|
292
|
+
function resolveTarget(source: string, target: string): string {
|
|
293
|
+
const path = target.split("#")[0] as string;
|
|
294
|
+
const base = path.startsWith("/") ? [] : source.split("/").slice(1, -1);
|
|
295
|
+
for (const segment of path.split("/")) {
|
|
296
|
+
if (segment === "..") base.pop();
|
|
297
|
+
else if (segment !== "." && segment !== "") base.push(segment);
|
|
298
|
+
}
|
|
299
|
+
return `/${base.join("/")}`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function attribute(element: XmlElement, local: string): string | undefined {
|
|
303
|
+
return element.attributes.find((a) => a.local === local && a.ns === "")?.value;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function text(data: Uint8Array, name: string): string {
|
|
307
|
+
const encoding =
|
|
308
|
+
data[0] === 0xff && data[1] === 0xfe
|
|
309
|
+
? "utf-16le"
|
|
310
|
+
: data[0] === 0xfe && data[1] === 0xff
|
|
311
|
+
? "utf-16be"
|
|
312
|
+
: "utf-8";
|
|
313
|
+
try {
|
|
314
|
+
return new TextDecoder(encoding, { fatal: true }).decode(data);
|
|
315
|
+
} catch {
|
|
316
|
+
throw new DocxError(`${name}: not valid ${encoding.toUpperCase()}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function xml(data: Uint8Array, name: string, options: ParseXmlOptions): XmlDocument {
|
|
321
|
+
const source = text(data, name);
|
|
322
|
+
try {
|
|
323
|
+
return parseXml(source, options);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
// The XmlError (with its offset) stays reachable as the cause.
|
|
326
|
+
throw new DocxError(`${name}: ${(error as Error).message}`, { cause: error });
|
|
327
|
+
}
|
|
328
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Word's document settings part (`settings.xml`): Foli reads and writes only
|
|
3
|
+
* `w:trackRevisions` (whether Word records edits as tracked changes); the rest is kept verbatim.
|
|
4
|
+
*/
|
|
5
|
+
import { isW, W } from "./import/ooxml.js";
|
|
6
|
+
import type { XmlElement } from "./xml.js";
|
|
7
|
+
|
|
8
|
+
/** Whether `settings` (the `w:settings` root) turns tracked changes on. */
|
|
9
|
+
export function trackRevisionsOf(settings: XmlElement | undefined): boolean {
|
|
10
|
+
const element = settings?.children.find(
|
|
11
|
+
(c): c is XmlElement => c.kind === "element" && isW(c, "trackRevisions"),
|
|
12
|
+
);
|
|
13
|
+
if (!element) return false;
|
|
14
|
+
const value = element.attributes.find((a) => a.ns === W && a.local === "val")?.value;
|
|
15
|
+
return value === undefined || !["false", "0", "off"].includes(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Elements `w:settings` has before `w:trackRevisions` (ECMA-376 CT_Settings, in order). */
|
|
19
|
+
const BEFORE = new Set([
|
|
20
|
+
"writeProtection",
|
|
21
|
+
"view",
|
|
22
|
+
"zoom",
|
|
23
|
+
"removePersonalInformation",
|
|
24
|
+
"removeDateAndTime",
|
|
25
|
+
"doNotDisplayPageBoundaries",
|
|
26
|
+
"displayBackgroundShape",
|
|
27
|
+
"printPostScriptOverText",
|
|
28
|
+
"printFractionalCharacterWidth",
|
|
29
|
+
"printFormsData",
|
|
30
|
+
"embedTrueTypeFonts",
|
|
31
|
+
"embedSystemFonts",
|
|
32
|
+
"saveSubsetFonts",
|
|
33
|
+
"saveFormsData",
|
|
34
|
+
"mirrorMargins",
|
|
35
|
+
"alignBordersAndEdges",
|
|
36
|
+
"bordersDoNotSurroundHeader",
|
|
37
|
+
"bordersDoNotSurroundFooter",
|
|
38
|
+
"gutterAtTop",
|
|
39
|
+
"hideSpellingErrors",
|
|
40
|
+
"hideGrammaticalErrors",
|
|
41
|
+
"activeWritingStyle",
|
|
42
|
+
"proofState",
|
|
43
|
+
"formsDesign",
|
|
44
|
+
"attachedTemplate",
|
|
45
|
+
"linkStyles",
|
|
46
|
+
"stylePaneFormatFilter",
|
|
47
|
+
"stylePaneSortMethod",
|
|
48
|
+
"documentType",
|
|
49
|
+
"mailMerge",
|
|
50
|
+
"revisionView",
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
/** `source` (a settings part, `root` its `w:settings`) with tracked changes `on`. */
|
|
54
|
+
export function withTrackRevisions(source: string, root: XmlElement, on: boolean): string {
|
|
55
|
+
if (trackRevisionsOf(root) === on) return source;
|
|
56
|
+
const children = root.children.filter((c): c is XmlElement => c.kind === "element");
|
|
57
|
+
const existing = children.find((c) => isW(c, "trackRevisions"));
|
|
58
|
+
const prefix = root.prefix ? `${root.prefix}:` : "";
|
|
59
|
+
const element = `<${prefix}trackRevisions/>`;
|
|
60
|
+
// Off: removed. On over an explicit "off": replaced.
|
|
61
|
+
if (existing)
|
|
62
|
+
return source.slice(0, existing.start) + (on ? element : "") + source.slice(existing.end);
|
|
63
|
+
const after = children.filter((c) => c.ns === W && BEFORE.has(c.local)).at(-1);
|
|
64
|
+
if (after) return source.slice(0, after.end) + element + source.slice(after.end);
|
|
65
|
+
if (root.openEnd === root.end) {
|
|
66
|
+
// `<w:settings/>`: opened and closed.
|
|
67
|
+
return `${source.slice(0, root.openEnd - 2)}>${element}</${root.name}>${source.slice(root.end)}`;
|
|
68
|
+
}
|
|
69
|
+
return source.slice(0, root.openEnd) + element + source.slice(root.openEnd);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A new settings part with tracked changes on. */
|
|
73
|
+
export function newSettingsXml(): string {
|
|
74
|
+
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:settings xmlns:w="${W}"><w:trackRevisions/></w:settings>`;
|
|
75
|
+
}
|