llm-large-files 0.7.0 → 0.8.1

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 (196) hide show
  1. package/CHANGELOG.md +370 -1
  2. package/README.md +12 -8
  3. package/dist/aggregate.d.ts +103 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +651 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/analyze.d.ts +3 -1
  8. package/dist/analyze.d.ts.map +1 -1
  9. package/dist/analyze.js +109 -14
  10. package/dist/analyze.js.map +1 -1
  11. package/dist/anthropic/adapter.d.ts.map +1 -1
  12. package/dist/anthropic/adapter.js +4 -1
  13. package/dist/anthropic/adapter.js.map +1 -1
  14. package/dist/ask.d.ts +3 -3
  15. package/dist/ask.d.ts.map +1 -1
  16. package/dist/ask.js +72 -17
  17. package/dist/ask.js.map +1 -1
  18. package/dist/decode.d.ts +19 -0
  19. package/dist/decode.d.ts.map +1 -0
  20. package/dist/decode.js +97 -0
  21. package/dist/decode.js.map +1 -0
  22. package/dist/errors.d.ts +55 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js +65 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/events.d.ts +6 -0
  27. package/dist/events.d.ts.map +1 -1
  28. package/dist/events.js +5 -1
  29. package/dist/events.js.map +1 -1
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +23 -0
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +12 -18
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +82 -746
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts.map +1 -1
  38. package/dist/gemini/adapter.js +9 -5
  39. package/dist/gemini/adapter.js.map +1 -1
  40. package/dist/gemini/endpoints.d.ts +5 -1
  41. package/dist/gemini/endpoints.d.ts.map +1 -1
  42. package/dist/gemini/endpoints.js +11 -2
  43. package/dist/gemini/endpoints.js.map +1 -1
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +20 -3
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/groups.d.ts +54 -0
  48. package/dist/groups.d.ts.map +1 -0
  49. package/dist/groups.js +136 -0
  50. package/dist/groups.js.map +1 -0
  51. package/dist/html.d.ts +11 -0
  52. package/dist/html.d.ts.map +1 -0
  53. package/dist/html.js +1112 -0
  54. package/dist/html.js.map +1 -0
  55. package/dist/index.d.ts +2 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/library.d.ts.map +1 -1
  60. package/dist/library.js +57 -14
  61. package/dist/library.js.map +1 -1
  62. package/dist/limiter.d.ts +2 -1
  63. package/dist/limiter.d.ts.map +1 -1
  64. package/dist/limiter.js +3 -2
  65. package/dist/limiter.js.map +1 -1
  66. package/dist/model.d.ts.map +1 -1
  67. package/dist/model.js +8 -1
  68. package/dist/model.js.map +1 -1
  69. package/dist/node/handlers.d.ts.map +1 -1
  70. package/dist/node/handlers.js +69 -15
  71. package/dist/node/handlers.js.map +1 -1
  72. package/dist/node/index.d.ts +2 -0
  73. package/dist/node/index.d.ts.map +1 -1
  74. package/dist/node/index.js +1 -0
  75. package/dist/node/index.js.map +1 -1
  76. package/dist/node/ingest-child.d.ts +38 -0
  77. package/dist/node/ingest-child.d.ts.map +1 -0
  78. package/dist/node/ingest-child.js +42 -0
  79. package/dist/node/ingest-child.js.map +1 -0
  80. package/dist/node/isolated.d.ts +88 -0
  81. package/dist/node/isolated.d.ts.map +1 -0
  82. package/dist/node/isolated.js +381 -0
  83. package/dist/node/isolated.js.map +1 -0
  84. package/dist/office.d.ts +105 -0
  85. package/dist/office.d.ts.map +1 -0
  86. package/dist/office.js +1092 -0
  87. package/dist/office.js.map +1 -0
  88. package/dist/openai/adapter.d.ts.map +1 -1
  89. package/dist/openai/adapter.js +15 -1
  90. package/dist/openai/adapter.js.map +1 -1
  91. package/dist/pdf-pages.d.ts.map +1 -1
  92. package/dist/pdf-pages.js +2 -6
  93. package/dist/pdf-pages.js.map +1 -1
  94. package/dist/peers.d.ts +8 -0
  95. package/dist/peers.d.ts.map +1 -0
  96. package/dist/peers.js +32 -0
  97. package/dist/peers.js.map +1 -0
  98. package/dist/plan.d.ts +3 -1
  99. package/dist/plan.d.ts.map +1 -1
  100. package/dist/plan.js +17 -1
  101. package/dist/plan.js.map +1 -1
  102. package/dist/quality.d.ts +16 -0
  103. package/dist/quality.d.ts.map +1 -0
  104. package/dist/quality.js +157 -0
  105. package/dist/quality.js.map +1 -0
  106. package/dist/ranged.d.ts.map +1 -1
  107. package/dist/ranged.js +4 -2
  108. package/dist/ranged.js.map +1 -1
  109. package/dist/search.d.ts +99 -22
  110. package/dist/search.d.ts.map +1 -1
  111. package/dist/search.js +744 -140
  112. package/dist/search.js.map +1 -1
  113. package/dist/text-index.d.ts +3 -1
  114. package/dist/text-index.d.ts.map +1 -1
  115. package/dist/text-index.js +3 -1
  116. package/dist/text-index.js.map +1 -1
  117. package/dist/text.d.ts +27 -3
  118. package/dist/text.d.ts.map +1 -1
  119. package/dist/text.js +225 -23
  120. package/dist/text.js.map +1 -1
  121. package/dist/tools.d.ts +9 -0
  122. package/dist/tools.d.ts.map +1 -1
  123. package/dist/tools.js +457 -16
  124. package/dist/tools.js.map +1 -1
  125. package/dist/types.d.ts +23 -3
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/word-styles.d.ts +102 -0
  128. package/dist/word-styles.d.ts.map +1 -0
  129. package/dist/word-styles.js +419 -0
  130. package/dist/word-styles.js.map +1 -0
  131. package/dist/xlsx.d.ts +23 -0
  132. package/dist/xlsx.d.ts.map +1 -0
  133. package/dist/xlsx.js +511 -0
  134. package/dist/xlsx.js.map +1 -0
  135. package/dist/xml-stream.d.ts +55 -0
  136. package/dist/xml-stream.d.ts.map +1 -0
  137. package/dist/xml-stream.js +235 -0
  138. package/dist/xml-stream.js.map +1 -0
  139. package/docs/README.md +8 -8
  140. package/docs/getting-started.md +1 -1
  141. package/docs/guides/costs-and-limits.md +7 -5
  142. package/docs/guides/deployment.md +95 -29
  143. package/docs/guides/errors-and-reliability.md +23 -10
  144. package/docs/guides/pdfs.md +127 -74
  145. package/docs/guides/storage.md +1 -1
  146. package/docs/guides/testing.md +5 -1
  147. package/docs/guides/web-app.md +10 -9
  148. package/docs/how-it-works.md +80 -50
  149. package/docs/reference/ask.md +26 -8
  150. package/docs/reference/errors-and-retries.md +5 -3
  151. package/docs/reference/events.md +14 -6
  152. package/docs/reference/gemini.md +6 -2
  153. package/docs/reference/library.md +221 -79
  154. package/docs/reference/node.md +201 -23
  155. package/docs/reference/openai.md +1 -1
  156. package/docs/reference/tools.md +269 -23
  157. package/docs/security.md +114 -69
  158. package/docs/troubleshooting.md +40 -20
  159. package/package.json +6 -2
  160. package/src/aggregate.ts +674 -0
  161. package/src/analyze.ts +117 -13
  162. package/src/anthropic/adapter.ts +4 -1
  163. package/src/ask.ts +73 -17
  164. package/src/decode.ts +89 -0
  165. package/src/errors.ts +108 -0
  166. package/src/events.ts +10 -1
  167. package/src/evidence.ts +23 -0
  168. package/src/extract.ts +79 -701
  169. package/src/gemini/adapter.ts +9 -5
  170. package/src/gemini/endpoints.ts +12 -2
  171. package/src/gemini/generate.ts +19 -3
  172. package/src/groups.ts +162 -0
  173. package/src/html.ts +1071 -0
  174. package/src/index.ts +2 -1
  175. package/src/library.ts +52 -14
  176. package/src/limiter.ts +6 -1
  177. package/src/model.ts +8 -1
  178. package/src/node/handlers.ts +66 -16
  179. package/src/node/index.ts +2 -0
  180. package/src/node/ingest-child.ts +61 -0
  181. package/src/node/isolated.ts +464 -0
  182. package/src/office.ts +1047 -0
  183. package/src/openai/adapter.ts +14 -1
  184. package/src/pdf-pages.ts +2 -5
  185. package/src/peers.ts +29 -0
  186. package/src/plan.ts +19 -1
  187. package/src/quality.ts +146 -0
  188. package/src/ranged.ts +4 -2
  189. package/src/search.ts +738 -146
  190. package/src/text-index.ts +4 -2
  191. package/src/text.ts +214 -23
  192. package/src/tools.ts +440 -16
  193. package/src/types.ts +20 -3
  194. package/src/word-styles.ts +420 -0
  195. package/src/xlsx.ts +478 -0
  196. package/src/xml-stream.ts +224 -0
