llm-large-files 0.5.0 → 0.7.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 (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
package/dist/extract.js CHANGED
@@ -1,5 +1,11 @@
1
+ import { decodeNotUtf8 } from "./encoding.js";
2
+ import { TimeSlicer } from "./pause.js";
1
3
  import { layoutPage, plainPageText } from "./pdf-layout.js";
2
- import { findPicturePages } from "./pdf-pictures.js";
4
+ import { findPicturePages, parsePdf } from "./pdf-pictures.js";
5
+ import { checkPageWork, HeavyPage } from "./pdf-work.js";
6
+ import { formatBytes } from "./plan.js";
7
+ import { MAX_LINE_CHARACTERS, plural, sliceWhole, utf8Bytes } from "./text.js";
8
+ import { readZipDirectory } from "./zip-directory.js";
3
9
  const EXTENSION_FORMATS = {
4
10
  log: "log", out: "log", err: "log",
5
11
  md: "markdown", markdown: "markdown",
@@ -23,13 +29,23 @@ export function detectFormat(name, mimeType) {
23
29
  const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
24
30
  /**
25
31
  * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
26
- * Throws a readable error for compressed and other binary files.
32
+ * A file that is not UTF-8 is read in the older encoding it was saved in, or as UTF-8 with its
33
+ * characters that are not valid as U+FFFD (see encoding.ts). Throws a readable error for
34
+ * compressed and other binary files.
27
35
  */
28
36
  export function decodeText(bytes) {
37
+ const steps = decodeSteps(bytes);
38
+ let step = steps.next();
39
+ while (!step.done)
40
+ step = steps.next();
41
+ return step.value.text;
42
+ }
43
+ /** `decodeText` in steps: it yields between the steps of a file that is not valid UTF-8. */
44
+ function* decodeSteps(bytes) {
29
45
  if (bytes[0] === 0xff && bytes[1] === 0xfe)
30
- return new TextDecoder("utf-16le").decode(bytes.subarray(2));
46
+ return { text: new TextDecoder("utf-16le").decode(bytes.subarray(2)) };
31
47
  if (bytes[0] === 0xfe && bytes[1] === 0xff)
32
- return new TextDecoder("utf-16be").decode(bytes.subarray(2));
48
+ return { text: new TextDecoder("utf-16be").decode(bytes.subarray(2)) };
33
49
  // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
34
50
  if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
35
51
  throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
@@ -54,7 +70,7 @@ export function decodeText(bytes) {
54
70
  }
55
71
  const half = sample.length / 2;
56
72
  if (oddZeros / half > 0.6 && evenText / half > 0.6)
57
- return new TextDecoder("utf-16le").decode(bytes);
73
+ return { text: new TextDecoder("utf-16le").decode(bytes) };
58
74
  }
59
75
  if (sample.length > 0 && zeros / sample.length > 0.01)
60
76
  throw new Error(NOT_TEXT);
@@ -68,9 +84,35 @@ export function decodeText(bytes) {
68
84
  }
69
85
  if (sample.length >= 64 && controls / sample.length > 0.03)
70
86
  throw new Error(NOT_TEXT);
71
- return new TextDecoder("utf-8").decode(bytes);
87
+ try {
88
+ return { text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
89
+ }
90
+ catch (error) {
91
+ if (!(error instanceof TypeError))
92
+ throw error;
93
+ }
94
+ // Not valid UTF-8: decoded as it is, the text would be replacement characters.
95
+ return yield* decodeNotUtf8(bytes);
72
96
  }
73
- const plainText = async (bytes) => ({ text: decodeText(bytes) });
97
+ /**
98
+ * Text files. One that is not UTF-8 is read in the older encoding it was saved in, when that can
99
+ * be recognized, and other requests get a turn while it is read.
100
+ */
101
+ const plainText = async (bytes, input) => {
102
+ const slicer = new TimeSlicer(input?.signal);
103
+ const steps = decodeSteps(bytes);
104
+ let step = steps.next();
105
+ // Only a file that is not UTF-8 takes steps: its decoding is told as one piece of progress, at the end.
106
+ const stepped = !step.done;
107
+ while (!step.done) {
108
+ await slicer.maybePause();
109
+ step = steps.next();
110
+ }
111
+ if (stepped)
112
+ input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
113
+ const { text, encoding, replacedCharacters } = step.value;
114
+ return { text, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
115
+ };
74
116
  function decodeXmlEntities(value) {
75
117
  return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity) => {
76
118
  const lower = entity.toLowerCase();
@@ -90,6 +132,115 @@ function decodeXmlEntities(value) {
90
132
  }
91
133
  /** A tag name is read up to this many characters: the names that matter here are short. */
92
134
  const MAX_TAG_NAME = 64;
135
+ /** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
136
+ const MAX_PARAGRAPH_DEPTH = 32;
137
+ /** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
138
+ const MAX_OFFICE_PARAGRAPHS = 1_000_000;
139
+ /** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
140
+ const MAX_OFFICE_CHARACTERS = 32_000_000;
141
+ /**
142
+ * The text of an open paragraph is counted as written in the XML, where `"` is six characters
143
+ * for one: past this many times the limit, it is refused before the paragraph closes.
144
+ */
145
+ const MAX_ENTITY_GROWTH = 6;
146
+ /** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
147
+ const SLICE_COPIED_BELOW = 13;
148
+ /**
149
+ * Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
150
+ * of its paragraph that shows: a person reading the document does not see it. Each line is marked,
151
+ * so hidden text cannot end the mark and pass for text that shows.
152
+ */
153
+ export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
154
+ /** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
155
+ export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
156
+ /**
157
+ * The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
158
+ * `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
159
+ * slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
160
+ * `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
161
+ */
162
+ const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
163
+ const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
164
+ /** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
165
+ const MAX_ATTRIBUTE_PART = 6;
166
+ /**
167
+ * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
168
+ * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
169
+ * the hidden line on a line of its own, without the mark.
170
+ */
171
+ const HIDDEN_PIECE = MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1;
172
+ /**
173
+ * What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
174
+ * (ingest makes it one in a text with no other line break), or a line or paragraph separator
175
+ * (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
176
+ * U+0085 instead does no harm.
177
+ */
178
+ const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
179
+ /** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
180
+ const NOT_SPACE = /[^\s\x85]/g;
181
+ /**
182
+ * Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
183
+ * XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
184
+ * length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
185
+ * read as the attribute.
186
+ */
187
+ class AttributeReader {
188
+ wanted;
189
+ /** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
190
+ name = "";
191
+ /** Whether the next character of a name starts a new one. */
192
+ ended = true;
193
+ /** Whether "=" came after the name wanted, so the next value is its value. */
194
+ assigned = false;
195
+ /** The value of the attribute wanted, while it is read. */
196
+ value;
197
+ /** Whether the attribute wanted has one of the values wanted. */
198
+ found = false;
199
+ constructor(wanted) {
200
+ this.wanted = wanted;
201
+ }
202
+ /** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
203
+ outside(code) {
204
+ if (code === 32 || code === 9 || code === 10 || code === 13) {
205
+ this.ended = true;
206
+ }
207
+ else if (code === 61) {
208
+ this.assigned = this.name === this.wanted.name;
209
+ this.name = "";
210
+ this.ended = true;
211
+ }
212
+ else {
213
+ if (this.ended) {
214
+ this.name = "";
215
+ this.ended = false;
216
+ this.assigned = false;
217
+ }
218
+ if (this.name.length < MAX_ATTRIBUTE_PART)
219
+ this.name += String.fromCharCode(code);
220
+ }
221
+ }
222
+ /** A quote opens a value. */
223
+ open() {
224
+ if (this.assigned)
225
+ this.value = "";
226
+ this.assigned = false;
227
+ }
228
+ /** A character of a value. */
229
+ inValue(code) {
230
+ if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART)
231
+ this.value += String.fromCharCode(code);
232
+ }
233
+ /** The quote that closes a value. */
234
+ close() {
235
+ if (this.value !== undefined) {
236
+ this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
237
+ this.value = undefined;
238
+ }
239
+ this.name = "";
240
+ this.ended = true;
241
+ }
242
+ }
243
+ const NO_OFFICE_LIMITS = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
93
244
  /**
94
245
  * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
95
246
  * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
@@ -100,8 +251,17 @@ const MAX_TAG_NAME = 64;
100
251
  * of its own, after the one it is anchored in, which keeps its text before and after the box.
101
252
  * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
102
253
  * - Paragraph properties hold no text. Their tab stops are not tabs.
254
+ * - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
255
+ * text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
256
+ * is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
257
+ *
258
+ * What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
259
+ * when it closes, an empty one is dropped, and a file that nests paragraphs past
260
+ * `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
103
261
  */
104
262
  class OfficeText {
263
+ limits;
264
+ count;
105
265
  paragraphTag;
106
266
  paragraphEnd;
107
267
  textTag;
@@ -110,16 +270,37 @@ class OfficeText {
110
270
  propertiesEnd;
111
271
  tabTag;
112
272
  breakTags;
113
- /** The pieces of text of each paragraph, in the order the paragraphs start. */
273
+ /** Word marks hidden runs; PowerPoint hides whole slides. */
274
+ word;
275
+ /** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
276
+ attributesTag;
277
+ /** The attribute read of `attributesTag`, and the values that count. */
278
+ attribute;
279
+ /** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
114
280
  paragraphs = [];
115
- /** The paragraphs that are open, the innermost last. */
281
+ /**
282
+ * The paragraphs that are open, the innermost last: where each goes in `paragraphs`, its text so
283
+ * far (that which shows, and that which Word hides), and its length. In Word, also how many runs
284
+ * are open (a ruby's runs are inside a run), how deep the outermost hidden one is (0: none is
285
+ * hidden), and how deep in run properties the reading is.
286
+ */
116
287
  open = [];
288
+ /** Characters held in the paragraphs that are open, as written in the XML. */
289
+ pending = 0;
117
290
  inText = false;
118
291
  inProperties = 0;
119
292
  inFallback = 0;
120
- /** The tag being read, from its "<": its name so far, the quote of a value it is in, its last character. */
293
+ /**
294
+ * The tag being read, from its "<": its name so far, the quote of a value it is in, its last
295
+ * character, and for `attributesTag` the reader of its attribute.
296
+ */
121
297
  tag;
122
- constructor(prefix) {
298
+ /** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
299
+ hiddenSlide = false;
300
+ /** `count`: what the other parts of the same file held, shared with them. */
301
+ constructor(prefix, limits = NO_OFFICE_LIMITS, count = { characters: 0, paragraphs: 0 }) {
302
+ this.limits = limits;
303
+ this.count = count;
123
304
  this.paragraphTag = `${prefix}:p`;
124
305
  this.paragraphEnd = `/${prefix}:p`;
125
306
  this.textTag = `${prefix}:t`;
@@ -128,6 +309,9 @@ class OfficeText {
128
309
  this.propertiesEnd = `/${prefix}:pPr`;
129
310
  this.tabTag = `${prefix}:tab`;
130
311
  this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
312
+ this.word = prefix === "w";
313
+ this.attributesTag = this.word ? "w:vanish" : "p:sld";
314
+ this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
131
315
  }
132
316
  write(xml) {
133
317
  const length = xml.length;
@@ -138,24 +322,32 @@ class OfficeText {
138
322
  const start = xml.indexOf("<", at);
139
323
  const end = start === -1 ? length : start;
140
324
  if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0)
141
- this.open.at(-1)?.push(xml.slice(at, end));
325
+ this.add(xml.slice(at, end));
142
326
  if (start === -1)
143
327
  return;
144
- this.tag = { name: "", named: false, quote: 0, last: 0 };
328
+ this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined };
145
329
  at = start + 1;
146
330
  continue;
147
331
  }
148
332
  for (; at < length; at++) {
149
333
  const code = xml.charCodeAt(at);
150
334
  if (tag.quote !== 0) {
151
- if (code === tag.quote)
335
+ if (code === tag.quote) {
152
336
  tag.quote = 0;
337
+ tag.attributes?.close();
338
+ }
339
+ else {
340
+ tag.attributes?.inValue(code);
341
+ }
153
342
  continue;
154
343
  }
155
344
  if (!tag.named) {
156
345
  // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
157
- if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== ""))
346
+ if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
158
347
  tag.named = true;
348
+ if (tag.name === this.attributesTag)
349
+ tag.attributes = new AttributeReader(this.attribute);
350
+ }
159
351
  else {
160
352
  if (tag.name.length < MAX_TAG_NAME)
161
353
  tag.name += xml[at];
@@ -164,24 +356,124 @@ class OfficeText {
164
356
  }
165
357
  if (code === 62)
166
358
  break;
167
- if (code === 34 || code === 39)
359
+ if (code === 34 || code === 39) {
168
360
  tag.quote = code;
169
- else if (code !== 32 && code !== 9 && code !== 10 && code !== 13)
170
- tag.last = code;
361
+ tag.attributes?.open();
362
+ }
363
+ else {
364
+ tag.attributes?.outside(code);
365
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13)
366
+ tag.last = code;
367
+ }
171
368
  }
172
369
  if (at === length)
173
370
  return; // The tag goes on in the next piece.
174
371
  this.tag = undefined;
175
- this.read(tag.name, tag.last === 47);
372
+ this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false);
176
373
  at++;
177
374
  }
178
375
  }
179
376
  /** The text of each paragraph that has some, in the order the paragraphs start. */
180
377
  texts() {
181
- return this.paragraphs.map((pieces) => decodeXmlEntities(pieces.join(""))).filter((text) => text.trim());
378
+ // A paragraph never closed keeps the text it has, as when the file ends inside it.
379
+ while (this.open.length > 0)
380
+ this.close();
381
+ return this.paragraphs.filter((text) => !!text);
182
382
  }
183
- /** Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`. */
184
- read(name, empty) {
383
+ /** Adds text to the innermost open paragraph. */
384
+ add(piece) {
385
+ const paragraph = this.open.at(-1);
386
+ if (!paragraph)
387
+ return;
388
+ this.pending += piece.length;
389
+ paragraph.length += piece.length;
390
+ // The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
391
+ if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH)
392
+ throw this.tooMuchText();
393
+ if (paragraph.hiddenFrom !== 0)
394
+ (paragraph.hidden ??= []).push(piece);
395
+ else
396
+ paragraph.pieces.push(piece);
397
+ }
398
+ tooMuchText() {
399
+ const { kind, maxCharacters, byTextLimit } = this.limits;
400
+ return new Error(byTextLimit
401
+ ? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
402
+ : `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.`);
403
+ }
404
+ /** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
405
+ close() {
406
+ const paragraph = this.open.pop();
407
+ if (!paragraph)
408
+ return;
409
+ this.pending -= paragraph.length;
410
+ const shown = decodeXmlEntities(paragraph.pieces.join(""));
411
+ const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
412
+ if (text.trim()) {
413
+ this.count.characters += text.length;
414
+ if (this.count.characters > this.limits.maxCharacters)
415
+ throw this.tooMuchText();
416
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
417
+ 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.`);
418
+ }
419
+ // A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
420
+ this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
421
+ }
422
+ else if (paragraph.slot === this.paragraphs.length - 1) {
423
+ this.paragraphs.pop();
424
+ }
425
+ else {
426
+ this.paragraphs[paragraph.slot] = "";
427
+ }
428
+ }
429
+ /**
430
+ * A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
431
+ * long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
432
+ * make the text longer than the XML it came from, so it is refused as soon as it holds more than
433
+ * the room left under the limit, not once it is built.
434
+ */
435
+ withHiddenText(shown, hidden) {
436
+ const room = this.limits.maxCharacters - this.count.characters;
437
+ const lines = shown.trim() ? [shown] : [];
438
+ // The length of the lines joined with line breaks.
439
+ let length = lines.length > 0 ? shown.length : -1;
440
+ let marked = 0;
441
+ // Where the line being marked ends, found once a line: each of its pieces starts before it, as
442
+ // `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
443
+ let lineEnd = -1;
444
+ // Line by line, without splitting the text first: a run can hold millions of empty lines.
445
+ for (let at = 0;;) {
446
+ NOT_SPACE.lastIndex = at;
447
+ const first = NOT_SPACE.exec(hidden);
448
+ if (!first)
449
+ break;
450
+ const start = first.index;
451
+ if (start >= lineEnd) {
452
+ HIDDEN_LINE_END.lastIndex = start;
453
+ lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
454
+ }
455
+ let end = lineEnd;
456
+ if (end - start > HIDDEN_PIECE) {
457
+ // Cut after a space near the end of the piece, and never between the two halves of an emoji.
458
+ const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
459
+ const space = window.lastIndexOf(" ");
460
+ end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
461
+ }
462
+ const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
463
+ length += 1 + line.length;
464
+ if (length > room)
465
+ throw this.tooMuchText();
466
+ lines.push(line);
467
+ marked++;
468
+ at = end;
469
+ }
470
+ return marked === 0 ? shown : lines.join("\n");
471
+ }
472
+ /**
473
+ * Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
474
+ * `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
475
+ */
476
+ read(name, empty, found) {
185
477
  if (name === "mc:Fallback") {
186
478
  if (!empty)
187
479
  this.inFallback++;
@@ -196,13 +488,15 @@ class OfficeText {
196
488
  return;
197
489
  if (name === this.paragraphTag) {
198
490
  if (!empty) {
199
- const pieces = [];
200
- this.paragraphs.push(pieces);
201
- this.open.push(pieces);
491
+ if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
492
+ 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.`);
493
+ }
494
+ this.open.push({ slot: this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0 });
495
+ this.paragraphs.push(null);
202
496
  }
203
497
  }
204
498
  else if (name === this.paragraphEnd) {
205
- this.open.pop();
499
+ this.close();
206
500
  this.inText = false;
207
501
  this.inProperties = 0;
208
502
  }
@@ -222,16 +516,66 @@ class OfficeText {
222
516
  }
223
517
  else if (this.inProperties === 0) {
224
518
  if (name === this.tabTag)
225
- this.open.at(-1)?.push("\t");
519
+ this.add("\t");
226
520
  else if (this.breakTags.has(name))
227
- this.open.at(-1)?.push("\n");
521
+ this.add("\n");
522
+ else if (this.word)
523
+ this.readRun(name, empty, found);
524
+ else if (name === "p:sld" && found)
525
+ this.hiddenSlide = true;
526
+ }
527
+ }
528
+ /**
529
+ * Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
530
+ * run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
531
+ * A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
532
+ * hidden after it. `off`: the `w:vanish` turns hiding off.
533
+ */
534
+ readRun(name, empty, off) {
535
+ const paragraph = this.open.at(-1);
536
+ if (!paragraph)
537
+ return;
538
+ if (name === "w:r") {
539
+ if (empty)
540
+ return;
541
+ paragraph.runs++;
542
+ paragraph.runProperties = 0;
543
+ }
544
+ else if (name === "/w:r") {
545
+ if (paragraph.runs > 0) {
546
+ if (paragraph.hiddenFrom === paragraph.runs)
547
+ paragraph.hiddenFrom = 0;
548
+ paragraph.runs--;
549
+ }
550
+ paragraph.runProperties = 0;
551
+ }
552
+ else if (name === "w:rPr") {
553
+ if (!empty && paragraph.runs > 0)
554
+ paragraph.runProperties++;
555
+ }
556
+ else if (name === "/w:rPr") {
557
+ if (paragraph.runProperties > 0)
558
+ paragraph.runProperties--;
559
+ }
560
+ else if (name === "w:vanish" && paragraph.runProperties === 1) {
561
+ if (!off) {
562
+ if (paragraph.hiddenFrom === 0)
563
+ paragraph.hiddenFrom = paragraph.runs;
564
+ }
565
+ else if (paragraph.hiddenFrom === paragraph.runs) {
566
+ paragraph.hiddenFrom = 0;
567
+ }
228
568
  }
229
569
  }
230
570
  }
231
- /** Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. */
571
+ /**
572
+ * Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. The
573
+ * XML may be given in pieces, as it is unpacked.
574
+ */
232
575
  export function officeXmlParagraphs(xml, prefix) {
233
576
  const text = new OfficeText(prefix);
234
- text.write(xml);
577
+ for (const piece of typeof xml === "string" ? [xml] : xml)
578
+ text.write(piece);
235
579
  return text.texts();
236
580
  }
237
581
  /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
@@ -248,48 +592,116 @@ const megabytes = (size) => `${Math.round(size / 1024 / 1024)} MB`;
248
592
  /**
249
593
  * Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
250
594
  * counting what is unpacked: a file that grows far past its size is refused as it grows, before
251
- * that much is in memory. Unpacking yields to other work between pieces.
595
+ * that much is in memory. JSZip can unpack megabytes of XML in one turn of the event loop, so the
596
+ * stream is paused every few milliseconds of reading, and other requests get a turn.
252
597
  */
253
- function officeReader(archive, kind, size) {
598
+ function officeReader(archive, kind, size, input) {
254
599
  const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
255
600
  const refusal = limit === MAX_OFFICE_XML
256
601
  ? `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.`
257
602
  : `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.`;
603
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
604
+ // A character is at least one byte: a text with more characters than the limit is past it.
605
+ const limits = {
606
+ kind,
607
+ maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
608
+ byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
609
+ };
610
+ // One count for the whole file, across its parts.
611
+ const count = { characters: 0, paragraphs: 0 };
612
+ const slicer = new TimeSlicer(input?.signal);
258
613
  let unpacked = 0;
259
614
  return (name, prefix) => new Promise((resolve, reject) => {
260
615
  const file = archive.file(name);
261
616
  if (!file) {
262
- resolve([]);
617
+ resolve({ paragraphs: [], hiddenSlide: false });
263
618
  return;
264
619
  }
265
- const text = new OfficeText(prefix);
620
+ const text = new OfficeText(prefix, limits, count);
266
621
  let stopped = false;
622
+ let pausing = false;
623
+ let ended = false;
267
624
  const stream = file.internalStream("string");
625
+ const stop = (error) => {
626
+ if (stopped)
627
+ return;
628
+ stopped = true;
629
+ stream.pause();
630
+ reject(error);
631
+ };
632
+ const finish = () => {
633
+ try {
634
+ resolve({ paragraphs: text.texts(), hiddenSlide: text.hiddenSlide });
635
+ }
636
+ catch (error) {
637
+ stop(error);
638
+ }
639
+ };
268
640
  stream
269
641
  .on("data", (chunk) => {
270
642
  if (stopped)
271
643
  return;
644
+ if (input?.signal?.aborted) {
645
+ stop(input.signal.reason);
646
+ return;
647
+ }
272
648
  unpacked += chunk.length;
273
649
  if (unpacked > limit) {
274
- stopped = true;
275
- stream.pause();
276
- reject(new Error(refusal));
650
+ stop(new Error(refusal));
277
651
  return;
278
652
  }
279
- text.write(chunk);
280
- })
281
- .on("error", (error) => {
282
- stopped = true;
283
- reject(error);
653
+ try {
654
+ text.write(chunk);
655
+ }
656
+ catch (error) {
657
+ stop(error);
658
+ return;
659
+ }
660
+ if (!pausing && slicer.due) {
661
+ pausing = true;
662
+ stream.pause();
663
+ slicer.pauseNow().then(() => {
664
+ pausing = false;
665
+ if (stopped)
666
+ return;
667
+ if (ended)
668
+ finish();
669
+ else
670
+ stream.resume();
671
+ }, stop);
672
+ }
284
673
  })
674
+ .on("error", stop)
285
675
  .on("end", () => {
286
- if (!stopped)
287
- resolve(text.texts());
676
+ ended = true;
677
+ if (!stopped && !pausing)
678
+ finish();
288
679
  })
289
680
  .resume();
290
681
  });
291
682
  }
292
- async function loadZip(bytes) {
683
+ /**
684
+ * The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
685
+ * about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
686
+ * about 2 KB each, and 300,000 empty parts took over 500 MB.
687
+ */
688
+ const MAX_ZIP_ENTRIES = 20_000;
689
+ /**
690
+ * The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
691
+ * programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
692
+ * file of 4 MB made only of them took 250 MB.
693
+ */
694
+ const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
695
+ /**
696
+ * The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
697
+ * file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
698
+ * files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
699
+ * the data of a field can run over the records after it, so the size of the file does not bound
700
+ * them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
701
+ * two above took JSZip under 0.5 s and 140 MB.
702
+ */
703
+ const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
704
+ async function loadZip(bytes, kind) {
293
705
  let JSZip;
294
706
  try {
295
707
  JSZip = (await import("jszip")).default;
@@ -297,37 +709,80 @@ async function loadZip(bytes) {
297
709
  catch {
298
710
  throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
299
711
  }
712
+ // The directory is read first, as JSZip will read it: the count of parts it gives may say
713
+ // anything.
714
+ const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
715
+ if (directory?.endless) {
716
+ 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.`);
717
+ }
718
+ if (directory && directory.parts > MAX_ZIP_ENTRIES) {
719
+ 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.`);
720
+ }
721
+ // A mass of extra fields, or of names, comments and field data: no Office program writes either.
722
+ if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
723
+ 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.`);
724
+ }
300
725
  return JSZip.loadAsync(bytes);
301
726
  }
302
- const docx = async (bytes) => {
303
- const archive = await loadZip(bytes);
727
+ const docx = async (bytes, input) => {
728
+ input?.signal?.throwIfAborted();
729
+ const archive = await loadZip(bytes, "DOCX");
730
+ input?.signal?.throwIfAborted();
304
731
  const names = Object.keys(archive.files)
305
732
  .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
306
733
  .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
307
734
  if (!names.includes("word/document.xml"))
308
735
  throw new Error("This DOCX does not contain word/document.xml.");
309
- const read = officeReader(archive, "DOCX", bytes.byteLength);
736
+ const read = officeReader(archive, "DOCX", bytes.byteLength, input);
310
737
  const sections = [];
311
- for (const name of names)
312
- sections.push((await read(name, "w")).join("\n"));
738
+ for (const [index, name] of names.entries()) {
739
+ sections.push((await read(name, "w")).paragraphs.join("\n"));
740
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
741
+ }
313
742
  return { text: sections.filter(Boolean).join("\n\n") };
314
743
  };
315
- const pptx = async (bytes) => {
316
- const archive = await loadZip(bytes);
744
+ const pptx = async (bytes, input) => {
745
+ input?.signal?.throwIfAborted();
746
+ const archive = await loadZip(bytes, "PPTX");
747
+ input?.signal?.throwIfAborted();
317
748
  const slideNumber = (name) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
318
749
  const names = Object.keys(archive.files)
319
750
  .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
320
751
  .sort((left, right) => slideNumber(left) - slideNumber(right));
321
752
  if (names.length === 0)
322
753
  throw new Error("This PPTX does not contain any slides.");
323
- const read = officeReader(archive, "PPTX", bytes.byteLength);
754
+ const read = officeReader(archive, "PPTX", bytes.byteLength, input);
324
755
  const slides = [];
325
- for (const name of names) {
326
- const text = (await read(name, "a")).join("\n");
327
- slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
756
+ for (const [index, name] of names.entries()) {
757
+ const { paragraphs, hiddenSlide } = await read(name, "a");
758
+ const text = paragraphs.join("\n");
759
+ // A hidden slide keeps its text, and says that the slide show skips it.
760
+ slides.push(`## Slide ${slideNumber(name)}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}`);
761
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
328
762
  }
329
763
  return { text: slides.join("\n\n"), pages: names.length };
330
764
  };
765
+ /**
766
+ * A page tree that lists one page more than once makes the text of that page come back each time:
767
+ * a 3 KB file built that way held 107 MB of text. PDF writers do not do this.
768
+ */
769
+ const REPEATED_PAGE = "This PDF lists the same page more than once. A file built that way can hold far more text than its size, so it is not read. Print it to a new PDF, and attach that.";
770
+ /**
771
+ * pdf.js reads the text of a page in one go, and nothing can stop it. A page that paints forms
772
+ * inside forms, or whose content is packed hundreds of times, held the server for 6 s to 2 minutes
773
+ * from files of 2 to 650 KB. Such a page is found before pdf.js reads it (see pdf-work.ts).
774
+ */
775
+ const HEAVY_PAGE = (page) => `Page ${page} of this PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.`;
776
+ const HEAVY_FILE = "This PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.";
777
+ const UNREADABLE_PAGE = (page) => `Page ${page} of this PDF stores its content in a way that cannot be checked before it is read, so it is not read. Print it to a new PDF, and attach that.`;
778
+ /**
779
+ * The text of a PDF is smaller than the file: fonts and pictures take room, and text is
780
+ * compressed. A page that paints one form inside another, many times over, draws the text of the
781
+ * innermost form each time: a file of a few kilobytes can draw megabytes. Past the first 16 MB,
782
+ * text over this many times the size of the file is refused as it is read.
783
+ */
784
+ const MAX_PDF_EXPANSION = 100;
785
+ const PDF_ALLOWANCE = 16 * 1024 * 1024;
331
786
  /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
332
787
  const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
333
788
  /**
@@ -335,6 +790,63 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
335
790
  * not the model is later given a way to look at the page.
336
791
  */
337
792
  export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
793
+ /**
794
+ * The progress of the pages of one stage of reading a PDF, for `ExtractInput.onProgress`. The page
795
+ * check and the picture marks give up quietly on an error of their own: an error of the listener is
796
+ * kept, and `rethrow` throws it once they are done, as it would anywhere else.
797
+ */
798
+ function pageProgress(input, stage) {
799
+ const listener = input?.onProgress;
800
+ if (!listener)
801
+ return { rethrow() { } };
802
+ let failed;
803
+ return {
804
+ report(done, total) {
805
+ try {
806
+ listener({ stage, done, total, unit: "pages" });
807
+ }
808
+ catch (error) {
809
+ failed ??= { error };
810
+ throw error;
811
+ }
812
+ },
813
+ rethrow() {
814
+ if (failed)
815
+ throw failed.error;
816
+ },
817
+ };
818
+ }
819
+ /**
820
+ * Loads pdf.js through `unpdf`, and refuses a version of unpdf that cannot read PDFs on this
821
+ * version of Node (`node`, as in `process.versions.node`), with a message that says what to install:
822
+ * - unpdf 1.9 and later load a pdf.js that needs Node 22: on Node 20, every PDF fails.
823
+ * - pdf.js calls `Promise.try`, which Node 20 and 22 do not have (Node 24 does). unpdf adds it
824
+ * where it is missing, but 1.5.0 to 1.6.0 do not: there, the first PDF throws where nothing can
825
+ * catch it, and the whole process stops.
826
+ * The messages give the major version of Node only: an upload can be answered with them.
827
+ */
828
+ export async function checkUnpdf(unpdf, node = process.versions.node) {
829
+ if (typeof unpdf.getResolvedPDFJS !== "function")
830
+ return;
831
+ const major = Number.parseInt(node, 10);
832
+ try {
833
+ await unpdf.getResolvedPDFJS();
834
+ }
835
+ catch (error) {
836
+ if (major >= 22)
837
+ throw error;
838
+ const reason = error instanceof Error ? error.message : String(error);
839
+ throw new Error(`The unpdf installed cannot read PDF files on Node ${major} (${reason}). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`);
840
+ }
841
+ if (typeof Promise.try !== "function") {
842
+ const advice = major < 22
843
+ ? "Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later."
844
+ : major < 24
845
+ ? "Install unpdf 1.6.1 or later, or run Node 24 or later."
846
+ : "Install unpdf 1.6.1 or later.";
847
+ throw new Error(`The unpdf installed would stop the whole server at the first PDF file on Node ${major}, so PDF files are not read. ${advice}`);
848
+ }
849
+ }
338
850
  /**
339
851
  * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
340
852
  * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
@@ -342,6 +854,7 @@ export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.
342
854
  export function createPdfExtractor(options = {}) {
343
855
  const tables = options.tables ?? true;
344
856
  const pictures = options.pictures ?? true;
857
+ const checkPages = options.checkPages ?? true;
345
858
  return async (bytes, input) => {
346
859
  let unpdf;
347
860
  try {
@@ -350,13 +863,59 @@ export function createPdfExtractor(options = {}) {
350
863
  catch {
351
864
  throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
352
865
  }
866
+ await checkUnpdf(unpdf);
867
+ const signal = input?.signal;
868
+ signal?.throwIfAborted();
353
869
  // pdf.js may detach the buffer it reads, so give it a copy.
354
870
  const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
871
+ const maxPages = input?.maxPages;
872
+ if (maxPages !== undefined && document.numPages > maxPages) {
873
+ throw new Error(`This PDF has ${document.numPages.toLocaleString("en-US")} pages, more than the ${maxPages.toLocaleString("en-US")} read from one file. Split it, and attach the part you need.`);
874
+ }
875
+ // Read once with @cantoo/pdf-lib, when it is installed: to refuse a page that would hold the
876
+ // server before pdf.js reads it, and to mark the pages that show a picture.
877
+ let parsed = checkPages || pictures ? await parsePdf(bytes, signal) : undefined;
878
+ signal?.throwIfAborted();
879
+ if (parsed && checkPages) {
880
+ const checked = pageProgress(input, "check");
881
+ try {
882
+ await checkPageWork(parsed.library, parsed.document, bytes.byteLength, signal, checked.report);
883
+ }
884
+ catch (error) {
885
+ if (error instanceof HeavyPage)
886
+ throw new Error(error.reason === "unreadable" ? UNREADABLE_PAGE(error.page) : error.reason === "file" ? HEAVY_FILE : HEAVY_PAGE(error.page));
887
+ signal?.throwIfAborted();
888
+ checked.rethrow();
889
+ // Anything else unusual in the file: the check is given up, and the text is read as before.
890
+ }
891
+ }
892
+ if (!pictures)
893
+ parsed = undefined;
894
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
895
+ const mostDrawn = Math.max(PDF_ALLOWANCE, bytes.byteLength * MAX_PDF_EXPANSION);
896
+ const tooMuchText = () => new Error(maxTextBytes <= mostDrawn
897
+ ? `This PDF holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`
898
+ : `This PDF draws more than ${formatBytes(mostDrawn)} of text, over ${MAX_PDF_EXPANSION} times its size. A file that grows that much is not read: it may be built to exhaust the server.`);
899
+ const textLimit = Math.min(maxTextBytes, mostDrawn);
355
900
  const texts = [];
356
901
  const geometry = [];
902
+ /** The page objects read so far: a page tree that lists one page twice is refused. */
903
+ const seen = new Set();
904
+ // pdf.js reads a page through promises that never let a timer or another request run: other
905
+ // requests get a turn every few milliseconds, or a 2,000-page file holds the server for seconds.
906
+ const slicer = new TimeSlicer(signal);
907
+ let textBytes = 0;
357
908
  let hasText = false;
358
909
  for (let number = 1; number <= document.numPages; number++) {
910
+ signal?.throwIfAborted();
359
911
  const page = await document.getPage(number);
912
+ const ref = page.ref;
913
+ if (ref) {
914
+ const key = `${ref.num} ${ref.gen}`;
915
+ if (seen.has(key))
916
+ throw new Error(REPEATED_PAGE);
917
+ seen.add(key);
918
+ }
360
919
  const content = await page.getTextContent();
361
920
  const items = content.items.filter((item) => typeof item.str === "string");
362
921
  const transform = page.getViewport({ scale: 1 }).transform;
@@ -377,9 +936,15 @@ export function createPdfExtractor(options = {}) {
377
936
  text = text.trim();
378
937
  if (text)
379
938
  hasText = true;
939
+ // Counted as it is read: a small file can draw far more text than its own size.
940
+ textBytes += utf8Bytes(text);
941
+ if (textBytes > textLimit)
942
+ throw tooMuchText();
380
943
  texts.push(text);
381
944
  geometry.push({ view: page.view, transform, tables: found });
382
945
  page.cleanup();
946
+ input?.onProgress?.({ done: number, total: document.numPages, unit: "pages" });
947
+ await slicer.maybePause();
383
948
  }
384
949
  if (!hasText) {
385
950
  // A scan has nothing to search, but a short one can be read by looking at its pages, when the
@@ -388,11 +953,14 @@ export function createPdfExtractor(options = {}) {
388
953
  if (most <= 0)
389
954
  throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
390
955
  if (document.numPages > most) {
391
- throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} pages. It needs OCR first.`);
956
+ throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} ${plural(most, "page")}. It needs OCR first.`);
392
957
  }
393
958
  }
394
959
  // Which pages show a picture. Undefined when that could not be found out: then none is marked.
395
- const pictured = pictures ? await findPicturePages(bytes, geometry) : undefined;
960
+ const looked = pageProgress(input, "pictures");
961
+ const pictured = pictures ? await findPicturePages(parsed, geometry, signal, looked.report) : undefined;
962
+ signal?.throwIfAborted();
963
+ looked.rethrow();
396
964
  const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
397
965
  return { text: pages.join("\n\n"), pages: document.numPages };
398
966
  };