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/extract.ts CHANGED
@@ -1,731 +1,56 @@
1
- import { decodeNotUtf8, type DecodedText } from "./encoding.js";
1
+ import { decodeText, plainText } from "./decode.js";
2
+ import { html } from "./html.js";
2
3
  import { TimeSlicer } from "./pause.js";
3
4
  import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
4
5
  import { findPicturePages, parsePdf, type PageGeometry } from "./pdf-pictures.js";
5
6
  import { checkPageWork, HeavyPage } from "./pdf-work.js";
6
7
  import { formatBytes } from "./plan.js";
7
- import { MAX_LINE_CHARACTERS, plural, sliceWhole, utf8Bytes } from "./text.js";
8
+ import { docx, pptx } from "./office.js";
9
+ import { importPeer } from "./peers.js";
10
+ import { plural, utf8Bytes } from "./text.js";
8
11
  import type { DocumentFormat, ExtractedText, ExtractInput, ExtractProgress, Extractor } from "./types.js";
9
- import { readZipDirectory } from "./zip-directory.js";
12
+
13
+ import { xlsx } from "./xlsx.js";
14
+
15
+ export { decodeText };
16
+ export { HIDDEN_SLIDE, HIDDEN_TEXT, officeXmlParagraphs, SPEAKER_NOTES } from "./office.js";
10
17
 
11
18
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
12
19
  log: "log", out: "log", err: "log",
13
20
  md: "markdown", markdown: "markdown",
14
21
  json: "json", jsonl: "json", ndjson: "json",
15
22
  csv: "csv", tsv: "csv",
16
- pdf: "pdf", docx: "docx", pptx: "pptx",
23
+ pdf: "pdf", docx: "docx", docm: "docx", pptx: "pptx", pptm: "pptx",
24
+ xlsx: "xlsx", xlsm: "xlsx", xltx: "xlsx", xltm: "xlsx",
25
+ html: "html", htm: "html", xhtml: "html",
17
26
  };
18
27
 
19
28
  const MIME_FORMATS: Record<string, DocumentFormat> = {
20
29
  "application/pdf": "pdf",
21
30
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
22
31
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
32
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
33
+ "application/vnd.ms-excel.sheet.macroenabled.12": "xlsx",
34
+ "text/html": "html",
35
+ "application/xhtml+xml": "html",
23
36
  "text/markdown": "markdown",
24
37
  "application/json": "json",
25
38
  "text/csv": "csv",
26
39
  };
27
40
 