@@ -0,0 +1,235 @@
1
+ /**
2
+ * A small XML reader for the parts of Office files: tags with their attributes, and the text
3
+ * between them, from XML that may come in pieces as it is unpacked. It keeps one tag at a time, so
4
+ * the memory it holds does not grow with the XML. It is not a validating parser: Office files are
5
+ * machine-written, and what matters here is that a hostile one cannot make it slow or large.
6
+ */
7
+ /** A tag is read up to this many characters; a longer one is refused: no tag of an Office file comes near. */
8
+ const MAX_TAG_CHARACTERS = 64 * 1024;
9
+ /** Decodes the five XML entities and character references. */
10
+ export function decodeEntities(value) {
11
+ if (!value.includes("&"))
12
+ return value;
13
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity) => {
14
+ const lower = entity.toLowerCase();
15
+ if (lower === "amp")
16
+ return "&";
17
+ if (lower === "lt")
18
+ return "<";
19
+ if (lower === "gt")
20
+ return ">";
21
+ if (lower === "quot")
22
+ return "\"";
23
+ if (lower === "apos")
24
+ return "'";
25
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
26
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
27
+ });
28
+ }
29
+ /** White space, as XML and HTML count it between attributes. */
30
+ const isSpace = (code) => code === 32 || code === 9 || code === 10 || code === 13 || code === 12;
31
+ /**
32
+ * The attributes in the inside of a tag, after its name: `name="value"` or `name='value'`, in one
33
+ * pass. A regular expression backtracked from every position of a tag with no "=": a 64 K tag
34
+ * took 6.5 s. A name without a value, or with an unquoted one (HTML's `href=x`), is read too.
35
+ */
36
+ export function parseAttributes(inside) {
37
+ const attributes = Object.create(null);
38
+ const length = inside.length;
39
+ let at = 0;
40
+ while (at < length) {
41
+ while (at < length && (isSpace(inside.charCodeAt(at)) || inside[at] === "/"))
42
+ at++;
43
+ const start = at;
44
+ while (at < length && !isSpace(inside.charCodeAt(at)) && inside[at] !== "=" && inside[at] !== "/" && inside[at] !== ">")
45
+ at++;
46
+ const name = inside.slice(start, at);
47
+ while (at < length && isSpace(inside.charCodeAt(at)))
48
+ at++;
49
+ if (inside[at] !== "=") {
50
+ if (name)
51
+ attributes[name] = "";
52
+ if (at === start)
53
+ at++;
54
+ continue;
55
+ }
56
+ at++;
57
+ while (at < length && isSpace(inside.charCodeAt(at)))
58
+ at++;
59
+ const quote = inside[at];
60
+ let value;
61
+ if (quote === "\"" || quote === "'") {
62
+ const end = inside.indexOf(quote, at + 1);
63
+ value = inside.slice(at + 1, end === -1 ? length : end);
64
+ at = end === -1 ? length : end + 1;
65
+ }
66
+ else {
67
+ const begin = at;
68
+ while (at < length && !isSpace(inside.charCodeAt(at)) && inside[at] !== ">")
69
+ at++;
70
+ value = inside.slice(begin, at);
71
+ }
72
+ if (name)
73
+ attributes[name] = decodeEntities(value);
74
+ }
75
+ return attributes;
76
+ }
77
+ /**
78
+ * Reads XML given in pieces with `write`, and calls the handlers as tags and text go past.
79
+ * Comments, processing instructions and declarations are skipped; the text of a CDATA section is
80
+ * given as text. It reads in one loop, with no recursion, whatever the number of tags in a piece.
81
+ */
82
+ export class XmlStream {
83
+ handlers;
84
+ state = "text";
85
+ /**
86
+ * What is kept from the last piece, to be read again in front of the next one: the inside of a
87
+ * tag read so far, the start of a "<!" that cannot be told yet, or the last two characters of a
88
+ * comment or CDATA section, where its end mark may start.
89
+ */
90
+ kept = "";
91
+ /** In a tag: how much of `kept` has been scanned, and the quote of the attribute value it is in. */
92
+ scanned = 0;
93
+ quote = 0;
94
+ constructor(handlers) {
95
+ this.handlers = handlers;
96
+ }
97
+ write(piece) {
98
+ const xml = this.kept + piece;
99
+ const length = xml.length;
100
+ // In a tag, the inside starts at 0 and has been scanned up to `scanned`.
101
+ let tagStart = 0;
102
+ let at = this.state === "tag" ? this.scanned : 0;
103
+ this.kept = "";
104
+ this.scanned = 0;
105
+ while (at < length) {
106
+ if (this.state === "text") {
107
+ const start = xml.indexOf("<", at);
108
+ if (start === -1) {
109
+ // An entity cut at the end of the piece ("&am" + "p;") is read with the next piece.
110
+ const amp = xml.lastIndexOf("&");
111
+ const cut = amp >= at && length - amp <= MAX_ENTITY && !xml.includes(";", amp) ? amp : length;
112
+ if (cut > at)
113
+ this.handlers.text?.(decodeEntities(xml.slice(at, cut)));
114
+ this.kept = xml.slice(cut);
115
+ return;
116
+ }
117
+ if (start > at)
118
+ this.handlers.text?.(decodeEntities(xml.slice(at, start)));
119
+ const rest = xml.slice(start + 1, start + 9);
120
+ if (rest.startsWith("!--")) {
121
+ this.state = "comment";
122
+ at = start + 4;
123
+ }
124
+ else if (rest.startsWith("![CDATA[")) {
125
+ this.state = "cdata";
126
+ at = start + 9;
127
+ }
128
+ else if (rest.length < 8 && (CDATA_START.startsWith(rest) || COMMENT_START.startsWith(rest))) {
129
+ // Too little is known to tell a comment or CDATA from a tag: wait for the next piece.
130
+ this.kept = xml.slice(start);
131
+ return;
132
+ }
133
+ else {
134
+ this.state = "tag";
135
+ this.quote = 0;
136
+ tagStart = start + 1;
137
+ at = tagStart;
138
+ }
139
+ continue;
140
+ }
141
+ if (this.state === "comment" || this.state === "cdata") {
142
+ const mark = this.state === "comment" ? "-->" : "]]>";
143
+ const end = xml.indexOf(mark, at);
144
+ const stop = end === -1 ? Math.max(at, length - 2) : end;
145
+ if (this.state === "cdata" && stop > at)
146
+ this.handlers.text?.(xml.slice(at, stop));
147
+ if (end === -1) {
148
+ this.kept = xml.slice(stop);
149
+ return;
150
+ }
151
+ this.state = "text";
152
+ at = end + 3;
153
+ continue;
154
+ }
155
+ // In a tag: on to its ">", outside quotes.
156
+ let end = at;
157
+ for (; end < length; end++) {
158
+ const code = xml.charCodeAt(end);
159
+ if (this.quote !== 0) {
160
+ if (code === this.quote)
161
+ this.quote = 0;
162
+ }
163
+ else if (code === 34 || code === 39) {
164
+ this.quote = code;
165
+ }
166
+ else if (code === 62) {
167
+ break;
168
+ }
169
+ }
170
+ if (end - tagStart > MAX_TAG_CHARACTERS) {
171
+ throw new Error("The XML has a tag far longer than any Office file writes. It may be built to exhaust the server, so it is not read.");
172
+ }
173
+ if (end === length) {
174
+ this.kept = xml.slice(tagStart);
175
+ this.scanned = this.kept.length;
176
+ return;
177
+ }
178
+ this.state = "text";
179
+ at = end + 1;
180
+ this.tagRead(xml.slice(tagStart, end));
181
+ }
182
+ }
183
+ tagRead(inside) {
184
+ const first = inside.charCodeAt(0);
185
+ // <?xml ... ?> and <!DOCTYPE ...>: nothing to read.
186
+ if (first === 63 || first === 33)
187
+ return;
188
+ if (first === 47) {
189
+ this.handlers.close?.(inside.slice(1).trim());
190
+ return;
191
+ }
192
+ const empty = inside.charCodeAt(inside.length - 1) === 47;
193
+ const body = empty ? inside.slice(0, -1) : inside;
194
+ const space = body.search(/\s/);
195
+ const name = space === -1 ? body : body.slice(0, space);
196
+ this.handlers.open?.(name, space === -1 ? Object.create(null) : parseAttributes(body.slice(space)), empty);
197
+ }
198
+ }
199
+ /** The longest entity read: "&#x10FFFF;". */
200
+ const MAX_ENTITY = 10;
201
+ const COMMENT_START = "!--";
202
+ const CDATA_START = "![CDATA[";
203
+ /** Reads a whole piece of XML with `XmlStream`. */
204
+ export function readXml(xml, handlers) {
205
+ new XmlStream(handlers).write(xml);
206
+ }
207
+ /** The relationships of an Office part (`_rels/….rels`): target by ID, made absolute from `base`, the folder of the part. */
208
+ export function readRelationships(xml, base) {
209
+ const relationships = new Map();
210
+ if (!xml)
211
+ return relationships;
212
+ readXml(xml, {
213
+ open(name, attributes) {
214
+ if (name !== "Relationship" || !attributes.Id || !attributes.Target)
215
+ return;
216
+ const external = attributes.TargetMode === "External";
217
+ relationships.set(attributes.Id, { target: external ? attributes.Target : resolvePart(base, attributes.Target), type: attributes.Type ?? "", external });
218
+ },
219
+ });
220
+ return relationships;
221
+ }
222
+ /** A target of a relationship as a part name: `../notesSlides/notesSlide1.xml` from `ppt/slides` is `ppt/notesSlides/notesSlide1.xml`. */
223
+ export function resolvePart(base, target) {
224
+ if (target.startsWith("/"))
225
+ return target.slice(1);
226
+ const parts = base ? base.split("/") : [];
227
+ for (const piece of target.split("/")) {
228
+ if (piece === "..")
229
+ parts.pop();
230
+ else if (piece !== "." && piece !== "")
231
+ parts.push(piece);
232
+ }
233
+ return parts.join("/");
234
+ }
235
+ //# sourceMappingURL=xml-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xml-stream.js","sourceRoot":"","sources":["../src/xml-stream.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,8GAA8G;AAC9G,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AAarC,8DAA8D;AAC9D,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IACvC,OAAO,KAAK,CAAC,OAAO,CAAC,4CAA4C,EAAE,CAAC,KAAK,EAAE,MAAc,EAAE,EAAE;QAC3F,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;QACnC,IAAI,KAAK,KAAK,KAAK;YAAE,OAAO,GAAG,CAAC;QAChC,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,GAAG,CAAC;QAC/B,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,GAAG,CAAC;QAC/B,IAAI,KAAK,KAAK,MAAM;YAAE,OAAO,IAAI,CAAC;QAClC,IAAI,KAAK,KAAK,MAAM;YAAE,OAAO,GAAG,CAAC;QACjC,MAAM,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,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AI,EAAE,UAAU;YACnB,IAAI,IAAI,KAAK,cAAc,IAAI,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,MAAM;gBAAE,OAAO;YAC5E,MAAM,QAAQ,GAAG,UAAU,CAAC,UAAU,KAAK,UAAU,CAAC;YACtD,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,IAAI,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC3J,CAAC;KACF,CAAC,CAAC;IACH,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,0IAA0I;AAC1I,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,MAAc;IACtD,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnD,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1C,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACtC,IAAI,KAAK,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;aAC3B,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,EAAE;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5D,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC"}
package/docs/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # llm-large-files documentation
2
2
 
