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/pdf-pages.ts CHANGED
@@ -5,11 +5,13 @@
5
5
  * Copying pages the way a PDF library offers it is not enough. A link to another page takes that
6
6
  * page's content along, and a resource dictionary that pages share takes along every image it
7
7
  * lists: the contents page of a report came out at 89% of its file. So, before copying:
8
- * - every page that is not wanted is replaced by an empty one, so a reference to it costs nothing;
8
+ * - every page that is not wanted is set to null, so a reference to it costs nothing;
9
9
  * - a wanted page gets its own resource dictionary, without the images it does not paint.
10
10
  */
11
11
  import { getHeapStatistics } from "node:v8";
12
- import type { PDFContext, PDFDict, PDFObject, PDFPage, PDFPageLeaf } from "@cantoo/pdf-lib";
12
+ import { importPeer } from "./peers.js";
13
+ import type { PDFContext, PDFDict, PDFObject, PDFObjectCopier, PDFPage, PDFPageLeaf, PDFRef } from "@cantoo/pdf-lib";
14
+ import { TimeSlicer } from "./pause.js";
13
15
  import { formatBytes } from "./plan.js";
14
16
 
15
17
  type PdfLibrary = typeof import("@cantoo/pdf-lib");
@@ -24,8 +26,173 @@ export type PageCut = {
24
26
  pageCount: number;
25
27
  };
26
28
 
