llm-large-files 0.5.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  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 +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/extract.ts CHANGED
@@ -1,324 +1,56 @@
1
+ import { decodeText, plainText } from "./decode.js";
2
+ import { html } from "./html.js";
3
+ import { TimeSlicer } from "./pause.js";
1
4
  import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
2
- import { findPicturePages, type PageGeometry } from "./pdf-pictures.js";
3
- import type { DocumentFormat, ExtractedText, ExtractInput, Extractor } from "./types.js";
5
+ import { findPicturePages, parsePdf, type PageGeometry } from "./pdf-pictures.js";
6
+ import { checkPageWork, HeavyPage } from "./pdf-work.js";
7
+ import { formatBytes } from "./plan.js";
8
+ import { docx, pptx } from "./office.js";
9
+ import { importPeer } from "./peers.js";
10
+ import { plural, utf8Bytes } from "./text.js";
11
+ import type { DocumentFormat, ExtractedText, ExtractInput, ExtractProgress, Extractor } from "./types.js";
12
+
13
+ import { xlsx } from "./xlsx.js";
14
+
15
+ export { decodeText };
16
+ export { HIDDEN_SLIDE, HIDDEN_TEXT, officeXmlParagraphs, SPEAKER_NOTES } from "./office.js";
4
17
 
5
18
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
6
19
  log: "log", out: "log", err: "log",
7
20
  md: "markdown", markdown: "markdown",
8
21
  json: "json", jsonl: "json", ndjson: "json",
9
22
  csv: "csv", tsv: "csv",
10
- 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",
11
26
  };
12
27
 
13
28
  const MIME_FORMATS: Record<string, DocumentFormat> = {
14
29
  "application/pdf": "pdf",
15
30
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
16
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",
17
36
  "text/markdown": "markdown",
18
37
  "application/json": "json",
19
38
  "text/csv": "csv",
20
39
  };
21
40
 