3
3
  `llm-large-files` lets a language model answer questions about files larger than its context window
4
- or its request size limit: logs, books and other text, CSV, JSON, Word, PowerPoint and PDF files. A
5
- file that fits goes into the prompt whole; a larger one becomes a short card, and the model
6
- searches it, reads line ranges, reads all of it in parts or looks at the pages of a PDF, in one
7
- tool loop that works with Gemini and Vertex AI, OpenAI-compatible endpoints, Claude or a model of
8
- your own. This page is the map: where to start, which entry point to use, the words the other pages
9
- use, and every page in one line.
4
+ or its request size limit: logs, books and other text, CSV, JSON, HTML, Word, PowerPoint, Excel and
5
+ PDF files. A file that fits goes into the prompt whole; a larger one becomes a short card, and the
6
+ model searches it, reads line ranges, reads all of it in parts or looks at the pages of a PDF, in
7
+ one tool loop that works with Gemini and Vertex AI, OpenAI-compatible endpoints, Claude or a model
8
+ of your own. This page is the map: where to start, which entry point to use, the words the other
9
+ pages use, and every page in one line.
10
10
 
11
11
  ## Start here
12
12
 
@@ -252,7 +252,7 @@ import from.
252
252
 
253
253
  | Import from | Reference | What is there |
