llm-large-files 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Public types. Everything a consumer touches is defined here, so the package can be
2
2
  // published without exposing internal module layout.
3
3
 
4
- export type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx";
4
+ export type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx" | "xlsx" | "html";
5
5
 
6
6
  export type OutlineEntry = {
7
7
  /** 1-based line number in the extracted text. */
@@ -49,6 +49,19 @@ export type DocumentMeta = {
49
49
  /** Lines longer than the wrap limit are split so every line stays readable by line number. */
50
50
  wrappedLines: number;
51
51
  pages?: number;
52
+ /**
53
+ * The older encoding a text file was read in, because it is not UTF-8: "windows-1255" for a
54
+ * Hebrew CSV that Excel saved. Lines of it that are valid UTF-8 are read as UTF-8 all the same.
55
+ * Absent for valid UTF-8, for a file read as UTF-8 with characters that are not valid (see
56
+ * `replacedCharacters`), for UTF-16, for PDF, DOCX and PPTX, and on documents from before 0.6.0.
57
+ */
58
+ encoding?: string;
59
+ /**
60
+ * Characters of a text file that were not valid in the encoding it was read in, such as a
61
+ * character cut in two at the end of a UTF-8 log, or a byte that `encoding` does not have: each
62
+ * is stored as U+FFFD (�). Absent when there were none, and on documents from before 0.6.0.
63
+ */
64
+ replacedCharacters?: number;
52
65
  /**
53
66
  * True when the uploaded file itself is kept in the store next to its text (see `keepOriginals`).
54
67
  * Recorded here so that planning a request does not have to load the file to know.
@@ -72,6 +85,10 @@ export type DocumentSummary = {
72
85
  lines: number;
73
86
  estimatedTokens: number;
74
87
  pages?: number;
88
+ /** See `DocumentMeta.encoding`. */
89
+ encoding?: string;
90
+ /** See `DocumentMeta.replacedCharacters`. */
91
+ replacedCharacters?: number;
75
92
  expiresAt: string;
76
93
  };
77
94
 
@@ -109,7 +126,17 @@ export interface DocumentStore {
109
126
  getIndex?(id: string): Promise<Uint8Array | undefined>;
110
127
  }
111
128
 
112
- export type ExtractedText = { text: string; pages?: number };
129
+ export type ExtractedText = {
130
+ text: string;
131
+ pages?: number;
132
+ /**
133
+ * The older encoding the file was read in, when it is not UTF-8. Kept as `DocumentMeta.encoding`
134
+ * when it is a name, and not one of UTF-8 or UTF-16.
135
+ */
136
+ encoding?: string;
137
+ /** Characters that were not valid in the encoding the file was read in, each now U+FFFD. Kept as `DocumentMeta.replacedCharacters`. */
138
+ replacedCharacters?: number;
139
+ };
113
140
 
114
141
  export type ExtractInput = {
115
142
  name: string;
@@ -121,6 +148,38 @@ export type ExtractInput = {
121
148
  * always was. An extractor of your own may ignore it.
122
149
  */
123
150
  scannedPages?: number;
151
+ /**
152
+ * Aborted when the ingest's time is up (`ingestTimeoutMs`) or the caller gave up
153
+ * (`IngestInput.signal`). The built-in extractors stop between pages and pieces; its `reason`
154
+ * is the error to throw. An extractor of your own should stop too: `ingest` stops waiting for it
155
+ * either way, but cannot stop the work it does.
156
+ */
157
+ signal?: AbortSignal;
158
+ /**
159
+ * The most text to keep from this file, in UTF-8 bytes (`maxTextBytes`). The built-in extractors
160
+ * refuse a file as soon as its text grows past it. `ingest` refuses any larger result.
161
+ */
162
+ maxTextBytes?: number;
163
+ /** The most pages to read from one PDF (`maxPdfPages`). The built-in PDF extractor refuses more. */
164
+ maxPages?: number;
165
+ /**
166
+ * Call it as the extraction goes on, so `ingest` can report progress (`IngestInput.onEvent`).
167
+ * The built-in extractors call it for each page of a PDF (also for the page check and the
168
+ * picture marks: `stage` "check" and "pictures"), each part of a DOCX or PPTX, and once when a
169
+ * text file not in UTF-8 is decoded ("decode"). Calls after the extractor returned are dropped. An
170
+ * extractor of your own may ignore it. New in 0.7.0.
171
+ */
172
+ onProgress?: (progress: ExtractProgress) => void;
173
+ };
174
+
175
+ /** How far an extraction is, for `ExtractInput.onProgress`. */
176
+ export type ExtractProgress = {
177
+ /** "extract" (the default): text read; "check": pages checked before reading; "pictures": pages looked at for pictures; "decode": bytes of a text file decoded. */
178
+ stage?: "extract" | "check" | "pictures" | "decode";
179
+ done: number;
180
+ /** Absent when not known. */
181
+ total?: number;
182
+ unit: "pages" | "parts" | "bytes";
124
183
  };
125
184
 
126
185
  export type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
@@ -176,7 +235,8 @@ export type ToolOutput = { result: ToolResult; files: ToolFile[] };
176
235
  export type ToolCallLimits = {
177
236
  /**
178
237
  * The most bytes the files of this call may have together. Give the room left in your request,
179
- * times 3/4 when files are sent as base64. Defaults to about a third of `maxRequestBytes`.
238
+ * times 3/4 when files are sent as base64. Defaults to 3/8 of (`maxRequestBytes` − 262,144), the
239
+ * 256 KB the library keeps free in a request taken off first: 3,651,696 bytes for the default budget.
180
240
  */
181
241
  maxFileBytes?: number;
182
242
  /** The most pages this call may show. Lower it as the pages already shown use up your token budget. */
@@ -187,7 +247,49 @@ export type ToolCallLimits = {
187
247
  * says where to go on.
188
248
  */
189
249
  maxResultCharacters?: number;
250
+ /**
251
+ * The most model requests a whole-file read (`analyze_whole_document`) may make: what the
252
+ * question has left of `limits.requests`. A part the model refuses as too large is read as two
253
+ * halves only while that and `maxMapChunks` allow it.
254
+ */
255
+ maxRequests?: number;
256
+ };
257
+ /**
258
+ * Listeners for one tool call, next to its limits. New in 0.7.0: with them, the progress of two
259
+ * whole-file reads that run at once can be told apart.
260
+ */
261
+ export type ToolCallHooks = {
262
+ /** Progress of this call (a whole-file read), in place of `ToolOptions.onProgress` for it. */
263
+ onProgress?: ProgressListener;
264
+ /**
265
+ * Each model request this call makes (a whole-file read), as it starts. Tell the handle it
266
+ * returns about each retry of that request, and when it ends.
267
+ */
268
+ onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
190
269
  };
270
+
271
+ /** One model request of a tool call (`ToolCallHooks.onRequest`). */
272
+ export type ToolRequestHandle = {
273
+ /** The request failed and is sent again after `delayMs`. */
274
+ retry(notice: { attempt: number; delayMs: number; error: unknown }): void;
275
+ /** The request ended, after any retries. Call it once. */
276
+ end(end: ToolRequestEnd): void;
277
+ };
278
+
279
+ /** A model request of a tool call, as it starts (`ToolCallHooks.onRequest`). */
280
+ export type ToolRequestStart = {
281
+ purpose: "part" | "merge" | "final";
282
+ /** "part 3 of 12", "first half of part 3 of 12", "round 2: 1 of 4", "the answer". */
283
+ detail: string;
284
+ };
285
+
286
+ /** A model request of a tool call, as it ends. */
287
+ export type ToolRequestEnd = {
288
+ outcome: "ok" | "error";
289
+ usage?: GenerateUsage;
290
+ error?: unknown;
291
+ };
292
+
191
293
  /** The name of `ToolCallLimits` before 0.5.0. */
192
294
  export type ToolFileLimits = ToolCallLimits;
193
295
 
@@ -203,7 +305,7 @@ export type ToolSet = {
203
305
  * Runs a tool call and also returns the files it produced, to be sent to the model with the
204
306
  * result. Use it in place of `execute` in a loop that can send files.
205
307
  */
206
- executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits): Promise<ToolOutput>;
308
+ executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits, hooks?: ToolCallHooks): Promise<ToolOutput>;
207
309
  /** A short, human-readable line describing a call, for progress UIs. */
208
310
  describe(name: string, args: Record<string, unknown>): string;
209
311
  /**
@@ -230,7 +332,8 @@ export type GenerateText = (request: {
230
332
  onTruncated?: () => void;
231
333
  /**
232
334
  * Call this once for every request that was answered, with the tokens it used, so that the cost
233
- * of a whole-document read is counted. Optional: without it those requests are not in the totals.
335
+ * of a whole-document read is counted. Optional: without it, `askWithFiles` still counts each
336
+ * answered request (in `usage.requests` and against `limits.requests`), but not its tokens.
234
337
  */
235
338
  onUsage?: (usage: GenerateUsage) => void;
236
339
  }) => Promise<string>;