22
- /** Picks a format from the file name, then the MIME type. Unknown text-like files are "text". */
23
- export function detectFormat(name: string, mimeType: string): DocumentFormat {
24
- const extension = name.toLowerCase().split(".").at(-1) ?? "";
25
- return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
26
- }
27
-
28
- const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
29
-
30
- /**
31
- * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
32
- * Throws a readable error for compressed and other binary files.
33
- */
34
- export function decodeText(bytes: Uint8Array): string {
35
- if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
36
- if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
37
- // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
38
- if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
39
- throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
40
- }
41
- if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
42
- throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
43
- }
44
- const sample = bytes.subarray(0, 8_192);
45
- let zeros = 0;
46
- for (const byte of sample) if (byte === 0) zeros++;
47
- // UTF-16 without a BOM: about half the bytes of ASCII text are zero.
48
- if (sample.length > 64 && zeros / sample.length > 0.3) {
49
- let oddZeros = 0;
50
- let evenText = 0;
51
- for (let index = 0; index < sample.length; index++) {
52
- if (index % 2 === 1 && sample[index] === 0) oddZeros++;
53
- if (index % 2 === 0 && sample[index] !== 0) evenText++;
54
- }
55
- const half = sample.length / 2;
56
- if (oddZeros / half > 0.6 && evenText / half > 0.6) return new TextDecoder("utf-16le").decode(bytes);
57
- }
58
- if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
59
- // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
60
- // Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
61
- // feed, and ESC (colour codes) do not count.
62
- let controls = 0;
63
- for (const byte of sample) {
64
- if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
65
- }
66
- if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
67
- return new TextDecoder("utf-8").decode(bytes);
68
- }
69
-
70
- const plainText: Extractor = async (bytes) => ({ text: decodeText(bytes) });
71
-
72
- function decodeXmlEntities(value: string): string {
73
- return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity: string) => {
74
- const lower = entity.toLowerCase();
75
- if (lower === "amp") return "&";
76
- if (lower === "lt") return "<";
77
- if (lower === "gt") return ">";
78
- if (lower === "quot") return "\"";
79
- if (lower === "apos") return "'";
80
- const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
81
- return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
82
- });
83
- }
84
-
85
- /** A tag name is read up to this many characters: the names that matter here are short. */
86
- const MAX_TAG_NAME = 64;
87
-
88
- /**
89
- * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
90
- * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
91
- * pieces is read whole. Every character is looked at once, so the time follows the length of the
92
- * XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
93
- *
94
- * - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
95
- * of its own, after the one it is anchored in, which keeps its text before and after the box.
96
- * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
97
- * - Paragraph properties hold no text. Their tab stops are not tabs.
98
- */
99
- class OfficeText {
100
- private readonly paragraphTag: string;
101
- private readonly paragraphEnd: string;
102
- private readonly textTag: string;
103
- private readonly textEnd: string;
104
- private readonly propertiesTag: string;
105
- private readonly propertiesEnd: string;
106
- private readonly tabTag: string;
107
- private readonly breakTags: ReadonlySet<string>;
108
- /** The pieces of text of each paragraph, in the order the paragraphs start. */
109
- private readonly paragraphs: string[][] = [];
110
- /** The paragraphs that are open, the innermost last. */
111
- private readonly open: string[][] = [];
112
- private inText = false;
113
- private inProperties = 0;
114
- private inFallback = 0;
115
- /** The tag being read, from its "<": its name so far, the quote of a value it is in, its last character. */
116
- private tag: { name: string; named: boolean; quote: number; last: number } | undefined;
117
-
118
- constructor(prefix: "w" | "a") {
119
- this.paragraphTag = `${prefix}:p`;
120
- this.paragraphEnd = `/${prefix}:p`;
121
- this.textTag = `${prefix}:t`;
122
- this.textEnd = `/${prefix}:t`;
123
- this.propertiesTag = `${prefix}:pPr`;
124
- this.propertiesEnd = `/${prefix}:pPr`;
125
- this.tabTag = `${prefix}:tab`;
126
- this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
127
- }
128
-
129
- write(xml: string): void {
130
- const length = xml.length;
131
- let at = 0;
132
- while (at < length) {
133
- const tag = this.tag;
134
- if (!tag) {
135
- const start = xml.indexOf("<", at);
136
- const end = start === -1 ? length : start;
137
- if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.open.at(-1)?.push(xml.slice(at, end));
138
- if (start === -1) return;
139
- this.tag = { name: "", named: false, quote: 0, last: 0 };
140
- at = start + 1;
141
- continue;
142
- }
143
- for (; at < length; at++) {
144
- const code = xml.charCodeAt(at);
145
- if (tag.quote !== 0) {
146
- if (code === tag.quote) tag.quote = 0;
147
- continue;
148
- }
149
- if (!tag.named) {
150
- // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
151
- if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) tag.named = true;
152
- else {
153
- if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
154
- continue;
155
- }
156
- }
157
- if (code === 62) break;
158
- if (code === 34 || code === 39) tag.quote = code;
159
- else if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
160
- }
161
- if (at === length) return; // The tag goes on in the next piece.
162
- this.tag = undefined;
163
- this.read(tag.name, tag.last === 47);
164
- at++;
165
- }
166
- }
167
-
168
- /** The text of each paragraph that has some, in the order the paragraphs start. */
169
- texts(): string[] {
170
- return this.paragraphs.map((pieces) => decodeXmlEntities(pieces.join(""))).filter((text) => text.trim());
171
- }
172
-
173
- /** Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`. */
174
- private read(name: string, empty: boolean): void {
175
- if (name === "mc:Fallback") {
176
- if (!empty) this.inFallback++;
177
- return;
178
- }
179
- if (name === "/mc:Fallback") {
180
- if (this.inFallback > 0) this.inFallback--;
181
- return;
182
- }
183
- if (this.inFallback > 0) return;
184
- if (name === this.paragraphTag) {
185
- if (!empty) {
186
- const pieces: string[] = [];
187
- this.paragraphs.push(pieces);
188
- this.open.push(pieces);
189
- }
190
- } else if (name === this.paragraphEnd) {
191
- this.open.pop();
192
- this.inText = false;
193
- this.inProperties = 0;
194
- } else if (name === this.textTag) {
195
- this.inText = !empty;
196
- } else if (name === this.textEnd) {
197
- this.inText = false;
198
- } else if (name === this.propertiesTag) {
199
- if (!empty) this.inProperties++;
200
- } else if (name === this.propertiesEnd) {
201
- if (this.inProperties > 0) this.inProperties--;
202
- } else if (this.inProperties === 0) {
203
- if (name === this.tabTag) this.open.at(-1)?.push("\t");
204
- else if (this.breakTags.has(name)) this.open.at(-1)?.push("\n");
205
- }
206
- }
207
- }
208
-
209
- /** Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. */
210
- export function officeXmlParagraphs(xml: string, prefix: "w" | "a"): string[] {
211
- const text = new OfficeText(prefix);
212
- text.write(xml);
213
- return text.texts();
214
- }
215
-
216
- /** The part of JSZip's stream of one file that is used here. */
217
- type ZipStream = {
218
- on(event: "data", listener: (chunk: string) => void): ZipStream;
219
- on(event: "error", listener: (error: unknown) => void): ZipStream;
220
- on(event: "end", listener: () => void): ZipStream;
221
- resume(): ZipStream;
222
- pause(): ZipStream;
223
- };
224
- /** `internalStream` hands out a file of the archive in pieces, as it is unpacked. */
225
- type ZipFile = { internalStream(type: "string"): ZipStream };
226
- type ZipArchive = { files: Record<string, unknown>; file(name: string): ZipFile | null };
227
-
228
- /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
229
- const MAX_OFFICE_XML = 128 * 1024 * 1024;
230
- /**
231
- * The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
232
- * packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
233
- * A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
234
- * zip bomb, as Apache POI does.
235
- */
236
- const MAX_OFFICE_EXPANSION = 100;
237
- const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
238
-
239
- const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
240
-
241
41
  /**
242
- * Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
243
- * counting what is unpacked: a file that grows far past its size is refused as it grows, before
244
- * that much is in memory. Unpacking yields to other work between pieces.
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.
245
45
  */
