llm-large-files 0.7.0 → 0.8.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 (184) hide show
  1. package/CHANGELOG.md +319 -1
  2. package/README.md +10 -8
  3. package/dist/analyze.d.ts +3 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +109 -14
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts.map +1 -1
  8. package/dist/anthropic/adapter.js +4 -1
  9. package/dist/anthropic/adapter.js.map +1 -1
  10. package/dist/ask.d.ts +3 -3
  11. package/dist/ask.d.ts.map +1 -1
  12. package/dist/ask.js +72 -17
  13. package/dist/ask.js.map +1 -1
  14. package/dist/decode.d.ts +19 -0
  15. package/dist/decode.d.ts.map +1 -0
  16. package/dist/decode.js +97 -0
  17. package/dist/decode.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +65 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/events.d.ts +6 -0
  23. package/dist/events.d.ts.map +1 -1
  24. package/dist/events.js +5 -1
  25. package/dist/events.js.map +1 -1
  26. package/dist/evidence.d.ts.map +1 -1
  27. package/dist/evidence.js +6 -0
  28. package/dist/evidence.js.map +1 -1
  29. package/dist/extract.d.ts +7 -20
  30. package/dist/extract.d.ts.map +1 -1
  31. package/dist/extract.js +49 -751
  32. package/dist/extract.js.map +1 -1
  33. package/dist/gemini/adapter.d.ts.map +1 -1
  34. package/dist/gemini/adapter.js +9 -5
  35. package/dist/gemini/adapter.js.map +1 -1
  36. package/dist/gemini/endpoints.d.ts +5 -1
  37. package/dist/gemini/endpoints.d.ts.map +1 -1
  38. package/dist/gemini/endpoints.js +11 -2
  39. package/dist/gemini/endpoints.js.map +1 -1
  40. package/dist/gemini/generate.d.ts.map +1 -1
  41. package/dist/gemini/generate.js +20 -3
  42. package/dist/gemini/generate.js.map +1 -1
  43. package/dist/groups.d.ts +54 -0
  44. package/dist/groups.d.ts.map +1 -0
  45. package/dist/groups.js +136 -0
  46. package/dist/groups.js.map +1 -0
  47. package/dist/html.d.ts +11 -0
  48. package/dist/html.d.ts.map +1 -0
  49. package/dist/html.js +1112 -0
  50. package/dist/html.js.map +1 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts.map +1 -1
  56. package/dist/library.js +48 -12
  57. package/dist/library.js.map +1 -1
  58. package/dist/limiter.d.ts +2 -1
  59. package/dist/limiter.d.ts.map +1 -1
  60. package/dist/limiter.js +3 -2
  61. package/dist/limiter.js.map +1 -1
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +8 -1
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts.map +1 -1
  66. package/dist/node/handlers.js +69 -15
  67. package/dist/node/handlers.js.map +1 -1
  68. package/dist/node/index.d.ts +2 -0
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +1 -0
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/ingest-child.d.ts +38 -0
  73. package/dist/node/ingest-child.d.ts.map +1 -0
  74. package/dist/node/ingest-child.js +42 -0
  75. package/dist/node/ingest-child.js.map +1 -0
  76. package/dist/node/isolated.d.ts +88 -0
  77. package/dist/node/isolated.d.ts.map +1 -0
  78. package/dist/node/isolated.js +381 -0
  79. package/dist/node/isolated.js.map +1 -0
  80. package/dist/office.d.ts +105 -0
  81. package/dist/office.d.ts.map +1 -0
  82. package/dist/office.js +1092 -0
  83. package/dist/office.js.map +1 -0
  84. package/dist/openai/adapter.d.ts.map +1 -1
  85. package/dist/openai/adapter.js +15 -1
  86. package/dist/openai/adapter.js.map +1 -1
  87. package/dist/pdf-pages.d.ts.map +1 -1
  88. package/dist/pdf-pages.js +2 -6
  89. package/dist/pdf-pages.js.map +1 -1
  90. package/dist/peers.d.ts +8 -0
  91. package/dist/peers.d.ts.map +1 -0
  92. package/dist/peers.js +32 -0
  93. package/dist/peers.js.map +1 -0
  94. package/dist/plan.d.ts.map +1 -1
  95. package/dist/plan.js +1 -1
  96. package/dist/plan.js.map +1 -1
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +4 -2
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/search.d.ts +99 -22
  101. package/dist/search.d.ts.map +1 -1
  102. package/dist/search.js +744 -140
  103. package/dist/search.js.map +1 -1
  104. package/dist/text-index.d.ts +3 -1
  105. package/dist/text-index.d.ts.map +1 -1
  106. package/dist/text-index.js +3 -1
  107. package/dist/text-index.js.map +1 -1
  108. package/dist/text.d.ts +27 -3
  109. package/dist/text.d.ts.map +1 -1
  110. package/dist/text.js +225 -23
  111. package/dist/text.js.map +1 -1
  112. package/dist/tools.d.ts.map +1 -1
  113. package/dist/tools.js +200 -12
  114. package/dist/tools.js.map +1 -1
  115. package/dist/types.d.ts +3 -3
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/word-styles.d.ts +102 -0
  118. package/dist/word-styles.d.ts.map +1 -0
  119. package/dist/word-styles.js +419 -0
  120. package/dist/word-styles.js.map +1 -0
  121. package/dist/xlsx.d.ts +23 -0
  122. package/dist/xlsx.d.ts.map +1 -0
  123. package/dist/xlsx.js +511 -0
  124. package/dist/xlsx.js.map +1 -0
  125. package/dist/xml-stream.d.ts +55 -0
  126. package/dist/xml-stream.d.ts.map +1 -0
  127. package/dist/xml-stream.js +235 -0
  128. package/dist/xml-stream.js.map +1 -0
  129. package/docs/README.md +8 -8
  130. package/docs/getting-started.md +1 -1
  131. package/docs/guides/costs-and-limits.md +7 -5
  132. package/docs/guides/deployment.md +95 -29
  133. package/docs/guides/errors-and-reliability.md +23 -10
  134. package/docs/guides/pdfs.md +127 -74
  135. package/docs/guides/storage.md +1 -1
  136. package/docs/guides/testing.md +5 -1
  137. package/docs/guides/web-app.md +10 -9
  138. package/docs/how-it-works.md +73 -50
  139. package/docs/reference/ask.md +26 -8
  140. package/docs/reference/errors-and-retries.md +5 -3
  141. package/docs/reference/events.md +14 -6
  142. package/docs/reference/gemini.md +6 -2
  143. package/docs/reference/library.md +205 -74
  144. package/docs/reference/node.md +200 -22
  145. package/docs/reference/openai.md +1 -1
  146. package/docs/reference/tools.md +170 -22
  147. package/docs/security.md +114 -69
  148. package/docs/troubleshooting.md +40 -20
  149. package/package.json +6 -2
  150. package/src/analyze.ts +117 -13
  151. package/src/anthropic/adapter.ts +4 -1
  152. package/src/ask.ts +73 -17
  153. package/src/decode.ts +89 -0
  154. package/src/errors.ts +108 -0
  155. package/src/events.ts +10 -1
  156. package/src/evidence.ts +6 -0
  157. package/src/extract.ts +52 -709
  158. package/src/gemini/adapter.ts +9 -5
  159. package/src/gemini/endpoints.ts +12 -2
  160. package/src/gemini/generate.ts +19 -3
  161. package/src/groups.ts +162 -0
  162. package/src/html.ts +1071 -0
  163. package/src/index.ts +2 -1
  164. package/src/library.ts +43 -12
  165. package/src/limiter.ts +6 -1
  166. package/src/model.ts +8 -1
  167. package/src/node/handlers.ts +66 -16
  168. package/src/node/index.ts +2 -0
  169. package/src/node/ingest-child.ts +61 -0
  170. package/src/node/isolated.ts +464 -0
  171. package/src/office.ts +1047 -0
  172. package/src/openai/adapter.ts +14 -1
  173. package/src/pdf-pages.ts +2 -5
  174. package/src/peers.ts +29 -0
  175. package/src/plan.ts +2 -0
  176. package/src/ranged.ts +4 -2
  177. package/src/search.ts +738 -146
  178. package/src/text-index.ts +4 -2
  179. package/src/text.ts +214 -23
  180. package/src/tools.ts +192 -12
  181. package/src/types.ts +3 -3
  182. package/src/word-styles.ts +420 -0
  183. package/src/xlsx.ts +478 -0
  184. package/src/xml-stream.ts +224 -0
