@folijs/docx 0.5.0 → 1.0.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.
Files changed (123) hide show
  1. package/CHANGELOG.md +157 -0
  2. package/README.md +54 -17
  3. package/dist/custom.d.ts +2 -0
  4. package/dist/custom.d.ts.map +1 -0
  5. package/dist/custom.js +216 -0
  6. package/dist/custom.js.map +1 -0
  7. package/dist/export/balance.d.ts +2 -0
  8. package/dist/export/balance.d.ts.map +1 -0
  9. package/dist/export/balance.js +112 -0
  10. package/dist/export/balance.js.map +1 -0
  11. package/dist/export/content.d.ts +1 -14
  12. package/dist/export/content.d.ts.map +1 -1
  13. package/dist/export/content.js +157 -22
  14. package/dist/export/content.js.map +1 -1
  15. package/dist/export/controls.d.ts +2 -0
  16. package/dist/export/controls.d.ts.map +1 -0
  17. package/dist/export/controls.js +233 -0
  18. package/dist/export/controls.js.map +1 -0
  19. package/dist/export/index.d.ts +8 -2
  20. package/dist/export/index.d.ts.map +1 -1
  21. package/dist/export/index.js +218 -18
  22. package/dist/export/index.js.map +1 -1
  23. package/dist/export/parts.d.ts +1 -16
  24. package/dist/export/parts.d.ts.map +1 -1
  25. package/dist/export/parts.js +79 -11
  26. package/dist/export/parts.js.map +1 -1
  27. package/dist/export/pictures.d.ts +0 -42
  28. package/dist/export/pictures.d.ts.map +1 -1
  29. package/dist/export/pictures.js +24 -4
  30. package/dist/export/pictures.js.map +1 -1
  31. package/dist/export/properties.d.ts +1 -41
  32. package/dist/export/properties.d.ts.map +1 -1
  33. package/dist/export/properties.js +74 -15
  34. package/dist/export/properties.js.map +1 -1
  35. package/dist/export/tables.d.ts +0 -19
  36. package/dist/export/tables.d.ts.map +1 -1
  37. package/dist/export/tables.js +15 -3
  38. package/dist/export/tables.js.map +1 -1
  39. package/dist/export/xmlout.d.ts +1 -61
  40. package/dist/export/xmlout.d.ts.map +1 -1
  41. package/dist/export/xmlout.js +34 -7
  42. package/dist/export/xmlout.js.map +1 -1
  43. package/dist/import/content.d.ts +1 -33
  44. package/dist/import/content.d.ts.map +1 -1
  45. package/dist/import/content.js +208 -17
  46. package/dist/import/content.js.map +1 -1
  47. package/dist/import/controls.d.ts +2 -0
  48. package/dist/import/controls.d.ts.map +1 -0
  49. package/dist/import/controls.js +121 -0
  50. package/dist/import/controls.js.map +1 -0
  51. package/dist/import/index.d.ts +1 -1
  52. package/dist/import/index.d.ts.map +1 -1
  53. package/dist/import/index.js +82 -14
  54. package/dist/import/index.js.map +1 -1
  55. package/dist/import/ooxml.d.ts +1 -37
  56. package/dist/import/ooxml.d.ts.map +1 -1
  57. package/dist/import/ooxml.js +44 -8
  58. package/dist/import/ooxml.js.map +1 -1
  59. package/dist/import/parts.d.ts +1 -33
  60. package/dist/import/parts.d.ts.map +1 -1
  61. package/dist/import/parts.js +36 -10
  62. package/dist/import/parts.js.map +1 -1
  63. package/dist/import/pictures.d.ts +1 -33
  64. package/dist/import/pictures.d.ts.map +1 -1
  65. package/dist/import/pictures.js +7 -1
  66. package/dist/import/pictures.js.map +1 -1
  67. package/dist/import/properties.d.ts +1 -43
  68. package/dist/import/properties.d.ts.map +1 -1
  69. package/dist/import/properties.js +84 -6
  70. package/dist/import/properties.js.map +1 -1
  71. package/dist/import/report.d.ts +0 -10
  72. package/dist/import/report.d.ts.map +1 -1
  73. package/dist/import/report.js +1 -0
  74. package/dist/import/report.js.map +1 -1
  75. package/dist/import/stories.d.ts +2 -0
  76. package/dist/import/stories.d.ts.map +1 -0
  77. package/dist/import/stories.js +131 -0
  78. package/dist/import/stories.js.map +1 -0
  79. package/dist/import/tables.d.ts +0 -24
  80. package/dist/import/tables.d.ts.map +1 -1
  81. package/dist/import/tables.js +25 -6
  82. package/dist/import/tables.js.map +1 -1
  83. package/dist/package.d.ts +8 -4
  84. package/dist/package.d.ts.map +1 -1
  85. package/dist/package.js +38 -4
  86. package/dist/package.js.map +1 -1
  87. package/dist/settings.d.ts +1 -7
  88. package/dist/settings.d.ts.map +1 -1
  89. package/dist/settings.js +186 -26
  90. package/dist/settings.js.map +1 -1
  91. package/dist/xml.d.ts +8 -0
  92. package/dist/xml.d.ts.map +1 -1
  93. package/dist/xml.js +30 -2
  94. package/dist/xml.js.map +1 -1
  95. package/dist/zip.d.ts +0 -47
  96. package/dist/zip.d.ts.map +1 -1
  97. package/dist/zip.js +11 -2
  98. package/dist/zip.js.map +1 -1
  99. package/package.json +6 -5
  100. package/src/custom.ts +254 -0
  101. package/src/export/balance.ts +114 -0
  102. package/src/export/content.ts +203 -19
  103. package/src/export/controls.ts +260 -0
  104. package/src/export/index.ts +268 -20
  105. package/src/export/parts.ts +102 -10
  106. package/src/export/pictures.ts +21 -5
  107. package/src/export/properties.ts +90 -18
  108. package/src/export/tables.ts +15 -3
  109. package/src/export/xmlout.ts +36 -7
  110. package/src/import/content.ts +219 -17
  111. package/src/import/controls.ts +141 -0
  112. package/src/import/index.ts +103 -22
  113. package/src/import/ooxml.ts +44 -8
  114. package/src/import/parts.ts +44 -19
  115. package/src/import/pictures.ts +8 -1
  116. package/src/import/properties.ts +90 -6
  117. package/src/import/report.ts +1 -0
  118. package/src/import/stories.ts +134 -0
  119. package/src/import/tables.ts +25 -6
  120. package/src/package.ts +56 -6
  121. package/src/settings.ts +204 -27
  122. package/src/xml.ts +42 -2
  123. package/src/zip.ts +17 -5