254
254
  |---|---|---|
255
- | `llm-large-files` | [The library and its documents](./reference/library.md) | `createLargeFiles`, `LargeFiles` and its options, the budget, stores, extractors, document types, text helpers |
255
+ | `llm-large-files` | [The library and its documents](./reference/library.md) | `createLargeFiles`, `LargeFiles` and its options, `IngestError`, the budget, stores, extractors, document types, text helpers |
256
256
  | | [The tool loop and the adapter contract](./reference/ask.md) | `askWithFiles`, its options, limits and result, conversation types, the `ModelAdapter` contract, usage, evidence |
257
257
  | | [Errors, retries and streams](./reference/errors-and-retries.md) | `ModelRequestError` and error kinds, `withRetry`, timeouts, `parseSseJson` |
258
258
  | | [Tools](./reference/tools.md) | each tool the model sees: name, arguments, results, limits; `ToolSet` and its types |
@@ -260,7 +260,7 @@ import from.
260
260
  | `llm-large-files/gemini` | [Gemini](./reference/gemini.md) | `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()` and the other Gemini exports |
261
261
  | `llm-large-files/openai` | [OpenAI-compatible](./reference/openai.md) | `openAiCompatible()` and the other OpenAI exports |
262
262
  | `llm-large-files/anthropic` | [Claude](./reference/anthropic.md) | `anthropic()` and the other Anthropic exports |
263
- | `llm-large-files/node` | [Node HTTP handlers](./reference/node.md) | `createDocumentHandlers`: routes, requests, responses and statuses; `writeSseEvents` and `sseMessageOf`, events as Server-Sent Events |
263
+ | `llm-large-files/node` | [Node HTTP handlers](./reference/node.md) | `createDocumentHandlers`: routes, requests, responses and statuses; `createIsolatedExtractors`, files read in child processes; `writeSseEvents` and `sseMessageOf`, events as Server-Sent Events |
264
264
 
265
265
  ## Internals and measurements
266
266
 
@@ -24,7 +24,7 @@ npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
24
24
 
25
25
  | Package | What it enables |
26
26
  | --- | --- |
27
- | `jszip` | DOCX and PPTX files. |
27
+ | `jszip` | DOCX, PPTX and XLSX files. |
28
28
  | `unpdf` | PDF files: their text, with tables rebuilt as rows. |
29
29
  | `@cantoo/pdf-lib` | The model can look at the pages of a PDF (`view_pages`, with `keepOriginals`). The text of a PDF also marks the pages that show a picture. |
30
30
 
@@ -72,10 +72,10 @@ export async function ask(userId: string, documentIds: string[], question: strin
72
72
  **No limit throws.** A question that reaches a limit ends with a request for the answer, written
73
73
  from what the tools returned so far. That request usually ends with `FINAL_ANSWER_REQUEST`: "Stop
74
74
  using tools now. Answer my question using only what the tools returned above, with line citations.
75
- Say plainly what you could not find." When no tool ran (for example with `toolTurns: 1` or
76
- `requests: 1`), it ends with `FINAL_ANSWER_WITHOUT_TOOLS` instead. When pages were the only thing
77
- to look at, it ends with `FINAL_ANSWER_AFTER_PAGES`. `answered` is true when the reply has text and
78
- was not refused.
75
+ Say plainly what you could not find. Answer in the language of my question." When no tool ran (for
76
+ example with `toolTurns: 1` or `requests: 1`), it ends with `FINAL_ANSWER_WITHOUT_TOOLS` instead.
77
+ When pages were the only thing to look at, it ends with `FINAL_ANSWER_AFTER_PAGES`. `answered` is
78
+ true when the reply has text and was not refused.
79
79
 
