llm-large-files 0.2.0 → 0.3.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 (76) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +32 -6
  3. package/dist/extract.d.ts +13 -6
  4. package/dist/extract.d.ts.map +1 -1
  5. package/dist/extract.js +27 -6
  6. package/dist/extract.js.map +1 -1
  7. package/dist/gemini/chat.d.ts +16 -0
  8. package/dist/gemini/chat.d.ts.map +1 -1
  9. package/dist/gemini/chat.js +45 -11
  10. package/dist/gemini/chat.js.map +1 -1
  11. package/dist/gemini/generate.d.ts +34 -4
  12. package/dist/gemini/generate.d.ts.map +1 -1
  13. package/dist/gemini/generate.js +47 -7
  14. package/dist/gemini/generate.js.map +1 -1
  15. package/dist/gemini/index.d.ts +3 -3
  16. package/dist/gemini/index.d.ts.map +1 -1
  17. package/dist/gemini/index.js +2 -2
  18. package/dist/gemini/index.js.map +1 -1
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/library.d.ts +31 -1
  24. package/dist/library.d.ts.map +1 -1
  25. package/dist/library.js +44 -6
  26. package/dist/library.js.map +1 -1
  27. package/dist/pdf-layout.d.ts +7 -0
  28. package/dist/pdf-layout.d.ts.map +1 -1
  29. package/dist/pdf-layout.js +32 -2
  30. package/dist/pdf-layout.js.map +1 -1
  31. package/dist/pdf-pages.d.ts +45 -0
  32. package/dist/pdf-pages.d.ts.map +1 -0
  33. package/dist/pdf-pages.js +336 -0
  34. package/dist/pdf-pages.js.map +1 -0
  35. package/dist/pdf-pictures.d.ts +20 -0
  36. package/dist/pdf-pictures.d.ts.map +1 -0
  37. package/dist/pdf-pictures.js +336 -0
  38. package/dist/pdf-pictures.js.map +1 -0
  39. package/dist/plan.d.ts +13 -3
  40. package/dist/plan.d.ts.map +1 -1
  41. package/dist/plan.js +22 -17
  42. package/dist/plan.js.map +1 -1
  43. package/dist/search.d.ts +9 -0
  44. package/dist/search.d.ts.map +1 -1
  45. package/dist/search.js +41 -0
  46. package/dist/search.js.map +1 -1
  47. package/dist/stores.d.ts +7 -1
  48. package/dist/stores.d.ts.map +1 -1
  49. package/dist/stores.js +37 -5
  50. package/dist/stores.js.map +1 -1
  51. package/dist/tools.d.ts +11 -0
  52. package/dist/tools.d.ts.map +1 -1
  53. package/dist/tools.js +145 -13
  54. package/dist/tools.js.map +1 -1
  55. package/dist/types.d.ts +57 -3
  56. package/dist/types.d.ts.map +1 -1
  57. package/docs/api.md +39 -11
  58. package/docs/configuration.md +229 -5
  59. package/docs/getting-started.md +34 -3
  60. package/docs/how-it-works.md +52 -4
  61. package/docs/security.md +39 -4
  62. package/package.json +7 -2
  63. package/src/extract.ts +34 -8
  64. package/src/gemini/chat.ts +60 -13
  65. package/src/gemini/generate.ts +63 -9
  66. package/src/gemini/index.ts +3 -3
  67. package/src/index.ts +2 -2
  68. package/src/library.ts +74 -7
  69. package/src/pdf-layout.ts +37 -1
  70. package/src/pdf-pages.ts +315 -0
  71. package/src/pdf-pictures.ts +324 -0
  72. package/src/plan.ts +36 -16
  73. package/src/search.ts +37 -0
  74. package/src/stores.ts +39 -6
  75. package/src/tools.ts +147 -13
  76. package/src/types.ts +57 -3