@@ -0,0 +1,420 @@
1
+ import { sliceWhole } from "./text.js";
2
+ import { readXml, type XmlAttributes } from "./xml-stream.js";
3
+
4
+ /**
5
+ * Word's paragraph styles and list numbering, read from `word/styles.xml` and
6
+ * `word/numbering.xml`, so that a paragraph's text can be written with the number Word shows before
7
+ * it ("2.1", "(a)", "ג.") and a heading as a Markdown heading. Without them, "clause 2.2" of a
8
+ * contract cannot be found, and the document has no outline.
9
+ */
10
+
11
+ /** What a paragraph says of itself in its properties (`w:pPr`). */
12
+ export type ParagraphStyle = {
13
+ styleId?: string;
14
+ /** `w:numPr`: the list and its level. A `numId` of "0" takes numbering off. */
15
+ numId?: string;
16
+ ilvl?: number;
17
+ /** `w:outlineLvl`, 0-based: 0 is a top-level heading, 9 is body text. */
18
+ outlineLevel?: number;
19
+ };
20
+
21
+ /**
22
+ * A level of a list: its start, its number format, its number text cut into the text between the
23
+ * numbers and the level of each number (`"%1.%2"` is `[0, ".", 1]`), and whether it writes the
24
+ * numbers of all levels in Arabic digits (`w:isLgl`, Word's "legal style numbering").
25
+ */
26
+ type Level = { start: number; format: string; parts: Array<string | number>; legal: boolean };
27
+ /**
28
+ * A list definition (`w:abstractNum`): its levels, the list style it defines (`w:styleLink`), and
29
+ * the list style it takes its levels from instead (`w:numStyleLink`). Word writes a list made with
30
+ * a list style, as its "1 / 1.1 / 1.1.1" or "Article / Section", as a definition with no levels.
31
+ */
32
+ type ListDefinition = { levels: Level[]; styleLink?: string; numStyleLink?: string };
33
+ /** A list (`w:num`): its definition, and the levels it starts at another number. */
34
+ type Num = { abstractId: string; starts: Map<number, number> };
35
+ type StyleInfo = { name: string; basedOn?: string; numId?: string; ilvl?: number; outlineLevel?: number };
36
+ /** What a paragraph style and the styles it is based on give its paragraphs: a list and level, a heading level, an outline level. */
37
+ type Resolved = { numId?: string; ilvl?: number; heading?: number; outline?: number };
38
+ /** A list as it numbers paragraphs: the definition whose counts it shares, its levels, and its start overrides. */
39
+ type List = { key: string; levels: Level[]; starts: Map<number, number> };
40
+ /**
41
+ * A paragraph counted in its list, as `WordNumbering.count` gives it to `labelOf`: the levels of
42
+ * its list, its level, and the counts of the list.
43
+ */
44
+ type Counted ={ levels: Level[]; level: number; counts: Array<number | undefined> };
45
+
46
+ /** Levels of numbering a list may have in Word. */
47
+ const LEVELS = 9;
48
+ /**
49
+ * The characters of a level's number text kept, and of the number written from it: Word's dialog
50
+ * takes far fewer. Each `%n` of the text may be a Roman numeral of 15 letters, and the number is
51
+ * written before every paragraph of the list.
52
+ */
53
+ const MAX_LABEL = 64;
54
+ /** Links from a list definition to a list style, and on to the definition of that style, followed at most: Word makes one. */
55
+ const MAX_LIST_LINKS = 4;
56
+ const NOTHING: Resolved = {};
57
+
58
+ const attribute = (attributes: XmlAttributes, name: string) => attributes[`w:${name}`] ?? attributes[name];
59
+ const integerOf = (value: string | undefined): number | undefined => {
60
+ if (value === undefined) return undefined;
61
+ const number = Number.parseInt(value, 10);
62
+ return Number.isFinite(number) ? number : undefined;
63
+ };
64
+
65
+ /** A start value of a list, within what Word allows (0 to 32,767): a file may say anything. */
66
+ const startOf = (value: string | undefined): number | undefined => {
67
+ const number = integerOf(value);
68
+ return number === undefined ? undefined : Math.min(32_767, Math.max(0, number));
69
+ };
70
+
71
+ /**
72
+ * Reads `w:style` elements: names, the style each is based on, and the numbering and outline level
73
+ * in its paragraph properties. Paragraph styles and list styles (`w:type="numbering"`, whose list a
74
+ * list definition may take its levels from) are kept apart.
75
+ */
76
+ function readStyles(xml: string | undefined): { styles: Map<string, StyleInfo>; listStyles: Map<string, StyleInfo> } {
77
+ const styles = new Map<string, StyleInfo>();
78
+ const listStyles = new Map<string, StyleInfo>();
79
+ if (!xml) return { styles, listStyles };
80
+ let current: StyleInfo | undefined;
81
+ let inParagraphProperties = 0;
82
+ let inChange = 0;
83
+ readXml(xml, {
84
+ open(name, attributes, empty) {
85
+ if (name === "w:style") {
86
+ const id = attribute(attributes, "styleId");
87
+ const type = attribute(attributes, "type");
88
+ const kept = type === undefined || type === "paragraph" ? styles : type === "numbering" ? listStyles : undefined;
89
+ current = id && kept ? { name: "" } : undefined;
90
+ if (current && id) kept?.set(id, current);
91
+ return;
92
+ }
93
+ if (!current) return;
94
+ if (name === "w:pPrChange" && !empty) inChange++;
95
+ if (inChange > 0) return;
96
+ if (name === "w:pPr" && !empty) inParagraphProperties++;
97
+ else if (name === "w:name") current.name = (attribute(attributes, "val") ?? "").toLowerCase();
98
+ else if (name === "w:basedOn") current.basedOn = attribute(attributes, "val");
99
+ else if (inParagraphProperties > 0 && name === "w:numId") current.numId = attribute(attributes, "val");
100
+ else if (inParagraphProperties > 0 && name === "w:ilvl") current.ilvl = integerOf(attribute(attributes, "val"));
101
+ else if (inParagraphProperties > 0 && name === "w:outlineLvl") current.outlineLevel = integerOf(attribute(attributes, "val"));
102
+ },
103
+ close(name) {
104
+ if (name === "w:style") current = undefined;
105
+ else if (name === "w:pPrChange" && inChange > 0) inChange--;
106
+ else if (name === "w:pPr" && inParagraphProperties > 0) inParagraphProperties--;
107
+ },
108
+ });
109
+ return { styles, listStyles };
110
+ }
111
+
112
+ /** `"%1.%2."` as `[0, ".", 1, "."]`: the text of a level, with the level of each number in it. */
113
+ function partsOf(text: string): Array<string | number> {
114
+ const parts: Array<string | number> = [];
115
+ let from = 0;
116
+ for (const match of text.matchAll(/%([1-9])/g)) {
117
+ if (match.index > from) parts.push(text.slice(from, match.index));
118
+ parts.push(Number(match[1]) - 1);
119
+ from = match.index + match[0].length;
120
+ }
121
+ if (from < text.length) parts.push(text.slice(from));
122
+ return parts;
123
+ }
124
+
125
+ /** Reads `w:abstractNum` and `w:num` elements. */
126
+ function readNumbering(xml: string | undefined): { abstracts: Map<string, ListDefinition>; nums: Map<string, Num> } {
127
+ const abstracts = new Map<string, ListDefinition>();
128
+ const nums = new Map<string, Num>();
129
+ if (!xml) return { abstracts, nums };
130
+ let abstract: ListDefinition | undefined;
131
+ let level: Level | undefined;
132
+ let num: Num | undefined;
133
+ let overrideLevel: number | undefined;
134
+ readXml(xml, {
135
+ open(name, attributes, empty) {
136
+ if (name === "w:abstractNum" && !empty) {
137
+ abstract = { levels: [] };
138
+ const id = attribute(attributes, "abstractNumId");
139
+ if (id !== undefined) abstracts.set(id, abstract);
140
+ } else if (abstract && name === "w:lvl" && !empty) {
141
+ const index = integerOf(attribute(attributes, "ilvl")) ?? 0;
142
+ level = { start: 1, format: "decimal", parts: [index, "."], legal: false };
143
+ if (index >= 0 && index < LEVELS) abstract.levels[index] = level;
144
+ } else if (level && name === "w:start") {
145
+ level.start = startOf(attribute(attributes, "val")) ?? 1;
146
+ } else if (level && name === "w:numFmt") {
147
+ level.format = attribute(attributes, "val") ?? "decimal";
148
+ } else if (level && name === "w:lvlText") {
149
+ // Word writes a few characters here ("%1.%2."); a long one would be copied before every paragraph.
150
+ level.parts = partsOf(sliceWhole(attribute(attributes, "val") ?? "", MAX_LABEL));
151
+ } else if (level && name === "w:isLgl") {
152
+ level.legal = !["0", "false", "off"].includes(attribute(attributes, "val") ?? "");
153
+ } else if (abstract && !level && name === "w:styleLink") {
154
+ abstract.styleLink = attribute(attributes, "val");
155
+ } else if (abstract && !level && name === "w:numStyleLink") {
156
+ abstract.numStyleLink = attribute(attributes, "val");
157
+ } else if (name === "w:num" && !empty) {
158
+ num = { abstractId: "", starts: new Map() };
159
+ const id = attribute(attributes, "numId");
160
+ if (id !== undefined) nums.set(id, num);
161
+ } else if (num && name === "w:abstractNumId") {
162
+ num.abstractId = attribute(attributes, "val") ?? "";
163
+ } else if (num && name === "w:lvlOverride") {
164
+ overrideLevel = integerOf(attribute(attributes, "ilvl"));
165
+ } else if (num && overrideLevel !== undefined && overrideLevel >= 0 && overrideLevel < LEVELS && name === "w:startOverride") {
166
+ const start = startOf(attribute(attributes, "val"));
167
+ if (start !== undefined) num.starts.set(overrideLevel, start);
168
+ }
169
+ },
170
+ close(name) {
171
+ if (name === "w:abstractNum") abstract = undefined;
172
+ else if (name === "w:lvl") level = undefined;
173
+ else if (name === "w:num") num = undefined;
174
+ else if (name === "w:lvlOverride") overrideLevel = undefined;
175
+ },
176
+ });
177
+ return { abstracts, nums };
178
+ }
179
+
180
+ const ROMAN: Array<[number, string]> = [[1000, "m"], [900, "cm"], [500, "d"], [400, "cd"], [100, "c"], [90, "xc"], [50, "l"], [40, "xl"], [10, "x"], [9, "ix"], [5, "v"], [4, "iv"], [1, "i"]];
181
+
182
+ function roman(value: number): string {
183
+ // Roman numerals end at 3999; past it Word writes the number.
184
+ if (value < 1 || value > 3_999) return String(value);
185
+ let rest = value;
186
+ let out = "";
187
+ for (const [size, letters] of ROMAN) {
188
+ while (rest >= size) {
189
+ out += letters;
190
+ rest -= size;
191
+ }
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /** a, b, … z, aa, bb, …: Word repeats the letter. */
197
+ function letters(value: number): string {
198
+ // Past "zzzzzzzzzz" (260) the letters would only grow: the number is written.
199
+ if (value < 1 || value > 260) return String(value);
200
+ const letter = String.fromCharCode(97 + ((value - 1) % 26));
201
+ return letter.repeat(Math.floor((value - 1) / 26) + 1);
202
+ }
203
+
204
+ const HEBREW_ONES = ["", "א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט"];
205
+ const HEBREW_TENS = ["", "י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ"];
206
+ const HEBREW_HUNDREDS = ["", "ק", "ר", "ש", "ת"];
207
+ const HEBREW_LETTERS = "אבגדהוזחטיכלמנסעפצקרשת";
208
+
209
+ /** Hebrew numerals (hebrew1): א, ב, … י, יא, … טו and טז for 15 and 16, as Word writes them. */
210
+ function hebrewNumeral(value: number): string {
211
+ if (value < 1) return String(value);
212
+ let rest = value % 1000;
213
+ let out = "";
214
+ while (rest >= 400) {
215
+ out += "ת";
216
+ rest -= 400;
217
+ }
218
+ out += HEBREW_HUNDREDS[Math.floor(rest / 100)]!;
219
+ rest %= 100;
220
+ if (rest === 15) return `${out}טו`;
221
+ if (rest === 16) return `${out}טז`;
222
+ return out + HEBREW_TENS[Math.floor(rest / 10)]! + HEBREW_ONES[rest % 10]!;
223
+ }
224
+
225
+ /** A counter in a list format of Word. Formats it does not know are written as numbers. */
226
+ export function formatNumber(value: number, format: string): string {
227
+ switch (format) {
228
+ case "lowerLetter": return letters(value);
229
+ case "upperLetter": return letters(value).toUpperCase();
230
+ case "lowerRoman": return roman(value);
231
+ case "upperRoman": return roman(value).toUpperCase();
232
+ case "decimalZero": return value < 10 ? `0${value}` : String(value);
233
+ case "hebrew1": return hebrewNumeral(value);
234
+ case "hebrew2": return value < 1 ? String(value) : HEBREW_LETTERS[(value - 1) % HEBREW_LETTERS.length]!;
235
+ case "none": return "";
236
+ default: return String(value);
237
+ }
238
+ }
239
+
240
+ /** Private-use characters: the bullets of the Symbol and Wingdings fonts. */
241
+ const PRIVATE_USE = /[-]/u;
242
+
243
+ /**
244
+ * Numbers the paragraphs of one document in order, as Word does: one count for each list and level,
245
+ * shared by the lists made from one definition (or from one list style), restarted by a list that
246
+ * says where to start, and the deeper levels started again when a level counts up.
247
+ *
248
+ * Every paragraph of a list is counted, an empty one too, but its number is written only when it
249
+ * has text (`count`, then `labelOf`), and what a style gives is worked out once a style: a file of
250
+ * 312,500 empty paragraphs of a style based on 19 others, in a list whose number was 480
251
+ * characters long, took 25 seconds for 45 KB.
252
+ */
253
+ export class WordNumbering {
254
+ private readonly styles: Map<string, StyleInfo>;
255
+ private readonly listStyles: Map<string, StyleInfo>;
256
+ private readonly abstracts: Map<string, ListDefinition>;
257
+ private readonly nums: Map<string, Num>;
258
+ /** The list definition that defines each list style (`w:styleLink`). */
259
+ private readonly styleLinks = new Map<string, string>();
260
+ /** The counts of each list definition, by level: undefined for a level not counted since it was last started again. */
261
+ private readonly counts = new Map<string, Array<number | undefined>>();
262
+ /** Lists whose start override has been applied. */
263
+ private readonly started = new Set<string>();
264
+ /** What each paragraph style gives, worked out at its first paragraph: the styles of a document do not change. */
265
+ private readonly resolved = new Map<string, Resolved>();
266
+ /** Each list found so far, by its `numId`; null for one with no levels. */
267
+ private readonly lists = new Map<string, List | null>();
268
+
269
+ constructor(stylesXml: string | undefined, numberingXml: string | undefined) {
270
+ ({ styles: this.styles, listStyles: this.listStyles } = readStyles(stylesXml));
271
+ ({ abstracts: this.abstracts, nums: this.nums } = readNumbering(numberingXml));
272
+ for (const [id, definition] of this.abstracts) {
273
+ if (definition.styleLink !== undefined && !this.styleLinks.has(definition.styleLink)) this.styleLinks.set(definition.styleLink, id);
274
+ }
275
+ }
276
+
277
+ /** A style and the styles it is based on, nearest first, at most 20 deep. */
278
+ private *chain(styleId: string | undefined): Generator<StyleInfo> {
279
+ const seen = new Set<string>();
280
+ for (let id = styleId; id !== undefined && !seen.has(id) && seen.size < 20; id = this.styles.get(id)?.basedOn) {
281
+ seen.add(id);
282
+ const style = this.styles.get(id);
283
+ if (!style) return;
284
+ yield style;
285
+ }
286
+ }
287
+
288
+ /**
289
+ * What a paragraph style gives: the nearest list, level and outline level in its chain, and the
290
+ * level of its nearest heading style ("heading 2", or a style whose name Word gives in English
291
+ * even in a Hebrew document) or title style. Kept only for the styles the file defines, which
292
+ * bounds what is kept.
293
+ */
294
+ private resolve(styleId: string | undefined): Resolved {
295
+ if (styleId === undefined || !this.styles.has(styleId)) return NOTHING;
296
+ let resolved = this.resolved.get(styleId);
297
+ if (resolved) return resolved;
298
+ resolved = {};
299
+ for (const style of this.chain(styleId)) {
300
+ resolved.numId ??= style.numId;
301
+ resolved.ilvl ??= style.ilvl;
302
+ resolved.outline ??= style.outlineLevel;
303
+ if (resolved.heading === undefined) {
304
+ const named = /^heading (\d)$/.exec(style.name);
305
+ if (named) resolved.heading = Math.min(6, Math.max(1, Number(named[1])));
306
+ else if (style.name === "title") resolved.heading = 1;
307
+ }
308
+ }
309
+ this.resolved.set(styleId, resolved);
310
+ return resolved;
311
+ }
312
+
313
+ /**
314
+ * The level of a heading, 1 to 6, for a paragraph of a heading style, of the title style, or with
315
+ * an outline level. Undefined for body text.
316
+ */
317
+ headingLevel(paragraph: ParagraphStyle): number | undefined {
318
+ const style = this.resolve(paragraph.styleId);
319
+ if (style.heading !== undefined) return style.heading;
320
+ const outline = paragraph.outlineLevel ?? style.outline;
321
+ return outline !== undefined && outline >= 0 && outline < 6 ? outline + 1 : undefined;
322
+ }
323
+
324
+ /** The list a `numId` names, found at its first paragraph; undefined when the file defines none, or it has no levels. */
325
+ private list(numId: string): List | undefined {
326
+ const known = this.lists.get(numId);
327
+ if (known !== undefined) return known ?? undefined;
328
+ // A numId the file does not define is not kept: the paragraphs may name any number of them.
329
+ const num = this.nums.get(numId);
330
+ if (!num) return undefined;
331
+ const found = this.definitionOf(num.abstractId);
332
+ const list = found ? { key: found.id, levels: found.definition.levels, starts: num.starts } : null;
333
+ this.lists.set(numId, list);
334
+ return list ?? undefined;
335
+ }
336
+
337
+ /**
338
+ * The list definition whose levels and counts a definition uses: itself, or for one that takes
339
+ * them from a list style (`w:numStyleLink`), the definition of that style: the one that names it
340
+ * in `w:styleLink`, or that of the list in the style's own properties. A file may link them in a
341
+ * circle, so a few links are followed; a definition linked back to itself keeps its own levels.
342
+ */
343
+ private definitionOf(abstractId: string): { id: string; definition: ListDefinition } | undefined {
344
+ let id = abstractId;
345
+ for (let link = 0; link <= MAX_LIST_LINKS; link++) {
346
+ const definition = this.abstracts.get(id);
347
+ if (!definition) return undefined;
348
+ const style = definition.numStyleLink;
349
+ if (style === undefined) return { id, definition };
350
+ const styleNumId = this.listStyles.get(style)?.numId;
351
+ const linked = this.styleLinks.get(style) ?? (styleNumId === undefined ? undefined : this.nums.get(styleNumId)?.abstractId);
352
+ if (linked === undefined || linked === id) return { id, definition };
353
+ id = linked;
354
+ }
355
+ return undefined;
356
+ }
357
+
358
+ /**
359
+ * Counts a paragraph in its list, as Word counts every paragraph of a list, an empty one too. It
360
+ * gives what `labelOf` needs to write the paragraph's number, until the next paragraph is
361
+ * counted, or undefined for a paragraph of no list.
362
+ */
363
+ count(paragraph: ParagraphStyle): Counted | undefined {
364
+ const style = this.resolve(paragraph.styleId);
365
+ const numId = paragraph.numId ?? style.numId;
366
+ if (numId === undefined || numId === "0") return undefined;
367
+ const list = this.list(numId);
368
+ if (!list) return undefined;
369
+ const level = Math.min(LEVELS - 1, Math.max(0, paragraph.ilvl ?? style.ilvl ?? 0));
370
+ const definition = list.levels[level];
371
+ if (!definition) return undefined;
372
+ let counts = this.counts.get(list.key);
373
+ if (!counts) {
374
+ counts = new Array<number | undefined>(LEVELS).fill(undefined);
375
+ this.counts.set(list.key, counts);
376
+ }
377
+ if (!this.started.has(numId)) {
378
+ this.started.add(numId);
379
+ for (const [overridden, start] of list.starts) counts[overridden] = start - 1;
380
+ }
381
+ const count = counts[level];
382
+ counts[level] = count === undefined ? definition.start : count + 1;
383
+ for (let deeper = level + 1; deeper < LEVELS; deeper++) counts[deeper] = undefined;
384
+ return { levels: list.levels, level, counts };
385
+ }
386
+
387
+ /**
388
+ * The number Word writes before a paragraph that `count` has just counted ("2.1.", "(a)", "-"
389
+ * for a bullet), or undefined. It is cut after `MAX_LABEL` characters.
390
+ */
391
+ labelOf({ levels, level, counts }: Counted): string | undefined {
392
+ const definition = levels[level];
393
+ if (!definition) return undefined;
394
+ if (definition.format === "bullet") return "-";
395
+ let text = "";
396
+ for (const part of definition.parts) {
397
+ if (typeof part === "string") {
398
+ text += part;
399
+ } else {
400
+ const own = levels[part];
401
+ const format = own?.format ?? "decimal";
402
+ // A legal level writes the number of every level in Arabic digits. Word keeps the zero of
403
+ // decimalZero: "Section 1.01" of its "Article I. / Section 1.01" list is a legal level.
404
+ text += formatNumber(counts[part] ?? own?.start ?? 1, definition.legal && format !== "decimalZero" ? "decimal" : format);
405
+ }
406
+ if (text.length >= MAX_LABEL) {
407
+ text = sliceWhole(text, MAX_LABEL);
408
+ break;
409
+ }
410
+ }
411
+ if (PRIVATE_USE.test(text)) return "-";
412
+ return text.trim() || undefined;
413
+ }
414
+
415
+ /** Counts a paragraph (`count`), and gives the number Word writes before it (`labelOf`), or undefined. */
416
+ label(paragraph: ParagraphStyle): string | undefined {
417
+ const counted = this.count(paragraph);
418
+ return counted && this.labelOf(counted);
419
+ }
420
+ }