80
80
  - **The answer is asked for once more when it comes back without text**: empty, or with a tool call
81
81
  the model was told not to make. The note "Your last reply had no text. No tool can be called in
@@ -325,7 +325,9 @@ The documents are planned before the first request, with the scale the adapters
325
325
  question, the input tokens each provider reports raise the loop's estimate of each request's size,
326
326
  and so leave less room, when they are higher than the scale says (up to twice the estimate). The
327
327
  latest report counts: a lower one brings the estimate back down, but never below what the scale
328
- says. A scale set too low makes requests that the provider can refuse as too large. A scale set too
328
+ says, nor, since 0.7.1, below what a request the provider refused as too large showed (up to 8
329
+ times the estimate, for the rest of the question: see
330
+ [a request too large for the model](../how-it-works.md#a-request-too-large-for-the-model)). A scale set too low makes requests that the provider can refuse as too large. A scale set too
329
331
  high leaves part of the window unused.
330
332
 
331
333
  To find the scale of an OpenAI-compatible model, compare its count of a sample of a file like the
@@ -98,7 +98,7 @@ The built-in stores:
98
98
  | Searches of documents read by range | A few MB each: `scanChunkBytes` (1 MB) of text read, decoded and lowercased, and the next piece read ahead | `maxConcurrentScans` (4) per `LargeFiles`. The others wait, and those waiting for the same file share one pass over it |
99
99
  | Decoded pieces of a document read by range | Up to its whole decoded text | Kept within `cacheBytes`, and only for a document whose decoded text takes at most a quarter of it |
100
100
  | An upload | The body, buffered whole | `maxUploadBytes`, 100 MB by default |
101
- | An ingest | Several copies of the text at once (below), and what the parsers of PDF, DOCX and PPTX take while they read. A crafted PDF can make them take far more: one of 732 bytes ran a heap of 512 MB out of memory, and one of 1.6 KB took 1.6 GB of memory outside the heap, with 20 MB of heap, for a stream that unpacks to 512 MB ([Security](../security.md#uploads)) | `maxTextBytes` bounds the text (100 MB by default). Nothing bounds what the PDF parsers build or unpack. One at a time, or in a process of its own with a memory limit of its own (below) |
101
+ | An ingest | Several copies of the text at once (below), and what the parsers of PDF, DOCX, PPTX and XLSX take while they read. A crafted PDF can make them take far more: one of 732 bytes ran a heap of 512 MB out of memory, and one of 1.6 KB took 1.6 GB of memory outside the heap, with 20 MB of heap, for a stream that unpacks to 512 MB ([Security](../security.md#uploads)) | `maxTextBytes` bounds the text (100 MB by default). Nothing in the server bounds what the parsers build or unpack: read PDF and Office files with `createIsolatedExtractors`, in child processes with a heap limit of their own, or ingest in a process of its own with a memory limit of its own (below) |
102
102
  | A look at the pages of a PDF (`view_pages`) | The whole original, read and parsed: about twice the size of the file, plus 1 to 1.6 KB for each object in it (about 300 MB for a 100 MB file of photos, 700 MB for 54 MB of 330,000 objects). A crafted file can take far more: a look at a PDF of 8 MB that is one array of numbers took 422 to 427 MB of heap, one of 16 MB ran a heap of 512 MB out of memory, and one at the PDF of 1.6 KB above took 1.1 GB outside the heap. What `@cantoo/pdf-lib` keeps after a look adds up from file to file, until the server restarts | Refused for a file that declares more than 1,000,000 objects, or more objects than about 60% of the free heap can hold. A crafted file of few objects passes that check. Ingested in a process of its own (below), with `@cantoo/pdf-lib` installed, a file that needs more than that process's heap fails there and is not stored; one that fits is parsed again by each look, which takes more than its ingest did (232 to 244 MB for that file of 8 MB). For the documents of users you do not trust, `viewPages: false`, or no PDF originals |
103
103
  | A question in flight | Its conversation, and each request it builds: up to `maxRequestBytes` (10 MB by default) of JSON, the pages it was shown included as base64 | The budget ([Costs and limits](./costs-and-limits.md)) |
104
104
 
@@ -116,9 +116,10 @@ more than 150,000 objects; the marks are also given up when finding the pictures
116
116
  [measurements](../measurements.md).
117
117
 
118
118
  Set the heap limit of Node yourself: about three quarters of the memory of the container when
119
- everything runs in one process, less when ingest runs in a process of its own. The limit is more
120
- than the flag. `--max-old-space-size` sets the old generation, and Node adds its young generation
121
- above it: 48 MB on Node 20 and 22, 192 MB on Node 24, and 96 MB on Node 26.
119
+ everything runs in one process, less when files are read in child processes
120
+ (`createIsolatedExtractors`) or ingest runs in a process of its own: each has a heap of its own. The
121
+ limit is more than the flag. `--max-old-space-size` sets the old generation, and Node adds its young
122
+ generation above it: 48 MB on Node 20 and 22, 192 MB on Node 24, and 96 MB on Node 26.
122
123
  `v8.getHeapStatistics().heap_size_limit` gives the sum. For three quarters of 2 GB, a limit of
123
124
  1,536 MB:
124
125
 
@@ -143,13 +144,14 @@ its own: one forked with `execArgv: ["--max-old-space-size=512"]` had 560 MB on
143
144
  environment it inherits or without it.
144
145
 
145
146
  A starting point for a container of 2 GB, to check under your own load. The heaps are heap limits,
146
- not flags:
147
+ not flags. `maxHeapMb` of `createIsolatedExtractors` is the flag of its children, so it takes the
148
+ numbers of the last column:
147
149
 
148
- | Node | Main heap of 1 GB | Ingest heap of 512 MB |
150
+ | Node | Main heap of 1 GB | Heap of 512 MB for the child that reads a file |
149
151
  |---|---|---|
150
- | 20 and 22 | `--max-old-space-size=976` | `--max-old-space-size=464` |
151
- | 24 | `--max-old-space-size=832` | `--max-old-space-size=320` |
152
- | 26 | `--max-old-space-size=928` | `--max-old-space-size=416` |
152
+ | 20 and 22 | `--max-old-space-size=976` | `--max-old-space-size=464`, `maxHeapMb: 464` |
153
+ | 24 | `--max-old-space-size=832` | `--max-old-space-size=320`, `maxHeapMb: 320` |
154
+ | 26 | `--max-old-space-size=928` | `--max-old-space-size=416`, `maxHeapMb: 416` |
153
155
 
154
156
  The flags 1024 and 512 give heap limits of 1,216 and 704 MB on Node 24: 1,920 MB, which leaves
155
157
  about 128 MB of the container for the upload, its copy, files read from the store and two Node
@@ -158,11 +160,17 @@ processes. On Node 20 and 22 they give 1,072 and 560 MB.
158
160
  ```ts
159
161
  // large-files.ts: created once per process and imported by every route.
160
162
  // Run with a heap of 1 GB: NODE_OPTIONS=--max-old-space-size=832 on Node 24 (the table above has
161
- // the others). Ingests run in a process of their own (below).
163
+ // the others). PDF and Office files are read in a child process (below).
162
164
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
165
+ import { createIsolatedExtractors } from "llm-large-files/node";
166
+
167
+ // One file at a time, in a child with a heap limit of 512 MB on Node 24. Call isolated.close() when
168
+ // the server stops, next to server.close() (Stopping a server, below).
169
+ export const isolated = createIsolatedExtractors({ maxHeapMb: 320, concurrency: 1 });
163
170
 
164
171
  export const files = createLargeFiles({
165
172
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
173
+ extractors: isolated.extractors, // PDF, DOCX, PPTX and XLSX
166
174
  keepOriginals: ["pdf"], // view_pages: a look reads the whole PDF into this heap
167
175
  cacheBytes: 256 * 1024 * 1024, // the default
168
176
  maxConcurrentScans: 4, // the default
@@ -172,9 +180,9 @@ export const files = createLargeFiles({
172
180
 
173
181
  | Where 2 GB go | |
174
182
  |---|---|
175
- | The main heap, 1 GB | The cache (256 MB), the questions in flight, a look at the pages of a PDF |
176
- | One ingest at a time, in a process with a heap of 512 MB | An ingest of a 95 MB log fitted in a heap of 256 MB. A process takes about 50 MB more for Node itself |
177
- | Outside the heaps | The upload being read (up to 100 MB) and its copy sent to the ingest process, files read from the store, Node itself. Also what the PDF parsers unpack, which no heap limit bounds: a crafted PDF of 1.6 KB took 1.6 GB at ingest and 1.1 GB at a look, far more than this row has left. For uploads you do not trust, give the ingest process a container of its own, and do not offer `view_pages` on their documents |
183
+ | The main heap, 1 GB | The cache (256 MB), the questions in flight, a look at the pages of a PDF, and the ingests: the text and its copies (an ingest of a 95 MB log fitted in a heap of 256 MB) |
184
+ | One PDF or Office file at a time, read in a child process with a heap of 512 MB | What the parsers take. A process takes about 50 MB more for Node itself |
185
+ | Outside the heaps | The upload being read (up to 100 MB) and its copy sent to the child process, files read from the store, Node itself. Also what the PDF parsers unpack, which no heap limit bounds: a crafted PDF of 1.6 KB took 1.6 GB at ingest and 1.1 GB at a look, far more than this row has left. For uploads you do not trust, ingest in a container of its own, and do not offer `view_pages` on their documents |
178
186
 
179
187
  Raise `cacheBytes` to spend memory on speed: at 1 GB, the decoded pieces of an ASCII log of up to
180
188
  about 125 MB are kept between searches. Lower `maxUploadBytes` if large uploads are not needed:
@@ -206,8 +214,9 @@ The first PDF a process reads also loads the PDF parsers, in one block that no p
206
214
  about 0.4 s for `@cantoo/pdf-lib` and 0.05 s for pdf.js, measured on Node 24. Since 0.6.0 it loads
207
215
  `@cantoo/pdf-lib` even with `pictures: false`, for the page check. An app that reads PDFs with
208
216
  `createPdfExtractor({ pictures: false, checkPages: false })` does not load it at ingest, but then no
209
- page is checked ([PDFs](./pdfs.md#pages-that-would-hold-the-server)). Load them when the server
210
- starts, before it takes requests:
217
+ page is checked ([PDFs](./pdfs.md#pages-that-would-hold-the-server)). With
218
+ `createIsolatedExtractors` (below), each child process loads them for itself, and the server is not
219
+ held while it does. Otherwise, load them when the server starts, before it takes requests:
211
220
 
212
221
  ```ts
213
222
  // Before the server listens: the first upload of a PDF then does not hold it while they load.
@@ -223,15 +232,23 @@ What it does not do is keep its memory apart. The text and its copies, and what
223
232
  `@cantoo/pdf-lib` and JSZip take while they read, are in your server's heap, with the cache and the
224
233
  questions in flight. A file that needs more than the heap has left stops the whole process, and
225
234
  every answer streaming on it. A step under way, such as one slow page of a PDF, also runs to its
226
- end after the time limit. Three ways to bound that:
227
-
228
- - **Accept one or two ingests at a time** per server, and answer the others with 503 (the sample
229
- below does it): this bounds memory and keeps stalls from adding up.
230
- - **Ingest in a process of its own**, with a heap limit and a time limit: below. A process that
231
- runs out of memory stops alone, and the upload is answered with an error. The heap limit does not
232
- bound what a parser unpacks outside the heap: a crafted PDF of 1.6 KB took 1.6 GB that way
233
- ([Security](../security.md#uploads)). For uploads you do not trust, give that process a memory
234
- limit of its own too, such as a container or a cgroup of its own, or use a service of its own.
235
+ end after the time limit. Four ways to bound that:
236
+
237
+ - **Read PDF and Office files in child processes**, with `createIsolatedExtractors` from
238
+ `llm-large-files/node` (new in 0.8.0), as `large-files.ts` above does: below. Start here. The
239
+ parsers run in a child process with a heap flag (`maxHeapMb`, 512 by default: a heap limit of 560
240
+ to 704 MB, depending on the version of Node, as the tables above show) and a kill timer (120 s),
241
+ and a file that runs the child out of memory is refused while the server goes on.
242
+ - **Accept one or two ingests at a time** per server, and answer the others with 503: this bounds
243
+ memory and keeps stalls from adding up. `createIsolatedExtractors` does it for the files it reads
244
+ (`concurrency` and `maxQueue`); the recipe at the end of this section does it for whole ingests.
245
+ - **Ingest in a process of its own**, the whole ingest, with a heap limit and a time limit: at the
246
+ end of this section. It also keeps the copies of the text off your server's heap, and runs an
247
+ extractor of your own, such as OCR, apart. A process that runs out of memory stops alone, and the
248
+ upload is answered with an error. The heap limit does not bound what a parser unpacks outside the
249
+ heap: a crafted PDF of 1.6 KB took 1.6 GB that way ([Security](../security.md#uploads)). For
250
+ uploads you do not trust, give that process a memory limit of its own too, such as a container
251
+ or a cgroup of its own, or use a service of its own.
235
252
  - **Ingest in a service of its own.** All the state is in the store, so an upload service with its
236
253
  own `createLargeFiles` and `createDocumentHandlers`, on servers sized for uploads, can write the
237
254
  documents that the chat servers read. Give it the options that apply at ingest, the same as the
@@ -240,6 +257,30 @@ end after the time limit. Three ways to bound that:
240
257
  options that apply to reading: `cacheBytes`, `cacheSize`, `wholeDocumentBytes`, `scanChunkBytes`,
241
258
  `maxConcurrentScans` and `budget`.
242
259
 
260
+ **Child processes for the parsers.** With the `extractors` of `createIsolatedExtractors`, each PDF,
261
+ DOCX, PPTX or XLSX file is copied to a child process, read there by the built-in extractor, and its
262
+ text sent back; the text is then normalized, profiled, indexed and stored in your server, as
263
+ before. Text files, HTML included, are read in the server, in slices. What a file can do from there:
264
+
265
+ - run its child out of memory: the child stops, and the file is refused with an `IngestError` of
266
+ code `"out_of_memory"` (`422`, "report.pdf needed more memory than is allowed for reading one
267
+ file (320 MB). …"); the next file gets a new child;
268
+ - take longer than `timeoutMs` (120 s): its child is killed, also in the middle of a PDF page, and
269
+ the file is refused as `"timeout"`;
270
+ - arrive while `concurrency` files are read and `maxQueue` wait: it is refused at once as `"busy"`,
271
+ which the upload handler answers `503` with `Retry-After: 5`.
272
+
273
+ A child reads one file at a time, is replaced after 50 files (what `@cantoo/pdf-lib` keeps goes
274
+ with it) and stops after 30 s with nothing to read. `maxHeapMb` is the flag of the children, not
275
+ their heap limit: Node adds its young generation above it, as the tables above show. The server's
276
+ `NODE_OPTIONS` are not passed to the children, so the server's own heap flag does not replace
277
+ theirs, as it does a worker's. The limit bounds the heap only: a PDF that unpacks a stream outside
278
+ the heap takes the memory of the container all the same. For uploads you do not trust, give the
279
+ server a memory limit with that in mind, or ingest in a container or a service of its own. Call
280
+ `isolated.close()` when the server stops ([below](#stopping-a-server)), and read `isolated.stats()`
281
+ for a health check. Every option and refusal:
282
+ [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions).
283
+
243
284
  **Not a worker thread.** For uploads you do not trust, the security page of 0.5.0 suggested a
244
285
  worker thread or a separate process, and a draft of this guide on GitHub, before 0.6.0, ran each
245
286
  ingest in a worker thread
@@ -249,14 +290,23 @@ loop free, but it does not bound memory. The process's heap flag replaces the wo
249
290
  as that draft set it, that worker had 1,216 MB on Node 24, not 512. And a worker that runs out of
250
291
  memory can take the whole process down with it: in the 0.6 review, on the code before this release
251
292
  ([Measurements](../measurements.md#how-to-read-this-page)), a worker of 512 MB, with no heap flag
252
- on the process, did so on a hostile DOCX. A child process stops alone.
293
+ on the process, did so on a hostile DOCX. A child process stops alone, which is why
294
+ `createIsolatedExtractors` uses them.
253
295
 
254
- A process that runs one ingest, with the options of `large-files.ts` above:
296
+ **The whole ingest in a process of its own.** For an extractor of your own that should not run in
297
+ the server (`createIsolatedExtractors` runs the built-in ones), or to keep the copies of the text
298
+ off its heap too, fork a process for each ingest. A process that runs one ingest, with the options
299
+ of `large-files.ts` above that apply at ingest, and the built-in extractors, since the process
300
+ itself is the isolation:
255
301
 
256
302
  ```ts
257
303
  // ingest-process.ts: one ingest, in a process of its own, forked by documents.ts below.
258
- import type { IngestInput } from "llm-large-files";
259
- import { files } from "./large-files.js"; // the same options as the chat routes
304
+ import { createLargeFiles, FileDocumentStore, type IngestInput } from "llm-large-files";
305
+
306
+ const files = createLargeFiles({
307
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
308
+ keepOriginals: ["pdf"],
309
+ });
260
310
 
261
311
  process.once("message", async (message) => {
262
312
  try {
@@ -529,6 +579,10 @@ export function stopOnSigterm(server: Server, graceMs = 25_000): void {
529
579
 
530
580
  Abort with an `Error`, as here, not a string: `partialResultOf` needs an object to look the
531
581
  question up by. An upload cut by the restart leaves files that the sweep removes an hour later.
582
+ With [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
583
+ `isolated.close()` when the grace period ends, next to `stopping.abort`: it kills its child
584
+ processes, and refuses the files still waiting or being read as `"busy"` (503 "The server is
585
+ shutting down. Try again in a moment.").
532
586
 
533
587
  After a restart the cache is empty: the first tool calls read their documents from the store again,
534
588
  and a thinking model's first whole-file read in the new process may spend one request finding the
@@ -607,6 +661,18 @@ same conversations.
607
661
  - **Bundlers.** The optional packages below are loaded with a dynamic `import()` when they are
608
662
  first needed. A bundle of your server must keep them resolvable at run time: mark them external,
609
663
  and install them next to the bundle.
664
+ [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions) starts its
665
+ children with `ingest-child.js`, which it looks for next to its own module: in a bundle, that is
666
+ next to the bundle, where it is not. Mark `llm-large-files` external too, or install it next to
667
+ the bundle and point at its script, which imports the rest of the package and cannot be copied
668
+ alone:
669
+
670
+ ```ts
671
+ const isolated = createIsolatedExtractors({ childScript: import.meta.resolve("llm-large-files/node/ingest-child.js") });
672
+ ```
673
+
674
+ A child that cannot start fails each file with a 500, `The server could not start a reader for
675
+ report.pdf (exit code 1).`, and the child's standard error as its `cause`.
610
676
 
611
677
  ## Optional dependencies in production images
612
678
 
@@ -617,7 +683,7 @@ optional peer dependencies. Add the ones you need to the `dependencies` of your
617
683
  | Package | Version | Needed for | Without it |
618
684
  |---|---|---|---|
619
685
  | `unpdf` | `^1.4.0 \|\| ^2.0.0`, in a version that runs on your Node: 1.7.0 on Node 20, a 1.x from 1.6.1 on Node 22, any on Node 24 and later ([PDFs](./pdfs.md#formats)) | The text of PDFs | The upload is refused: `Reading PDF files needs the optional dependency "unpdf".` (422 from `createDocumentHandlers`). A version that does not run on your Node is refused too, with a message that says what to install: `The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` |
620
- | `jszip` | `^3.10.0` | DOCX and PPTX | The upload is refused: `Reading DOCX and PPTX files needs the optional dependency "jszip".` |
686
+ | `jszip` | `^3.10.0` | DOCX, PPTX and XLSX | The upload is refused: `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
621
687
  | `@cantoo/pdf-lib` | `^2.11.1` | `view_pages`, the check of PDF pages that would hold the server, and the marks on PDF pages that show a picture | `view_pages` answers the model `report.pdf: Showing PDF pages needs the optional dependency "@cantoo/pdf-lib".` (with the file's name), and PDFs are ingested without the check and without the marks, with no error |
622
688
 
623
689
  The last one fails quietly at ingest, so an image without it ingests PDFs differently from your
@@ -327,7 +327,10 @@ When the abort comes just after a request failed, that request's error may be th
327
327
  test which signal aborted, as above, not the error.
328
328
 
329
329
  `partialResultOf(error)` works for a stopped question too, when the reason is an object. Abort with
330
- an `Error`, or with no reason, rather than a string. Its `usage` is what was counted when the
330
+ an `Error`, or with no reason, rather than a string. When several questions share the signal, they
331
+ all throw the same reason, and `partialResultOf` gives none of them a result for it (since 0.7.1;
332
+ before, each got the result of the one that failed last): give each question an `AbortController`
333
+ of its own that the shared signal aborts with a new reason. Its `usage` is what was counted when the
331
334
  question stopped: a request still running then, in an adapter that did not stop, may be billed by
332
335
  the provider, and is not counted.
333
336
 
@@ -599,11 +602,16 @@ export async function askAndRecord(model: ModelAdapter, sessionId: string) {
599
602
 
600
603
  ## Errors of uploads and of the store
601
604
 
602
- `files.ingest` throws a plain `Error`, with a message written for the user, when it cannot take a
603
- file: it is empty, larger than `maxUploadBytes` (100 MB by default), has no text, is a gzip or ZIP
604
- archive, is binary, needs an optional dependency that is not installed (`jszip` for DOCX and PPTX,
605
- `unpdf` for PDF) or an `unpdf` that runs on this Node, or is a PDF without a text layer (see
606
- [PDFs](./pdfs.md)). Show its message. A text file is never refused for its encoding: one that is
605
+ `files.ingest` throws an [`IngestError`](../reference/library.md#ingesterror), with a message
606
+ written for the user and a `code` for your app, when it cannot take a file: it is empty
607
+ (`"empty"`), larger than `maxUploadBytes` (100 MB by default, `"too_large"`), has no text
608
+ (`"no_text"`), is a gzip or ZIP archive (`"compressed"`), is binary (`"not_text"`), is an Office
609
+ file of before 2007 or with a password (`"legacy_office"`), needs an optional dependency that is not
610
+ installed (`jszip` for DOCX, PPTX and XLSX, `unpdf` for PDF) or an `unpdf` that runs on this Node
611
+ (`"missing_dependency"`: the setup of the server, not the file, as in "The unpdf installed cannot
612
+ read PDF files on Node 20 (…). …"), or is a PDF without a text layer (see [PDFs](./pdfs.md)). Show
613
+ its message, or words of your own for its `code`. Until 0.8.0 it was a plain `Error`, with the same
614
+ message. A text file is never refused for its encoding: one that is
607
615
  not UTF-8 is read in the encoding it was saved in, or as UTF-8 with the characters that are not
608
616
  valid counted ([Text encodings](./pdfs.md#text-encodings)).
609
617
 
@@ -612,10 +620,15 @@ the file. `createDocumentHandlers` answers it 500 `{ "error": "Upload failed (em
612
620
  `{ "error": "Upload failed (owner is not a string)." }` for an owner that is neither a string nor a
613
621
  finite number, before it reads the upload ([Storage](./storage.md#how-ownership-works)).
614
622
 
615
- A file the parser cannot read (a damaged DOCX, PPTX or PDF) throws the parser's own error (jszip's,
616
- or pdf.js's `InvalidPDFException`), and an extractor of your own throws its own. Their messages are
617
- not written for users: show "This file could not be read." for an error whose message you do not
618
- recognise.
623
+ A file the parser cannot read (a damaged DOCX, PPTX, XLSX or PDF) throws an `IngestError` of code
624
+ `"unreadable"` with the parser's message (jszip's, or that of pdf.js's `InvalidPDFException`), and
625
+ the parser's error as `cause`; an extractor of your own that throws an `Error` gets the same, with
626
+ the code its message gives. Those messages are not written for users: show "This file could not
627
+ be read." for the code `"unreadable"`. With `createIsolatedExtractors`, a file whose reader ran out
628
+ of memory or time is `"out_of_memory"` or `"timeout"`, readers that are all busy give `"busy"`,
629
+ answered `503` with `Retry-After`, and a reader that could not start at all (a `childScript` that
630
+ is not there) is not an `IngestError`, but an `Error` with `status` 500
631
+ ([node reference](../reference/node.md#createisolatedextractorsoptions)).
619
632
 
620
633
  A store that fails while it writes throws its own error, as it came: its message may name a path or
621
634
  a host, so log it and show a general message. `createDocumentHandlers` answers a file it cannot take