llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
package/src/cache.ts CHANGED
@@ -4,12 +4,22 @@ import type { DocumentMeta } from "./types.js";
4
4
  export type Sized = { readonly memoryBytes: number };
5
5
 
6
6
  /**
7
- * What identifies the contents of a document. A document ID is never reused, but a store can be
8
- * restored from a backup or written by another program: a cached copy is used only while the
9
- * store still describes the same text.
7
+ * Whose a document is: its owner and its scope, as one string. Part of every version of a document
8
+ * kept in memory, so that a copy of one owner's or scope's document is never served to another.
9
+ */
10
+ export function holderOf(meta: DocumentMeta): string {
11
+ return JSON.stringify([meta.owner ?? null, meta.scope ?? null]);
12
+ }
13
+
14
+ /**
15
+ * What identifies the contents of a document. An application's ID (0.9.0) is reused: a document is
16
+ * deleted and another stored under its ID, by another owner or in another scope, possibly within
17
+ * the same millisecond and with a text of the same size. A store can also be restored from a backup
18
+ * or written by another program. So a cached copy is used only while the store still describes the
19
+ * same text, of the same owner and scope.
10
20
  */
11
21
  export function documentVersion(meta: DocumentMeta): string {
12
- return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}`;
22
+ return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}|${holderOf(meta)}`;
13
23
  }
14
24
 
15
25
  /**
@@ -102,6 +112,11 @@ export class DocumentCache<T extends Sized> {
102
112
 
103
113
  /** Drops every entry whose key starts with `prefix`: all the pieces of one document. */
104
114
  deletePrefix(prefix: string): void {
105
- for (const key of [...this.entries.keys()]) if (key.startsWith(prefix)) this.delete(key);
115
+ this.deleteWhere((key) => key.startsWith(prefix));
116
+ }
117
+
118
+ /** Drops every entry whose key passes `test`: one document in every scope, with its pieces. */
119
+ deleteWhere(test: (key: string) => boolean): void {
120
+ for (const key of [...this.entries.keys()]) if (test(key)) this.delete(key);
106
121
  }
107
122
  }