@@ -4,7 +4,8 @@
4
4
  * against the schema: one the model cannot hold is reported and stays in the element's `ext`.
5
5
  */
6
6
 
7
- import { type AttributeSpec, schema, TABLE_CONDITIONS } from "@folijs/core";
7
+ import { type AttributeSpec, TABLE_CONDITIONS } from "@folijs/core";
8
+ import { schema } from "@folijs/core/internal";
8
9
  import type { XmlElement } from "../xml.js";
9
10
  import { attr, child, compact, elements, integer, toggle } from "./ooxml.js";
10
11
  import { type Context, onOff, revisionOf, sourceOf } from "./properties.js";
@@ -37,6 +38,7 @@ function set(
37
38
  /**
38
39
  * A measure (`w:tblW`, `w:tcW`, `w:tblInd`, a margin): `w:w` in twips or fiftieths of a percent
39
40
  * (`pct`, which Strict files may write as `50%`). Undefined, reported, when unreadable.
41
+ * @internal
40
42
  */
41
43
  export function measure(el: XmlElement | undefined, context: Context): Json | undefined {
42
44
  if (!el) return undefined;
@@ -56,7 +58,10 @@ export function measure(el: XmlElement | undefined, context: Context): Json | un
56
58
  return { value, type };
57
59
  }
58
60
 
59
- /** A border element's attributes. */
61
+ /**
62
+ * A border element's attributes.
63
+ * @internal
64
+ */
60
65
  export function border(el: XmlElement, context: Context): Json | undefined {
61
66
  const whole = (local: string) => {
62
67
  const value = attr(el, local);
@@ -88,6 +93,7 @@ function margins(el: XmlElement | undefined, context: Context): Json | undefined
88
93
  );
89
94
  }
90
95
 
96
+ /** @internal */
91
97
  export function shading(el: XmlElement | undefined): Json | undefined {
92
98
  if (!el) return undefined;
93
99
  return compact({
@@ -126,6 +132,7 @@ const on = (el: XmlElement | undefined) => (el ? toggle(el) : undefined);
126
132
  /**
127
133
  * `w:tblPr` (or `w:tblPrEx`) as table properties. With `ext`, the element itself is kept
128
134
  * verbatim (a table's and a row's exceptions; a style's are in its own `ext`).
135
+ * @internal
129
136
  */
130
137
  export function tableProperties(el: XmlElement | undefined, context: Context, ext: boolean): Json {
131
138
  const out: Json = {};
@@ -149,7 +156,10 @@ export function tableProperties(el: XmlElement | undefined, context: Context, ex
149
156
  return out;
150
157
  }
151
158
 
152
- /** `w:tblGrid`'s column widths. */
159
+ /**
160
+ * `w:tblGrid`'s column widths.
161
+ * @internal
162
+ */
153
163
  export function grid(el: XmlElement | undefined, context: Context): number[] {
154
164
  if (!el) return [];
155
165
  const widths = elements(el)
@@ -163,7 +173,10 @@ export function grid(el: XmlElement | undefined, context: Context): number[] {
163
173
  return widths;
164
174
  }
165
175
 
166
- /** `w:trPr` as row properties; with `node`, also the row's revision and the element verbatim. */
176
+ /**
177
+ * `w:trPr` as row properties; with `node`, also the row's revision and the element verbatim.
178
+ * @internal
179
+ */
167
180
  export function rowProperties(el: XmlElement | undefined, context: Context, node: boolean): Json {
168
181
  const out: Json = {};
169
182
  if (!el) return out;
@@ -196,7 +209,10 @@ export function rowProperties(el: XmlElement | undefined, context: Context, node
196
209
  return out;
197
210
  }
198
211
 
199
- /** `w:tcPr` as cell properties; with `node`, also the element verbatim. */
212
+ /**
213
+ * `w:tcPr` as cell properties; with `node`, also the element verbatim.
214
+ * @internal
215
+ */
200
216
  export function cellProperties(el: XmlElement | undefined, context: Context, node: boolean): Json {
201
217
  const out: Json = {};
202
218
  if (!el) return out;
@@ -220,7 +236,10 @@ export function cellProperties(el: XmlElement | undefined, context: Context, nod
220
236
 
221
237
  const nonEmpty = (json: Json) => (Object.keys(json).length ? json : undefined);
222
238
 
223
- /** A table style's parts (`w:tblPr`, `w:trPr`, `w:tcPr`, `w:tblStylePr`) for its `StyleJSON`. */
239
+ /**
240
+ * A table style's parts (`w:tblPr`, `w:trPr`, `w:tcPr`, `w:tblStylePr`) for its `StyleJSON`.
241
+ * @internal
242
+ */
224
243
  export function tableStyleParts(
225
244
  style: XmlElement,
226
245
  context: Context,
package/src/package.ts CHANGED
@@ -4,7 +4,13 @@
4
4
  * was not asked to replace copied from the original file byte for byte.
5
5
  */
6
6
 
7
- import { type ParseXmlOptions, parseXml, type XmlDocument, type XmlElement } from "./xml.js";
7
+ import {
8
+ type ParseXmlOptions,
9
+ parseXmlCosting,
10
+ type XmlDocument,
11
+ type XmlElement,
12
+ XmlLimitError,
13
+ } from "./xml.js";
8
14
  import {
9
15
  deflateEntry,
10
16
  inflateEntry,
@@ -37,7 +43,30 @@ export interface Relationship {
37
43
  readonly partName?: string;
38
44
  }
39
45
 
40
- export interface ReadPackageOptions extends ZipLimits, ParseXmlOptions {}
46
+ /**
47
+ * Measured in 12.11 (Node, built packages): a 659-page Word document of dense tables (250 tables
48
+ * of 30 × 5 cells, 46 000 paragraphs) counts 1.9 million and takes 0.8 GB at its peak to import;
49
+ * 4 million of the costliest crafted content (empty paragraphs, or paragraphs of one tab) about
50
+ * 2.3 GB and 12-28 s depending on heap headroom. Far below a file's 512 MiB `maxSize`.
51
+ */
52
+ const DEFAULT_MAX_NODES = 4_000_000;
53
+ const W_MAIN = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
54
+ /**
55
+ * A paragraph costs about four times what other nodes do once imported (its node, properties
56
+ * and JSON: 1.4 KB at the peak against 0.1-0.5 KB), so a file of empty paragraphs is no cheaper
57
+ * way past the limit.
58
+ */
59
+ const PARAGRAPH_COST = 4;
60
+ const cost = (ns: string, local: string) => (local === "p" && ns === W_MAIN ? PARAGRAPH_COST : 1);
61
+
62
+ export interface ReadPackageOptions extends ZipLimits, ParseXmlOptions {
63
+ /**
64
+ * Most XML nodes in all the parts read, together: each element, attribute, text, comment and
65
+ * processing instruction counts one, a paragraph (`w:p`) four. Default 4 000 000: a 659-page
66
+ * document of dense tables counts 1.9 million; at the limit an import can take about 2.3 GB.
67
+ */
68
+ readonly maxNodes?: number;
69
+ }
41
70
 
42
71
  /** A file that is not a `.docx` package, or is damaged. */
43
72
  export class DocxError extends Error {
@@ -69,6 +98,10 @@ export class DocxPackage {
69
98
  readonly mainDocument: string;
70
99
  readonly #entries: readonly ZipEntry[];
71
100
  readonly #options: ParseXmlOptions;
101
+ /** `maxNodes`: for the whole package, every part read counting towards it. */
102
+ readonly #maxNodes: number;
103
+ /** Nodes the parts parsed from now on may still hold. */
104
+ #nodes: number;
72
105
  readonly #byName = new Map<string, DocxPart>();
73
106
  readonly #relationships = new Map<string, readonly Relationship[]>();
74
107
  readonly #xml = new Map<string, XmlDocument>();
@@ -80,9 +113,11 @@ export class DocxPackage {
80
113
  constructor(entries: readonly ZipEntry[], data: readonly Uint8Array[], options: ParseXmlOptions) {
81
114
  this.#entries = entries;
82
115
  this.#options = options.maxDepth === undefined ? {} : { maxDepth: options.maxDepth };
116
+ this.#maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
117
+ this.#nodes = this.#maxNodes;
83
118
  const index = entries.findIndex((e) => key(partName(e.name)) === key(CONTENT_TYPES));
84
119
  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);
120
+ const typesXml = this.#parse(data[index] as Uint8Array, CONTENT_TYPES);
86
121
  const types = contentTypes(typesXml.root);
87
122
  this.#defaults = types.defaults;
88
123
  this.#overridden = new Set(types.overrides.keys());
@@ -138,13 +173,28 @@ export class DocxPackage {
138
173
  return text(part.data, part.name);
139
174
  }
140
175
 
176
+ #parse(data: Uint8Array, name: string): XmlDocument {
177
+ try {
178
+ const doc = xml(data, name, { ...this.#options, maxNodes: this.#nodes });
179
+ this.#nodes -= doc.nodes;
180
+ return doc;
181
+ } catch (error) {
182
+ if (!((error as Error).cause instanceof XmlLimitError)) throw error;
183
+ throw new DocxError(
184
+ `${name}: the package holds more than ${this.#maxNodes} XML nodes, the limit ` +
185
+ "(maxNodes) of elements, attributes, text and comments read",
186
+ { cause: (error as Error).cause },
187
+ );
188
+ }
189
+ }
190
+
141
191
  /** The part parsed as XML (once); every node keeps its offsets into the part's text. */
142
192
  xml(name: string): XmlDocument {
143
193
  const part = this.part(name);
144
194
  if (!part) throw new DocxError(`No part ${name}`);
145
195
  let doc = this.#xml.get(key(part.name));
146
196
  if (!doc) {
147
- doc = xml(part.data, part.name, this.#options);
197
+ doc = this.#parse(part.data, part.name);
148
198
  this.#xml.set(key(part.name), doc);
149
199
  }
150
200
  return doc;
@@ -160,7 +210,7 @@ export class DocxPackage {
160
210
  async write(
161
211
  replace: ReadonlyMap<string, Uint8Array> = new Map(),
162
212
  add: readonly NewPart[] = [],
163
- ): Promise<Uint8Array> {
213
+ ): Promise<Uint8Array<ArrayBuffer>> {
164
214
  const pending = new Map<string, Uint8Array>();
165
215
  for (const [name, data] of replace) {
166
216
  const part = this.part(name);
@@ -320,7 +370,7 @@ function text(data: Uint8Array, name: string): string {
320
370
  function xml(data: Uint8Array, name: string, options: ParseXmlOptions): XmlDocument {
321
371
  const source = text(data, name);
322
372
  try {
323
- return parseXml(source, options);
373
+ return parseXmlCosting(source, options, cost);
324
374
  } catch (error) {
325
375
  // The XmlError (with its offset) stays reachable as the cause.
326
376
  throw new DocxError(`${name}: ${(error as Error).message}`, { cause: error });
package/src/settings.ts CHANGED
@@ -1,22 +1,77 @@
1
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.
2
+ * Word's document settings part (`settings.xml`): Foli reads and writes `w:trackRevisions`
3
+ * (whether Word records edits as tracked changes), `w:evenAndOddHeaders` and the note properties
4
+ * of `w:footnotePr` and `w:endnotePr`, and reads `w:doNotUseHTMLParagraphAutoSpacing`; the rest is
5
+ * kept verbatim, and so is the part when none of them changes.
4
6
  */
5
- import { isW, W } from "./import/ooxml.js";
6
- import type { XmlElement } from "./xml.js";
7
+ import type { NotePropertiesJSON, WordSettingsJSON } from "@folijs/core";
8
+ import { child, isW, toggle, W } from "./import/ooxml.js";
9
+ import { parseXml, type XmlElement } from "./xml.js";
7
10
 
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
- );
11
+ const elementsOf = (parent: XmlElement) =>
12
+ parent.children.filter((c): c is XmlElement => c.kind === "element");
13
+ const valOf = (element: XmlElement | undefined, name = "val") =>
14
+ element?.attributes.find((a) => a.ns === W && a.local === name)?.value;
15
+
16
+ /** Whether the on-off element `local` of `settings` is on. */
17
+ function isOn(settings: XmlElement | undefined, local: string): boolean {
18
+ const element = settings && elementsOf(settings).find((c) => isW(c, local));
13
19
  if (!element) return false;
14
- const value = element.attributes.find((a) => a.ns === W && a.local === "val")?.value;
20
+ const value = valOf(element);
15
21
  return value === undefined || !["false", "0", "off"].includes(value);
16
22
  }
17
23
 
18
- /** Elements `w:settings` has before `w:trackRevisions` (ECMA-376 CT_Settings, in order). */
19
- const BEFORE = new Set([
24
+ /**
25
+ * Whether `settings` (the `w:settings` root) turns tracked changes on.
26
+ * @internal
27
+ */
28
+ export const trackRevisionsOf = (settings: XmlElement | undefined): boolean =>
29
+ isOn(settings, "trackRevisions");
30
+
31
+ const POSITIONS = new Set(["pageBottom", "beneathText", "sectEnd", "docEnd"]);
32
+ const RESTARTS = new Set(["continuous", "eachSect", "eachPage"]);
33
+
34
+ /** A `w:footnotePr` or `w:endnotePr` of the settings (its separators stay in the file). */
35
+ function noteProperties(element: XmlElement | undefined): NotePropertiesJSON {
36
+ const value = (local: string) => valOf(element && elementsOf(element).find((c) => isW(c, local)));
37
+ const position = value("pos");
38
+ const format = value("numFmt");
39
+ const start = Number(value("numStart"));
40
+ const restart = value("numRestart");
41
+ return {
42
+ ...(position && POSITIONS.has(position)
43
+ ? { position: position as NotePropertiesJSON["position"] & string }
44
+ : {}),
45
+ ...(format && /^[\w-]+$/.test(format) ? { format } : {}),
46
+ ...(Number.isInteger(start) && start >= 0 && value("numStart") ? { start } : {}),
47
+ ...(restart && RESTARTS.has(restart)
48
+ ? { restart: restart as NotePropertiesJSON["restart"] & string }
49
+ : {}),
50
+ };
51
+ }
52
+
53
+ /**
54
+ * What the document's `settings` model holds of the part, undefined when nothing.
55
+ * @internal
56
+ */
57
+ export function readSettings(settings: XmlElement | undefined): WordSettingsJSON | undefined {
58
+ if (!settings) return undefined;
59
+ const notes = (local: string) => noteProperties(elementsOf(settings).find((c) => isW(c, local)));
60
+ const footnotes = notes("footnotePr");
61
+ const endnotes = notes("endnotePr");
62
+ const compat = child(settings, "compat");
63
+ const spacing = compat && child(compat, "doNotUseHTMLParagraphAutoSpacing");
64
+ const out: WordSettingsJSON = {
65
+ ...(spacing && toggle(spacing) ? { doNotUseHTMLParagraphAutoSpacing: true } : {}),
66
+ ...(isOn(settings, "evenAndOddHeaders") ? { evenAndOddHeaders: true } : {}),
67
+ ...(Object.keys(footnotes).length ? { footnotes } : {}),
68
+ ...(Object.keys(endnotes).length ? { endnotes } : {}),
69
+ };
70
+ return Object.keys(out).length ? out : undefined;
71
+ }
72
+
73
+ /** `w:settings`' children in their order (ECMA-376 CT_Settings), as far as Foli writes them. */
74
+ const ORDER = [
20
75
  "writeProtection",
21
76
  "view",
22
77
  "zoom",
@@ -48,19 +103,65 @@ const BEFORE = new Set([
48
103
  "documentType",
49
104
  "mailMerge",
50
105
  "revisionView",
51
- ]);
106
+ "trackRevisions",
107
+ "doNotTrackMoves",
108
+ "doNotTrackFormatting",
109
+ "documentProtection",
110
+ "autoFormatOverride",
111
+ "styleLockTheme",
112
+ "styleLockQFSet",
113
+ "defaultTabStop",
114
+ "autoHyphenation",
115
+ "consecutiveHyphenLimit",
116
+ "hyphenationZone",
117
+ "doNotHyphenateCaps",
118
+ "showEnvelope",
119
+ "summaryLength",
120
+ "clickAndTypeStyle",
121
+ "defaultTableStyle",
122
+ "evenAndOddHeaders",
123
+ "bookFoldRevPrinting",
124
+ "bookFoldPrinting",
125
+ "bookFoldPrintingSheets",
126
+ "drawingGridHorizontalSpacing",
127
+ "drawingGridVerticalSpacing",
128
+ "displayHorizontalDrawingGridEvery",
129
+ "displayVerticalDrawingGridEvery",
130
+ "doNotUseMarginsForDrawingGridOrigin",
131
+ "drawingGridHorizontalOrigin",
132
+ "drawingGridVerticalOrigin",
133
+ "doNotShadeFormData",
134
+ "noPunctuationKerning",
135
+ "characterSpacingControl",
136
+ "printTwoOnOne",
137
+ "strictFirstAndLastChars",
138
+ "noLineBreaksAfter",
139
+ "noLineBreaksBefore",
140
+ "savePreviewPicture",
141
+ "doNotValidateAgainstSchema",
142
+ "saveInvalidXml",
143
+ "ignoreMixedContent",
144
+ "alwaysShowPlaceholderText",
145
+ "doNotDemarcateInvalidXml",
146
+ "saveXmlDataOnly",
147
+ "useXSLTWhenSaving",
148
+ "saveThroughXslt",
149
+ "showXMLTags",
150
+ "alwaysMergeEmptyNamespace",
151
+ "updateFields",
152
+ "hdrShapeDefaults",
153
+ "footnotePr",
154
+ "endnotePr",
155
+ ];
52
156
 
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);
157
+ /** `source` with the child `local` of `root` being `element` ("": none), in its place. */
158
+ function placed(source: string, root: XmlElement, local: string, element: string): string {
159
+ const children = elementsOf(root);
160
+ const existing = children.find((c) => isW(c, local));
161
+ if (existing) return source.slice(0, existing.start) + element + source.slice(existing.end);
162
+ if (!element) return source;
163
+ const before = new Set(ORDER.slice(0, ORDER.indexOf(local)));
164
+ const after = children.filter((c) => c.ns === W && before.has(c.local)).at(-1);
64
165
  if (after) return source.slice(0, after.end) + element + source.slice(after.end);
65
166
  if (root.openEnd === root.end) {
66
167
  // `<w:settings/>`: opened and closed.
@@ -69,7 +170,83 @@ export function withTrackRevisions(source: string, root: XmlElement, on: boolean
69
170
  return source.slice(0, root.openEnd) + element + source.slice(root.openEnd);
70
171
  }
71
172
 
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>`;
173
+ const prefixOf = (root: XmlElement) => (root.prefix ? `${root.prefix}:` : "");
174
+
175
+ /**
176
+ * `source` (a settings part, `root` its `w:settings`) with tracked changes `on`.
177
+ * @internal
178
+ */
179
+ export function withTrackRevisions(source: string, root: XmlElement, on: boolean): string {
180
+ if (trackRevisionsOf(root) === on) return source;
181
+ return placed(source, root, "trackRevisions", on ? `<${prefixOf(root)}trackRevisions/>` : "");
182
+ }
183
+
184
+ /** A note properties element: `kept` (its separators, verbatim) after the properties. */
185
+ function notesXml(prefix: string, local: string, v: NotePropertiesJSON, kept = ""): string {
186
+ const value = (name: string, x: string | number | undefined) =>
187
+ x === undefined ? "" : `<${prefix}${name} ${prefix}val="${x}"/>`;
188
+ const children =
189
+ value("pos", v.position) +
190
+ value("numFmt", v.format) +
191
+ value("numStart", v.start) +
192
+ value("numRestart", v.restart) +
193
+ kept;
194
+ return children ? `<${prefix}${local}>${children}</${prefix}${local}>` : "";
195
+ }
196
+
197
+ const NOTES = [
198
+ ["footnotes", "footnotePr", "footnote"],
199
+ ["endnotes", "endnotePr", "endnote"],
200
+ ] as const;
201
+
202
+ /** The same properties, whatever their order. */
203
+ const sameNotes = (a: NotePropertiesJSON, b: NotePropertiesJSON) =>
204
+ a.position === b.position &&
205
+ a.format === b.format &&
206
+ a.start === b.start &&
207
+ a.restart === b.restart;
208
+
209
+ /**
210
+ * `source` saying what `settings` says. What they leave out stays as the file has it, and a part
211
+ * that already says it is returned as it is.
212
+ * @internal
213
+ */
214
+ export function withSettings(source: string, root: XmlElement, settings: WordSettingsJSON): string {
215
+ let text = source;
216
+ let current = root;
217
+ const put = (local: string, element: string) => {
218
+ text = placed(text, current, local, element);
219
+ current = parseXml(text).root;
220
+ };
221
+ const prefix = prefixOf(root);
222
+ const even = settings.evenAndOddHeaders;
223
+ if (even !== undefined && even !== isOn(current, "evenAndOddHeaders"))
224
+ put("evenAndOddHeaders", even ? `<${prefix}evenAndOddHeaders/>` : "");
225
+ for (const [key, local, separator] of NOTES) {
226
+ const wanted = settings[key];
227
+ if (!wanted) continue;
228
+ const element = elementsOf(current).find((c) => isW(c, local));
229
+ if (sameNotes(wanted, noteProperties(element))) continue;
230
+ const kept = (element ? elementsOf(element) : [])
231
+ .filter((c) => isW(c, separator))
232
+ .map((c) => text.slice(c.start, c.end))
233
+ .join("");
234
+ put(local, notesXml(prefix, local, wanted, kept));
235
+ }
236
+ return text;
237
+ }
238
+
239
+ /**
240
+ * A new settings part.
241
+ * @internal
242
+ */
243
+ export function newSettingsXml(trackRevisions: boolean, settings: WordSettingsJSON = {}): string {
244
+ const children =
245
+ (trackRevisions ? "<w:trackRevisions/>" : "") +
246
+ (settings.evenAndOddHeaders ? "<w:evenAndOddHeaders/>" : "") +
247
+ NOTES.map(([key, local]) => notesXml("w:", local, settings[key] ?? {})).join("") +
248
+ (settings.doNotUseHTMLParagraphAutoSpacing
249
+ ? "<w:compat><w:doNotUseHTMLParagraphAutoSpacing/></w:compat>"
250
+ : "");
251
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:settings xmlns:w="${W}">${children}</w:settings>`;
75
252
  }
package/src/xml.ts CHANGED
@@ -67,6 +67,8 @@ export interface XmlDocument {
67
67
  /** Everything at the top level in order: declaration, comments, whitespace, the root. */
68
68
  readonly children: readonly XmlNode[];
69
69
  readonly root: XmlElement;
70
+ /** How many nodes the source holds: elements, attributes, text, comments, instructions. */
71
+ readonly nodes: number;
70
72
  }
71
73
 
72
74
  /** Source that is not well-formed XML; `offset` is where in the source. */
@@ -80,6 +82,12 @@ export class XmlError extends Error {
80
82
  }
81
83
  }
82
84
 
85
+ /**
86
+ * More nodes than `maxNodes` allows.
87
+ * @internal
88
+ */
89
+ export class XmlLimitError extends XmlError {}
90
+
83
91
  const XML_NS = "http://www.w3.org/XML/1998/namespace";
84
92
  const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
85
93
  const ENTITIES: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
@@ -103,6 +111,12 @@ export interface ParseXmlOptions {
103
111
  * tables, content controls) stay far below, and code walking the tree recursively is safe.
104
112
  */
105
113
  readonly maxDepth?: number;
114
+ /**
115
+ * Most nodes accepted: elements, attributes, text, comments and processing instructions, each
116
+ * one, since each costs memory. No limit by default here; `readPackage` and `importDocx` set
117
+ * one for a package (its `maxNodes`).
118
+ */
119
+ readonly maxNodes?: number;
106
120
  }
107
121
 
108
122
  /** The first character XML 1.0 does not allow (outside its Char production), or -1. */
@@ -124,7 +138,26 @@ function illegalCharacter(source: string): number {
124
138
 
125
139
  /** Parses `source`; throws {@link XmlError} where it is not well-formed. */
126
140
  export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocument {
141
+ return parseXmlCosting(source, options);
142
+ }
143
+
144
+ /**
145
+ * `parseXml`, an element costing `cost(namespace, local name)` nodes of `maxNodes` (default 1).
146
+ * @internal
147
+ */
148
+ export function parseXmlCosting(
149
+ source: string,
150
+ options: ParseXmlOptions,
151
+ cost?: (ns: string, local: string) => number,
152
+ ): XmlDocument {
127
153
  const maxDepth = options.maxDepth ?? 1000;
154
+ const maxNodes = options.maxNodes ?? Number.POSITIVE_INFINITY;
155
+ let nodes = 0;
156
+ /** Every node read costs memory, whatever its kind: counted before it is kept. */
157
+ const charge = (offset: number, n = 1) => {
158
+ nodes += n;
159
+ if (nodes > maxNodes) throw new XmlLimitError(`More than ${maxNodes} nodes`, offset);
160
+ };
128
161
  if (source.charCodeAt(0) === 0xfeff) {
129
162
  throw new XmlError("Byte order mark in the text: decode the bytes without it", 0);
130
163
  }
@@ -151,6 +184,7 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
151
184
  }
152
185
  const cdataEnd = raw.indexOf("]]>");
153
186
  if (cdataEnd !== -1) throw new XmlError('"]]>" in text', at + cdataEnd);
187
+ charge(at);
154
188
  siblings().push({
155
189
  kind: "text",
156
190
  text: decode(raw, false, at),
@@ -167,12 +201,14 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
167
201
  if (close === -1) throw new XmlError("Unclosed comment", at);
168
202
  const dashes = source.indexOf("--", at + 4);
169
203
  if (dashes < close) throw new XmlError('"--" in a comment', dashes);
204
+ charge(at);
170
205
  siblings().push({ kind: "comment", start: at, end: close + 3 });
171
206
  at = close + 3;
172
207
  } else if (source.startsWith("<![CDATA[", at)) {
173
208
  if (stack.length === 0) throw new XmlError("CDATA outside the root element", at);
174
209
  const close = source.indexOf("]]>", at + 9);
175
210
  if (close === -1) throw new XmlError("Unclosed CDATA section", at);
211
+ charge(at);
176
212
  siblings().push({
177
213
  kind: "text",
178
214
  text: source.slice(at + 9, close).replace(/\r\n?/g, "\n"),
@@ -192,6 +228,7 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
192
228
  if (declaration && (at !== 0 || target !== "xml")) {
193
229
  throw new XmlError("XML declaration not at the start", at);
194
230
  }
231
+ charge(at);
195
232
  siblings().push({
196
233
  kind: declaration ? "declaration" : "instruction",
197
234
  start: at,
@@ -219,7 +256,7 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
219
256
  const unclosed = stack[stack.length - 1];
220
257
  if (unclosed) throw new XmlError(`Unclosed element <${unclosed.name}>`, unclosed.start);
221
258
  if (!root) throw new XmlError("No root element", 0);
222
- return { source, children: top, root };
259
+ return { source, children: top, root, nodes };
223
260
 
224
261
  function finish(element: XmlElement, start: number): void {
225
262
  if (stack.length === 0) {
@@ -265,6 +302,7 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
265
302
  if (value.includes("<")) throw new XmlError(`"<" in attribute ${attrName}`, open);
266
303
  if (names.has(attrName)) throw new XmlError(`Duplicate attribute ${attrName}`, next);
267
304
  names.add(attrName);
305
+ charge(next);
268
306
  raw.push({
269
307
  name: attrName,
270
308
  value: decode(value, true, open + 1),
@@ -319,10 +357,12 @@ export function parseXml(source: string, options: ParseXmlOptions = {}): XmlDocu
319
357
  if (stack.length >= maxDepth) {
320
358
  throw new XmlError(`Elements nested deeper than ${maxDepth}`, start);
321
359
  }
360
+ const ns = resolve(scope, qualified.prefix, start);
361
+ charge(start, cost?.(ns, qualified.local) ?? 1);
322
362
  const element = {
323
363
  kind: "element" as const,
324
364
  ...qualified,
325
- ns: resolve(scope, qualified.prefix, start),
365
+ ns,
326
366
  attributes,
327
367
  start,
328
368
  openEnd: at,
package/src/zip.ts CHANGED
@@ -7,7 +7,10 @@
7
7
  * replaced entries are compressed again.
8
8
  */
9
9
 
10
- /** A file in the zip. `raw` is its data as stored (compressed when `method` is 8). */
10
+ /**
11
+ * A file in the zip. `raw` is its data as stored (compressed when `method` is 8).
12
+ * @internal
13
+ */
11
14
  export interface ZipEntry {
12
15
  readonly name: string;
13
16
  /** The name's bytes as stored, written back unchanged. */
@@ -57,6 +60,7 @@ const textDecoder = new TextDecoder();
57
60
  * Lists the entries of a zip from its central directory, in the directory's order. Nothing is
58
61
  * decompressed: see {@link inflateEntry}. Every entry is checked against its local header, and
59
62
  * entries may not overlap: Foli reads what any other zip reader would.
63
+ * @internal
60
64
  */
61
65
  export function readZip(bytes: Uint8Array, limits: ZipLimits = {}): ZipEntry[] {
62
66
  const maxEntries = limits.maxEntries ?? 10_000;
@@ -227,7 +231,10 @@ function findEnd(view: DataView): number {
227
231
  throw new ZipError("Not a zip archive");
228
232
  }
229
233
 
230
- /** The entry's data, decompressed, checked against its size and CRC-32. */
234
+ /**
235
+ * The entry's data, decompressed, checked against its size and CRC-32.
236
+ * @internal
237
+ */
231
238
  export async function inflateEntry(entry: ZipEntry): Promise<Uint8Array> {
232
239
  const data =
233
240
  entry.method === 0
@@ -265,6 +272,7 @@ async function inflateRaw(raw: Uint8Array, size: number, name: string): Promise<
265
272
  /**
266
273
  * A new deflated entry holding `data`. With `like` (the entry it replaces) it keeps that entry's
267
274
  * name bytes, name encoding flag, time and date.
275
+ * @internal
268
276
  */
269
277
  export async function deflateEntry(
270
278
  name: string,
@@ -296,8 +304,9 @@ export async function deflateEntry(
296
304
  * The zip of `entries`, in order; each entry's data written as it is in `raw`. An entry read
297
305
  * from a zip keeps its headers byte for byte (only its offset in the directory changes), so a
298
306
  * zip written back with its entries unchanged is the same file, short of a trailing comment.
307
+ * @internal
299
308
  */
300
- export function writeZip(entries: readonly ZipEntry[]): Uint8Array {
309
+ export function writeZip(entries: readonly ZipEntry[]): Uint8Array<ArrayBuffer> {
301
310
  const parts: Uint8Array[] = [];
302
311
  const directory: Uint8Array[] = [];
303
312
  let offset = 0;
@@ -371,7 +380,7 @@ function streamOf(data: Uint8Array): ReadableStream<BufferSource> {
371
380
  });
372
381
  }
373
382
 
374
- function concat(chunks: readonly Uint8Array[]): Uint8Array {
383
+ function concat(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {
375
384
  const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
376
385
  let at = 0;
377
386
  for (const chunk of chunks) {
@@ -383,7 +392,10 @@ function concat(chunks: readonly Uint8Array[]): Uint8Array {
383
392
 
384
393
  let table: Uint32Array | undefined;
385
394
 
386
- /** CRC-32 (IEEE), as zip stores it. */
395
+ /**
396
+ * CRC-32 (IEEE), as zip stores it.
397
+ * @internal
398
+ */
387
399
  export function crc32(data: Uint8Array): number {
388
400
  if (!table) {
389
401
  table = new Uint32Array(256);