246
- function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number) {
247
- const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
248
- const refusal = limit === MAX_OFFICE_XML
249
- ? `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.`
250
- : `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.`;
251
- let unpacked = 0;
252
- return (name: string, prefix: "w" | "a") => new Promise<string[]>((resolve, reject) => {
253
- const file = archive.file(name);
254
- if (!file) {
255
- resolve([]);
256
- return;
257
- }
258
- const text = new OfficeText(prefix);
259
- let stopped = false;
260
- const stream = file.internalStream("string");
261
- stream
262
- .on("data", (chunk) => {
263
- if (stopped) return;
264
- unpacked += chunk.length;
265
- if (unpacked > limit) {
266
- stopped = true;
267
- stream.pause();
268
- reject(new Error(refusal));
269
- return;
270
- }
271
- text.write(chunk);
272
- })
273
- .on("error", (error) => {
274
- stopped = true;
275
- reject(error);
276
- })
277
- .on("end", () => {
278
- if (!stopped) resolve(text.texts());
279
- })
280
- .resume();
281
- });
282
- }
283
-
284
- async function loadZip(bytes: Uint8Array): Promise<ZipArchive> {
285
- let JSZip: { loadAsync(data: Uint8Array): Promise<ZipArchive> };
286
- try {
287
- JSZip = (await import("jszip")).default as unknown as typeof JSZip;
288
- } catch {
289
- throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
290
- }
291
- 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";
292
52
  }