27
- /** Objects parsed between two pauses that let other work on the server run. */
28
- const OBJECTS_PER_TICK = 4_000;
29
+ /**
30
+ * Objects parsed between two pauses that let other work on the server run, when the parse cannot
31
+ * be paused by time (see `loadPdf`). A count is a poor measure: 500 objects of large arrays took
32
+ * 100 to 180 ms.
33
+ */
34
+ export const OBJECTS_PER_TICK = 500;
35
+ /** Pauses while one file is parsed, at most. Each is a timer: about 15 ms on Windows, 1 ms elsewhere. */
36
+ const MOST_TICKS = 100;
37
+ const MOST_OBJECTS_PER_TICK = 4_000;
38
+
39
+ /**
40
+ * The `parseSpeed` for pdf-lib: `OBJECTS_PER_TICK`, or more for a file that declares so many
41
+ * objects that pausing that often would add seconds of waiting (300 pauses of 15 ms for 150,000).
42
+ */
43
+ export function objectsPerTick(bytes: Uint8Array): number {
44
+ const objects = declaredObjectCount(bytes) ?? 0;
45
+ return Math.min(MOST_OBJECTS_PER_TICK, Math.max(OBJECTS_PER_TICK, Math.ceil(objects / MOST_TICKS)));
46
+ }
47
+
48
+ /**
49
+ * Work between two pauses of a parse, at least. A slice also runs twice as long as a pause took,
50
+ * up to `MOST_PARSE_SLICE_MS`: a pause is a timer, which waits about 15 ms on Windows and 1 ms
51
+ * elsewhere, and waiting should not take most of the parse.
52
+ */
53
+ const PARSE_SLICE_MS = 12;
54
+ const MOST_PARSE_SLICE_MS = 40;
55
+
56
+ /** What pdf-lib's parsers and writers offer to change how they pause. Not in its types: checked before use. */
57
+ type Pausing = { shouldWaitForTick?: unknown };
58
+ /** What pdf-lib's cross-reference stream keeps. Not in its types: checked before use. */
59
+ type CrossReferences = { entries?: unknown; appendEntry?: unknown };
60
+ type CrossReference = { ref?: { objectNumber?: unknown } };
61
+
62
+ /** The files `loadPdf` is reading, each with how many reads of it are running. */
63
+ const timedFiles = new WeakMap<Uint8Array, number>();
64
+ /** The documents (their contexts) that `copyPages` saves. */
65
+ const timedSaves = new WeakSet<object>();
66
+ /** The factories of pdf-lib changed here, by class: one class for each copy of pdf-lib loaded. */
67
+ const changedFactories = new WeakMap<object, Set<string>>();
68
+
69
+ /**
70
+ * pdf-lib asks after each object it parses or writes whether to pause, and pauses with a timer
71
+ * when told so. This answers by time: once a slice of work has run its length. The time of the
72
+ * pauses is not counted.
73
+ */
74
+ function pauseByTime(): () => boolean {
75
+ let sliceStart = performance.now();
76
+ let pausedAt: number | undefined;
77
+ /** The shortest pause seen, with the one object parsed after it. */
78
+ let pauseMs = 0;
79
+ return () => {
80
+ const now = performance.now();
81
+ if (pausedAt !== undefined) {
82
+ pauseMs = pauseMs === 0 ? now - pausedAt : Math.min(pauseMs, now - pausedAt);
83
+ pausedAt = undefined;
84
+ sliceStart = now;
85
+ return false;
86
+ }
87
+ if (now - sliceStart < Math.min(MOST_PARSE_SLICE_MS, Math.max(PARSE_SLICE_MS, 2 * pauseMs))) return false;
88
+ pausedAt = now;
89
+ return true;
90
+ };
91
+ }
92
+
93
+ /** Makes a parser or a writer of pdf-lib pause by time. */
94
+ function pauseInTime(made: unknown): void {
95
+ const pausing = made as Pausing | undefined;
96
+ if (typeof pausing?.shouldWaitForTick === "function") pausing.shouldWaitForTick = pauseByTime();
97
+ }
98
+
99
+ /**
100
+ * Has `change` look at what `owner[name]`, a static factory of one of pdf-lib's classes, creates,
101
+ * with the first argument it was given: once for each class. Any other use of pdf-lib in the
102
+ * process is left as it was. A version of pdf-lib built otherwise is left as it is: its parse and
103
+ * its writer pause by the count they are given.
104
+ */
105
+ function changeFactory(owner: unknown, name: string, change: (first: unknown, made: unknown) => void): void {
106
+ if (typeof owner !== "function") return;
107
+ const factories = owner as unknown as Record<string, unknown>;
108
+ const create = factories[name];
109
+ const done = changedFactories.get(owner) ?? new Set<string>();
110
+ if (typeof create !== "function" || done.has(name)) return;
111
+ try {
112
+ factories[name] = (first: unknown, ...rest: unknown[]) => {
113
+ const made: unknown = create.call(owner, first, ...rest);
114
+ change(first, made);
115
+ return made;
116
+ };
117
+ done.add(name);
118
+ changedFactories.set(owner, done);
119
+ } catch {
120
+ // A class that cannot be changed.
121
+ }
122
+ }
123
+
124
+ /** Makes pdf-lib's parsers of the files in `timedFiles` pause by time. */
125
+ function timeParsers(library: PdfLibrary): void {
126
+ const parsers = (library as unknown as { PDFParser?: unknown }).PDFParser;
127
+ changeFactory(parsers, "forBytesWithOptions", (bytes, parser) => {
128
+ if (timedFiles.has(bytes as Uint8Array)) pauseInTime(parser);
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Makes pdf-lib's writers of the documents in `timedSaves` pause by time. Left to itself, a writer
134
+ * of a cut never paused: it counts objects, and the objects it packs into streams 50 at a time
135
+ * make the count miss every multiple of 50 it pauses at.
136
+ *
137
+ * The writer also adds each object to its cross-reference stream by searching all the entries
138
+ * added so far for where it goes, though the objects come in order: the time grows with the square
139
+ * of their count, 0.5 s in one block for 20,000 objects. For these documents an entry that goes
140
+ * after the last one is added at the end at once, which gives the same entries in the same order.
141
+ */
142
+ function timeWriters(library: PdfLibrary): void {
143
+ const classes = library as unknown as { PDFWriter?: unknown; PDFStreamWriter?: unknown; PDFCrossRefStream?: unknown };
144
+ for (const writers of [classes.PDFWriter, classes.PDFStreamWriter]) {
145
+ changeFactory(writers, "forContext", (context, writer) => {
146
+ if (timedSaves.has(context as object)) pauseInTime(writer);
147
+ });
148
+ }
149
+ // The writer makes its stream with a dictionary of the document it writes.
150
+ changeFactory(classes.PDFCrossRefStream, "create", (dictionary, stream) => {
151
+ const context = (dictionary as { context?: unknown } | undefined)?.context;
152
+ if (typeof context === "object" && context !== null && timedSaves.has(context)) appendInOrder(stream);
153
+ });
154
+ }
155
+
156
+ /** Adds an entry that goes after the last one to the end of `stream` at once. Entries are kept by object number. */
157
+ function appendInOrder(stream: unknown): void {
158
+ const references = stream as CrossReferences | undefined;
159
+ const append = references?.appendEntry;
160
+ if (!references || typeof append !== "function" || !Array.isArray(references.entries)) return;
161
+ references.appendEntry = (entry: CrossReference) => {
162
+ const entries = references.entries as CrossReference[];
163
+ const last = entries.at(-1)?.ref?.objectNumber;
164
+ const number = entry?.ref?.objectNumber;
165
+ if (typeof last === "number" && typeof number === "number" && last <= number) entries.push(entry);
166
+ else append.call(references, entry);
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Reads a PDF into objects with pdf-lib, which cannot be stopped once it has started, and pauses
172
+ * after every 12 to 40 ms of work so that other requests get a turn. pdf-lib itself pauses by a
173
+ * count of objects, and objects differ in cost a hundred times: a count of 500 held the server for
174
+ * 100 to 180 ms on a file of large arrays, and a file of 150,000 objects, parsed 1,500 at a time,
175
+ * for 0.2 to 0.55 s. What pdf-lib reads in one step still holds the server for as long as it
176
+ * takes, and grows with the file: one object (about 0.15 s for each MB of an array of numbers,
177
+ * about 0.03 s for each MB of a stream whose length the file does not give directly), and a
178
+ * cross-reference table written as text (0.15 s for 150,000 objects).
179
+ *
180
+ * The file is read with an empty password, which opens the many PDFs that are encrypted only to
181
+ * restrict printing or copying. Throws what pdf-lib throws.
182
+ */
183
+ export async function loadPdf(library: PdfLibrary, bytes: Uint8Array): Promise<import("@cantoo/pdf-lib").PDFDocument> {
184
+ timeParsers(library);
185
+ timedFiles.set(bytes, (timedFiles.get(bytes) ?? 0) + 1);
186
+ try {
187
+ // parseSpeed pauses the parse by count, when it could not be timed.
188
+ return await library.PDFDocument.load(bytes, { updateMetadata: false, parseSpeed: objectsPerTick(bytes), password: "" });
189
+ } finally {
190
+ const reads = (timedFiles.get(bytes) ?? 1) - 1;
191
+ if (reads > 0) timedFiles.set(bytes, reads);
192
+ else timedFiles.delete(bytes);
193
+ }
194
+ }
195
+
29
196
  /** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
30
197
  const BYTES_PER_OBJECT = 1_700;
31
198
  /** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
@@ -42,11 +209,7 @@ export function latin1(bytes: Uint8Array): string {
42
209
  }
43
210
 
44
211
  export async function loadPdfLibrary(): Promise<PdfLibrary> {
45
- try {
46
- return await import("@cantoo/pdf-lib");
47
- } catch {
48
- throw new Error("Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
49
- }
212
+ return importPeer("@cantoo/pdf-lib", () => import("@cantoo/pdf-lib"), "Showing PDF pages needs the optional dependency \"@cantoo/pdf-lib\".");
50
213
  }
51
214
 
52
215
  /**
@@ -101,15 +264,27 @@ export function tooManyObjects(original: Uint8Array, most = MAX_OBJECTS): number
101
264
  return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
102
265
  }
103
266
 
104
- /** A PDF name as the characters it stands for, so that "#20" and a space are the same name. */
105
- export function canonicalName(raw: string): string {
267
+ /**
268
+ * Decodings that may still change a name. A library may keep an escape it did not decode as
269
+ * literal characters, so a name is decoded again; no writer escapes a name more deeply than that.
270
+ */
271
+ const NAME_DECODINGS = 3;
272
+
273
+ /**
274
+ * A PDF name as the characters it stands for, so that "#20" and a space are the same name.
275
+ * Undefined for a name that still changes after `NAME_DECODINGS` decodings: only a file built to
276
+ * hold the server writes one ("#2323...2341" loses one level a decoding, and decoding it until
277
+ * nothing changed took 20 s for 400,000 characters). Callers treat it as a name they cannot read.
278
+ */
279
+ export function canonicalName(raw: string): string | undefined {
106
280
  let name = raw;
107
- // Until nothing changes: a library may keep an escape it did not decode as literal characters.
108
- for (;;) {
281
+ for (let decoding = 0; decoding <= NAME_DECODINGS; decoding++) {
282
+ if (!name.includes("#")) return name;
109
283
  const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
110
284
  if (next === name) return name;
111
285
  name = next;
112
286
  }
287
+ return undefined;
113
288
  }
114
289
 
115
290
  const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
@@ -133,14 +308,21 @@ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPag
133
308
  if (!(xobjects instanceof PDFDict)) return;
134
309
  const entries = xobjects.entries();
135
310
  if (entries.length < 2) return;
136
- const byName = new Map(entries.map(([name, value]) => [canonicalName(name.asString().slice(1)), value]));
311
+ const names = entries.map(([name]) => canonicalName(name.asString().slice(1)));
312
+ // A name that cannot be read cannot be matched with what the content paints: keep every image.
313
+ if (names.includes(undefined)) return;
314
+ const byName = new Map(entries.map(([, value], index) => [names[index]!, value]));
137
315
 
138
316
  let readable = true;
139
317
  /** Names found in content that looks them up in this page's dictionary, still to be followed. */
140
318
  const found: string[] = [];
141
319
  const decode = (stream: PDFObject | undefined) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
142
320
  const read = (text: string) => {
143
- for (const match of text.matchAll(PAINTED)) found.push(canonicalName(match[1]!));
321
+ for (const match of text.matchAll(PAINTED)) {
322
+ const name = canonicalName(match[1]!);
323
+ if (name === undefined) readable = false;
324
+ else found.push(name);
325
+ }
144
326
  };
145
327
  const readStream = (stream: PDFObject | undefined) => {
146
328
  const text = decode(stream);
@@ -223,7 +405,7 @@ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPag
223
405
  }
224
406
  if (!readable) return;
225
407
 
226
- const kept = entries.filter(([name]) => painted.has(canonicalName(name.asString().slice(1))));
408
+ const kept = entries.filter((_entry, index) => painted.has(names[index]!));
227
409
  if (kept.length === entries.length) return;
228
410
  const fewer = context.obj({});
229
411
  for (const [name, value] of kept) fewer.set(name, value);
@@ -256,18 +438,87 @@ async function copyPages(library: PdfLibrary, source: import("@cantoo/pdf-lib").
256
438
  // One copier for everything, and each page copied through its reference: an annotation's /P then
257
439
  // points at the copied page, and the layer settings below name the layers the pages use.
258
440
  const copier = PDFObjectCopier.for(context, target.context);
441
+ // Without these, a layer that the file hides would be shown.
442
+ const layers = source.catalog.get(PDFName.of("OCProperties"));
443
+ const roots: PDFObject[] = wanted.map((page) => page.ref);
444
+ await copyInTurns(library, copier, context, target.context, layers ? [...roots, layers] : roots);
259
445
  for (const page of wanted) {
260
446
  const reference = copier.copy(page.ref);
261
447
  const node = target.context.lookup(reference);
262
448
  if (!(node instanceof Leaf)) throw new Error("A page of this PDF is not a page object.");
263
449
  target.addPage(Page.of(node, reference, target));
264
450
  }
265
- // Without these, a layer that the file hides would be shown.
266
- const layers = source.catalog.get(PDFName.of("OCProperties"));
267
451
  if (layers) target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
452
+ timeWriters(library);
453
+ timedSaves.add(target.context);
268
454
  return target.save();
269
455
  }
270
456
 
457
+ /**
458
+ * Does the work of `copier.copy(root)` for each of `roots`, with pauses so that other requests get
459
+ * a turn. pdf-lib's copier follows every reference at once: a page that refers to 4,000 large
460
+ * arrays held the server for 0.3 s, and one that refers to 20,000 for 0.9 s. So the objects are
461
+ * first numbered in the order the copier would number them, which keeps the cut the same to the
462
+ * byte, then copied one at a time. `copier.copy(root)` afterwards finds them copied. A copier built
463
+ * otherwise is left to copy everything at once.
464
+ */
465
+ async function copyInTurns(library: PdfLibrary, copier: PDFObjectCopier, source: PDFContext, target: PDFContext, roots: PDFObject[]): Promise<void> {
466
+ const copied = (copier as unknown as { traversedObjects?: unknown }).traversedObjects;
467
+ if (!(copied instanceof Map)) return;
468
+ const { PDFArray, PDFDict, PDFName, PDFPageLeaf: Leaf, PDFRef, PDFStream } = library;
469
+ const slicer = new TimeSlicer();
470
+ /** Each object referred to, with its number in the cut, in the order the copier numbers them. */
471
+ const numbered: [PDFRef, PDFRef][] = [];
472
+ const seen = new Set<PDFObject>();
473
+ /** What the copier copies next, when it copies `object`: undefined when there is nothing more. */
474
+ const inside = (object: PDFObject): PDFObject[] | undefined => {
475
+ if (object instanceof PDFRef) {
476
+ if (copied.has(object)) return undefined;
477
+ const reference = target.nextRef();
478
+ copied.set(object, reference);
479
+ numbered.push([object, reference]);
480
+ const value = source.lookup(object);
481
+ return value ? [value] : undefined;
482
+ }
483
+ if (object instanceof Leaf) {
484
+ // As the copier copies a page: with what it inherits from the page tree, without its parent.
485
+ const page = object.clone();
486
+ for (const name of Leaf.InheritableEntries) {
487
+ const key = PDFName.of(name);
488
+ const value = page.getInheritableAttribute(key);
489
+ if (!page.get(key) && value) page.set(key, value);
490
+ }
491
+ page.delete(PDFName.of("Parent"));
492
+ return page.entries().map(([, value]) => value);
493
+ }
494
+ if (!(object instanceof PDFDict || object instanceof PDFArray || object instanceof PDFStream) || seen.has(object)) return undefined;
495
+ seen.add(object);
496
+ if (object instanceof PDFArray) return object.asArray();
497
+ return (object instanceof PDFStream ? object.dict : object).entries().map(([, value]) => value);
498
+ };
499
+ // Depth first, each object before what it refers to, as the copier goes.
500
+ const stack: { items: PDFObject[]; at: number }[] = [];
501
+ const enter = (object: PDFObject) => {
502
+ const items = inside(object);
503
+ if (items !== undefined && items.length > 0) stack.push({ items, at: 0 });
504
+ };
505
+ let steps = 0;
506
+ for (const root of roots) {
507
+ enter(root);
508
+ while (stack.length > 0) {
509
+ const top = stack[stack.length - 1]!;
510
+ if (top.at === top.items.length) stack.pop();
511
+ else enter(top.items[top.at++]!);
512
+ if (++steps % 1_000 === 0) await slicer.maybePause();
513
+ }
514
+ }
515
+ for (const [original, reference] of numbered) {
516
+ const value = source.lookup(original);
517
+ if (value) target.assign(reference, copier.copy(value));
518
+ await slicer.maybePause();
519
+ }
520
+ }
521
+
271
522
  /**
272
523
  * Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
273
524
  * `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
@@ -286,8 +537,7 @@ export async function cutPdfPages(original: Uint8Array, from: number, to: number
286
537
  let source: import("@cantoo/pdf-lib").PDFDocument;
287
538
  let pages: PDFPage[];
288
539
  try {
289
- // An empty password opens the many PDFs that are encrypted only to restrict printing or copying.
290
- source = await library.PDFDocument.load(original, { updateMetadata: false, parseSpeed: OBJECTS_PER_TICK, password: "" });
540
+ source = await loadPdf(library, original);
291
541
  pages = source.getPages();
292
542
  } catch (error) {
293
543
  const needsPassword = /password/i.test(error instanceof Error ? error.message : String(error));
@@ -9,8 +9,9 @@
9
9
  *
10
10
  * Needs the optional dependency "@cantoo/pdf-lib". Without it, no page is marked.
11
11
  */
12
- import type { PDFContext, PDFDict, PDFObject } from "@cantoo/pdf-lib";
13
- import { decodeContent, loadPdfLibrary, tooManyObjects } from "./pdf-pages.js";
12
+ import type { PDFContext, PDFDict, PDFDocument, PDFObject } from "@cantoo/pdf-lib";
13
+ import { fairPause } from "./pause.js";
14
+ import { decodeContent, loadPdf, loadPdfLibrary, tooManyObjects } from "./pdf-pages.js";
14
15
 
15
16
  type PdfLibrary = typeof import("@cantoo/pdf-lib");
16
17
  /** `[x0, y0, x1, y1]` with x0 <= x1 and y0 <= y1. */
@@ -32,6 +33,8 @@ export type PageGeometry = {
32
33
  const MAX_OBJECTS = 150_000;
33
34
  /** Time for everything after the file is read into objects. Past it, no page is marked. */
34
35
  const TIME_LIMIT_MS = 5_000;
36
+ /** Work on pages between two pauses for other requests. */
37
+ const PAGES_SLICE_MS = 12;
35
38
  /** A content stream past this size (compressed) is not text or a table: it is a drawing. */
36
39
  const MAX_CONTENT_BYTES = 2 * 1024 * 1024;
37
40
  /** Images must cover this share of the page together. A logo covers about 1%, a small figure 4%. */
@@ -322,26 +325,68 @@ function showsPicture(graphics: Graphics, geometry: PageGeometry, furniture: Rea
322
325
  return false;
323
326
  }
324
327
 
328
+ /** A PDF read into objects by @cantoo/pdf-lib: once for a file, by the page-work check and the picture marks. */
329
+ export type ParsedPdf = { library: PdfLibrary; document: PDFDocument };
330
+
331
+ /**
332
+ * Reads a PDF into objects with @cantoo/pdf-lib. Undefined when that cannot be done: the library is
333
+ * not installed, the file declares more than `MAX_OBJECTS` objects, it cannot be read, or `signal`
334
+ * was aborted. It never throws.
335
+ */
336
+ export async function parsePdf(bytes: Uint8Array, signal?: AbortSignal): Promise<ParsedPdf | undefined> {
337
+ try {
338
+ if (signal?.aborted || tooManyObjects(bytes, MAX_OBJECTS) !== undefined) return undefined;
339
+ // The first time, loading the library is one block of about 0.4 s, as is opening pdf.js just
340
+ // before: other requests get a turn between the two, and before the parse. One pause runs
341
+ // straight after the work before it, in the same turn of the event loop; the second comes after
342
+ // the timers and the I/O of other requests.
343
+ await fairPause();
344
+ await fairPause();
345
+ const library = await loadPdfLibrary();
346
+ await fairPause();
347
+ const document = await loadPdf(library, bytes);
348
+ return signal?.aborted ? undefined : { library, document };
349
+ } catch {
350
+ return undefined;
351
+ }
352
+ }
353
+
325
354
  /**
326
355
  * For each page, whether it shows a picture (images that cover a real share of the page, other
327
356
  * than one repeated on many pages) or a drawing (shapes filled in several colours, outside the
328
357
  * tables). Undefined when that could not be worked out: the library is not installed, the file has
329
- * too many objects or took too long, or it does not have the pages the text was extracted from.
330
- * It never throws.
358
+ * too many objects or took too long, it does not have the pages the text was extracted from, or
359
+ * `signal` was aborted (the caller then stops). It never throws. `source`: the bytes of the file, or
360
+ * the file as `parsePdf` read it (undefined when it could not). `onProgress` is told the pages
361
+ * looked at so far, after each page.
331
362
  */
332
- export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGeometry[]): Promise<boolean[] | undefined> {
363
+ export async function findPicturePages(
364
+ source: Uint8Array | ParsedPdf | undefined,
365
+ pages: readonly PageGeometry[],
366
+ signal?: AbortSignal,
367
+ onProgress?: (done: number, total: number) => void,
368
+ ): Promise<boolean[] | undefined> {
333
369
  try {
334
- if (tooManyObjects(bytes, MAX_OBJECTS) !== undefined) return undefined;
335
- const library = await loadPdfLibrary();
336
- const { PDFArray, PDFDocument, PDFRawStream } = library;
337
- const document = await PDFDocument.load(bytes, { updateMetadata: false, parseSpeed: 4_000, password: "" });
370
+ const opened = source instanceof Uint8Array ? await parsePdf(source, signal) : source;
371
+ if (!opened || signal?.aborted) return undefined;
372
+ const { library, document } = opened;
373
+ const { PDFArray, PDFRawStream } = library;
338
374
  const leaves = document.getPages();
339
375
  if (leaves.length !== pages.length) return undefined;
340
376
  const { context } = document;
341
377
  const reading: Reading = { library, context, forms: new Map(), kept: 0, deadline: performance.now() + TIME_LIMIT_MS };
342
378
  const graphics: Graphics[] = [];
379
+ let sliceStart = performance.now();
343
380
  for (const leaf of leaves) {
344
381
  if (performance.now() > reading.deadline) return undefined;
382
+ // Other requests get a turn every few pages. The time spent waiting for them is not counted.
383
+ if (performance.now() - sliceStart > PAGES_SLICE_MS) {
384
+ const before = performance.now();
385
+ await fairPause();
386
+ if (signal?.aborted) return undefined;
387
+ reading.deadline += performance.now() - before;
388
+ sliceStart = performance.now();
389
+ }
345
390
  const found: Graphics = { images: [], shapes: [], tooLarge: false, read: 0 };
346
391
  graphics.push(found);
347
392
  try {
@@ -360,6 +405,8 @@ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGe
360
405
  // A page that paints more than a page of text can is a drawing. Any other trouble leaves
361
406
  // an unusual page unmarked.
362
407
  if (error instanceof PaintsTooMuch) found.tooLarge = true;
408
+ } finally {
409
+ onProgress?.(graphics.length, leaves.length);
363
410
  }
364
411
  }
365
412
  // An image painted on many pages is part of the page design, whatever its size.