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
@@ -0,0 +1,61 @@
1
+ // The child process of `createIsolatedExtractors` (isolated.ts): it reads the files it is sent with
2
+ // the built-in extractors, one at a time, and answers over the IPC channel. It runs with a heap
3
+ // limit of its own: a file that would exhaust the memory kills this process, not the server.
4
+ import { createPdfExtractor, extractText, type PdfExtractorOptions } from "../extract.js";
5
+ import type { DocumentFormat, ExtractedText, ExtractProgress } from "../types.js";
6
+
7
+ /** A file to read. */
8
+ export type ChildJob = {
9
+ type: "extract";
10
+ id: number;
11
+ bytes: Uint8Array;
12
+ input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number; maxTextBytes?: number; maxPages?: number; progress: boolean };
13
+ pdf?: PdfExtractorOptions;
14
+ };
15
+
16
+ /** What the child answers. */
17
+ export type ChildMessage =
18
+ | { type: "ready" }
19
+ | { type: "progress"; id: number; progress: ExtractProgress }
20
+ | { type: "done"; id: number; result: ExtractedText }
21
+ | { type: "error"; id: number; message: string; name: string; code?: string; syscall?: string };
22
+
23
+ const send = (message: ChildMessage) => {
24
+ process.send?.(message);
25
+ };
26
+
27
+ process.on("message", (message: ChildJob | { type: "abort"; id: number }) => {
28
+ if (message?.type === "extract") void run(message);
29
+ });
30
+
31
+ // The parent went away: nothing is left to answer.
32
+ process.on("disconnect", () => process.exit(0));
33
+
34
+ let pdfExtractor: { options: string; extract: ReturnType<typeof createPdfExtractor> } | undefined;
35
+
36
+ async function run(job: ChildJob): Promise<void> {
37
+ try {
38
+ const options = JSON.stringify(job.pdf ?? {});
39
+ if (job.input.format === "pdf" && pdfExtractor?.options !== options) pdfExtractor = { options, extract: createPdfExtractor(job.pdf ?? {}) };
40
+ const { progress, ...input } = job.input;
41
+ const result = await extractText(job.bytes, {
42
+ ...input,
43
+ ...(progress ? { onProgress: (report: ExtractProgress) => send({ type: "progress", id: job.id, progress: report }) } : {}),
44
+ }, job.input.format === "pdf" && pdfExtractor ? { pdf: pdfExtractor.extract } : {});
45
+ const { text, pages, encoding, replacedCharacters } = result;
46
+ send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}) } });
47
+ } catch (error) {
48
+ // A system error keeps its code and system call: the server tells it apart from a file that cannot be read.
49
+ const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
50
+ send({
51
+ type: "error",
52
+ id: job.id,
53
+ message: error instanceof Error ? error.message : String(error),
54
+ name: error instanceof Error ? error.name : "Error",
55
+ ...(typeof code === "string" ? { code } : {}),
56
+ ...(typeof syscall === "string" ? { syscall } : {}),
57
+ });
58
+ }
59
+ }
60
+
61
+ send({ type: "ready" });
@@ -0,0 +1,464 @@
1
+ import { fork, type ChildProcess } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { IngestError } from "../errors.js";
4
+ import type { PdfExtractorOptions } from "../extract.js";
5
+ import type { DocumentFormat, ExtractedText, ExtractInput, Extractor } from "../types.js";
6
+ import type { ChildJob, ChildMessage } from "./ingest-child.js";
7
+
8
+ export type IsolatedExtractorOptions = {
9
+ /**
10
+ * The heap of each child process, in MB: a file that needs more is refused ("out_of_memory"),
11
+ * and the server goes on. Defaults to 512; at least 1, and finite. The server's own
12
+ * `NODE_OPTIONS` are not passed to the children: a heap flag there would replace this one.
13
+ */
14
+ maxHeapMb?: number;
15
+ /**
16
+ * The most time one file may take, in milliseconds: past it, its child process is killed and the
17
+ * file refused ("timeout"). Defaults to 120,000. 0 sets none, and so does a time past what a
18
+ * timer can wait (2,147,483,647 ms), `Infinity` included. `ingestTimeoutMs` of the library stops
19
+ * a file too; this one holds even for a page that pdf.js reads in one block.
20
+ */
21
+ timeoutMs?: number;
22
+ /** How many files are read at once, each in a child process of its own. Defaults to 2. */
23
+ concurrency?: number;
24
+ /**
25
+ * How many files may wait for a child process. Past it, a file is refused at once with
26
+ * `IngestError` "busy" (`retryAfterMs`), which the upload handler answers with 503 and
27
+ * `Retry-After`. Defaults to 8.
28
+ */
29
+ maxQueue?: number;
30
+ /**
31
+ * The formats read in child processes. Defaults to the ones whose parsers a hostile file can
32
+ * exhaust: "pdf", "docx", "pptx" and "xlsx". Text formats are read in the server, in slices.
33
+ */
34
+ formats?: DocumentFormat[];
35
+ /** Options of the built-in PDF extractor in the children (see `createPdfExtractor`). */
36
+ pdf?: PdfExtractorOptions;
37
+ /**
38
+ * How many files one child process reads before it is replaced by a new one. Defaults to 50.
39
+ * Some parsers keep memory for the life of their process (pdf-lib keeps every name it reads).
40
+ */
41
+ maxFilesPerChild?: number;
42
+ /**
43
+ * A child process with nothing to read is stopped after this many milliseconds. Defaults to
44
+ * 30,000. 0, or a time past what a timer can wait, keeps the children until `close()`. Either
45
+ * way an idle child does not keep your process alive.
46
+ */
47
+ idleMs?: number;
48
+ /** Further Node options for the children, beside the heap limit. */
49
+ execArgv?: string[];
50
+ /**
51
+ * The script the children run: a path, a `file:` URL, or a string of one (as
52
+ * `import.meta.resolve("llm-large-files/node/ingest-child.js")` gives). Defaults to the one
53
+ * shipped next to this module. For a bundler that moves files.
54
+ */
55
+ childScript?: string | URL;
56
+ };
57
+
58
+ export type IsolatedExtractors = {
59
+ /** Pass them to `createLargeFiles({ extractors })`. */
60
+ extractors: Partial<Record<DocumentFormat, Extractor>>;
61
+ /** Files being read, files waiting, and child processes running: for a health check or a metric. */
62
+ stats(): { running: number; queued: number; children: number };
63
+ /**
64
+ * Stops every child process, and refuses the files waiting. Resolves once the children have
65
+ * exited. Files sent later start new ones.
66
+ */
67
+ close(): Promise<void>;
68
+ };
69
+
70
+ /** What the out-of-memory death of a child process writes on its standard error. */
71
+ const OUT_OF_MEMORY = /heap out of memory|Reached heap limit|allocation failed/i;
72
+ /** The last characters kept of a child's standard error, to tell why it died. */
73
+ const STDERR_KEPT = 4_096;
74
+ /** How long to wait before trying again, when every reader is busy. */
75
+ const BUSY_RETRY_MS = 5_000;
76
+ /** The longest a Node.js timer waits: a longer one fires at once. A time past it is no limit, as for `ingestTimeoutMs`. */
77
+ const LONGEST_TIMER_MS = 2 ** 31 - 1;
78
+
79
+ const DEFAULT_FORMATS: DocumentFormat[] = ["pdf", "docx", "pptx", "xlsx"];
80
+
81
+ type Job = {
82
+ id: number;
83
+ bytes: Uint8Array;
84
+ input: ExtractInput;
85
+ resolve(result: ExtractedText): void;
86
+ reject(error: unknown): void;
87
+ /** Takes the job out of the queue when its caller gives up while it waits. */
88
+ cancel?: () => void;
89
+ };
90
+
91
+ type Child = {
92
+ process: ChildProcess;
93
+ ready: Promise<void>;
94
+ /** Whether it said it is ready: a child that dies before has not been sent a file. */
95
+ started: boolean;
96
+ /** Settled once it is gone: it exited, or could not start at all. */
97
+ gone: Promise<void>;
98
+ job: Job | undefined;
99
+ files: number;
100
+ stderr: string;
101
+ idle: ReturnType<typeof setTimeout> | undefined;
102
+ /** Set when this module killed it, and why. */
103
+ killedFor?: unknown;
104
+ };
105
+
106
+ function positive(name: string, value: number | undefined, fallback: number, zeroAllowed = false): number {
107
+ if (value === undefined) return fallback;
108
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0 || (!zeroAllowed && value === 0)) {
109
+ throw new RangeError(`${name} must be a number above ${zeroAllowed ? "or equal to " : ""}0, and is ${String(value)}.`);
110
+ }
111
+ return value;
112
+ }
113
+
114
+ /** Calls `then` once the standard error of a child that has exited is read to its end, or after a second. */
115
+ function afterStderr(child: ChildProcess, then: () => void): void {
116
+ const stderr = child.stderr;
117
+ if (!stderr || stderr.destroyed || stderr.readableEnded) {
118
+ then();
119
+ return;
120
+ }
121
+ let called = false;
122
+ const once = () => {
123
+ if (called) return;
124
+ called = true;
125
+ clearTimeout(timer);
126
+ then();
127
+ };
128
+ const timer = setTimeout(once, 1_000);
129
+ stderr.once("close", once);
130
+ }
131
+
132
+ /** A time option as a timer takes it: one past the longest timer, `Infinity` included, is none (0). */
133
+ const timerMs = (ms: number) => (ms > LONGEST_TIMER_MS ? 0 : ms);
134
+
135
+ /** A time limit as the refusal gives it, as `ingestTimeoutMs`'s does: "500 ms", "45 s", "2 min". */
136
+ function formatDuration(ms: number): string {
137
+ if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
138
+ if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
139
+ return `${Number((ms / 60_000).toFixed(1))} min`;
140
+ }
141
+
142
+ /**
143
+ * The largest heap given to a child, in MB: 1 TB. Node reads a far larger --max-old-space-size
144
+ * wrong (Number.MAX_SAFE_INTEGER gave a 47 MB heap, and every file failed).
145
+ */
146
+ const MAX_HEAP_MB = 1_048_576;
147
+
148
+ /**
149
+ * Extractors that read files in child processes, each with a heap limit and a kill timer, so that
150
+ * a hostile upload (a zip bomb, a PDF that draws gigabytes) is refused while the server goes on:
151
+ * a worker thread does not reliably contain running out of memory, a process does. At most
152
+ * `concurrency` files are read at once, and at most `maxQueue` wait; past that a file is refused
153
+ * as "busy". Use them in place of the built-in extractors for files from users:
154
+ *
155
+ * ```ts
156
+ * const isolated = createIsolatedExtractors({ maxHeapMb: 512, concurrency: 2 });
157
+ * const files = createLargeFiles({ store, extractors: isolated.extractors });
158
+ * // A SIGTERM listener replaces Node's own exit: stop the server there too, or it goes on serving.
159
+ * process.once("SIGTERM", () => {
160
+ * server.close();
161
+ * void isolated.close();
162
+ * });
163
+ * ```
164
+ *
165
+ * A file costs its bytes copied to the child and its text copied back. The children load the same
166
+ * optional dependencies (`unpdf`, `jszip`, `@cantoo/pdf-lib`) the server would.
167
+ */
168
+ export function createIsolatedExtractors(options: IsolatedExtractorOptions = {}): IsolatedExtractors {
169
+ const maxHeapMb = Math.trunc(positive("maxHeapMb", options.maxHeapMb, 512));
170
+ // Node takes --max-old-space-size=0 for its default heap, not for none, and a child given a
171
+ // value it cannot read stops at its start: every file would then be refused.
172
+ if (!Number.isSafeInteger(maxHeapMb) || maxHeapMb < 1 || maxHeapMb > MAX_HEAP_MB) throw new RangeError(`maxHeapMb must be a number from 1 to ${MAX_HEAP_MB.toLocaleString("en-US")} (1 TB), and is ${String(options.maxHeapMb)}.`);
173
+ const timeoutMs = timerMs(positive("timeoutMs", options.timeoutMs, 120_000, true));
174
+ const concurrency = Math.max(1, Math.trunc(positive("concurrency", options.concurrency, 2)));
175
+ const maxQueue = Math.trunc(positive("maxQueue", options.maxQueue, 8, true));
176
+ const maxFiles = Math.max(1, Math.trunc(positive("maxFilesPerChild", options.maxFilesPerChild, 50)));
177
+ const idleMs = timerMs(positive("idleMs", options.idleMs, 30_000, true));
178
+ const script = options.childScript ?? new URL("./ingest-child.js", import.meta.url);
179
+ // fork() takes a path: a file URL given as a string (import.meta.resolve) would be read as a relative path.
180
+ const scriptPath = script instanceof URL || script.startsWith("file:") ? fileURLToPath(script) : script;
181
+ const children: Child[] = [];
182
+ /** Every child not yet gone, those stopped and not yet exited included: close() waits for them. */
183
+ const alive = new Set<Child>();
184
+ const queue: Job[] = [];
185
+ let nextId = 1;
186
+ let closed = false;
187
+
188
+ const environment = () => {
189
+ const env = { ...process.env };
190
+ delete env.NODE_OPTIONS;
191
+ return env;
192
+ };
193
+
194
+ function spawn(): Child {
195
+ const child = fork(scriptPath, [], {
196
+ execArgv: [`--max-old-space-size=${maxHeapMb}`, ...(options.execArgv ?? [])],
197
+ env: environment(),
198
+ serialization: "advanced",
199
+ stdio: ["ignore", "ignore", "pipe", "ipc"],
200
+ });
201
+ let markReady: () => void = () => undefined;
202
+ let markGone: () => void = () => undefined;
203
+ const entry: Child = {
204
+ process: child,
205
+ ready: new Promise((resolve) => (markReady = resolve)),
206
+ started: false,
207
+ gone: new Promise((resolve) => (markGone = resolve)),
208
+ job: undefined,
209
+ files: 0,
210
+ stderr: "",
211
+ idle: undefined,
212
+ };
213
+ child.stderr?.setEncoding("utf8");
214
+ child.stderr?.on("data", (chunk: string) => {
215
+ entry.stderr = (entry.stderr + chunk).slice(-STDERR_KEPT);
216
+ });
217
+ child.on("message", (message: ChildMessage) => {
218
+ if (message.type === "ready") {
219
+ entry.started = true;
220
+ markReady();
221
+ return;
222
+ }
223
+ const job = entry.job;
224
+ if (!job || message.id !== job.id) return;
225
+ if (message.type === "progress") {
226
+ try {
227
+ job.input.onProgress?.(message.progress);
228
+ } catch (error) {
229
+ finish(entry, () => job.reject(error), true);
230
+ }
231
+ return;
232
+ }
233
+ finish(entry, () => (message.type === "done" ? job.resolve(message.result) : job.reject(childError(message))));
234
+ });
235
+ // A child that dies ends with "exit"; one that could not start (EAGAIN, EMFILE, ENOENT) only
236
+ // with "error". Either way it is gone once, and its file is refused.
237
+ let gone = false;
238
+ const end = (code: number | null, signal: NodeJS.Signals | null, error?: unknown) => {
239
+ if (gone) return;
240
+ gone = true;
241
+ clearTimeout(entry.idle);
242
+ const index = children.indexOf(entry);
243
+ if (index !== -1) children.splice(index, 1);
244
+ alive.delete(entry);
245
+ markReady();
246
+ markGone();
247
+ const job = entry.job;
248
+ entry.job = undefined;
249
+ if (job) {
250
+ const reason = entry.killedFor ?? (error !== undefined ? unstarted(job, error) : entry.started ? deathOf(entry, job, code, signal) : undefined);
251
+ if (reason !== undefined) job.reject(reason);
252
+ // A child that stopped before it was ready wrote why on its standard error, which may come
253
+ // after "exit": its end is waited for, a second at most.
254
+ else afterStderr(child, () => job.reject(notStarted(entry, job, code, signal)));
255
+ }
256
+ pump();
257
+ };
258
+ child.on("exit", (code, signal) => end(code, signal));
259
+ child.on("error", (error) => {
260
+ if (child.pid === undefined) end(null, null, error);
261
+ });
262
+ children.push(entry);
263
+ alive.add(entry);
264
+ return entry;
265
+ }
266
+
267
+ /** The refusal of a file whose reader could not be started. */
268
+ function unstarted(job: Job, error: unknown): IngestError {
269
+ const code = (error as { code?: unknown } | null)?.code;
270
+ return new IngestError("busy", `${job.input.name} could not be read now: a reader could not be started${typeof code === "string" ? ` (${code})` : ""}. Try again in a moment.`, { cause: error, retryAfterMs: BUSY_RETRY_MS });
271
+ }
272
+
273
+ /** The error a child sent back: a system error keeps its code, so it is not told to a user as a file that cannot be read. */
274
+ function childError(message: Extract<ChildMessage, { type: "error" }>): Error {
275
+ const error = new Error(message.message);
276
+ if (message.code !== undefined) Object.assign(error, { code: message.code, ...(message.syscall !== undefined ? { syscall: message.syscall } : {}) });
277
+ return error;
278
+ }
279
+
280
+ /**
281
+ * The error of a file whose child stopped before it was ready, so before it was sent the file: a
282
+ * script that is not there, a Node option it does not know. That is the server's trouble, not the
283
+ * file's, so it is not an `IngestError`: its status is 500, and the upload handler answers with
284
+ * its message. The child's standard error names paths of the server, so it is only the `cause`.
285
+ */
286
+ function notStarted(entry: Child, job: Job, code: number | null, signal: NodeJS.Signals | null): Error {
287
+ const stderr = entry.stderr.trim();
288
+ const cause = new Error(stderr ? `The reader stopped before it was ready. The end of its standard error:\n${stderr}` : "The reader stopped before it was ready, and wrote nothing on its standard error.");
289
+ return Object.assign(new Error(`The server could not start a reader for ${job.input.name} (${signal ?? `exit code ${code}`}).`, { cause }), { status: 500 });
290
+ }
291
+
292
+ /** Why a child process died while it read a file. */
293
+ function deathOf(entry: Child, job: Job, code: number | null, signal: NodeJS.Signals | null): IngestError {
294
+ if (OUT_OF_MEMORY.test(entry.stderr) || signal === "SIGABRT" || code === 134) {
295
+ return new IngestError("out_of_memory", `${job.input.name} needed more memory than is allowed for reading one file (${maxHeapMb} MB). It may be built to exhaust the server, so it is not read. Split it, or save it as plain text, and attach that.`);
296
+ }
297
+ return new IngestError("unreadable", `${job.input.name} could not be read: its reader stopped (${signal ?? `exit code ${code}`}).`);
298
+ }
299
+
300
+ /** Ends the job of a child: settles it, and gives the child the next job, or replaces it. */
301
+ function finish(entry: Child, settle: () => void, kill = false): void {
302
+ const job = entry.job;
303
+ if (!job) return;
304
+ entry.job = undefined;
305
+ job.cancel?.();
306
+ entry.process.channel?.unref();
307
+ settle();
308
+ if (kill || entry.files >= maxFiles) stop(entry);
309
+ pump();
310
+ }
311
+
312
+ /** Kills a child. `reason`: what its job, if it has one, is refused with. */
313
+ function stop(entry: Child, reason?: unknown): void {
314
+ if (reason !== undefined) entry.killedFor = reason;
315
+ const index = children.indexOf(entry);
316
+ if (index !== -1) children.splice(index, 1);
317
+ clearTimeout(entry.idle);
318
+ // A child that could not start has no pid, so no process to signal: its "error" event, on the
319
+ // next tick, ends it (and close() waits for that).
320
+ if (entry.process.pid === undefined) return;
321
+ // An idle child was unref'd: held again, the process lives until its "exit", which close() waits for.
322
+ entry.process.ref();
323
+ entry.process.kill("SIGKILL");
324
+ }
325
+
326
+ /** Gives waiting jobs to idle children, starting new ones up to `concurrency`. */
327
+ function pump(): void {
328
+ while (queue.length > 0) {
329
+ let entry = children.find((child) => !child.job);
330
+ if (!entry) {
331
+ if (children.length >= concurrency) return;
332
+ try {
333
+ entry = spawn();
334
+ } catch (error) {
335
+ // fork can throw at once (out of process slots or file handles): the waiting files are told to try again.
336
+ for (const job of queue.splice(0)) {
337
+ job.cancel?.();
338
+ job.reject(unstarted(job, error));
339
+ }
340
+ return;
341
+ }
342
+ }
343
+ const job = queue.shift()!;
344
+ job.cancel?.();
345
+ start(entry, job);
346
+ }
347
+ for (const child of children) {
348
+ if (child.job || child.idle) continue;
349
+ // An idle child, its channel and its pipe hold the server open no longer.
350
+ child.process.unref();
351
+ child.process.channel?.unref();
352
+ (child.process.stderr as { unref?: () => void } | null)?.unref?.();
353
+ if (idleMs === 0) continue;
354
+ child.idle = setTimeout(() => {
355
+ child.idle = undefined;
356
+ if (!child.job) stop(child);
357
+ }, idleMs);
358
+ child.idle.unref?.();
359
+ }
360
+ }
361
+
362
+ function start(entry: Child, job: Job): void {
363
+ clearTimeout(entry.idle);
364
+ entry.idle = undefined;
365
+ entry.job = job;
366
+ entry.files++;
367
+ entry.process.ref();
368
+ entry.process.channel?.ref();
369
+ (entry.process.stderr as { ref?: () => void } | null)?.ref?.();
370
+ const signal = job.input.signal;
371
+ let timer: ReturnType<typeof setTimeout> | undefined;
372
+ const onAbort = () => stop(entry, signal!.reason);
373
+ const cleanup = () => {
374
+ clearTimeout(timer);
375
+ signal?.removeEventListener("abort", onAbort);
376
+ };
377
+ const { resolve, reject } = job;
378
+ job.resolve = (result) => {
379
+ cleanup();
380
+ resolve(result);
381
+ };
382
+ job.reject = (error) => {
383
+ cleanup();
384
+ reject(error);
385
+ };
386
+ if (signal?.aborted) {
387
+ stop(entry, signal.reason);
388
+ return;
389
+ }
390
+ signal?.addEventListener("abort", onAbort, { once: true });
391
+ if (timeoutMs > 0) {
392
+ timer = setTimeout(() => stop(entry, new IngestError("timeout", `${job.input.name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs);
393
+ }
394
+ const { name, mimeType, format, scannedPages, maxTextBytes, maxPages } = job.input;
395
+ const message: ChildJob = {
396
+ type: "extract",
397
+ id: job.id,
398
+ bytes: job.bytes,
399
+ input: {
400
+ name, mimeType, format,
401
+ ...(scannedPages !== undefined ? { scannedPages } : {}),
402
+ ...(maxTextBytes !== undefined && Number.isFinite(maxTextBytes) ? { maxTextBytes } : {}),
403
+ ...(maxPages !== undefined ? { maxPages } : {}),
404
+ progress: typeof job.input.onProgress === "function",
405
+ },
406
+ ...(options.pdf ? { pdf: options.pdf } : {}),
407
+ };
408
+ entry.ready.then(() => {
409
+ if (entry.job !== job || !entry.process.connected) return;
410
+ entry.process.send(message, (error) => {
411
+ if (error && entry.job === job) stop(entry, new IngestError("unreadable", `${name} could not be read: its reader could not be reached.`, { cause: error }));
412
+ });
413
+ }, () => undefined);
414
+ }
415
+
416
+ const extract: Extractor = (bytes, input) => new Promise<ExtractedText>((resolve, reject) => {
417
+ if (closed) {
418
+ reject(new IngestError("busy", "The server is shutting down. Try again in a moment.", { retryAfterMs: BUSY_RETRY_MS }));
419
+ return;
420
+ }
421
+ input.signal?.throwIfAborted();
422
+ const job: Job = { id: nextId++, bytes, input, resolve, reject };
423
+ const idle = children.some((child) => !child.job) || children.length < concurrency;
424
+ if (!idle && queue.length >= maxQueue) {
425
+ reject(new IngestError("busy", "The server is reading other files right now. Try again in a moment.", { retryAfterMs: BUSY_RETRY_MS }));
426
+ return;
427
+ }
428
+ // A caller that gives up while its file waits takes it out of the queue.
429
+ const signal = input.signal;
430
+ if (signal) {
431
+ const onAbort = () => {
432
+ const index = queue.indexOf(job);
433
+ if (index !== -1) {
434
+ queue.splice(index, 1);
435
+ reject(signal.reason);
436
+ }
437
+ };
438
+ signal.addEventListener("abort", onAbort, { once: true });
439
+ job.cancel = () => signal.removeEventListener("abort", onAbort);
440
+ }
441
+ queue.push(job);
442
+ pump();
443
+ });
444
+
445
+ const formats = options.formats ?? DEFAULT_FORMATS;
446
+ return {
447
+ extractors: Object.fromEntries(formats.map((format) => [format, extract])) as Partial<Record<DocumentFormat, Extractor>>,
448
+ stats: () => ({ running: children.filter((child) => child.job).length, queued: queue.length, children: children.length }),
449
+ async close() {
450
+ closed = true;
451
+ const waiting = queue.splice(0);
452
+ for (const job of waiting) {
453
+ job.cancel?.();
454
+ job.reject(new IngestError("busy", "The server is shutting down. Try again in a moment.", { retryAfterMs: BUSY_RETRY_MS }));
455
+ }
456
+ // Each child is gone once it has exited, or, if it could not start, once its "error" came.
457
+ // Those stopped earlier (replaced, idle) and not yet exited are waited for too.
458
+ const exits = [...alive].map((child) => child.gone);
459
+ for (const child of [...children]) stop(child, new IngestError("busy", "The server is shutting down. Try again in a moment.", { retryAfterMs: BUSY_RETRY_MS }));
460
+ await Promise.all(exits);
461
+ closed = false;
462
+ },
463
+ };
464
+ }