293
53
 
294
- const docx: Extractor = async (bytes) => {
295
- const archive = await loadZip(bytes);
296
- const names = Object.keys(archive.files)
297
- .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
298
- .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
299
- if (!names.includes("word/document.xml")) throw new Error("This DOCX does not contain word/document.xml.");
300
- const read = officeReader(archive, "DOCX", bytes.byteLength);
301
- const sections: string[] = [];
302
- for (const name of names) sections.push((await read(name, "w")).join("\n"));
303
- return { text: sections.filter(Boolean).join("\n\n") };
304
- };
305
-
306
- const pptx: Extractor = async (bytes) => {
307
- const archive = await loadZip(bytes);
308
- const slideNumber = (name: string) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
309
- const names = Object.keys(archive.files)
310
- .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
311
- .sort((left, right) => slideNumber(left) - slideNumber(right));
312
- if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
313
- const read = officeReader(archive, "PPTX", bytes.byteLength);
314
- const slides: string[] = [];
315
- for (const name of names) {
316
- const text = (await read(name, "a")).join("\n");
317
- slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
318
- }
319
- return { text: slides.join("\n\n"), pages: names.length };
320
- };
321
-
322
54
  export type PdfExtractorOptions = {
323
55
  /**
324
56
  * Rebuild tables from the position of the text, and write each row as `| cell | cell | |`, so an
@@ -332,8 +64,37 @@ export type PdfExtractorOptions = {
332
64
  * optional dependency `@cantoo/pdf-lib`; without it, and with false, the text is that of 0.2.0.
333
65
  */
334
66
  pictures?: boolean;
67
+ /**
68
+ * Before pdf.js reads any page, add up what each page would make it run, and refuse a file with
69
+ * a page that would hold the server for a long time: pdf.js reads a page in one block that no
70
+ * time limit can cut short. Defaults to true. It needs the optional dependency
71
+ * `@cantoo/pdf-lib`. With false, and `pictures: false`, the file is not read with it at ingest.
72
+ */
73
+ checkPages?: boolean;
335
74
  };
336
75
 
76
+ /**
77
+ * A page tree that lists one page more than once makes the text of that page come back each time:
78
+ * a 3 KB file built that way held 107 MB of text. PDF writers do not do this.
79
+ */
80
+ 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.";
81
+ /**
82
+ * pdf.js reads the text of a page in one go, and nothing can stop it. A page that paints forms
83
+ * inside forms, or whose content is packed hundreds of times, held the server for 6 s to 2 minutes
84
+ * from files of 2 to 650 KB. Such a page is found before pdf.js reads it (see pdf-work.ts).
85
+ */
86
+ const HEAVY_PAGE = (page: number) => `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.`;
87
+ 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.";
88
+ const UNREADABLE_PAGE = (page: number) => `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.`;
89
+ /**
90
+ * The text of a PDF is smaller than the file: fonts and pictures take room, and text is
91
+ * compressed. A page that paints one form inside another, many times over, draws the text of the
92
+ * innermost form each time: a file of a few kilobytes can draw megabytes. Past the first 16 MB,
93
+ * text over this many times the size of the file is refused as it is read.
94
+ */
95
+ const MAX_PDF_EXPANSION = 100;
96
+ const PDF_ALLOWANCE = 16 * 1024 * 1024;
97
+
337
98
  /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
338
99
  const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
339
100
  /**
@@ -342,6 +103,72 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
342
103
  */
343
104
  export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