28
- /** Picks a format from the file name, then the MIME type. Unknown text-like files are "text". */
29
- export function detectFormat(name: string, mimeType: string): DocumentFormat {
30
- const extension = name.toLowerCase().split(".").at(-1) ?? "";
31
- return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
32
- }
33
-
34
- const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
35
-
36
- /**
37
- * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
38
- * A file that is not UTF-8 is read in the older encoding it was saved in, or as UTF-8 with its
39
- * characters that are not valid as U+FFFD (see encoding.ts). Throws a readable error for
40
- * compressed and other binary files.
41
- */
42
- export function decodeText(bytes: Uint8Array): string {
43
- const steps = decodeSteps(bytes);
44
- let step = steps.next();
45
- while (!step.done) step = steps.next();
46
- return step.value.text;
47
- }
48
-
49
- /** `decodeText` in steps: it yields between the steps of a file that is not valid UTF-8. */
50
- function* decodeSteps(bytes: Uint8Array): Generator<void, DecodedText> {
51
- if (bytes[0] === 0xff && bytes[1] === 0xfe) return { text: new TextDecoder("utf-16le").decode(bytes.subarray(2)) };
52
- if (bytes[0] === 0xfe && bytes[1] === 0xff) return { text: new TextDecoder("utf-16be").decode(bytes.subarray(2)) };
53
- // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
54
- if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
55
- throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
56
- }
57
- if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
58
- throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
59
- }
60
- const sample = bytes.subarray(0, 8_192);
61
- let zeros = 0;
62
- for (const byte of sample) if (byte === 0) zeros++;
63
- // UTF-16 without a BOM: about half the bytes of ASCII text are zero.
64
- if (sample.length > 64 && zeros / sample.length > 0.3) {
65
- let oddZeros = 0;
66
- let evenText = 0;
67
- for (let index = 0; index < sample.length; index++) {
68
- if (index % 2 === 1 && sample[index] === 0) oddZeros++;
69
- if (index % 2 === 0 && sample[index] !== 0) evenText++;
70
- }
71
- const half = sample.length / 2;
72
- if (oddZeros / half > 0.6 && evenText / half > 0.6) return { text: new TextDecoder("utf-16le").decode(bytes) };
73
- }
74
- if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
75
- // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
76
- // Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
77
- // feed, and ESC (colour codes) do not count.
78
- let controls = 0;
79
- for (const byte of sample) {
80
- if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
81
- }
82
- if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
83
- try {
84
- return { text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
85
- } catch (error) {
86
- if (!(error instanceof TypeError)) throw error;
87
- }
88
- // Not valid UTF-8: decoded as it is, the text would be replacement characters.
89
- return yield* decodeNotUtf8(bytes);
90
- }
91
-
92
- /**
93
- * Text files. One that is not UTF-8 is read in the older encoding it was saved in, when that can
94
- * be recognized, and other requests get a turn while it is read.
95
- */
96
- const plainText: Extractor = async (bytes, input) => {
97
- const slicer = new TimeSlicer(input?.signal);
98
- const steps = decodeSteps(bytes);
99
- let step = steps.next();
100
- // Only a file that is not UTF-8 takes steps: its decoding is told as one piece of progress, at the end.
101
- const stepped = !step.done;
102
- while (!step.done) {
103
- await slicer.maybePause();
104
- step = steps.next();
105
- }
106
- if (stepped) input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
107
- const { text, encoding, replacedCharacters } = step.value;
108
- return { text, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
109
- };
110
-
111
- function decodeXmlEntities(value: string): string {
112
- return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity: string) => {
113
- const lower = entity.toLowerCase();
114
- if (lower === "amp") return "&";
115
- if (lower === "lt") return "<";
116
- if (lower === "gt") return ">";
117
- if (lower === "quot") return "\"";
118
- if (lower === "apos") return "'";
119
- const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
120
- return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
121
- });
122
- }
123
-
124
- /** A tag name is read up to this many characters: the names that matter here are short. */
125
- const MAX_TAG_NAME = 64;
126
- /** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
127
- const MAX_PARAGRAPH_DEPTH = 32;
128
- /** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
129
- const MAX_OFFICE_PARAGRAPHS = 1_000_000;
130
- /** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
131
- const MAX_OFFICE_CHARACTERS = 32_000_000;
132
- /**
133
- * The text of an open paragraph is counted as written in the XML, where `&quot;` is six characters
134
- * for one: past this many times the limit, it is refused before the paragraph closes.
135
- */
136
- const MAX_ENTITY_GROWTH = 6;
137
- /** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
138
- const SLICE_COPIED_BELOW = 13;
139
-
140
- /**
141
- * Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
142
- * of its paragraph that shows: a person reading the document does not see it. Each line is marked,
143
- * so hidden text cannot end the mark and pass for text that shows.
144
- */
145
- export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
146
- /** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
147
- export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
148
- /**
149
- * The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
150
- * `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
151
- * slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
152
- * `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
153
- */
154
- const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
155
- const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
156
- type WantedAttribute = typeof VANISH_OFF;
157
- /** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
158
- const MAX_ATTRIBUTE_PART = 6;
159
- /**
160
- * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
161
- * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
162
- * the hidden line on a line of its own, without the mark.
163
- */
164
- const HIDDEN_PIECE = MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1;
165
- /**
166
- * What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
167
- * (ingest makes it one in a text with no other line break), or a line or paragraph separator
168
- * (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
169
- * U+0085 instead does no harm.
170
- */
171
- const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
172
- /** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
173
- const NOT_SPACE = /[^\s\x85]/g;
174
-
175
- /**
176
- * Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
177
- * XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
178
- * length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
179
- * read as the attribute.
180
- */
181
- class AttributeReader {
182
- /** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
183
- private name = "";
184
- /** Whether the next character of a name starts a new one. */
185
- private ended = true;
186
- /** Whether "=" came after the name wanted, so the next value is its value. */
187
- private assigned = false;
188
- /** The value of the attribute wanted, while it is read. */
189
- private value: string | undefined;
190
- /** Whether the attribute wanted has one of the values wanted. */
191
- found = false;
192
-
193
- constructor(private readonly wanted: WantedAttribute) {}
194
-
195
- /** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
196
- outside(code: number): void {
197
- if (code === 32 || code === 9 || code === 10 || code === 13) {
198
- this.ended = true;
199
- } else if (code === 61) {
200
- this.assigned = this.name === this.wanted.name;
201
- this.name = "";
202
- this.ended = true;
203
- } else {
204
- if (this.ended) {
205
- this.name = "";
206
- this.ended = false;
207
- this.assigned = false;
208
- }
209
- if (this.name.length < MAX_ATTRIBUTE_PART) this.name += String.fromCharCode(code);
210
- }
211
- }
212
-
213
- /** A quote opens a value. */
214
- open(): void {
215
- if (this.assigned) this.value = "";
216
- this.assigned = false;
217
- }
218
-
219
- /** A character of a value. */
220
- inValue(code: number): void {
221
- if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART) this.value += String.fromCharCode(code);
222
- }
223
-
224
- /** The quote that closes a value. */
225
- close(): void {
226
- if (this.value !== undefined) {
227
- this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
228
- this.value = undefined;
229
- }
230
- this.name = "";
231
- this.ended = true;
232
- }
233
- }
234
-
235
- /** What an Office file may hold before it is refused, and what to call it in the refusal. */
236
- type OfficeLimits = { kind: string; maxCharacters: number; byTextLimit: boolean };
237
- const NO_OFFICE_LIMITS: OfficeLimits = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
238
- /** The text and the paragraphs read from all the parts of one Office file so far. */
239
- type OfficeCount = { characters: number; paragraphs: number };
240
-
241
- /**
242
- * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
243
- * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
244
- * pieces is read whole. Every character is looked at once, so the time follows the length of the
245
- * XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
246
- *
247
- * - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
248
- * of its own, after the one it is anchored in, which keeps its text before and after the box.
249
- * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
250
- * - Paragraph properties hold no text. Their tab stops are not tabs.
251
- * - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
252
- * text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
253
- * is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
254
- *
255
- * What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
256
- * when it closes, an empty one is dropped, and a file that nests paragraphs past
257
- * `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
258
- */
259
- class OfficeText {
260
- private readonly paragraphTag: string;
261
- private readonly paragraphEnd: string;
262
- private readonly textTag: string;
263
- private readonly textEnd: string;
264
- private readonly propertiesTag: string;
265
- private readonly propertiesEnd: string;
266
- private readonly tabTag: string;
267
- private readonly breakTags: ReadonlySet<string>;
268
- /** Word marks hidden runs; PowerPoint hides whole slides. */
269
- private readonly word: boolean;
270
- /** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
271
- private readonly attributesTag: string;
272
- /** The attribute read of `attributesTag`, and the values that count. */
273
- private readonly attribute: WantedAttribute;
274
- /** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
275
- private readonly paragraphs: Array<string | null> = [];
276
- /**
277
- * The paragraphs that are open, the innermost last: where each goes in `paragraphs`, its text so
278
- * far (that which shows, and that which Word hides), and its length. In Word, also how many runs
279
- * are open (a ruby's runs are inside a run), how deep the outermost hidden one is (0: none is
280
- * hidden), and how deep in run properties the reading is.
281
- */
282
- private readonly open: Array<{ slot: number; pieces: string[]; hidden: string[] | undefined; length: number; runs: number; hiddenFrom: number; runProperties: number }> = [];
283
- /** Characters held in the paragraphs that are open, as written in the XML. */
284
- private pending = 0;
285
- private inText = false;
286
- private inProperties = 0;
287
- private inFallback = 0;
288
- /**
289
- * The tag being read, from its "<": its name so far, the quote of a value it is in, its last
290
- * character, and for `attributesTag` the reader of its attribute.
291
- */
292
- private tag: { name: string; named: boolean; quote: number; last: number; attributes: AttributeReader | undefined } | undefined;
293
- /** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
294
- hiddenSlide = false;
295
-
296
- /** `count`: what the other parts of the same file held, shared with them. */
297
- constructor(prefix: "w" | "a", private readonly limits: OfficeLimits = NO_OFFICE_LIMITS, private readonly count: OfficeCount = { characters: 0, paragraphs: 0 }) {
298
- this.paragraphTag = `${prefix}:p`;
299
- this.paragraphEnd = `/${prefix}:p`;
300
- this.textTag = `${prefix}:t`;
301
- this.textEnd = `/${prefix}:t`;
302
- this.propertiesTag = `${prefix}:pPr`;
303
- this.propertiesEnd = `/${prefix}:pPr`;
304
- this.tabTag = `${prefix}:tab`;
305
- this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
306
- this.word = prefix === "w";
307
- this.attributesTag = this.word ? "w:vanish" : "p:sld";
308
- this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
309
- }
310
-
311
- write(xml: string): void {
312
- const length = xml.length;
313
- let at = 0;
314
- while (at < length) {
315
- const tag = this.tag;
316
- if (!tag) {
317
- const start = xml.indexOf("<", at);
318
- const end = start === -1 ? length : start;
319
- if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.add(xml.slice(at, end));
320
- if (start === -1) return;
321
- this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined };
322
- at = start + 1;
323
- continue;
324
- }
325
- for (; at < length; at++) {
326
- const code = xml.charCodeAt(at);
327
- if (tag.quote !== 0) {
328
- if (code === tag.quote) {
329
- tag.quote = 0;
330
- tag.attributes?.close();
331
- } else {
332
- tag.attributes?.inValue(code);
333
- }
334
- continue;
335
- }
336
- if (!tag.named) {
337
- // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
338
- if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
339
- tag.named = true;
340
- if (tag.name === this.attributesTag) tag.attributes = new AttributeReader(this.attribute);
341
- } else {
342
- if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
343
- continue;
344
- }
345
- }
346
- if (code === 62) break;
347
- if (code === 34 || code === 39) {
348
- tag.quote = code;
349
- tag.attributes?.open();
350
- } else {
351
- tag.attributes?.outside(code);
352
- if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
353
- }
354
- }
355
- if (at === length) return; // The tag goes on in the next piece.
356
- this.tag = undefined;
357
- this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false);
358
- at++;
359
- }
360
- }
361
-
362
- /** The text of each paragraph that has some, in the order the paragraphs start. */
363
- texts(): string[] {
364
- // A paragraph never closed keeps the text it has, as when the file ends inside it.
365
- while (this.open.length > 0) this.close();
366
- return this.paragraphs.filter((text): text is string => !!text);
367
- }
368
-
369
- /** Adds text to the innermost open paragraph. */
370
- private add(piece: string): void {
371
- const paragraph = this.open.at(-1);
372
- if (!paragraph) return;
373
- this.pending += piece.length;
374
- paragraph.length += piece.length;
375
- // The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
376
- if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH) throw this.tooMuchText();
377
- if (paragraph.hiddenFrom !== 0) (paragraph.hidden ??= []).push(piece);
378
- else paragraph.pieces.push(piece);
379
- }
380
-
381
- private tooMuchText(): Error {
382
- const { kind, maxCharacters, byTextLimit } = this.limits;
383
- return new Error(byTextLimit
384
- ? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
385
- : `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.`);
386
- }
387
-
388
- /** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
389
- private close(): void {
390
- const paragraph = this.open.pop();
391
- if (!paragraph) return;
392
- this.pending -= paragraph.length;
393
- const shown = decodeXmlEntities(paragraph.pieces.join(""));
394
- const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
395
- if (text.trim()) {
396
- this.count.characters += text.length;
397
- if (this.count.characters > this.limits.maxCharacters) throw this.tooMuchText();
398
- if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
399
- 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.`);
400
- }
401
- // A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
402
- this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
403
- } else if (paragraph.slot === this.paragraphs.length - 1) {
404
- this.paragraphs.pop();
405
- } else {
406
- this.paragraphs[paragraph.slot] = "";
407
- }
408
- }
409
-
410
- /**
411
- * A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
412
- * long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
413
- * make the text longer than the XML it came from, so it is refused as soon as it holds more than
414
- * the room left under the limit, not once it is built.
415
- */
416
- private withHiddenText(shown: string, hidden: string): string {
417
- const room = this.limits.maxCharacters - this.count.characters;
418
- const lines = shown.trim() ? [shown] : [];
419
- // The length of the lines joined with line breaks.
420
- let length = lines.length > 0 ? shown.length : -1;
421
- let marked = 0;
422
- // Where the line being marked ends, found once a line: each of its pieces starts before it, as
423
- // `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
424
- let lineEnd = -1;
425
- // Line by line, without splitting the text first: a run can hold millions of empty lines.
426
- for (let at = 0; ;) {
427
- NOT_SPACE.lastIndex = at;
428
- const first = NOT_SPACE.exec(hidden);
429
- if (!first) break;
430
- const start = first.index;
431
- if (start >= lineEnd) {
432
- HIDDEN_LINE_END.lastIndex = start;
433
- lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
434
- }
435
- let end = lineEnd;
436
- if (end - start > HIDDEN_PIECE) {
437
- // Cut after a space near the end of the piece, and never between the two halves of an emoji.
438
- const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
439
- const space = window.lastIndexOf(" ");
440
- end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
441
- }
442
- const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
443
- length += 1 + line.length;
444
- if (length > room) throw this.tooMuchText();
445
- lines.push(line);
446
- marked++;
447
- at = end;
448
- }
449
- return marked === 0 ? shown : lines.join("\n");
450
- }
451
-
452
- /**
453
- * Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
454
- * `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
455
- */
456
- private read(name: string, empty: boolean, found: boolean): void {
457
- if (name === "mc:Fallback") {
458
- if (!empty) this.inFallback++;
459
- return;
460
- }
461
- if (name === "/mc:Fallback") {
462
- if (this.inFallback > 0) this.inFallback--;
463
- return;
464
- }
465
- if (this.inFallback > 0) return;
466
- if (name === this.paragraphTag) {
467
- if (!empty) {
468
- if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
469
- 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.`);
470
- }
471
- this.open.push({ slot: this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0 });
472
- this.paragraphs.push(null);
473
- }
474
- } else if (name === this.paragraphEnd) {
475
- this.close();
476
- this.inText = false;
477
- this.inProperties = 0;
478
- } else if (name === this.textTag) {
479
- this.inText = !empty;
480
- } else if (name === this.textEnd) {
481
- this.inText = false;
482
- } else if (name === this.propertiesTag) {
483
- if (!empty) this.inProperties++;
484
- } else if (name === this.propertiesEnd) {
485
- if (this.inProperties > 0) this.inProperties--;
486
- } else if (this.inProperties === 0) {
487
- if (name === this.tabTag) this.add("\t");
488
- else if (this.breakTags.has(name)) this.add("\n");
489
- else if (this.word) this.readRun(name, empty, found);
490
- else if (name === "p:sld" && found) this.hiddenSlide = true;
491
- }
492
- }
493
-
494
- /**
495
- * Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
496
- * run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
497
- * A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
498
- * hidden after it. `off`: the `w:vanish` turns hiding off.
499
- */
500
- private readRun(name: string, empty: boolean, off: boolean): void {
501
- const paragraph = this.open.at(-1);
502
- if (!paragraph) return;
503
- if (name === "w:r") {
504
- if (empty) return;
505
- paragraph.runs++;
506
- paragraph.runProperties = 0;
507
- } else if (name === "/w:r") {
508
- if (paragraph.runs > 0) {
509
- if (paragraph.hiddenFrom === paragraph.runs) paragraph.hiddenFrom = 0;
510
- paragraph.runs--;
511
- }
512
- paragraph.runProperties = 0;
513
- } else if (name === "w:rPr") {
514
- if (!empty && paragraph.runs > 0) paragraph.runProperties++;
515
- } else if (name === "/w:rPr") {
516
- if (paragraph.runProperties > 0) paragraph.runProperties--;
517
- } else if (name === "w:vanish" && paragraph.runProperties === 1) {
518
- if (!off) {
519
- if (paragraph.hiddenFrom === 0) paragraph.hiddenFrom = paragraph.runs;
520
- } else if (paragraph.hiddenFrom === paragraph.runs) {
521
- paragraph.hiddenFrom = 0;
522
- }
523
- }
524
- }
525
- }
526
-
527
- /**
528
- * Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. The
529
- * XML may be given in pieces, as it is unpacked.
530
- */
531
- export function officeXmlParagraphs(xml: string | string[], prefix: "w" | "a"): string[] {
532
- const text = new OfficeText(prefix);
533
- for (const piece of typeof xml === "string" ? [xml] : xml) text.write(piece);
534
- return text.texts();
535
- }
536
-
537
- /** The part of JSZip's stream of one file that is used here. */
538
- type ZipStream = {
539
- on(event: "data", listener: (chunk: string) => void): ZipStream;
540
- on(event: "error", listener: (error: unknown) => void): ZipStream;
541
- on(event: "end", listener: () => void): ZipStream;
542
- resume(): ZipStream;
543
- pause(): ZipStream;
544
- };
545
- /** `internalStream` hands out a file of the archive in pieces, as it is unpacked. */
546
- type ZipFile = { internalStream(type: "string"): ZipStream };
547
- type ZipArchive = { files: Record<string, unknown>; file(name: string): ZipFile | null };
548
-
549
- /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
550
- const MAX_OFFICE_XML = 128 * 1024 * 1024;
551
- /**
552
- * The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
553
- * packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
554
- * A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
555
- * zip bomb, as Apache POI does.
556
- */
557
- const MAX_OFFICE_EXPANSION = 100;
558
- const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
559
-
560
- const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
561
-
562
- /**
563
- * Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
564
- * counting what is unpacked: a file that grows far past its size is refused as it grows, before
565
- * that much is in memory. JSZip can unpack megabytes of XML in one turn of the event loop, so the
566
- * stream is paused every few milliseconds of reading, and other requests get a turn.
567
- */
568
- function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number, input: ExtractInput | undefined) {
569
- const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
570
- const refusal = limit === MAX_OFFICE_XML
571
- ? `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.`
572
- : `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.`;
573
- const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
574
- // A character is at least one byte: a text with more characters than the limit is past it.
575
- const limits: OfficeLimits = {
576
- kind,
577
- maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
578
- byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
579
- };
580
- // One count for the whole file, across its parts.
581
- const count: OfficeCount = { characters: 0, paragraphs: 0 };
582
- const slicer = new TimeSlicer(input?.signal);
583
- let unpacked = 0;
584
- return (name: string, prefix: "w" | "a") => new Promise<{ paragraphs: string[]; hiddenSlide: boolean }>((resolve, reject) => {
585
- const file = archive.file(name);
586
- if (!file) {
587
- resolve({ paragraphs: [], hiddenSlide: false });
588
- return;
589
- }
590
- const text = new OfficeText(prefix, limits, count);
591
- let stopped = false;
592
- let pausing = false;
593
- let ended = false;
594
- const stream = file.internalStream("string");
595
- const stop = (error: unknown) => {
596
- if (stopped) return;
597
- stopped = true;
598
- stream.pause();
599
- reject(error);
600
- };
601
- const finish = () => {
602
- try {
603
- resolve({ paragraphs: text.texts(), hiddenSlide: text.hiddenSlide });
604
- } catch (error) {
605
- stop(error);
606
- }
607
- };
608
- stream
609
- .on("data", (chunk) => {
610
- if (stopped) return;
611
- if (input?.signal?.aborted) {
612
- stop(input.signal.reason);
613
- return;
614
- }
615
- unpacked += chunk.length;
616
- if (unpacked > limit) {
617
- stop(new Error(refusal));
618
- return;
619
- }
620
- try {
621
- text.write(chunk);
622
- } catch (error) {
623
- stop(error);
624
- return;
625
- }
626
- if (!pausing && slicer.due) {
627
- pausing = true;
628
- stream.pause();
629
- slicer.pauseNow().then(() => {
630
- pausing = false;
631
- if (stopped) return;
632
- if (ended) finish();
633
- else stream.resume();
634
- }, stop);
635
- }
636
- })
637
- .on("error", stop)
638
- .on("end", () => {
639
- ended = true;
640
- if (!stopped && !pausing) finish();
641
- })
642
- .resume();
643
- });
644
- }
645
-
646
- /**
647
- * The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
648
- * about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
649
- * about 2 KB each, and 300,000 empty parts took over 500 MB.
650
- */
651
- const MAX_ZIP_ENTRIES = 20_000;
652
- /**
653
- * The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
654
- * programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
655
- * file of 4 MB made only of them took 250 MB.
656
- */
657
- const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
658
41
  /**
659
- * The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
660
- * file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
661
- * files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
662
- * the data of a field can run over the records after it, so the size of the file does not bound
663
- * them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
664
- * two above took JSZip under 0.5 s and 140 MB.
42
+ * Picks a format from the file name, then the MIME type. Unknown text-like files are "text". Both
43
+ * come from the upload: only the tables' own keys count, not "constructor" or "__proto__", which
44
+ * every object has.
665
45
  */
666
- const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
667
-
668
- async function loadZip(bytes: Uint8Array, kind: "DOCX" | "PPTX"): Promise<ZipArchive> {
669
- let JSZip: { loadAsync(data: Uint8Array): Promise<ZipArchive> };
670
- try {
671
- JSZip = (await import("jszip")).default as unknown as typeof JSZip;
672
- } catch {
673
- throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
674
- }
675
- // The directory is read first, as JSZip will read it: the count of parts it gives may say
676
- // anything.
677
- const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
678
- if (directory?.endless) {
679
- 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.`);
680
- }
681
- if (directory && directory.parts > MAX_ZIP_ENTRIES) {
682
- 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.`);
683
- }
684
- // A mass of extra fields, or of names, comments and field data: no Office program writes either.
685
- if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
686
- 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.`);
687
- }
688
- return JSZip.loadAsync(bytes);
46
+ export function detectFormat(name: string, mimeType: string): DocumentFormat {
47
+ const extension = name.toLowerCase().split(".").at(-1) ?? "";
48
+ const mime = mimeType.toLowerCase();
49
+ return (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
50
+ ?? (Object.hasOwn(MIME_FORMATS, mime) ? MIME_FORMATS[mime] : undefined)
51
+ ?? "text";
689
52
  }
690
53
 
691
- const docx: Extractor = async (bytes, input) => {
692
- input?.signal?.throwIfAborted();
693
- const archive = await loadZip(bytes, "DOCX");
694
- input?.signal?.throwIfAborted();
695
- const names = Object.keys(archive.files)
696
- .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
697
- .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
698
- if (!names.includes("word/document.xml")) throw new Error("This DOCX does not contain word/document.xml.");
699
- const read = officeReader(archive, "DOCX", bytes.byteLength, input);
700
- const sections: string[] = [];
701
- for (const [index, name] of names.entries()) {
702
- sections.push((await read(name, "w")).paragraphs.join("\n"));
703
- input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
704
- }
705
- return { text: sections.filter(Boolean).join("\n\n") };
706
- };
707
-
708
- const pptx: Extractor = async (bytes, input) => {
709
- input?.signal?.throwIfAborted();
710
- const archive = await loadZip(bytes, "PPTX");
711
- input?.signal?.throwIfAborted();
712
- const slideNumber = (name: string) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
713
- const names = Object.keys(archive.files)
714
- .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
715
- .sort((left, right) => slideNumber(left) - slideNumber(right));
716
- if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
717
- const read = officeReader(archive, "PPTX", bytes.byteLength, input);
718
- const slides: string[] = [];
719
- for (const [index, name] of names.entries()) {
720
- const { paragraphs, hiddenSlide } = await read(name, "a");
721
- const text = paragraphs.join("\n");
722
- // A hidden slide keeps its text, and says that the slide show skips it.
723
- slides.push(`## Slide ${slideNumber(name)}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}`);
724
- input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
725
- }
726
- return { text: slides.join("\n\n"), pages: names.length };
727
- };
728
-
729
54
  export type PdfExtractorOptions = {
730
55
  /**
731
56
  * Rebuild tables from the position of the text, and write each row as `| cell | cell | |`, so an
@@ -778,6 +103,19 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
778
103
  */
779
104
  export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
780
105
 
106
+ /** A line of a page's text that reads as one the extractor writes: a page header, or one of the two notes above. */
107
+ const OWN_LINE = /^(?:--- Page \d+ ---|\[Picture on this page\. This text cannot show it\.\]|\[No text on this page\. It may be a scan, a photo, or a chart\.\])$/gm;
108
+
109
+ /**
110
+ * A page's text, with each line that reads as a line of the extractor's own moved by a space: a
111
+ * document that quotes "--- Page 3 ---" on page 2 must not start page 3 there, nor tell a model of a
112
+ * picture it does not have. Only the extractor's lines have the exact form, which search and
113
+ * `view_pages` look for.
114
+ */
115
+ function ownLines(text: string): string {
116
+ return text.includes("--- Page ") || text.includes("[Picture on this page") || text.includes("[No text on this page") ? text.replace(OWN_LINE, (line) => ` ${line}`) : text;
117
+ }
118
+
781
119
  /**
782
120
  * The progress of the pages of one stage of reading a PDF, for `ExtractInput.onProgress`. The page
783
121
  * check and the picture marks give up quietly on an error of their own: an error of the listener is
@@ -840,17 +178,20 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
840
178
  const pictures = options.pictures ?? true;
841
179
  const checkPages = options.checkPages ?? true;
842
180
  return async (bytes, input) => {
843
- let unpdf: typeof import("unpdf");
844
- try {
845
- unpdf = await import("unpdf");
846
- } catch {
847
- throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
848
- }
181
+ const unpdf = await importPeer("unpdf", () => import("unpdf"), "Reading PDF files needs the optional dependency \"unpdf\".");
849
182
  await checkUnpdf(unpdf);
850
183
  const signal = input?.signal;
851
184
  signal?.throwIfAborted();
852
185
  // pdf.js may detach the buffer it reads, so give it a copy.
853
- const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
186
+ let document: Awaited<ReturnType<typeof unpdf.getDocumentProxy>>;
187
+ try {
188
+ document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
189
+ } catch (error) {
190
+ if ((error as { name?: unknown } | null)?.name === "PasswordException") {
191
+ throw new Error("This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.", { cause: error });
192
+ }
193
+ throw error;
194
+ }
854
195
  const maxPages = input?.maxPages;
855
196
  if (maxPages !== undefined && document.numPages > maxPages) {
856
197
  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.`);
@@ -935,7 +276,7 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
935
276
  const pictured = pictures ? await findPicturePages(parsed, geometry, signal, looked.report) : undefined;
936
277
  signal?.throwIfAborted();
937
278
  looked.rethrow();
938
- const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
279
+ const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text ? ownLines(text) : PAGE_WITHOUT_TEXT}`);
939
280
  return { text: pages.join("\n\n"), pages: document.numPages };
940
281
  };
941
282
  }
@@ -949,6 +290,8 @@ export const defaultExtractors: Record<DocumentFormat, Extractor> = {
949
290
  pdf: createPdfExtractor(),
950
291
  docx,
951
292
  pptx,
293
+ xlsx,
294
+ html,
952
295
  };
953
296
 
954
297
  export async function extractText(