package/src/office.ts ADDED
@@ -0,0 +1,1047 @@
1
+ import { LEGACY_OFFICE } from "./decode.js";
2
+ import { importPeer } from "./peers.js";
3
+ import { TimeSlicer } from "./pause.js";
4
+ import { formatBytes } from "./plan.js";
5
+ import { MAX_LINE_CHARACTERS, sliceWhole } from "./text.js";
6
+ import type { ExtractInput, Extractor } from "./types.js";
7
+ import { WordNumbering, type ParagraphStyle } from "./word-styles.js";
8
+ import { parseAttributes, readRelationships, readXml } from "./xml-stream.js";
9
+ import { readZipDirectory } from "./zip-directory.js";
10
+
11
+ // Office files are ZIP archives of XML: Word (DOCX) and PowerPoint (PPTX) are read here, and the
12
+ // parts are streamed for the spreadsheet reader (xlsx.ts) too. No XML parser is used: each part is
13
+ // read a piece at a time as it is unpacked, under limits a hostile file cannot get past.
14
+
15
+ function decodeXmlEntities(value: string): string {
16
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity: string) => {
17
+ const lower = entity.toLowerCase();
18
+ if (lower === "amp") return "&";
19
+ if (lower === "lt") return "<";
20
+ if (lower === "gt") return ">";
21
+ if (lower === "quot") return "\"";
22
+ if (lower === "apos") return "'";
23
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
24
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
25
+ });
26
+ }
27
+
28
+ /** A tag name is read up to this many characters: the names that matter here are short. */
29
+ const MAX_TAG_NAME = 64;
30
+ /** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
31
+ const MAX_PARAGRAPH_DEPTH = 32;
32
+ /** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
33
+ const MAX_OFFICE_PARAGRAPHS = 1_000_000;
34
+ /** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
35
+ const MAX_OFFICE_CHARACTERS = 32_000_000;
36
+ /**
37
+ * The text of an open paragraph is counted as written in the XML, where `&quot;` is six characters
38
+ * for one: past this many times the limit, it is refused before the paragraph closes.
39
+ */
40
+ const MAX_ENTITY_GROWTH = 6;
41
+ /** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
42
+ const SLICE_COPIED_BELOW = 13;
43
+ /** The attributes of a tag are read up to this many characters: the few that are read are short. */
44
+ const MAX_RAW_TAG = 1_024;
45
+ /** Grid columns one table cell may span (`w:gridSpan`); Word allows 63 columns in a table. */
46
+ const MAX_CELL_SPAN = 63;
47
+ /** Tags whose attributes are read, beside `w:vanish` and `p:sld`. */
48
+ const WORD_ATTRIBUTE_TAGS = new Set(["w:pStyle", "w:numId", "w:ilvl", "w:outlineLvl", "w:gridSpan", "w:gridBefore", "w:gridAfter", "w:sym"]);
49
+ const DRAWING_ATTRIBUTE_TAGS = new Set(["p:ph"]);
50
+ /** The properties of a Word table row and cell, and those of them that are read. */
51
+ const TABLE_PROPERTY_TAGS = new Set(["w:trPr", "/w:trPr", "w:tcPr", "/w:tcPr", "w:gridSpan", "w:gridBefore", "w:gridAfter"]);
52
+ /**
53
+ * The placeholders of a notes page whose text is not the speaker's notes: the slide number, the
54
+ * date, the header and the footer (Header & Footer, Notes and Handouts), and the picture of the
55
+ * slide. The notes are in the body placeholder; a text box the presenter added is kept too.
56
+ */
57
+ const NOTES_PAGE_PLACEHOLDERS: ReadonlySet<string> = new Set(["sldNum", "dt", "hdr", "ftr", "sldImg"]);
58
+
59
+ /** How the text of a part is read: with Word's numbering, or as a PowerPoint notes page. */
60
+ type PartOptions = { numbering?: WordNumbering; notesPage?: boolean };
61
+
62
+ /** A table cell's text as a cell of a `| cell | cell |` row: one line, its pipes escaped, as the PDF extractor writes them. */
63
+ function cellText(text: string): string {
64
+ return text.replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
65
+ }
66
+
67
+ /**
68
+ * Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
69
+ * of its paragraph that shows: a person reading the document does not see it. Each line is marked,
70
+ * so hidden text cannot end the mark and pass for text that shows.
71
+ */
72
+ export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
73
+ /** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
74
+ export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
75
+ /**
76
+ * The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
77
+ * `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
78
+ * slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
79
+ * `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
80
+ */
81
+ const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
82
+ const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
83
+ type WantedAttribute = typeof VANISH_OFF;
84
+ /** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
85
+ const MAX_ATTRIBUTE_PART = 6;
86
+ /**
87
+ * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
88
+ * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
89
+ * the hidden line on a line of its own, without the mark.
90
+ */
91
+ // A tenth is kept free: ingest composes the text (NFC) and bounds runs of marks after it is cut,
92
+ // which can lengthen a line, and a line past the wrap limit would leave its rest without a mark.
93
+ const HIDDEN_PIECE = Math.floor((MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1) * 0.9);
94
+ /**
95
+ * What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
96
+ * (ingest makes it one in a text with no other line break), or a line or paragraph separator
97
+ * (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
98
+ * U+0085 instead does no harm.
99
+ */
100
+ const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
101
+ /** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
102
+ const NOT_SPACE = /[^\s\x85]/g;
103
+
104
+ /**
105
+ * Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
106
+ * XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
107
+ * length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
108
+ * read as the attribute.
109
+ */
110
+ class AttributeReader {
111
+ /** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
112
+ private name = "";
113
+ /** Whether the next character of a name starts a new one. */
114
+ private ended = true;
115
+ /** Whether "=" came after the name wanted, so the next value is its value. */
116
+ private assigned = false;
117
+ /** The value of the attribute wanted, while it is read. */
118
+ private value: string | undefined;
119
+ /** Whether the attribute wanted has one of the values wanted. */
120
+ found = false;
121
+
122
+ constructor(private readonly wanted: WantedAttribute) {}
123
+
124
+ /** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
125
+ outside(code: number): void {
126
+ if (code === 32 || code === 9 || code === 10 || code === 13) {
127
+ this.ended = true;
128
+ } else if (code === 61) {
129
+ this.assigned = this.name === this.wanted.name;
130
+ this.name = "";
131
+ this.ended = true;
132
+ } else {
133
+ if (this.ended) {
134
+ this.name = "";
135
+ this.ended = false;
136
+ this.assigned = false;
137
+ }
138
+ if (this.name.length < MAX_ATTRIBUTE_PART) this.name += String.fromCharCode(code);
139
+ }
140
+ }
141
+
142
+ /** A quote opens a value. */
143
+ open(): void {
144
+ if (this.assigned) this.value = "";
145
+ this.assigned = false;
146
+ }
147
+
148
+ /** A character of a value. */
149
+ inValue(code: number): void {
150
+ if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART) this.value += String.fromCharCode(code);
151
+ }
152
+
153
+ /** The quote that closes a value. */
154
+ close(): void {
155
+ if (this.value !== undefined) {
156
+ this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
157
+ this.value = undefined;
158
+ }
159
+ this.name = "";
160
+ this.ended = true;
161
+ }
162
+ }
163
+
164
+ /** What an Office file may hold before it is refused, and what to call it in the refusal. */
165
+ export type OfficeLimits = { kind: string; maxCharacters: number; byTextLimit: boolean };
166
+ const NO_OFFICE_LIMITS: OfficeLimits = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
167
+ /** The text and the paragraphs read from all the parts of one Office file so far. */
168
+ export type OfficeCount = { characters: number; paragraphs: number };
169
+
170
+ /**
171
+ * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
172
+ * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
173
+ * pieces is read whole. Every character is looked at once, so the time follows the length of the
174
+ * XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
175
+ *
176
+ * - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
177
+ * of its own, after the one it is anchored in, which keeps its text before and after the box.
178
+ * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
179
+ * - Paragraph properties hold no text. Their tab stops are not tabs.
180
+ * - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
181
+ * text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
182
+ * is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
183
+ *
184
+ * What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
185
+ * when it closes, an empty one is dropped, and a file that nests paragraphs past
186
+ * `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
187
+ */
188
+ class OfficeText {
189
+ private readonly paragraphTag: string;
190
+ private readonly paragraphEnd: string;
191
+ private readonly textTag: string;
192
+ private readonly textEnd: string;
193
+ private readonly propertiesTag: string;
194
+ private readonly propertiesEnd: string;
195
+ private readonly tabTag: string;
196
+ private readonly breakTags: ReadonlySet<string>;
197
+ /** Word marks hidden runs; PowerPoint hides whole slides. */
198
+ private readonly word: boolean;
199
+ /** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
200
+ private readonly attributesTag: string;
201
+ /** The attribute read of `attributesTag`, and the values that count. */
202
+ private readonly attribute: WantedAttribute;
203
+ /** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
204
+ private readonly paragraphs: Array<string | null> = [];
205
+ /**
206
+ * The paragraphs that are open, the innermost last: where each goes in `paragraphs` (-1: into
207
+ * the table cell that is open), its text so far (that which shows, and that which Word hides),
208
+ * and its length. In Word, also how many runs are open (a ruby's runs are inside a run), how deep
209
+ * the outermost hidden one is (0: none is hidden), how deep in run properties the reading is, and
210
+ * its style and numbering.
211
+ */
212
+ private readonly open: Array<{ slot: number; pieces: string[]; hidden: string[] | undefined; length: number; runs: number; hiddenFrom: number; runProperties: number; style: ParagraphStyle | undefined }> = [];
213
+ /**
214
+ * The table being read, and how deep in tables (a table in a cell is read as text of that cell).
215
+ * Its rows so far, the row and the cell open, and in Word: how many grid columns the cell open
216
+ * spans, how many empty columns end the row open (`w:gridAfter`), and how deep in the properties
217
+ * of the row or cell the reading is (those of a change they record are one level deeper).
218
+ */
219
+ private table: { slot: number; depth: number; rows: string[][]; row: string[] | undefined; cell: string[] | undefined; span: number; after: number; properties: number } | undefined;
220
+ private readonly tableTag: string;
221
+ private readonly rowTag: string;
222
+ private readonly cellTag: string;
223
+ /** Tags whose attributes are read (see `read`). */
224
+ private readonly attributeTags: ReadonlySet<string>;
225
+ /** Characters held in the paragraphs that are open, as written in the XML. */
226
+ private pending = 0;
227
+ private inText = false;
228
+ private inProperties = 0;
229
+ private inFallback = 0;
230
+ /**
231
+ * The tag being read, from its "<": its name so far, the quote of a value it is in, its last
232
+ * character, and for `attributesTag` the reader of its attribute.
233
+ */
234
+ private tag: { name: string; named: boolean; quote: number; last: number; attributes: AttributeReader | undefined; raw: string | undefined } | undefined;
235
+ /** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
236
+ hiddenSlide = false;
237
+ /** Word's styles and lists, to write headings as `#` lines and each paragraph with its list number. */
238
+ private readonly numbering: WordNumbering | undefined;
239
+ /** On a notes page, the placeholders whose text is left out (`NOTES_PAGE_PLACEHOLDERS`). */
240
+ private readonly leftOut: ReadonlySet<string> | undefined;
241
+ /** In PowerPoint, whether a shape (`p:sp`) is open, and whether it is a placeholder left out. */
242
+ private inShape = false;
243
+ private inLeftOut = false;
244
+
245
+ /** `count`: what the other parts of the same file held, shared with them. */
246
+ constructor(prefix: "w" | "a", private readonly limits: OfficeLimits = NO_OFFICE_LIMITS, private readonly count: OfficeCount = { characters: 0, paragraphs: 0 }, options: PartOptions = {}) {
247
+ this.numbering = options.numbering;
248
+ this.leftOut = options.notesPage ? NOTES_PAGE_PLACEHOLDERS : undefined;
249
+ this.paragraphTag = `${prefix}:p`;
250
+ this.paragraphEnd = `/${prefix}:p`;
251
+ this.textTag = `${prefix}:t`;
252
+ this.textEnd = `/${prefix}:t`;
253
+ this.propertiesTag = `${prefix}:pPr`;
254
+ this.propertiesEnd = `/${prefix}:pPr`;
255
+ this.tabTag = `${prefix}:tab`;
256
+ this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
257
+ this.word = prefix === "w";
258
+ this.attributesTag = this.word ? "w:vanish" : "p:sld";
259
+ this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
260
+ this.tableTag = `${prefix}:tbl`;
261
+ this.rowTag = `${prefix}:tr`;
262
+ this.cellTag = `${prefix}:tc`;
263
+ this.attributeTags = this.word ? WORD_ATTRIBUTE_TAGS : DRAWING_ATTRIBUTE_TAGS;
264
+ }
265
+
266
+ write(xml: string): void {
267
+ const length = xml.length;
268
+ let at = 0;
269
+ while (at < length) {
270
+ const tag = this.tag;
271
+ if (!tag) {
272
+ const start = xml.indexOf("<", at);
273
+ const end = start === -1 ? length : start;
274
+ if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.add(xml.slice(at, end));
275
+ if (start === -1) return;
276
+ this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined, raw: undefined };
277
+ at = start + 1;
278
+ continue;
279
+ }
280
+ for (; at < length; at++) {
281
+ const code = xml.charCodeAt(at);
282
+ if (tag.quote !== 0) {
283
+ if (tag.raw !== undefined && tag.raw.length < MAX_RAW_TAG) tag.raw += xml[at];
284
+ if (code === tag.quote) {
285
+ tag.quote = 0;
286
+ tag.attributes?.close();
287
+ } else {
288
+ tag.attributes?.inValue(code);
289
+ }
290
+ continue;
291
+ }
292
+ if (!tag.named) {
293
+ // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
294
+ if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
295
+ tag.named = true;
296
+ if (tag.name === this.attributesTag) tag.attributes = new AttributeReader(this.attribute);
297
+ if (this.attributeTags.has(tag.name)) tag.raw = "";
298
+ } else {
299
+ if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
300
+ continue;
301
+ }
302
+ }
303
+ if (code === 62) break;
304
+ if (tag.raw !== undefined && tag.raw.length < MAX_RAW_TAG) tag.raw += xml[at];
305
+ if (code === 34 || code === 39) {
306
+ tag.quote = code;
307
+ tag.attributes?.open();
308
+ } else {
309
+ tag.attributes?.outside(code);
310
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
311
+ }
312
+ }
313
+ if (at === length) return; // The tag goes on in the next piece.
314
+ this.tag = undefined;
315
+ this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false, tag.raw);
316
+ at++;
317
+ }
318
+ }
319
+
320
+ /** The text of each paragraph that has some, in the order the paragraphs start. A table is one, of a line a row. */
321
+ texts(): string[] {
322
+ // A paragraph never closed keeps the text it has, as when the file ends inside it; so does a table.
323
+ while (this.open.length > 0) this.close();
324
+ while (this.table) this.closeTable();
325
+ return this.paragraphs.filter((text): text is string => !!text);
326
+ }
327
+
328
+ /** Adds text to the innermost open paragraph. */
329
+ private add(piece: string): void {
330
+ const paragraph = this.open.at(-1);
331
+ if (!paragraph || this.inLeftOut) return;
332
+ this.pending += piece.length;
333
+ paragraph.length += piece.length;
334
+ // The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
335
+ if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH) throw this.tooMuchText();
336
+ if (paragraph.hiddenFrom !== 0) (paragraph.hidden ??= []).push(piece);
337
+ else paragraph.pieces.push(piece);
338
+ }
339
+
340
+ private tooMuchText(): Error {
341
+ const { kind, maxCharacters, byTextLimit } = this.limits;
342
+ return new Error(byTextLimit
343
+ ? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
344
+ : `This ${kind} holds more than ${Math.round(maxCharacters / 1_000_000)} million characters of text, more than is read from one file. Split it, and attach the part you need.`);
345
+ }
346
+
347
+ /** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
348
+ private close(): void {
349
+ const paragraph = this.open.pop();
350
+ if (!paragraph) return;
351
+ this.pending -= paragraph.length;
352
+ let shown = decodeXmlEntities(paragraph.pieces.join(""));
353
+ if (this.numbering && paragraph.style) {
354
+ // An empty paragraph is counted in its list too, as Word shows its number there. The number
355
+ // is written only before text: empty paragraphs count toward no limit, and a file of them
356
+ // would have its numbers written, at up to 64 characters each, only to be thrown away.
357
+ const counted = this.numbering.count(paragraph.style);
358
+ if (shown.trim()) {
359
+ const label = counted && this.numbering.labelOf(counted);
360
+ const level = paragraph.slot !== -1 ? this.numbering.headingLevel(paragraph.style) : undefined;
361
+ shown = `${level ? `${"#".repeat(level)} ` : ""}${label ? `${label} ` : ""}${shown}`;
362
+ }
363
+ }
364
+ const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
365
+ if (paragraph.slot === -1) {
366
+ // A paragraph of a table cell: its text goes into the cell, counted as any paragraph's.
367
+ if (text.trim()) {
368
+ this.count.characters += text.length;
369
+ if (this.count.characters > this.limits.maxCharacters) throw this.tooMuchText();
370
+ this.table?.cell?.push(text);
371
+ }
372
+ return;
373
+ }
374
+ if (text.trim()) {
375
+ this.count.characters += text.length;
376
+ if (this.count.characters > this.limits.maxCharacters) throw this.tooMuchText();
377
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
378
+ throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.`);
379
+ }
380
+ // A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
381
+ this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
382
+ } else if (paragraph.slot === this.paragraphs.length - 1) {
383
+ this.paragraphs.pop();
384
+ } else {
385
+ this.paragraphs[paragraph.slot] = "";
386
+ }
387
+ }
388
+
389
+ /**
390
+ * A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
391
+ * long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
392
+ * make the text longer than the XML it came from, so it is refused as soon as it holds more than
393
+ * the room left under the limit, not once it is built.
394
+ */
395
+ private withHiddenText(shown: string, hidden: string): string {
396
+ const room = this.limits.maxCharacters - this.count.characters;
397
+ const lines = shown.trim() ? [shown] : [];
398
+ // The length of the lines joined with line breaks.
399
+ let length = lines.length > 0 ? shown.length : -1;
400
+ let marked = 0;
401
+ // Where the line being marked ends, found once a line: each of its pieces starts before it, as
402
+ // `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
403
+ let lineEnd = -1;
404
+ // Line by line, without splitting the text first: a run can hold millions of empty lines.
405
+ for (let at = 0; ;) {
406
+ NOT_SPACE.lastIndex = at;
407
+ const first = NOT_SPACE.exec(hidden);
408
+ if (!first) break;
409
+ const start = first.index;
410
+ if (start >= lineEnd) {
411
+ HIDDEN_LINE_END.lastIndex = start;
412
+ lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
413
+ }
414
+ let end = lineEnd;
415
+ if (end - start > HIDDEN_PIECE) {
416
+ // Cut after a space near the end of the piece, and never between the two halves of an emoji.
417
+ const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
418
+ const space = window.lastIndexOf(" ");
419
+ end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
420
+ }
421
+ const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
422
+ length += 1 + line.length;
423
+ if (length > room) throw this.tooMuchText();
424
+ lines.push(line);
425
+ marked++;
426
+ at = end;
427
+ }
428
+ return marked === 0 ? shown : lines.join("\n");
429
+ }
430
+
431
+ /**
432
+ * Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
433
+ * `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
434
+ */
435
+ private read(name: string, empty: boolean, found: boolean, raw?: string): void {
436
+ if (name === "mc:Fallback") {
437
+ if (!empty) this.inFallback++;
438
+ return;
439
+ }
440
+ if (name === "/mc:Fallback") {
441
+ if (this.inFallback > 0) this.inFallback--;
442
+ return;
443
+ }
444
+ if (this.inFallback > 0) return;
445
+ if (name === this.paragraphTag) {
446
+ if (!empty) {
447
+ if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
448
+ throw new Error(`This ${this.limits.kind} nests paragraphs more than ${MAX_PARAGRAPH_DEPTH} deep, which no document does. It may be built to exhaust the server, so it is not read.`);
449
+ }
450
+ const inCell = this.table?.cell !== undefined;
451
+ this.open.push({ slot: inCell ? -1 : this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0, style: undefined });
452
+ if (!inCell) this.paragraphs.push(null);
453
+ }
454
+ } else if (name === this.tableTag || name === this.rowTag || name === this.cellTag || name === `/${this.tableTag}` || name === `/${this.rowTag}` || name === `/${this.cellTag}`) {
455
+ this.readTable(name, empty);
456
+ } else if (name === this.paragraphEnd) {
457
+ this.close();
458
+ this.inText = false;
459
+ this.inProperties = 0;
460
+ } else if (name === this.textTag) {
461
+ this.inText = !empty;
462
+ } else if (name === this.textEnd) {
463
+ this.inText = false;
464
+ } else if (name === this.propertiesTag) {
465
+ if (!empty) this.inProperties++;
466
+ } else if (name === this.propertiesEnd) {
467
+ if (this.inProperties > 0) this.inProperties--;
468
+ } else if (this.inProperties === 0) {
469
+ if (name === this.tabTag) this.add("\t");
470
+ else if (this.breakTags.has(name)) this.add("\n");
471
+ else if (this.word && name === "w:noBreakHyphen") this.add("-");
472
+ else if (this.word && name === "w:sym") this.addSymbol(raw);
473
+ else if (this.word && TABLE_PROPERTY_TAGS.has(name)) this.readTableProperty(name, empty, raw);
474
+ else if (this.word) this.readRun(name, empty, found);
475
+ else if (name === "p:sld" && found) this.hiddenSlide = true;
476
+ else if (name === "p:sp" || name === "/p:sp") {
477
+ this.inShape = name === "p:sp" && !empty;
478
+ this.inLeftOut = false;
479
+ } else if (name === "p:ph" && this.inShape && this.leftOut?.has(parseAttributes(raw ?? "").type ?? "")) {
480
+ // The placeholder of the shape comes before its text (`p:nvSpPr`, then `p:txBody`).
481
+ this.inLeftOut = true;
482
+ }
483
+ } else if (this.inProperties === 1 && this.word && raw !== undefined) {
484
+ // The paragraph's own properties; those of a change it records (`w:pPrChange`) are one level deeper.
485
+ this.readParagraphProperty(name, raw);
486
+ }
487
+ }
488
+
489
+ /** `w:pStyle`, `w:numId`, `w:ilvl` and `w:outlineLvl` of the innermost open paragraph. */
490
+ private readParagraphProperty(name: string, raw: string): void {
491
+ const paragraph = this.open.at(-1);
492
+ if (!paragraph) return;
493
+ const value = parseAttributes(raw)["w:val"];
494
+ if (value === undefined) return;
495
+ const style = (paragraph.style ??= {});
496
+ if (name === "w:pStyle") style.styleId = value;
497
+ else if (name === "w:numId") style.numId = value;
498
+ else if (name === "w:ilvl") style.ilvl = Number.parseInt(value, 10) || 0;
499
+ else if (name === "w:outlineLvl") style.outlineLevel = Number.parseInt(value, 10);
500
+ }
501
+
502
+ /**
503
+ * A symbol of a symbol font (`<w:sym w:char="F0B7"/>`). Those fonts put their characters in the
504
+ * private-use area: one that stands for a printable ASCII character is written as it, others are
505
+ * left out.
506
+ */
507
+ private addSymbol(raw: string | undefined): void {
508
+ const code = Number.parseInt(parseAttributes(raw ?? "")["w:char"] ?? "", 16);
509
+ if (!Number.isFinite(code)) return;
510
+ const plain = code >= 0xf000 ? code - 0xf000 : code;
511
+ if (plain >= 0x20 && plain <= 0x7e) this.add(String.fromCharCode(plain));
512
+ }
513
+
514
+ /**
515
+ * The properties of the Word table row and cell that are open: `w:gridSpan` of a cell, and
516
+ * `w:gridBefore` and `w:gridAfter` of a row, the grid columns that the row leaves empty before its
517
+ * first cell and after its last. Those of a change the properties record (`w:tcPrChange`,
518
+ * `w:trPrChange`) are the properties before the change, one level deeper, and are not read.
519
+ */
520
+ private readTableProperty(name: string, empty: boolean, raw: string | undefined): void {
521
+ const table = this.table;
522
+ if (!table || table.depth !== 1) return;
523
+ if (name === "w:trPr" || name === "w:tcPr") {
524
+ if (!empty) table.properties++;
525
+ return;
526
+ }
527
+ if (name === "/w:trPr" || name === "/w:tcPr") {
528
+ if (table.properties > 0) table.properties--;
529
+ return;
530
+ }
531
+ if (table.properties > 1) return;
532
+ const columns = Math.min(MAX_CELL_SPAN, Math.max(0, Number.parseInt(parseAttributes(raw ?? "")["w:val"] ?? "", 10) || 0));
533
+ if (name === "w:gridSpan") {
534
+ if (table.cell) table.span = Math.max(1, columns);
535
+ } else if (name === "w:gridBefore") {
536
+ // Once, before the row's first cell.
537
+ if (table.row?.length === 0 && !table.cell) for (let index = 0; index < columns; index++) this.addCell(table.row, "");
538
+ } else if (table.row && !table.cell) {
539
+ table.after = columns;
540
+ }
541
+ }
542
+
543
+ /**
544
+ * The start and end of tables, rows and cells. A table becomes one paragraph, written when it
545
+ * closes: a line for each row, as `| cell | cell | |`, with its empty cells, as the PDF extractor
546
+ * writes rows. A Word cell that spans grid columns is followed by an empty cell for each column
547
+ * past the first, and a row that leaves grid columns empty before its first cell or after its
548
+ * last has an empty cell for each, so that every row keeps its columns. A cell that continues a
549
+ * merged cell (`w:vMerge` in Word; in PowerPoint, where the cells a merged cell covers are in the
550
+ * XML already, `hMerge` and `vMerge`) is written in its column: Word and PowerPoint leave it
551
+ * empty, and the text another program left in it is kept. A table inside a cell is read as text
552
+ * of that cell.
553
+ */
554
+ private readTable(name: string, empty: boolean): void {
555
+ if (name === this.tableTag) {
556
+ if (empty) return;
557
+ if (this.table) {
558
+ this.table.depth++;
559
+ return;
560
+ }
561
+ // Inside a paragraph of a cell of no table (a malformed file): the table is that paragraph's.
562
+ this.table = { slot: this.paragraphs.length, depth: 1, rows: [], row: undefined, cell: undefined, span: 1, after: 0, properties: 0 };
563
+ this.paragraphs.push(null);
564
+ return;
565
+ }
566
+ const table = this.table;
567
+ if (!table) return;
568
+ if (name === `/${this.tableTag}`) {
569
+ if (table.depth > 1) table.depth--;
570
+ else this.closeTable();
571
+ return;
572
+ }
573
+ if (table.depth !== 1) return;
574
+ if (name === this.rowTag) {
575
+ this.closeRow();
576
+ table.row = empty ? undefined : [];
577
+ table.properties = 0;
578
+ } else if (name === `/${this.rowTag}`) {
579
+ this.closeRow();
580
+ } else if (name === this.cellTag) {
581
+ this.closeCell();
582
+ table.span = 1;
583
+ table.properties = 0;
584
+ table.cell = [];
585
+ if (empty) this.closeCell();
586
+ } else if (name === `/${this.cellTag}`) {
587
+ this.closeCell();
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Adds a cell to a row. Each cell is counted as a paragraph, empty or not, and its separator as
593
+ * text: a table of millions of empty cells is bounded as a document of millions of paragraphs is.
594
+ */
595
+ private addCell(row: string[], text: string): void {
596
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
597
+ throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs and table cells, more than a document holds. It may be built to exhaust the server, so it is not read.`);
598
+ }
599
+ this.count.characters += 3;
600
+ if (this.count.characters > this.limits.maxCharacters) throw this.tooMuchText();
601
+ row.push(text);
602
+ }
603
+
604
+ /** Ends the table cell that is open, if any: its paragraphs become one cell of the row. */
605
+ private closeCell(): void {
606
+ const table = this.table;
607
+ if (!table?.cell) return;
608
+ // Paragraphs of the cell left open (a malformed file) give their text to it first.
609
+ while (this.open.length > 0 && this.open.at(-1)!.slot === -1) this.close();
610
+ const text = cellText(table.cell.join(" "));
611
+ table.cell = undefined;
612
+ const row = (table.row ??= []);
613
+ const cells = this.word ? table.span : 1;
614
+ for (let index = 0; index < cells; index++) this.addCell(row, index === 0 ? text : "");
615
+ }
616
+
617
+ /** Ends the table row that is open, if any, with an empty cell for each grid column it leaves empty after its last cell. */
618
+ private closeRow(): void {
619
+ const table = this.table;
620
+ if (!table) return;
621
+ this.closeCell();
622
+ const row = table.row;
623
+ if (row && row.length > 0) {
624
+ for (let index = 0; index < table.after; index++) this.addCell(row, "");
625
+ table.rows.push(row);
626
+ }
627
+ table.row = undefined;
628
+ table.after = 0;
629
+ }
630
+
631
+ /** Ends the table: its rows become the text of its paragraph. Also when the file ends inside it. */
632
+ private closeTable(): void {
633
+ const table = this.table;
634
+ if (!table) return;
635
+ this.closeRow();
636
+ this.table = undefined;
637
+ if (table.rows.some((row) => row.some((cell) => cell !== ""))) {
638
+ const text = table.rows.map((row) => `| ${row.join(" | ")} |`).join("\n");
639
+ this.paragraphs[table.slot] = text;
640
+ } else if (table.slot === this.paragraphs.length - 1) {
641
+ this.paragraphs.pop();
642
+ } else {
643
+ this.paragraphs[table.slot] = "";
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
649
+ * run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
650
+ * A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
651
+ * hidden after it. `off`: the `w:vanish` turns hiding off.
652
+ */
653
+ private readRun(name: string, empty: boolean, off: boolean): void {
654
+ const paragraph = this.open.at(-1);
655
+ if (!paragraph) return;
656
+ if (name === "w:r") {
657
+ if (empty) return;
658
+ paragraph.runs++;
659
+ paragraph.runProperties = 0;
660
+ } else if (name === "/w:r") {
661
+ if (paragraph.runs > 0) {
662
+ if (paragraph.hiddenFrom === paragraph.runs) paragraph.hiddenFrom = 0;
663
+ paragraph.runs--;
664
+ }
665
+ paragraph.runProperties = 0;
666
+ } else if (name === "w:rPr") {
667
+ if (!empty && paragraph.runs > 0) paragraph.runProperties++;
668
+ } else if (name === "/w:rPr") {
669
+ if (paragraph.runProperties > 0) paragraph.runProperties--;
670
+ } else if (name === "w:vanish" && paragraph.runProperties === 1) {
671
+ if (!off) {
672
+ if (paragraph.hiddenFrom === 0) paragraph.hiddenFrom = paragraph.runs;
673
+ } else if (paragraph.hiddenFrom === paragraph.runs) {
674
+ paragraph.hiddenFrom = 0;
675
+ }
676
+ }
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. The
682
+ * XML may be given in pieces, as it is unpacked.
683
+ */
684
+ export function officeXmlParagraphs(xml: string | string[], prefix: "w" | "a"): string[] {
685
+ const text = new OfficeText(prefix);
686
+ for (const piece of typeof xml === "string" ? [xml] : xml) text.write(piece);
687
+ return text.texts();
688
+ }
689
+
690
+ /** The part of JSZip's stream of one file that is used here. */
691
+ type ZipStream = {
692
+ on(event: "data", listener: (chunk: string) => void): ZipStream;
693
+ on(event: "error", listener: (error: unknown) => void): ZipStream;
694
+ on(event: "end", listener: () => void): ZipStream;
695
+ resume(): ZipStream;
696
+ pause(): ZipStream;
697
+ };
698
+ /** `internalStream` hands out a file of the archive in pieces, as it is unpacked. */
699
+ type ZipFile = { internalStream(type: "string"): ZipStream };
700
+ export type ZipArchive = { files: Record<string, unknown>; file(name: string): ZipFile | null };
701
+
702
+ /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
703
+ const MAX_OFFICE_XML = 128 * 1024 * 1024;
704
+ /**
705
+ * The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
706
+ * packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
707
+ * A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
708
+ * zip bomb, as Apache POI does.
709
+ */
710
+ const MAX_OFFICE_EXPANSION = 100;
711
+ const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
712
+
713
+ const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
714
+
715
+ /** The kinds of zipped Office files read here, as refusals name them. */
716
+ export type OfficeKind = "DOCX" | "PPTX" | "XLSX";
717
+
718
+ /** What `officeReader` gives: ways to read the parts of one Office file, under one count of what is unpacked. */
719
+ export type OfficeParts = {
720
+ /**
721
+ * The paragraphs of a part of Word (`w`) or DrawingML (`a`) XML; none when the part is missing.
722
+ * `options`: Word's numbering, for the document itself; or that the part is a notes page.
723
+ */
724
+ paragraphs(name: string, prefix: "w" | "a", options?: PartOptions): Promise<{ paragraphs: string[]; hiddenSlide: boolean }>;
725
+ /**
726
+ * A small part whole (styles, relationships, the list of slides or sheets), or undefined when it
727
+ * is missing or larger than `maxCharacters`: it is then read no further, and the file is read
728
+ * without it.
729
+ */
730
+ small(name: string, maxCharacters?: number): Promise<string | undefined>;
731
+ /** Feeds a part to `write` a piece at a time as it is unpacked. False when the part is missing. */
732
+ stream(name: string, write: (piece: string) => void): Promise<boolean>;
733
+ /** The limits of the text kept, and the count shared by the parts, for a reader of a part's text. */
734
+ readonly limits: OfficeLimits;
735
+ readonly count: OfficeCount;
736
+ };
737
+
738
+ /** The most a small part (`OfficeParts.small`) may hold. Styles of a large document take about 1 MB. */
739
+ const MAX_SMALL_PART = 8 * 1024 * 1024;
740
+
741
+ /** Thrown inside `small` when a part is larger than it may be: the part is then left out. */
742
+ class PartTooLarge extends Error {}
743
+
744
+ /**
745
+ * Reads the parts of one Office file, each a piece at a time as it is unpacked, counting what is
746
+ * unpacked: a file that grows far past its size is refused as it grows, before that much is in
747
+ * memory. The parsing is paused every few milliseconds, and other requests get a turn. The
748
+ * unpacking is not: JSZip inflates and decodes a whole deflated block (up to about 16 MB of XML)
749
+ * in one turn before any of it is handed out, and what it hands out once paused is held, and
750
+ * written in the slices after the pause, which costs memory for that block. Reading a file in a
751
+ * child process (`createIsolatedExtractors`) is what bounds both for files from users.
752
+ */
753
+ export function officeReader(archive: ZipArchive, kind: OfficeKind, size: number, input: ExtractInput | undefined): OfficeParts {
754
+ const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
755
+ const refusal = limit === MAX_OFFICE_XML
756
+ ? `This ${kind} unpacks to more than ${megabytes(limit)} of XML, more than is read from one file. Save it as text or PDF, and attach that.`
757
+ : `This ${kind} unpacks to more than ${megabytes(limit)}, over ${MAX_OFFICE_EXPANSION} times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.`;
758
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
759
+ // A character is at least one byte: a text with more characters than the limit is past it.
760
+ const limits: OfficeLimits = {
761
+ kind,
762
+ maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
763
+ byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
764
+ };
765
+ // One count for the whole file, across its parts.
766
+ const count: OfficeCount = { characters: 0, paragraphs: 0 };
767
+ const slicer = new TimeSlicer(input?.signal);
768
+ let unpacked = 0;
769
+ /** Feeds a part to `write`, then calls `done`; false when the part is missing. */
770
+ const stream = (name: string, write: (piece: string) => void, done: () => void = () => undefined) => new Promise<boolean>((resolve, reject) => {
771
+ const file = archive.file(name);
772
+ if (!file) {
773
+ resolve(false);
774
+ return;
775
+ }
776
+ let stopped = false;
777
+ let pausing = false;
778
+ let ended = false;
779
+ /**
780
+ * The pieces that came while the stream was paused, and the next one to write. Pausing JSZip
781
+ * does not stop the block it is unpacking: it hands out the rest of it, up to 16 MB of XML from
782
+ * 16 KB of a deflated part, in the same turn. Those pieces wait for the next slice.
783
+ */
784
+ let waiting: string[] = [];
785
+ let next = 0;
786
+ const unzip = file.internalStream("string");
787
+ const stop = (error: unknown) => {
788
+ if (stopped) return;
789
+ stopped = true;
790
+ waiting = [];
791
+ unzip.pause();
792
+ reject(error);
793
+ };
794
+ const finish = () => {
795
+ try {
796
+ done();
797
+ resolve(true);
798
+ } catch (error) {
799
+ stop(error);
800
+ }
801
+ };
802
+ /** Pauses, then writes the pieces that came meanwhile, a slice at a time, and goes on with the stream. */
803
+ const pauseThenGoOn = async () => {
804
+ try {
805
+ do {
806
+ await slicer.pauseNow();
807
+ while (!stopped && next < waiting.length && !slicer.due) write(waiting[next++]!);
808
+ if (stopped) return;
809
+ } while (next < waiting.length);
810
+ } catch (error) {
811
+ stop(error);
812
+ return;
813
+ }
814
+ waiting = [];
815
+ next = 0;
816
+ pausing = false;
817
+ if (ended) finish();
818
+ else unzip.resume();
819
+ };
820
+ unzip
821
+ .on("data", (chunk) => {
822
+ if (stopped) return;
823
+ if (input?.signal?.aborted) {
824
+ stop(input.signal.reason);
825
+ return;
826
+ }
827
+ // Counted as it comes, written or not: a file that grows past the limit is refused at once.
828
+ unpacked += chunk.length;
829
+ if (unpacked > limit) {
830
+ stop(new Error(refusal));
831
+ return;
832
+ }
833
+ if (pausing) {
834
+ waiting.push(chunk);
835
+ return;
836
+ }
837
+ try {
838
+ write(chunk);
839
+ } catch (error) {
840
+ stop(error);
841
+ return;
842
+ }
843
+ if (slicer.due) {
844
+ pausing = true;
845
+ unzip.pause();
846
+ void pauseThenGoOn();
847
+ }
848
+ })
849
+ .on("error", stop)
850
+ .on("end", () => {
851
+ ended = true;
852
+ if (!stopped && !pausing) finish();
853
+ })
854
+ .resume();
855
+ });
856
+ return {
857
+ limits,
858
+ count,
859
+ stream: (name, write) => stream(name, write),
860
+ async paragraphs(name, prefix, options) {
861
+ const text = new OfficeText(prefix, limits, count, options);
862
+ let result = { paragraphs: [] as string[], hiddenSlide: false };
863
+ await stream(name, (piece) => text.write(piece), () => {
864
+ result = { paragraphs: text.texts(), hiddenSlide: text.hiddenSlide };
865
+ });
866
+ return result;
867
+ },
868
+ async small(name, maxCharacters = MAX_SMALL_PART) {
869
+ const pieces: string[] = [];
870
+ let length = 0;
871
+ try {
872
+ const found = await stream(name, (piece) => {
873
+ length += piece.length;
874
+ if (length > maxCharacters) throw new PartTooLarge();
875
+ pieces.push(piece);
876
+ });
877
+ return found ? pieces.join("") : undefined;
878
+ } catch (error) {
879
+ if (error instanceof PartTooLarge) return undefined;
880
+ throw error;
881
+ }
882
+ },
883
+ };
884
+ }
885
+
886
+ /**
887
+ * The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
888
+ * about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
889
+ * about 2 KB each, and 300,000 empty parts took over 500 MB.
890
+ */
891
+ const MAX_ZIP_ENTRIES = 20_000;
892
+ /**
893
+ * The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
894
+ * programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
895
+ * file of 4 MB made only of them took 250 MB.
896
+ */
897
+ const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
898
+ /**
899
+ * The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
900
+ * file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
901
+ * files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
902
+ * the data of a field can run over the records after it, so the size of the file does not bound
903
+ * them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
904
+ * two above took JSZip under 0.5 s and 140 MB.
905
+ */
906
+ const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
907
+
908
+ export async function loadZip(bytes: Uint8Array, kind: OfficeKind): Promise<ZipArchive> {
909
+ const JSZip = (await importPeer("jszip", () => import("jszip"), "Reading DOCX, PPTX and XLSX files needs the optional dependency \"jszip\".")).default as unknown as { loadAsync(data: Uint8Array): Promise<ZipArchive> };
910
+ // The directory is read first, as JSZip will read it: the count of parts it gives may say
911
+ // anything.
912
+ const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
913
+ if (directory?.endless) {
914
+ throw new Error(`This ${kind} ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.`);
915
+ }
916
+ if (directory && directory.parts > MAX_ZIP_ENTRIES) {
917
+ throw new Error(`This ${kind} has more than ${MAX_ZIP_ENTRIES.toLocaleString("en-US")} parts, more than an Office document has. It may be built to exhaust the server, so it is not read.`);
918
+ }
919
+ // A mass of extra fields, or of names, comments and field data: no Office program writes either.
920
+ if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
921
+ throw new Error(`This ${kind} lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.`);
922
+ }
923
+ return JSZip.loadAsync(bytes);
924
+ }
925
+
926
+ /**
927
+ * Opens an Office file, or refuses it in words for its user: an Office file of before 2007, or one
928
+ * protected by a password, is not a ZIP archive but a compound file, and JSZip says only that it
929
+ * found no ZIP in it.
930
+ */
931
+ export async function openOffice(bytes: Uint8Array, kind: OfficeKind): Promise<ZipArchive> {
932
+ if (bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0) throw new Error(LEGACY_OFFICE);
933
+ return loadZip(bytes, kind);
934
+ }
935
+
936
+ /** The parts of a DOCX read after the document itself, in this order, each under a heading of its own. */
937
+ const WORD_SECTIONS: Array<{ part: RegExp; title: string }> = [
938
+ { part: /^word\/footnotes\.xml$/i, title: "Footnotes" },
939
+ { part: /^word\/endnotes\.xml$/i, title: "Endnotes" },
940
+ { part: /^word\/comments\.xml$/i, title: "Comments" },
941
+ { part: /^word\/header\d+\.xml$/i, title: "Header" },
942
+ { part: /^word\/footer\d+\.xml$/i, title: "Footer" },
943
+ ];
944
+
945
+ /** A part's number, for an order that follows it: header2.xml before header10.xml. */
946
+ const partNumber = (name: string) => Number(/(\d+)\.xml$/i.exec(name)?.[1] ?? 0);
947
+
948
+ /**
949
+ * Word files. The document's paragraphs come first: a heading as a Markdown heading ("## 2.1
950
+ * Scope"), each paragraph with the list number Word shows before it, and each table as rows of
951
+ * `| cell | cell |`, empty cells kept. Then the footnotes, endnotes, comments, headers and footers,
952
+ * each under a heading of its own; a header or footer that repeats one already read is left out.
953
+ */
954
+ export const docx: Extractor = async (bytes, input) => {
955
+ input?.signal?.throwIfAborted();
956
+ const archive = await openOffice(bytes, "DOCX");
957
+ input?.signal?.throwIfAborted();
958
+ if (!archive.file("word/document.xml")) throw new Error("This DOCX does not contain word/document.xml.");
959
+ const parts = Object.keys(archive.files);
960
+ const extra = WORD_SECTIONS.flatMap(({ part, title }) => parts.filter((name) => part.test(name)).sort((left, right) => partNumber(left) - partNumber(right)).map((name) => ({ name, title })));
961
+ const read = officeReader(archive, "DOCX", bytes.byteLength, input);
962
+ const numbering = new WordNumbering(await read.small("word/styles.xml"), await read.small("word/numbering.xml"));
963
+ const total = 1 + extra.length;
964
+ const sections = [(await read.paragraphs("word/document.xml", "w", { numbering })).paragraphs.join("\n")];
965
+ input?.onProgress?.({ done: 1, total, unit: "parts" });
966
+ const seen = new Set<string>();
967
+ for (const [index, { name, title }] of extra.entries()) {
968
+ const text = (await read.paragraphs(name, "w")).paragraphs.join("\n");
969
+ input?.onProgress?.({ done: index + 2, total, unit: "parts" });
970
+ if (!text.trim() || seen.has(text)) continue;
971
+ seen.add(text);
972
+ sections.push(`# ${title}\n${text}`);
973
+ }
974
+ return { text: sections.filter(Boolean).join("\n\n") };
975
+ };
976
+
977
+ /** Speaker notes of a slide are written after this line. */
978
+ export const SPEAKER_NOTES = "[Speaker notes]";
979
+
980
+ /**
981
+ * The slide parts of a deck, in the order of the slide show: the list in `ppt/presentation.xml`,
982
+ * through its relationships. A deck reordered by a tool that does not rename the parts has them in
983
+ * another order than their names. Without that list, the parts in the order of their numbers.
984
+ */
985
+ async function slideOrder(read: OfficeParts, parts: string[]): Promise<string[]> {
986
+ const byName = parts.filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name)).sort((left, right) => partNumber(left) - partNumber(right));
987
+ const [presentation, relationshipsXml] = [await read.small("ppt/presentation.xml"), await read.small("ppt/_rels/presentation.xml.rels")];
988
+ if (!presentation || !relationshipsXml) return byName;
989
+ const relationships = readRelationships(relationshipsXml, "ppt");
990
+ const ordered: string[] = [];
991
+ const listed = new Set<string>();
992
+ const existing = new Set(parts);
993
+ let inList = false;
994
+ readXml(presentation, {
995
+ open(name, attributes) {
996
+ if (name === "p:sldIdLst") inList = true;
997
+ else if (inList && name === "p:sldId") {
998
+ const target = relationships.get(attributes["r:id"] ?? "")?.target;
999
+ if (target && existing.has(target) && !listed.has(target)) {
1000
+ listed.add(target);
1001
+ ordered.push(target);
1002
+ }
1003
+ }
1004
+ },
1005
+ close(name) {
1006
+ if (name === "p:sldIdLst") inList = false;
1007
+ },
1008
+ });
1009
+ return ordered.length > 0 ? ordered : byName;
1010
+ }
1011
+
1012
+ /** The notes part of a slide, from the slide's relationships, or undefined. */
1013
+ async function notesOf(read: OfficeParts, slide: string): Promise<string | undefined> {
1014
+ const folder = slide.slice(0, slide.lastIndexOf("/"));
1015
+ const file = slide.slice(slide.lastIndexOf("/") + 1);
1016
+ const relationships = readRelationships(await read.small(`${folder}/_rels/${file}.rels`), folder);
1017
+ for (const { target, type, external } of relationships.values()) if (!external && type.endsWith("/notesSlide")) return target;
1018
+ return undefined;
1019
+ }
1020
+
1021
+ /**
1022
+ * PowerPoint files: a "## Slide N" section for each slide, numbered in the order of the slide show,
1023
+ * with its text, its tables as rows of `| cell | cell |`, and its speaker notes after
1024
+ * `SPEAKER_NOTES`. A slide the slide show skips says so in its heading.
1025
+ */
1026
+ export const pptx: Extractor = async (bytes, input) => {
1027
+ input?.signal?.throwIfAborted();
1028
+ const archive = await openOffice(bytes, "PPTX");
1029
+ input?.signal?.throwIfAborted();
1030
+ const read = officeReader(archive, "PPTX", bytes.byteLength, input);
1031
+ const names = await slideOrder(read, Object.keys(archive.files));
1032
+ if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
1033
+ const slides: string[] = [];
1034
+ for (const [index, name] of names.entries()) {
1035
+ const { paragraphs, hiddenSlide } = await read.paragraphs(name, "a");
1036
+ const notesPart = await notesOf(read, name);
1037
+ // The notes page holds the slide's number, and may hold the date, a header and a footer, as
1038
+ // text of placeholders of their own: those are left out, and a note that is only a number is kept.
1039
+ const notes = notesPart ? (await read.paragraphs(notesPart, "a", { notesPage: true })).paragraphs : [];
1040
+ const text = paragraphs.join("\n");
1041
+ // A hidden slide keeps its text, and says that the slide show skips it.
1042
+ slides.push(`## Slide ${index + 1}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}${notes.length > 0 ? `\n${SPEAKER_NOTES}\n${notes.join("\n")}` : ""}`);
1043
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
1044
+ }
1045
+ return { text: slides.join("\n\n"), pages: names.length };
1046
+ };
1047
+