344
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
+
119
+ /**
120
+ * The progress of the pages of one stage of reading a PDF, for `ExtractInput.onProgress`. The page
121
+ * check and the picture marks give up quietly on an error of their own: an error of the listener is
122
+ * kept, and `rethrow` throws it once they are done, as it would anywhere else.
123
+ */
124
+ function pageProgress(input: ExtractInput | undefined, stage: ExtractProgress["stage"]): { report?: (done: number, total: number) => void; rethrow(): void } {
125
+ const listener = input?.onProgress;
126
+ if (!listener) return { rethrow() {} };
127
+ let failed: { error: unknown } | undefined;
128
+ return {
129
+ report(done, total) {
130
+ try {
131
+ listener({ stage, done, total, unit: "pages" });
132
+ } catch (error) {
133
+ failed ??= { error };
134
+ throw error;
135
+ }
136
+ },
137
+ rethrow() {
138
+ if (failed) throw failed.error;
139
+ },
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Loads pdf.js through `unpdf`, and refuses a version of unpdf that cannot read PDFs on this
145
+ * version of Node (`node`, as in `process.versions.node`), with a message that says what to install:
146
+ * - unpdf 1.9 and later load a pdf.js that needs Node 22: on Node 20, every PDF fails.
147
+ * - pdf.js calls `Promise.try`, which Node 20 and 22 do not have (Node 24 does). unpdf adds it
148
+ * where it is missing, but 1.5.0 to 1.6.0 do not: there, the first PDF throws where nothing can
149
+ * catch it, and the whole process stops.
150
+ * The messages give the major version of Node only: an upload can be answered with them.
151
+ */
152
+ export async function checkUnpdf(unpdf: { getResolvedPDFJS?: unknown }, node: string = process.versions.node): Promise<void> {
153
+ if (typeof unpdf.getResolvedPDFJS !== "function") return;
154
+ const major = Number.parseInt(node, 10);
155
+ try {
156
+ await (unpdf.getResolvedPDFJS as () => Promise<unknown>)();
157
+ } catch (error) {
158
+ if (major >= 22) throw error;
159
+ const reason = error instanceof Error ? error.message : String(error);
160
+ 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.`);
161
+ }
162
+ if (typeof (Promise as { try?: unknown }).try !== "function") {
163
+ const advice = major < 22
164
+ ? "Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later."
165
+ : major < 24
166
+ ? "Install unpdf 1.6.1 or later, or run Node 24 or later."
167
+ : "Install unpdf 1.6.1 or later.";
168
+ 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}`);
169
+ }
170
+ }
171
+
345
172
  /**
346
173
  * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
347
174
  * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
@@ -349,20 +176,66 @@ export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.
349
176
  export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor {
350
177
  const tables = options.tables ?? true;
351
178
  const pictures = options.pictures ?? true;
179
+ const checkPages = options.checkPages ?? true;
352
180
  return async (bytes, input) => {
353
- let unpdf: typeof import("unpdf");
181
+ const unpdf = await importPeer("unpdf", () => import("unpdf"), "Reading PDF files needs the optional dependency \"unpdf\".");
182
+ await checkUnpdf(unpdf);
183
+ const signal = input?.signal;
184
+ signal?.throwIfAborted();
185
+ // pdf.js may detach the buffer it reads, so give it a copy.
186
+ let document: Awaited<ReturnType<typeof unpdf.getDocumentProxy>>;
354
187
  try {
355
- unpdf = await import("unpdf");
356
- } catch {
357
- throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
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;
358
194
  }
359
- // pdf.js may detach the buffer it reads, so give it a copy.
360
- const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
195
+ const maxPages = input?.maxPages;
196
+ if (maxPages !== undefined && document.numPages > maxPages) {
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.`);
198
+ }
199
+ // Read once with @cantoo/pdf-lib, when it is installed: to refuse a page that would hold the
200
+ // server before pdf.js reads it, and to mark the pages that show a picture.
201
+ let parsed = checkPages || pictures ? await parsePdf(bytes, signal) : undefined;
202
+ signal?.throwIfAborted();
203
+ if (parsed && checkPages) {
204
+ const checked = pageProgress(input, "check");
205
+ try {
206
+ await checkPageWork(parsed.library, parsed.document, bytes.byteLength, signal, checked.report);
207
+ } catch (error) {
208
+ if (error instanceof HeavyPage) throw new Error(error.reason === "unreadable" ? UNREADABLE_PAGE(error.page) : error.reason === "file" ? HEAVY_FILE : HEAVY_PAGE(error.page));
209
+ signal?.throwIfAborted();
210
+ checked.rethrow();
211
+ // Anything else unusual in the file: the check is given up, and the text is read as before.
212
+ }
213
+ }
214
+ if (!pictures) parsed = undefined;
215
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
216
+ const mostDrawn = Math.max(PDF_ALLOWANCE, bytes.byteLength * MAX_PDF_EXPANSION);
217
+ const tooMuchText = () => new Error(maxTextBytes <= mostDrawn
218
+ ? `This PDF holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`
219
+ : `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.`);
220
+ const textLimit = Math.min(maxTextBytes, mostDrawn);
361
221
  const texts: string[] = [];
362
222
  const geometry: PageGeometry[] = [];
223
+ /** The page objects read so far: a page tree that lists one page twice is refused. */
224
+ const seen = new Set<string>();
225
+ // pdf.js reads a page through promises that never let a timer or another request run: other
226
+ // requests get a turn every few milliseconds, or a 2,000-page file holds the server for seconds.
227
+ const slicer = new TimeSlicer(signal);
228
+ let textBytes = 0;
363
229
  let hasText = false;
364
230
  for (let number = 1; number <= document.numPages; number++) {
231
+ signal?.throwIfAborted();
365
232
  const page = await document.getPage(number);
233
+ const ref = page.ref;
234
+ if (ref) {
235
+ const key = `${ref.num} ${ref.gen}`;
236
+ if (seen.has(key)) throw new Error(REPEATED_PAGE);
237
+ seen.add(key);
238
+ }
366
239
  const content = await page.getTextContent();
367
240
  const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
368
241
  const transform = page.getViewport({ scale: 1 }).transform as number[];
@@ -380,9 +253,14 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
380
253
  }
381
254
  text = text.trim();
382
255
  if (text) hasText = true;
256
+ // Counted as it is read: a small file can draw far more text than its own size.
257
+ textBytes += utf8Bytes(text);
258
+ if (textBytes > textLimit) throw tooMuchText();
383
259
  texts.push(text);
384
260
  geometry.push({ view: page.view, transform, tables: found });
385
261
  page.cleanup();
262
+ input?.onProgress?.({ done: number, total: document.numPages, unit: "pages" });
263
+ await slicer.maybePause();
386
264
  }