package/src/pdf-layout.ts CHANGED
@@ -719,6 +719,37 @@ function tablesInLines(lines: Line[], depth: number): Table[] {
719
719
 
720
720
  // ---------- The page ----------
721
721
 
722
+ /** `[left, top, right, bottom]` in the coordinates the viewport transform gives. */
723
+ export type LayoutBox = [number, number, number, number];
724
+
725
+ /** Where a table lies on the page: the box around its text, widened by about one line for the padding of its cells. */
726
+ function tableBox(table: Table, items: readonly PdfTextItem[], viewport: readonly number[]): LayoutBox {
727
+ const box: LayoutBox = [Infinity, Infinity, -Infinity, -Infinity];
728
+ let padding = 0;
729
+ for (const index of table.indexes) {
730
+ const item = items[index]!;
731
+ const matrix = item.transform;
732
+ const a = viewport[0]! * matrix[0]! + viewport[2]! * matrix[1]!;
733
+ const b = viewport[1]! * matrix[0]! + viewport[3]! * matrix[1]!;
734
+ const x = viewport[0]! * matrix[4]! + viewport[2]! * matrix[5]! + viewport[4]!;
735
+ const y = viewport[1]! * matrix[4]! + viewport[3]! * matrix[5]! + viewport[5]!;
736
+ const scale = Math.hypot(a, b) || 1;
737
+ const size = item.height > 0 ? item.height : scale;
738
+ const width = item.width > 0 ? item.width : item.str.length * size * 0.5;
739
+ // Along the text, and from the baseline up to the top of the letters.
740
+ const along = [a / scale * width, b / scale * width];
741
+ const up = [b / scale * size, -a / scale * size];
742
+ for (const [px, py] of [[x, y], [x + along[0]!, y + along[1]!], [x + up[0]!, y + up[1]!], [x + along[0]! + up[0]!, y + along[1]! + up[1]!]]) {
743
+ box[0] = Math.min(box[0], px!);
744
+ box[1] = Math.min(box[1], py!);
745
+ box[2] = Math.max(box[2], px!);
746
+ box[3] = Math.max(box[3], py!);
747
+ }
748
+ padding = Math.max(padding, size);
749
+ }
750
+ return [box[0] - padding, box[1] - padding, box[2] + padding, box[3] + padding];
751
+ }
752
+
722
753
  /**
723
754
  * The text of one PDF page, with tables written as `| cell | cell |` rows.
724
755
  *
@@ -727,6 +758,11 @@ function tablesInLines(lines: Line[], depth: number): Table[] {
727
758
  * rotation. Without it, the page is assumed to be upright.
728
759
  */
729
760
  export function layoutPageText(items: readonly PdfTextItem[], viewportTransform: readonly number[] = FLIP_Y): string {
761
+ return layoutPage(items, viewportTransform).text;
762
+ }
763
+
764
+ /** As `layoutPageText`, and also where the tables it found lie on the page. */
765
+ export function layoutPage(items: readonly PdfTextItem[], viewportTransform: readonly number[] = FLIP_Y): { text: string; tables: LayoutBox[] } {
730
766
  const tableOf = new Map<number, Table>();
731
767
  const pieceOf = new Map<number, Piece>();
732
768
  for (const group of toPieces(items, viewportTransform)) {
@@ -767,5 +803,5 @@ export function layoutPageText(items: readonly PdfTextItem[], viewportTransform:
767
803
  text += item.str + (item.hasEOL ? "\n" : "");
768
804
  last = piece && !item.hasEOL && item.str.trim() ? piece : undefined;
769
805
  });
770
- return text;
806
+ return { text, tables: [...new Set(tableOf.values())].map((table) => tableBox(table, items, viewportTransform)) };
771
807
  }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Cuts pages out of a PDF into a small PDF of their own, so a model can be shown the real pages.
3
+ * Needs the optional dependency "@cantoo/pdf-lib".
4
+ *
5
+ * Copying pages the way a PDF library offers it is not enough. A link to another page takes that
6
+ * page's content along, and a resource dictionary that pages share takes along every image it
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;
9
+ * - a wanted page gets its own resource dictionary, without the images it does not paint.
10
+ */
11
+ import { getHeapStatistics } from "node:v8";
12
+ import type { PDFContext, PDFDict, PDFObject, PDFPage, PDFPageLeaf } from "@cantoo/pdf-lib";
13
+ import { formatBytes } from "./plan.js";
14
+
15
+ type PdfLibrary = typeof import("@cantoo/pdf-lib");
16
+
17
+ export type PageCut = {
18
+ /** A PDF with pages `from` to `to` of the original. */
19
+ bytes: Uint8Array;
20
+ from: number;
21
+ /** The last page in the cut. Lower than the page asked for when the pages did not all fit. */
22
+ to: number;
23
+ /** How many pages the original has. */
24
+ pageCount: number;
25
+ };
26
+
27
+ /** Objects parsed between two pauses that let other work on the server run. */
28
+ const OBJECTS_PER_TICK = 4_000;
29
+ /** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
30
+ const BYTES_PER_OBJECT = 1_700;
31
+ /** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
32
+ const MAX_OBJECTS = 1_000_000;
33
+ /** Content streams larger than this are not read to find out which images a page paints. */
34
+ const MAX_CONTENT_BYTES = 4 * 1024 * 1024;
35
+ /** Not needed to show a page, and able to hold a lot: editor data, article threads, actions, a thumbnail. */
36
+ const DROPPED_PAGE_ENTRIES = ["PieceInfo", "B", "AA", "Thumb"];
37
+ const UNREADABLE = "This PDF could not be read to cut pages from it. It may be damaged.";
38
+
39
+ /** Bytes as a string of the same length: each byte becomes the character with that code. */
40
+ export function latin1(bytes: Uint8Array): string {
41
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
42
+ }
43
+
44
+ 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
+ }
50
+ }
51
+
52
+ /**
53
+ * The content of a stream as text, one character per byte, or undefined when it cannot be had:
54
+ * the stream is larger than `maxBytes`, uses a filter the library does not undo, or is damaged.
55
+ */
56
+ export function decodeContent(library: PdfLibrary, context: PDFContext, stream: PDFObject | undefined, maxBytes: number): string | undefined {
57
+ const { PDFArray, PDFDict, PDFName, PDFRawStream, decodePDFRawStream } = library;
58
+ if (!(stream instanceof PDFRawStream) || stream.contents.length > maxBytes) return undefined;
59
+ // The library does not undo a predictor, and would hand back bytes that are not the content.
60
+ const parameters = stream.dict.lookup(PDFName.of("DecodeParms"));
61
+ const list = parameters instanceof PDFArray ? parameters.asArray().map((entry) => context.lookup(entry)) : [parameters];
62
+ if (list.some((entry) => entry instanceof PDFDict && entry.has(PDFName.of("Predictor")))) return undefined;
63
+ try {
64
+ return latin1(decodePDFRawStream(stream).decode());
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * How many objects the file says it has: the largest /Size in its trailer or in its
72
+ * cross-reference stream. Undefined when neither is found where a well-formed file has it.
73
+ */
74
+ export function declaredObjectCount(bytes: Uint8Array): number | undefined {
75
+ const text = (start: number, end: number) => latin1(bytes.subarray(Math.max(0, start), Math.min(bytes.length, end)));
76
+ let found = 0;
77
+ const read = (chunk: string) => {
78
+ for (const match of chunk.matchAll(/\/Size[\s\0]+(\d{1,12})/g)) found = Math.max(found, Number(match[1]));
79
+ };
80
+ const tail = text(bytes.length - 2048, bytes.length);
81
+ read(tail);
82
+ // A cross-reference stream keeps /Size in its own dictionary, which can be far from the end.
83
+ const start = [...tail.matchAll(/startxref[\s\0]+(\d{1,15})/g)].at(-1);
84
+ if (start) {
85
+ const offset = Number(start[1]);
86
+ if (offset < bytes.length) read(text(offset, offset + 2048));
87
+ }
88
+ return found > 0 ? found : undefined;
89
+ }
90
+
91
+ /**
92
+ * The library reads the whole file into objects before anything can be done with a page. The
93
+ * number of objects a file declares, when that is more than `most` or more than this process can
94
+ * hold; undefined when the file can be read.
95
+ */
96
+ export function tooManyObjects(original: Uint8Array, most = MAX_OBJECTS): number | undefined {
97
+ const objects = declaredObjectCount(original);
98
+ if (objects === undefined) return undefined;
99
+ const heap = getHeapStatistics();
100
+ const free = heap.heap_size_limit - heap.used_heap_size;
101
+ return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
102
+ }
103
+
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 {
106
+ let name = raw;
107
+ // Until nothing changes: a library may keep an escape it did not decode as literal characters.
108
+ for (;;) {
109
+ const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
110
+ if (next === name) return name;
111
+ name = next;
112
+ }
113
+ }
114
+
115
+ const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
116
+ /** `/Name Do`: the operator that paints an image or a form. */
117
+ const PAINTED = new RegExp(`/(${REGULAR_CHARACTER}*)[\\x00\\t\\n\\f\\r ]+Do(?!${REGULAR_CHARACTER})`, "g");
118
+
119
+ /**
120
+ * Gives a page its own resource dictionary without the images it does not paint. FPDF, TCPDF,
121
+ * jsPDF and others list every image of the file in one dictionary that all pages share.
122
+ *
123
+ * It only keeps more than is needed, never less: a name found anywhere in the content counts as
124
+ * painted, and nothing is dropped unless every stream that can name an image of this dictionary
125
+ * was read.
126
+ */
127
+ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPageLeaf): void {
128
+ const { PDFArray, PDFDict, PDFName, PDFStream } = library;
129
+ const key = (value: string) => PDFName.of(value);
130
+ const resources = page.Resources();
131
+ if (!resources) return;
132
+ const xobjects = resources.lookup(key("XObject"));
133
+ if (!(xobjects instanceof PDFDict)) return;
134
+ const entries = xobjects.entries();
135
+ if (entries.length < 2) return;
136
+ const byName = new Map(entries.map(([name, value]) => [canonicalName(name.asString().slice(1)), value]));
137
+
138
+ let readable = true;
139
+ /** Names found in content that looks them up in this page's dictionary, still to be followed. */
140
+ const found: string[] = [];
141
+ const decode = (stream: PDFObject | undefined) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
142
+ const read = (text: string) => {
143
+ for (const match of text.matchAll(PAINTED)) found.push(canonicalName(match[1]!));
144
+ };
145
+ const readStream = (stream: PDFObject | undefined) => {
146
+ const text = decode(stream);
147
+ if (text === undefined) readable = false;
148
+ else read(text);
149
+ };
150
+ // A form, a pattern, a Type 3 glyph or an annotation's appearance that has no resource dictionary
151
+ // of its own (old PDFs allow that), or has this page's, takes its names from this page's
152
+ // dictionary: read it. One with its own dictionary is independent, but can hold more content of
153
+ // the first kind: look inside.
154
+ const seen = new Set<PDFDict>();
155
+ const content = (object: PDFObject | undefined) => {
156
+ if (!(object instanceof PDFStream)) return;
157
+ const own = object.dict.lookup(key("Resources"));
158
+ if (own instanceof PDFDict && own !== resources) inside(own);
159
+ else readStream(object);
160
+ };
161
+ const patternsAndFonts = (dictionary: PDFDict) => {
162
+ const patterns = dictionary.lookup(key("Pattern"));
163
+ if (patterns instanceof PDFDict) for (const [, value] of patterns.entries()) content(context.lookup(value));
164
+ const fonts = dictionary.lookup(key("Font"));
165
+ if (!(fonts instanceof PDFDict)) return;
166
+ for (const [, value] of fonts.entries()) {
167
+ const font = context.lookup(value);
168
+ if (!(font instanceof PDFDict) || font.lookup(key("Subtype")) !== key("Type3")) continue;
169
+ const own = font.lookup(key("Resources"));
170
+ if (own instanceof PDFDict && own !== resources) {
171
+ inside(own);
172
+ continue;
173
+ }
174
+ const glyphs = font.lookup(key("CharProcs"));
175
+ if (glyphs instanceof PDFDict) for (const [, glyph] of glyphs.entries()) readStream(context.lookup(glyph));
176
+ }
177
+ };
178
+ const inside = (dictionary: PDFDict) => {
179
+ if (seen.has(dictionary)) return;
180
+ seen.add(dictionary);
181
+ const forms = dictionary.lookup(key("XObject"));
182
+ if (forms instanceof PDFDict) {
183
+ for (const [, value] of forms.entries()) {
184
+ const object = context.lookup(value);
185
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
186
+ }
187
+ }
188
+ patternsAndFonts(dictionary);
189
+ };
190
+
191
+ // 1. The page's own content. Split over several streams it is still one text: "/Im1" may end one
192
+ // stream and "Do" start the next.
193
+ const contents = page.Contents();
194
+ const streams = contents instanceof PDFArray ? contents.asArray().map((entry) => context.lookup(entry)) : contents ? [contents] : [];
195
+ const parts = streams.map(decode);
196
+ if (parts.includes(undefined)) readable = false;
197
+ else read(parts.join(" "));
198
+ // 2. The page's patterns and Type 3 fonts, and what its annotations show. Which of them the page
199
+ // uses is not worked out: all count.
200
+ patternsAndFonts(resources);
201
+ const annotations = page.Annots();
202
+ if (annotations) {
203
+ for (const entry of annotations.asArray()) {
204
+ const annotation = context.lookup(entry);
205
+ const appearances = annotation instanceof PDFDict ? annotation.lookup(key("AP")) : undefined;
206
+ if (!(appearances instanceof PDFDict)) continue;
207
+ for (const [, value] of appearances.entries()) {
208
+ const appearance = context.lookup(value);
209
+ if (appearance instanceof PDFStream) content(appearance);
210
+ else if (appearance instanceof PDFDict) for (const [, state] of appearance.entries()) content(context.lookup(state));
211
+ }
212
+ }
213
+ }
214
+ // 3. Follow what is painted: a form that is painted paints more.
215
+ const painted = new Set<string>();
216
+ while (found.length > 0) {
217
+ const next = found.pop()!;
218
+ if (painted.has(next)) continue;
219
+ painted.add(next);
220
+ const value = byName.get(next);
221
+ const object = value ? context.lookup(value) : undefined;
222
+ if (object instanceof PDFStream && object.dict.lookup(key("Subtype")) === key("Form")) content(object);
223
+ }
224
+ if (!readable) return;
225
+
226
+ const kept = entries.filter(([name]) => painted.has(canonicalName(name.asString().slice(1))));
227
+ if (kept.length === entries.length) return;
228
+ const fewer = context.obj({});
229
+ for (const [name, value] of kept) fewer.set(name, value);
230
+ const own = resources.clone(context);
231
+ own.set(key("XObject"), fewer);
232
+ page.set(key("Resources"), own);
233
+ }
234
+
235
+ /** A PDF with pages `from` to `last` of `source`. Changes `source`: use it only for smaller cuts afterwards. */
236
+ async function copyPages(library: PdfLibrary, source: import("@cantoo/pdf-lib").PDFDocument, pages: PDFPage[], from: number, last: number): Promise<Uint8Array> {
237
+ const { PDFDocument, PDFName, PDFNull, PDFObjectCopier, PDFPage: Page, PDFPageLeaf: Leaf } = library;
238
+ const { context } = source;
239
+ const wanted = pages.slice(from - 1, last);
240
+ const wantedReferences = new Set(wanted.map((page) => page.ref));
241
+ // Every other page becomes nothing, so a link, a form field or a thread that leads to it copies
242
+ // a few bytes and not the page. (Null, not an empty page: the cut must not hold objects that
243
+ // call themselves pages and are not among its pages.)
244
+ for (const page of pages) {
245
+ if (!wantedReferences.has(page.ref)) context.assign(page.ref, PDFNull);
246
+ }
247
+ for (const page of wanted) {
248
+ for (const entry of DROPPED_PAGE_ENTRIES) page.node.delete(PDFName.of(entry));
249
+ try {
250
+ dropUnusedImages(library, context, page.node);
251
+ } catch {
252
+ // An unusual resource dictionary: the page is copied with everything it lists.
253
+ }
254
+ }
255
+ const target = await PDFDocument.create({ updateMetadata: false });
256
+ // One copier for everything, and each page copied through its reference: an annotation's /P then
257
+ // points at the copied page, and the layer settings below name the layers the pages use.
258
+ const copier = PDFObjectCopier.for(context, target.context);
259
+ for (const page of wanted) {
260
+ const reference = copier.copy(page.ref);
261
+ const node = target.context.lookup(reference);
262
+ if (!(node instanceof Leaf)) throw new Error("A page of this PDF is not a page object.");
263
+ target.addPage(Page.of(node, reference, target));
264
+ }
265
+ // Without these, a layer that the file hides would be shown.
266
+ const layers = source.catalog.get(PDFName.of("OCProperties"));
267
+ if (layers) target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
268
+ return target.save();
269
+ }
270
+
271
+ /**
272
+ * Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
273
+ * `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
274
+ * Throws an Error whose message can be shown to a model: for a file that cannot be opened, a page
275
+ * that does not exist, and a first page that does not fit by itself.
276
+ *
277
+ * `expectedPages` is the page count the text of the file was extracted with. The text came from
278
+ * another PDF reader; if the two do not count the same pages, a page number may not mean the same
279
+ * page in both, and showing the wrong page is worse than showing none.
280
+ */
281
+ export async function cutPdfPages(original: Uint8Array, from: number, to: number, maxBytes: number, expectedPages?: number): Promise<PageCut> {
282
+ const library = await loadPdfLibrary();
283
+ // Refuse a file that says it has more objects than this process can hold, instead of running out of memory.
284
+ const objects = tooManyObjects(original);
285
+ if (objects !== undefined) throw new Error(`This PDF has ${objects.toLocaleString("en-US")} objects, too many to cut pages from it in memory.`);
286
+ let source: import("@cantoo/pdf-lib").PDFDocument;
287
+ let pages: PDFPage[];
288
+ 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: "" });
291
+ pages = source.getPages();
292
+ } catch (error) {
293
+ const needsPassword = /password/i.test(error instanceof Error ? error.message : String(error));
294
+ throw new Error(needsPassword ? "This PDF needs a password to open, so its pages cannot be shown." : UNREADABLE);
295
+ }
296
+ const pageCount = pages.length;
297
+ // A damaged file can be read as a file without pages: the library skips what it cannot parse.
298
+ if (pageCount === 0) throw new Error(UNREADABLE);
299
+ if (expectedPages !== undefined && pageCount !== expectedPages) {
300
+ throw new Error(`The pages of this PDF could not be matched to its text (${pageCount} pages against ${expectedPages}), so they cannot be shown.`);
301
+ }
302
+ if (from < 1 || from > pageCount) throw new Error(`There is no page ${from}: the file has ${pageCount} ${pageCount === 1 ? "page" : "pages"}.`);
303
+ let smallest = 0;
304
+ for (let last = Math.min(Math.max(to, from), pageCount); last >= from; last--) {
305
+ let bytes: Uint8Array;
306
+ try {
307
+ bytes = await copyPages(library, source, pages, from, last);
308
+ } catch {
309
+ throw new Error("The pages could not be cut out of this PDF. It may be damaged.");
310
+ }
311
+ if (bytes.length <= maxBytes) return { bytes, from, to: last, pageCount };
312
+ smallest = bytes.length;
313
+ }
314
+ throw new Error(`Page ${from} is ${formatBytes(smallest)} as a file, more than the ${formatBytes(Math.max(0, maxBytes))} that fit in this request.`);
315
+ }