@@ -0,0 +1,294 @@
1
+ // The line citations of an answer, checked against what the tools showed the model. New in 0.10.0.
2
+ import { mergeRanges, type Evidence, type NumberRange } from "./evidence.js";
3
+ import type { DocumentFormat } from "./types.js";
4
+
5
+ /** What `checkCitations` found in an answer (`AskResult.citations`). New in 0.10.0. */
6
+ export type CitationCheck = {
7
+ /** Citations matched to a file and a line. */
8
+ checked: number;
9
+ /** Of those, the ones inside what the tools showed. A file sent whole counts as shown. */
10
+ supported: number;
11
+ /** Citations recognized but not matched: no file name when there are several files, or the row of a workbook. */
12
+ unchecked: number;
13
+ /** The citations of lines the tools did not show: the document's name, and the line. */
14
+ unsupported: Array<{ document: string; line: number }>;
15
+ };
16
+
17
+ /** A citation found in the text: where it is, the lines it names, and whether it names lines or rows. */
18
+ type Cited = { start: number; end: number; from: number; to: number; form: "line" | "row"; bare: boolean };
19
+
20
+ /** Where a file name is written in the text (`from` with its prefix letter, `start` without), and the documents of that name. */
21
+ type Named = { from: number; start: number; end: number; ids: string[] };
22
+
23
+ /**
24
+ * Hebrew points and cantillation marks, which a word may carry ("שׁוּרָה"). Not the maqaf (־), the
25
+ * paseq, the sof pasuq or the nun hafukha, which are punctuation.
26
+ */
27
+ const POINTS = /[֑-ׇֽֿׁׂׅׄ]/gu;
28
+ /** Marks that set the direction of text and show nothing: LRM, RLM, the embeddings and overrides, the isolates, the Arabic letter mark. */
29
+ const DIRECTION_MARKS = /[؜‎‏‪-‮⁦-⁩]/gu;
30
+ /** A text without the marks a model may put in Hebrew or mixed text: what is left is read as a person reads it. */
31
+ const plain = (text: string) => text.replace(POINTS, "").replace(DIRECTION_MARKS, "");
32
+
33
+ /** Not a letter, a digit or "_" before or after: the edge of a word, in any script. */
34
+ const EDGE_BEFORE = String.raw`(?<![\p{L}\p{N}_])`;
35
+ const EDGE_AFTER = String.raw`(?![\p{L}\p{N}_])`;
36
+ /** The second number of a range: "12-14", "12–14", "12־14" (a maqaf), "12 to 14", "12 עד 14". */
37
+ const RANGE_END = String.raw`(?:\s*[-–—־]\s*|\s+(?:to|עד)\s+)`;
38
+ /** "L" or "l", and a space at most, before a line number: "L12", "l12", "L 12". */
39
+ const LINE_LETTER = String.raw`[Ll][  ]?`;
40
+
41
+ /**
42
+ * The forms of a citation, each with the numbers it names:
43
+ * - "L12", "L12-14", "L12-L14", "L 12", "l12": lines, as the tools and the closing request write them;
44
+ * - "line 12", "lines 12-14": lines, in words;
45
+ * - "Row 12": a row, which for a workbook may be Excel's row and not a line;
46
+ * - "שורה 12", "שורות 12-14", with a prefix letter ("בשורה 12") or "מס'": in Hebrew "שורה" is
47
+ * both a line and a row.
48
+ */
49
+ const FORMS: Array<{ pattern: RegExp; form: "line" | "row"; bare: boolean }> = [
50
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}${LINE_LETTER}(\d{1,9})(?:${RANGE_END}(?:${LINE_LETTER})?(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "line", bare: true },
51
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Ll]ines?\s+(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "line", bare: false },
52
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Rr]ows?\s+(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
53
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[בלמוהכש]{0,2}שור(?:ה|ות)\s+(?:(?:מס['׳]?|מספר)\s*)?(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
54
+ ];
55
+
56
+ /** How far, in characters on one line, a file name may be from the citation it goes with. */
57
+ const NAME_DISTANCE = 40;
58
+ /**
59
+ * What ends a clause between a citation and a name: a comma, a semicolon, the end of a sentence, or
60
+ * "and" ("ו" in Hebrew, alone or with a hyphen). A name across one is farther than its characters say.
61
+ */
62
+ const CLAUSE_BREAK = /[,;.!?]|(?<!\p{L})(?:and|ו)(?!\p{L})/iu;
63
+ /**
64
+ * What may stand between a citation and a name after it that it belongs to: "of", "in", "from",
65
+ * "בקובץ", "של" and the like, or only a space when the name carries the prefix letter "ב" or "מ"
66
+ * ("שורה 40 בחשבוניות.csv").
67
+ */
68
+ const INTRODUCED = /^\s*(?:of|in|from|בקובץ|מקובץ|בגיליון|של)\s*$/iu;
69
+ /** A name followed by a comma or a colon and then the citation: "app.log, line 97", "חוזה.docx: שורה 12". */
70
+ const LISTED = /^\s*[,:]\s*$/u;
71
+
72
+ /** A text for a regular expression that matches it as it is. */
73
+ const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
74
+
75
+ /** The index of the first item of `items`, in order of `key`, whose key is `value` or more: `items.length` when none is. */
76
+ function firstFrom<T>(items: T[], key: (item: T) => number, value: number): number {
77
+ let low = 0;
78
+ let high = items.length;
79
+ while (low < high) {
80
+ const middle = (low + high) >>> 1;
81
+ if (key(items[middle]!) < value) low = middle + 1;
82
+ else high = middle;
83
+ }
84
+ return low;
85
+ }
86
+
87
+ /**
88
+ * Every citation of `text`, in order. One place in the text is one citation, of the first form that
89
+ * reads it. The matches of each form come in order, so each is checked only against the citations
90
+ * already kept around it.
91
+ */
92
+ function citationsIn(text: string): Cited[] {
93
+ let kept: Cited[] = [];
94
+ for (const { pattern, form, bare } of FORMS) {
95
+ const added: Cited[] = [];
96
+ // The first citation kept that ends after the start of the match: the only one it may overlap first.
97
+ let next = 0;
98
+ for (const match of text.matchAll(pattern)) {
99
+ const start = match.index;
100
+ const end = start + match[0].length;
101
+ while (next < kept.length && kept[next]!.end <= start) next++;
102
+ if (next < kept.length && kept[next]!.start < end) continue;
103
+ const first = Number(match[1]);
104
+ const second = match[2] === undefined ? first : Number(match[2]);
105
+ if (first < 1 || second < 1) continue;
106
+ added.push({ start, end, from: Math.min(first, second), to: Math.max(first, second), form, bare });
107
+ }
108
+ // The two lists, each in order and apart from the other, made one.
109
+ const merged: Cited[] = [];
110
+ let left = 0;
111
+ let right = 0;
112
+ while (left < kept.length || right < added.length) {
113
+ if (right >= added.length || (left < kept.length && kept[left]!.start < added[right]!.start)) merged.push(kept[left++]!);
114
+ else merged.push(added[right++]!);
115
+ }
116
+ kept = merged;
117
+ }
118
+ return kept;
119
+ }
120
+
121
+ /**
122
+ * Where the documents' names are written in `text`: each name whole, and without its extension
123
+ * when what is left has 3 characters or more ("report" for "report.docx"). A Hebrew prefix letter
124
+ * may come before it ("בדוח.docx"). Where two overlap, the longer one is taken. In order.
125
+ */
126
+ function namesIn(text: string, names: Map<string, string[]>): Named[] {
127
+ const aliases = new Map<string, Set<string>>();
128
+ const alias = (name: string, ids: string[]) => {
129
+ const key = name.toLocaleLowerCase();
130
+ const known = aliases.get(key) ?? new Set<string>();
131
+ for (const id of ids) known.add(id);
132
+ aliases.set(key, known);
133
+ };
134
+ for (const [written, ids] of names) {
135
+ const name = plain(written);
136
+ if (!name.trim()) continue;
137
+ alias(name, ids);
138
+ const dot = name.lastIndexOf(".");
139
+ if (dot >= 3) alias(name.slice(0, dot), ids);
140
+ }
141
+ const hits: Named[] = [];
142
+ for (const [name, ids] of aliases) {
143
+ const pattern = new RegExp(String.raw`${EDGE_BEFORE}(?:[בלמוהכש]{1,2}[-־]?)?(${escaped(name)})${EDGE_AFTER}`, "giud");
144
+ for (const match of text.matchAll(pattern)) {
145
+ const [start, end] = match.indices![1]!;
146
+ hits.push({ from: match.index, start, end, ids: [...ids] });
147
+ }
148
+ }
149
+ hits.sort((left, right) => left.start - right.start || (right.end - right.start) - (left.end - left.start));
150
+ const kept: Named[] = [];
151
+ for (const hit of hits) {
152
+ const last = kept.at(-1);
153
+ if (last && hit.start < last.end) continue;
154
+ kept.push(hit);
155
+ }
156
+ return kept;
157
+ }
158
+
159
+ /**
160
+ * A function that gives the parentheses around a place of `text`, on its line: their start and
161
+ * end, or undefined when it is not inside any. The parentheses and line breaks are found once.
162
+ */
163
+ function parenthesesOf(text: string): (start: number, end: number) => [number, number] | undefined {
164
+ const marks: number[] = [];
165
+ for (let index = 0; index < text.length; index++) {
166
+ const code = text.charCodeAt(index);
167
+ if (code === 0x28 || code === 0x29 || code === 0x0a) marks.push(index);
168
+ }
169
+ return (start, end) => {
170
+ // The mark nearest before the place must open parentheses; the nearest after it must close them.
171
+ const before = firstFrom(marks, (mark) => mark, start) - 1;
172
+ if (before < 0 || text[marks[before]!] !== "(") return undefined;
173
+ const after = firstFrom(marks, (mark) => mark, end);
174
+ return after < marks.length && text[marks[after]!] === ")" ? [marks[before]!, marks[after]! + 1] : undefined;
175
+ };
176
+ }
177
+
178
+ /** True when nothing between `from` and `to` breaks the line, and they are close enough. */
179
+ const near = (text: string, from: number, to: number) => to - from <= NAME_DISTANCE && !text.slice(from, to).includes("\n");
180
+
181
+ /**
182
+ * How far a name is from a citation, in characters, with `NAME_DISTANCE` more when a clause ends
183
+ * between them (`broken`, or a break in what is between). A long gap is not read: it is far.
184
+ */
185
+ function distance(text: string, from: number, to: number, broken: boolean): number {
186
+ if (to - from > 2 * NAME_DISTANCE) return to - from + NAME_DISTANCE;
187
+ return to - from + (broken || CLAUSE_BREAK.test(text.slice(from, to)) ? NAME_DISTANCE : 0);
188
+ }
189
+
190
+ /**
191
+ * The nearer of the name before a citation and the name after it. A name after it introduced as
192
+ * its own ("of x", "בקובץ x", "בx") is its name. A name before it followed by only a comma or a
193
+ * colon ("x, line 97") is as near as its characters say. Otherwise a citation that opens with "ו"
194
+ * ("ושורה 40") starts a clause of its own, and so does a name after it that opens with "ו". When
195
+ * both are as near, the name before.
196
+ */
197
+ function nearer(text: string, cited: Cited, before: Named | undefined, after: Named | undefined): Named | undefined {
198
+ if (!before || !after) return before ?? after;
199
+ const ahead = text.slice(cited.end, after.from);
200
+ // "line 40 of x", "שורה 40 בקובץ x", "שורה 40 בx": the name after is introduced as the citation's.
201
+ if (INTRODUCED.test(ahead) || (/^\s*$/u.test(ahead) && after.from < after.start && (text[after.from] === "ב" || text[after.from] === "מ"))) return after;
202
+ // "x, line 97" and "x: שורה 12": the comma gives the citation to the name before, no clause.
203
+ const back = LISTED.test(text.slice(before.end, cited.start)) ? cited.start - before.end : distance(text, before.end, cited.start, text[cited.start] === "ו");
204
+ const far = distance(text, cited.end, after.from, after.from < after.start && text[after.from] === "ו");
205
+ return far < back ? after : before;
206
+ }
207
+
208
+ /**
209
+ * The name a citation goes with: one inside the same parentheses, else one on its line within
210
+ * `NAME_DISTANCE` characters; of the name before it and the name after it, the nearer.
211
+ */
212
+ function nameOf(text: string, cited: Cited, named: Named[], around: [number, number] | undefined): Named | undefined {
213
+ // The names are in order and apart, so their ends are in order too.
214
+ const following = firstFrom(named, (hit) => hit.start, cited.end);
215
+ const before = named[firstFrom(named, (hit) => hit.end, cited.start + 1) - 1];
216
+ const after = named[following];
217
+ if (around) {
218
+ const inside = nearer(text, cited, before && before.start >= around[0] ? before : undefined, after && after.end <= around[1] ? after : undefined);
219
+ if (inside) return inside;
220
+ }
221
+ return nearer(text, cited, before && near(text, before.end, cited.start) ? before : undefined, after && near(text, cited.end, after.from) ? after : undefined);
222
+ }
223
+
224
+ /**
225
+ * The first line of `from`-`to` that `shown` does not hold, or undefined when it holds them all.
226
+ * `shown` is in order, its ranges apart and not touching (`mergeRanges`).
227
+ */
228
+ function firstNotShown(shown: NumberRange[] | "whole", from: number, to: number): number | undefined {
229
+ if (shown === "whole") return undefined;
230
+ // The range that holds `from`, if any: the last one that starts at or before it.
231
+ const holding = shown[firstFrom(shown, (range) => range[0], from + 1) - 1];
232
+ if (!holding || holding[1] < from) return from;
233
+ return holding[1] >= to ? undefined : holding[1] + 1;
234
+ }
235
+
236
+ /**
237
+ * Finds the line citations of `text` ("(name L12)", "(name L12-14)", "name L12", "line 12", "Row
238
+ * 12", and the Hebrew "שורה 12" and "שורות 12-14") and checks them against `evidence`. `names`
239
+ * gives each document ID's file name, and `formats` its format. Hebrew points and marks of
240
+ * direction in the text are not read.
241
+ *
242
+ * A citation goes with the file name next to it: in the same parentheses, or on the same line
243
+ * within 40 characters. A name after it introduced as its own ("line 40 of x", "בשורה 40 בקובץ
244
+ * x", "שורה 40 בx") is its name. Else, of the name before it and the name after it, the nearer
245
+ * one, where a comma, a semicolon, the end of a sentence or "and" ("ו") between them counts as far,
246
+ * except a comma or colon right after the name before ("x, line 97"). With one file it may have none. A bare "L12"
247
+ * with no name next to it counts only inside parentheses ("(L12)"): "L2 cache" is no citation. A
248
+ * citation is supported when every line it names was shown, by the lines of an evidence entry of
249
+ * that document. An entry with `whole` (a file read whole, or sent whole) and no lines shows every
250
+ * line; one with lines (`[[1, lines]]`) shows those, so a line past the end of the file is not
251
+ * supported. Two documents of one name support it by either. A row ("Row 12", "שורה 12") of a
252
+ * workbook (XLSX) is unchecked: it may be Excel's row, which is not the line. New in 0.10.0.
253
+ */
254
+ export function checkCitations(text: string, evidence: Evidence[], names: Record<string, string>, formats?: Record<string, DocumentFormat>): CitationCheck {
255
+ const check: CitationCheck = { checked: 0, supported: 0, unchecked: 0, unsupported: [] };
256
+ if (typeof text !== "string" || !text) return check;
257
+ const read = plain(text);
258
+ // The name of each document: the one given, else the one its evidence says.
259
+ const nameById = new Map<string, string>(Object.entries(names ?? {}).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
260
+ for (const entry of evidence) if (typeof entry.document === "string" && !nameById.has(entry.documentId)) nameById.set(entry.documentId, entry.document);
261
+ const byName = new Map<string, string[]>();
262
+ for (const [id, name] of nameById) byName.set(name, [...byName.get(name) ?? [], id]);
263
+ // What was shown of each document: its lines, or all of it.
264
+ const shown = new Map<string, NumberRange[] | "whole">();
265
+ for (const entry of evidence) {
266
+ const before = shown.get(entry.documentId);
267
+ if (before === "whole") continue;
268
+ if (entry.whole === true && !Array.isArray(entry.lines)) shown.set(entry.documentId, "whole");
269
+ else if (entry.lines?.length) shown.set(entry.documentId, mergeRanges([...before ?? [], ...entry.lines]));
270
+ }
271
+ const only = nameById.size === 1 ? [...nameById.keys()] : undefined;
272
+ const named = namesIn(read, byName);
273
+ const parentheses = parenthesesOf(read);
274
+ for (const cited of citationsIn(read)) {
275
+ // A part of a file name ("report-L3.docx") is not a citation.
276
+ const overlapping = named[firstFrom(named, (hit) => hit.end, cited.start + 1)];
277
+ if (overlapping && overlapping.start < cited.end) continue;
278
+ const around = parentheses(cited.start, cited.end);
279
+ const hit = nameOf(read, cited, named, around);
280
+ if (!hit && cited.bare && !around) continue;
281
+ const ids = hit?.ids ?? only;
282
+ // A row of a workbook may be Excel's row: there is no line to check it against.
283
+ const lined = ids?.filter((id) => cited.form === "line" || formats?.[id] !== "xlsx");
284
+ if (!lined?.length) {
285
+ check.unchecked++;
286
+ continue;
287
+ }
288
+ check.checked++;
289
+ const missing = lined.map((id) => firstNotShown(shown.get(id) ?? [], cited.from, cited.to));
290
+ if (missing.some((line) => line === undefined)) check.supported++;
291
+ else check.unsupported.push({ document: nameById.get(lined[0]!) ?? lined[0]!, line: missing[0]! });
292
+ }
293
+ return check;
294
+ }
package/src/encoding.ts CHANGED
@@ -506,11 +506,13 @@ function fits(sample: Uint8Array, encoding: string, script: Script): boolean {
506
506
  }
507
507
 
508
508
  /**
509
- * A decoder for an older encoding. Node 20 reads windows-1252 (and its other Latin-1 labels) as
510
- * Latin-1 in a decode call that is not streamed, so 0x80-0x9F come out as control characters
511
- * ("’" as U+0092), until the decoder has been called once streamed: that call is made here.
509
+ * A decoder for an older encoding. Some versions of Node read windows-1252 (and its other Latin-1
510
+ * labels) as Latin-1 in a decode call that is not streamed, so 0x80-0x9F come out as control
511
+ * characters ("’" as U+0092), until the decoder has been called once streamed: that call is made
512
+ * here. Not only Node 20 (20.18.3 and later): Node 22.13.0 brought the same bug
513
+ * (nodejs/node#60888), which 22.23.5 no longer has. Keep the call while such a 22.x is supported.
512
514
  */
513
- function decoderFor(encoding: string, options?: TextDecoderOptions): TextDecoder {
515
+ function decoderFor(encoding: string, options?: ConstructorParameters<typeof TextDecoder>[1]): InstanceType<typeof TextDecoder> {
514
516
  const decoder = new TextDecoder(encoding, options);
515
517
  decoder.decode(new Uint8Array(0), { stream: true });
516
518
  return decoder;
@@ -0,0 +1,290 @@
1
+ // What an error means for an application: one record to choose a status, a retry and words of
2
+ // your own by, in any language. New in 0.9.0.
3
+ import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode, type DocumentScopeErrorCode, type IngestErrorCode } from "./errors.js";
4
+ import { eventErrorOf, isPlainData } from "./events.js";
5
+ import { modelFailureReason } from "./map-reduce.js";
6
+ import { classifyModelError, DocumentsNotFoundError, isModelStatus, ModelRequestError, type ModelErrorKind } from "./model.js";
7
+
8
+ /**
9
+ * What kind of failure an error is (`ErrorInfo.category`):
10
+ * - "ingest": a file `ingest` refused (`IngestError`): `code` says why;
11
+ * - "store": the document store failed just now (`DocumentStoreError`);
12
+ * - "missing": documents that are gone (`DocumentsNotFoundError`), or the chat of a scope that is
13
+ * gone (`DocumentScopeError` "scope_missing");
14
+ * - "model": a model request failed (`ModelRequestError`): `code` is its kind;
15
+ * - "aborted": stopped by a signal (an `AbortError`, or a `TimeoutError` of `AbortSignal.timeout`);
16
+ * - "input": a mistake in the call (a `TypeError` or `RangeError`, or a `DocumentScopeError`
17
+ * "scope_invalid" or "scope_required", and the `EventError` of each): a bug of the server, not
18
+ * of the user;
19
+ * - "unknown": anything else.
20
+ *
21
+ * A switch over every category must handle the categories added in a later version.
22
+ */
23
+ export type ErrorCategory = "ingest" | "store" | "missing" | "model" | "aborted" | "input" | "unknown";
24
+
25
+ /** What `errorInfoOf` tells of an error. New in 0.9.0. */
26
+ export type ErrorInfo = {
27
+ category: ErrorCategory;
28
+ /**
29
+ * More precise than the category, when there is more to say: the `IngestErrorCode` ("too_large",
30
+ * "busy"…), the `ModelErrorKind` ("rate_limit"…), "documents_missing", the `DocumentScopeError`
31
+ * code, "aborted" or "timeout", or the code of the system error behind it ("EIO").
32
+ */
33
+ code?: string;
34
+ /** The HTTP status to answer with: 400 to 599. */
35
+ status: number;
36
+ /** Whether the same call may work when it is made again, later. */
37
+ retryable: boolean;
38
+ /** How long to wait before trying again, in milliseconds, when that is known. */
39
+ retryAfterMs?: number;
40
+ /**
41
+ * Words a user may see, in English. Never a path, a host, a stack or the provider's own words:
42
+ * those stay on the error, for your log. Show your own words for the category and code instead,
43
+ * in your users' language.
44
+ */
45
+ message: string;
46
+ };
47
+
48
+ /** How long to wait after a store failed, before the same call is made again. */
49
+ export const STORE_RETRY_AFTER_MS = 5_000;
50
+ /** How long to wait after a disk was full (`ENOSPC`, `EDQUOT`), before the same call is made again. New in 0.10.0. */
51
+ export const NO_ROOM_RETRY_AFTER_MS = 30_000;
52
+
53
+ /**
54
+ * The codes of system errors that say the server, or a service it needs, could not answer just
55
+ * now: a time limit, a connection that was refused or cut, a name that could not be looked up, too
56
+ * many files open, a busy file or a stale handle on a network volume. The same call may work a
57
+ * moment later. New in 0.10.0: before, they were "unknown", 500, and not retryable.
58
+ */
59
+ export const TRANSIENT_CODES: ReadonlySet<string> = new Set([
60
+ "ETIMEDOUT", "ECONNRESET", "ECONNREFUSED", "EPIPE", "EAI_AGAIN", "EAGAIN", "EBUSY", "EMFILE", "ENFILE", "ESTALE", "EHOSTUNREACH", "ENETUNREACH",
61
+ ]);
62
+ /** The codes of a disk that is full: retryable too, later. New in 0.10.0. */
63
+ export const NO_ROOM_CODES: ReadonlySet<string> = new Set(["ENOSPC", "EDQUOT"]);
64
+
65
+ /** How long to wait before the same call is made again after a system error of `code`, or undefined when it is not one to retry. New in 0.10.0. */
66
+ export function retryAfterOfCode(code: unknown): number | undefined {
67
+ if (typeof code !== "string") return undefined;
68
+ if (TRANSIENT_CODES.has(code)) return STORE_RETRY_AFTER_MS;
69
+ if (NO_ROOM_CODES.has(code)) return NO_ROOM_RETRY_AFTER_MS;
70
+ return undefined;
71
+ }
72
+
73
+ const SOMETHING_WENT_WRONG = "Something went wrong.";
74
+ /**
75
+ * What a user is told of an "unreadable" file, whose message is a parser's or an extractor's of
76
+ * your own (which may name a host): by `errorInfoOf`, and by the upload handlers.
77
+ */
78
+ export const UNREADABLE_MESSAGE = "This file could not be read. It may be damaged, or not of the type its name says.";
79
+ const CHAT_GONE = "This chat no longer exists.";
80
+
81
+ /** The HTTP status of a model error, by its kind: the answer of a server that asked a model for its user. */
82
+ const MODEL_STATUS: Record<ModelErrorKind, number> = {
83
+ context_overflow: 413,
84
+ rate_limit: 429,
85
+ quota: 503,
86
+ timeout: 504,
87
+ unreachable: 502,
88
+ server: 502,
89
+ auth: 500,
90
+ invalid: 500,
91
+ };
92
+ const RETRYABLE_KINDS = new Set<ModelErrorKind>(["rate_limit", "timeout", "unreachable", "server"]);
93
+
94
+ /** Every `DocumentScopeErrorCode`, to read the `code` of an `EventError`. */
95
+ const SCOPE_CODES: Record<DocumentScopeErrorCode, true> = { scope_required: true, scope_invalid: true, scope_missing: true };
96
+ /** Statuses of plain data that say "try again later": too many requests, and a server that could not answer. */
97
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
98
+
99
+ /** Every `IngestErrorCode`, to read the `code` of an `EventError`. */
100
+ const INGEST_CODES: Record<IngestErrorCode, true> = {
101
+ empty: true, too_large: true, too_much_text: true, too_many_pages: true, not_text: true, compressed: true, legacy_office: true,
102
+ encrypted: true, no_text: true, hostile: true, timeout: true, out_of_memory: true, busy: true, missing_dependency: true, unreadable: true, exists: true,
103
+ };
104
+
105
+ const isKind = (value: unknown): value is ModelErrorKind => typeof value === "string" && Object.hasOwn(MODEL_STATUS, value);
106
+ const isStatus = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
107
+ const isWait = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
108
+
109
+ /** The code of a Node system error (one with a `code` and a `syscall`), whose message names paths or hosts. */
110
+ function systemCode(error: object): string | undefined {
111
+ const { code, syscall } = error as { code?: unknown; syscall?: unknown };
112
+ return typeof syscall === "string" && isErrorCode(code) ? code : undefined;
113
+ }
114
+
115
+ /**
116
+ * The kind of a model error: its own, or the one its status (0, or 400 to 599), message and code
117
+ * give (an error of an adapter of your own), as its `EventError` and its message have it.
118
+ */
119
+ function modelKindOf(error: object): ModelErrorKind | undefined {
120
+ const { kind, status, message, code } = error as { kind?: unknown; status?: unknown; message?: unknown; code?: unknown };
121
+ if (isKind(kind)) return kind;
122
+ if (ModelRequestError.is(error) || isModelStatus(status)) {
123
+ return classifyModelError(typeof status === "number" ? status : 0, typeof message === "string" ? message : "", { code: typeof code === "string" ? code : undefined }).kind;
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ /**
129
+ * The code in the library's own words for a system error, as an `EventError` holds them: "The
130
+ * file could not be read from storage (ELOOP)." of `ingest.error` and `run.error`, "Upload failed
131
+ * (ENOSPC)." of the upload handlers' `ingest.error`. The error itself has the code: its event, only
132
+ * these words.
133
+ */
134
+ function codeInWords(message: unknown): string | undefined {
135
+ const code = typeof message === "string" ? /^(?:The file could not be read from storage|Upload failed) \(([A-Z][A-Z0-9_]{0,31})\)\.$/.exec(message)?.[1] : undefined;
136
+ return isErrorCode(code) ? code : undefined;
137
+ }
138
+
139
+ /**
140
+ * Whether `message` is the library's own words for a model's error of `kind`, with any status:
141
+ * "The model was busy (HTTP 429).". An `EventError` holds them, and the upload handlers' names the
142
+ * provider's status in them and the answer's in `status` ("The model failed on its side (HTTP
143
+ * 503).", 502): they are kept. Any other words, a provider's, are not.
144
+ */
145
+ function isModelWords(kind: ModelErrorKind, message: unknown): message is string {
146
+ if (typeof message !== "string") return false;
147
+ const status = /\(HTTP (\d{1,3})\)\.$/.exec(message)?.[1];
148
+ return message === modelFailureReason({ kind, ...(status !== undefined ? { status: Number(status) } : {}) });
149
+ }
150
+
151
+ /** A refused file, from an `IngestError` or the `EventError` of one. */
152
+ function ingestInfo(code: string, status: unknown, retryAfterMs: unknown, message: unknown): ErrorInfo {
153
+ return {
154
+ category: "ingest",
155
+ code,
156
+ status: isStatus(status) ? status : 422,
157
+ retryable: code === "busy",
158
+ ...(code === "busy" && isWait(retryAfterMs) ? { retryAfterMs } : {}),
159
+ // An unreadable file has the parser's message, or that of an extractor of your own: not words for a user.
160
+ message: code === "unreadable" || typeof message !== "string" || !message ? UNREADABLE_MESSAGE : message,
161
+ };
162
+ }
163
+
164
+ const storeInfo = (code: unknown, message: string): ErrorInfo => ({
165
+ category: "store",
166
+ // As the store's message does, a code is given only when it reads as one.
167
+ ...(isErrorCode(code) ? { code } : {}),
168
+ status: 503,
169
+ retryable: true,
170
+ retryAfterMs: STORE_RETRY_AFTER_MS,
171
+ message,
172
+ });
173
+
174
+ /**
175
+ * A scope that cannot be used: a chat that is gone, or a scope the server should have given, or
176
+ * given right (its bug, not the user's). Its own words are not used: a store of your own wrote them.
177
+ */
178
+ function scopeInfo(code: unknown): ErrorInfo {
179
+ if (code === "scope_missing") return { category: "missing", code: "scope_missing", status: 404, retryable: false, message: CHAT_GONE };
180
+ const known = typeof code === "string" && Object.hasOwn(SCOPE_CODES, code);
181
+ return { category: "input", ...(known ? { code } : {}), status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
182
+ }
183
+
184
+ /**
185
+ * An `EventError`: the plain data of `run.error`, `request.end`, `retry` and `ingest.error`, which
186
+ * the library made from an error with words safe to show. It is read by its `name` and `code`;
187
+ * a model error by its `kind`, below, as any error with one. Undefined for other data.
188
+ */
189
+ function eventInfoOf(record: { name?: unknown; code?: unknown; kind?: unknown; status?: unknown; message?: unknown }): ErrorInfo | undefined {
190
+ const { name, code, kind, status, message } = record;
191
+ if (typeof message !== "string" || kind !== undefined) return undefined;
192
+ // `ingest.error` of the upload handler has no name for a refused file.
193
+ if (typeof code === "string" && Object.hasOwn(INGEST_CODES, code) && (name === undefined || name === "IngestError")) return ingestInfo(code, status, undefined, message);
194
+ if (name === "DocumentStoreError") return storeInfo(undefined, message || "The document store could not be used. Try again.");
195
+ if (name === "DocumentsNotFoundError") return { category: "missing", code: "documents_missing", status: 404, retryable: false, message: message || "A document is no longer available. Upload it again." };
196
+ if (name === "DocumentScopeError") return scopeInfo(code);
197
+ // A mistake in the call, as the error itself is read (`ingest.error` of a TypeError of ingest).
198
+ if (name === "TypeError" || name === "RangeError") return inputInfo();
199
+ return undefined;
200
+ }
201
+
202
+ /** A `TypeError` or `RangeError`: a mistake in the call, the server's bug and not the user's. */
203
+ const inputInfo = (): ErrorInfo => ({ category: "input", status: 500, retryable: false, message: SOMETHING_WENT_WRONG });
204
+
205
+ function infoOf(error: unknown): ErrorInfo {
206
+ if (IngestError.is(error)) return ingestInfo(error.code, error.status, error.retryAfterMs, error.message);
207
+ // Written to be shown: the operation and a code, never a path or a host.
208
+ if (DocumentStoreError.is(error)) return storeInfo(error.code, eventErrorOf(error).message);
209
+ if (DocumentsNotFoundError.is(error)) {
210
+ return { category: "missing", code: "documents_missing", status: 404, retryable: false, message: eventErrorOf(error).message };
211
+ }
212
+ if (DocumentScopeError.is(error)) return scopeInfo(error.code);
213
+ if (typeof error !== "object" || error === null) return { category: "unknown", status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
214
+ const { name, retryAfterMs } = error as { name?: unknown; retryAfterMs?: unknown };
215
+ if (name === "AbortError") return { category: "aborted", code: "aborted", status: 503, retryable: true, message: "It was stopped before it finished." };
216
+ if (name === "TimeoutError") return { category: "aborted", code: "timeout", status: 504, retryable: true, message: "It took too long, and was stopped. Try again." };
217
+ const plain = isPlainData(error);
218
+ if (plain) {
219
+ const fromEvent = eventInfoOf(error);
220
+ if (fromEvent) return fromEvent;
221
+ // Plain data without a `kind` is not a model's error: an `EventError` of one always has its
222
+ // kind. The `ingest.error` of the upload handler for a hook that failed ({ message, status })
223
+ // keeps its status, and that of a system error its code.
224
+ const { kind, status, message } = error as { kind?: unknown; status?: unknown; message?: unknown };
225
+ if (typeof kind !== "string") return plainInfo(error, status, systemCode(error) ?? codeInWords(message));
226
+ }
227
+ const kind = modelKindOf(error);
228
+ if (kind !== undefined) {
229
+ const { message } = error as { message?: unknown };
230
+ return {
231
+ category: "model",
232
+ code: kind,
233
+ status: MODEL_STATUS[kind],
234
+ retryable: RETRYABLE_KINDS.has(kind),
235
+ ...(isWait(retryAfterMs) ? { retryAfterMs } : {}),
236
+ // By its kind and status, never in the provider's words (eventErrorOf). The library's own
237
+ // words, in an EventError, are kept.
238
+ message: plain && isModelWords(kind, message) ? message : eventErrorOf(error).message,
239
+ };
240
+ }
241
+ if (error instanceof TypeError || error instanceof RangeError) return inputInfo();
242
+ return plainInfo(error, undefined);
243
+ }
244
+
245
+ /**
246
+ * Anything else: "unknown", with the code of a system error (of its event, from the library's
247
+ * words), never its message. `status`, of plain data, is kept when it is one of an error (400 to
248
+ * 599), and says whether to retry. Since 0.10.0 a code that says the server could not answer just
249
+ * now (`TRANSIENT_CODES`) is 503 and retryable, with 5 s to wait, and one of a full disk
250
+ * (`NO_ROOM_CODES`) the same with 30 s, whatever status the data holds.
251
+ */
252
+ function plainInfo(error: object, status: unknown, code = systemCode(error)): ErrorInfo {
253
+ const retryAfterMs = retryAfterOfCode(code);
254
+ if (code && retryAfterMs !== undefined) {
255
+ return {
256
+ category: "unknown",
257
+ code,
258
+ status: 503,
259
+ retryable: true,
260
+ retryAfterMs,
261
+ message: NO_ROOM_CODES.has(code) ? `The server has no room right now (${code}). Try again later.` : `The server could not do this just now (${code}). Try again in a moment.`,
262
+ };
263
+ }
264
+ return {
265
+ category: "unknown",
266
+ ...(code ? { code } : {}),
267
+ status: isStatus(status) ? status : 500,
268
+ retryable: RETRY_STATUSES.has(status as number),
269
+ message: code ? `Something went wrong (${code}).` : SOMETHING_WENT_WRONG,
270
+ };
271
+ }
272
+
273
+ /**
274
+ * What an error of the library means, for an application that tells its users in its own words:
275
+ * its category and code, the HTTP status to answer with, whether to retry it, and a message in
276
+ * English that is safe to show (never a path, a host, a stack or a provider's words). It reads
277
+ * the errors of every copy of the package (two versions side by side, or one bundled), and the
278
+ * `EventError` of an event (`run.error`, `ingest.error`, the upload handlers' `ingest.error` too),
279
+ * by its `code`, `name` and `kind`, keeping the words the library wrote. Plain data with none of
280
+ * them is "unknown", with its status. It never throws: what it cannot read is "unknown". New in
281
+ * 0.9.0.
282
+ */
283
+ export function errorInfoOf(error: unknown): ErrorInfo {
284
+ try {
285
+ return infoOf(error);
286
+ } catch {
287
+ // An error whose fields throw when read (a getter, a proxy).
288
+ return { category: "unknown", status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
289
+ }
290
+ }