387
265
  if (!hasText) {
388
266
  // A scan has nothing to search, but a short one can be read by looking at its pages, when the
@@ -390,12 +268,15 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
390
268
  const most = input?.scannedPages ?? 0;
391
269
  if (most <= 0) throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
392
270
  if (document.numPages > most) {
393
- 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.`);
271
+ 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.`);
394
272
  }
395
273
  }
396
274
  // Which pages show a picture. Undefined when that could not be found out: then none is marked.
397
- const pictured = pictures ? await findPicturePages(bytes, geometry) : undefined;
398
- const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
275
+ const looked = pageProgress(input, "pictures");
276
+ const pictured = pictures ? await findPicturePages(parsed, geometry, signal, looked.report) : undefined;
277
+ signal?.throwIfAborted();
278
+ looked.rethrow();
279
+ const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text ? ownLines(text) : PAGE_WITHOUT_TEXT}`);
399
280
  return { text: pages.join("\n\n"), pages: document.numPages };
400
281
  };
401
282
  }
@@ -409,6 +290,8 @@ export const defaultExtractors: Record<DocumentFormat, Extractor> = {
409
290
  pdf: createPdfExtractor(),
410
291
  docx,
411
292
  pptx,
293
+ xlsx,
294
+ html,
412
295
  };
413
296
 
414
297
  export async function extractText(