llm-large-files 0.5.0 → 0.7.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.
- package/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/pdf-pages.ts
CHANGED
|
@@ -5,11 +5,12 @@
|
|
|
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
|
|
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 type { PDFContext, PDFDict, PDFObject, PDFObjectCopier, PDFPage, PDFPageLeaf, PDFRef } from "@cantoo/pdf-lib";
|
|
13
|
+
import { TimeSlicer } from "./pause.js";
|
|
13
14
|
import { formatBytes } from "./plan.js";
|
|
14
15
|
|
|
15
16
|
type PdfLibrary = typeof import("@cantoo/pdf-lib");
|
|
@@ -24,8 +25,173 @@ export type PageCut = {
|
|
|
24
25
|
pageCount: number;
|
|
25
26
|
};
|
|
26
27
|
|
|
27
|
-
/**
|
|
28
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Objects parsed between two pauses that let other work on the server run, when the parse cannot
|
|
30
|
+
* be paused by time (see `loadPdf`). A count is a poor measure: 500 objects of large arrays took
|
|
31
|
+
* 100 to 180 ms.
|
|
32
|
+
*/
|
|
33
|
+
export const OBJECTS_PER_TICK = 500;
|
|
34
|
+
/** Pauses while one file is parsed, at most. Each is a timer: about 15 ms on Windows, 1 ms elsewhere. */
|
|
35
|
+
const MOST_TICKS = 100;
|
|
36
|
+
const MOST_OBJECTS_PER_TICK = 4_000;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The `parseSpeed` for pdf-lib: `OBJECTS_PER_TICK`, or more for a file that declares so many
|
|
40
|
+
* objects that pausing that often would add seconds of waiting (300 pauses of 15 ms for 150,000).
|
|
41
|
+
*/
|
|
42
|
+
export function objectsPerTick(bytes: Uint8Array): number {
|
|
43
|
+
const objects = declaredObjectCount(bytes) ?? 0;
|
|
44
|
+
return Math.min(MOST_OBJECTS_PER_TICK, Math.max(OBJECTS_PER_TICK, Math.ceil(objects / MOST_TICKS)));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Work between two pauses of a parse, at least. A slice also runs twice as long as a pause took,
|
|
49
|
+
* up to `MOST_PARSE_SLICE_MS`: a pause is a timer, which waits about 15 ms on Windows and 1 ms
|
|
50
|
+
* elsewhere, and waiting should not take most of the parse.
|
|
51
|
+
*/
|
|
52
|
+
const PARSE_SLICE_MS = 12;
|
|
53
|
+
const MOST_PARSE_SLICE_MS = 40;
|
|
54
|
+
|
|
55
|
+
/** What pdf-lib's parsers and writers offer to change how they pause. Not in its types: checked before use. */
|
|
56
|
+
type Pausing = { shouldWaitForTick?: unknown };
|
|
57
|
+
/** What pdf-lib's cross-reference stream keeps. Not in its types: checked before use. */
|
|
58
|
+
type CrossReferences = { entries?: unknown; appendEntry?: unknown };
|
|
59
|
+
type CrossReference = { ref?: { objectNumber?: unknown } };
|
|
60
|
+
|
|
61
|
+
/** The files `loadPdf` is reading, each with how many reads of it are running. */
|
|
62
|
+
const timedFiles = new WeakMap<Uint8Array, number>();
|
|
63
|
+
/** The documents (their contexts) that `copyPages` saves. */
|
|
64
|
+
const timedSaves = new WeakSet<object>();
|
|
65
|
+
/** The factories of pdf-lib changed here, by class: one class for each copy of pdf-lib loaded. */
|
|
66
|
+
const changedFactories = new WeakMap<object, Set<string>>();
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* pdf-lib asks after each object it parses or writes whether to pause, and pauses with a timer
|
|
70
|
+
* when told so. This answers by time: once a slice of work has run its length. The time of the
|
|
71
|
+
* pauses is not counted.
|
|
72
|
+
*/
|
|
73
|
+
function pauseByTime(): () => boolean {
|
|
74
|
+
let sliceStart = performance.now();
|
|
75
|
+
let pausedAt: number | undefined;
|
|
76
|
+
/** The shortest pause seen, with the one object parsed after it. */
|
|
77
|
+
let pauseMs = 0;
|
|
78
|
+
return () => {
|
|
79
|
+
const now = performance.now();
|
|
80
|
+
if (pausedAt !== undefined) {
|
|
81
|
+
pauseMs = pauseMs === 0 ? now - pausedAt : Math.min(pauseMs, now - pausedAt);
|
|
82
|
+
pausedAt = undefined;
|
|
83
|
+
sliceStart = now;
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
if (now - sliceStart < Math.min(MOST_PARSE_SLICE_MS, Math.max(PARSE_SLICE_MS, 2 * pauseMs))) return false;
|
|
87
|
+
pausedAt = now;
|
|
88
|
+
return true;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Makes a parser or a writer of pdf-lib pause by time. */
|
|
93
|
+
function pauseInTime(made: unknown): void {
|
|
94
|
+
const pausing = made as Pausing | undefined;
|
|
95
|
+
if (typeof pausing?.shouldWaitForTick === "function") pausing.shouldWaitForTick = pauseByTime();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Has `change` look at what `owner[name]`, a static factory of one of pdf-lib's classes, creates,
|
|
100
|
+
* with the first argument it was given: once for each class. Any other use of pdf-lib in the
|
|
101
|
+
* process is left as it was. A version of pdf-lib built otherwise is left as it is: its parse and
|
|
102
|
+
* its writer pause by the count they are given.
|
|
103
|
+
*/
|
|
104
|
+
function changeFactory(owner: unknown, name: string, change: (first: unknown, made: unknown) => void): void {
|
|
105
|
+
if (typeof owner !== "function") return;
|
|
106
|
+
const factories = owner as unknown as Record<string, unknown>;
|
|
107
|
+
const create = factories[name];
|
|
108
|
+
const done = changedFactories.get(owner) ?? new Set<string>();
|
|
109
|
+
if (typeof create !== "function" || done.has(name)) return;
|
|
110
|
+
try {
|
|
111
|
+
factories[name] = (first: unknown, ...rest: unknown[]) => {
|
|
112
|
+
const made: unknown = create.call(owner, first, ...rest);
|
|
113
|
+
change(first, made);
|
|
114
|
+
return made;
|
|
115
|
+
};
|
|
116
|
+
done.add(name);
|
|
117
|
+
changedFactories.set(owner, done);
|
|
118
|
+
} catch {
|
|
119
|
+
// A class that cannot be changed.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Makes pdf-lib's parsers of the files in `timedFiles` pause by time. */
|
|
124
|
+
function timeParsers(library: PdfLibrary): void {
|
|
125
|
+
const parsers = (library as unknown as { PDFParser?: unknown }).PDFParser;
|
|
126
|
+
changeFactory(parsers, "forBytesWithOptions", (bytes, parser) => {
|
|
127
|
+
if (timedFiles.has(bytes as Uint8Array)) pauseInTime(parser);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Makes pdf-lib's writers of the documents in `timedSaves` pause by time. Left to itself, a writer
|
|
133
|
+
* of a cut never paused: it counts objects, and the objects it packs into streams 50 at a time
|
|
134
|
+
* make the count miss every multiple of 50 it pauses at.
|
|
135
|
+
*
|
|
136
|
+
* The writer also adds each object to its cross-reference stream by searching all the entries
|
|
137
|
+
* added so far for where it goes, though the objects come in order: the time grows with the square
|
|
138
|
+
* of their count, 0.5 s in one block for 20,000 objects. For these documents an entry that goes
|
|
139
|
+
* after the last one is added at the end at once, which gives the same entries in the same order.
|
|
140
|
+
*/
|
|
141
|
+
function timeWriters(library: PdfLibrary): void {
|
|
142
|
+
const classes = library as unknown as { PDFWriter?: unknown; PDFStreamWriter?: unknown; PDFCrossRefStream?: unknown };
|
|
143
|
+
for (const writers of [classes.PDFWriter, classes.PDFStreamWriter]) {
|
|
144
|
+
changeFactory(writers, "forContext", (context, writer) => {
|
|
145
|
+
if (timedSaves.has(context as object)) pauseInTime(writer);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
// The writer makes its stream with a dictionary of the document it writes.
|
|
149
|
+
changeFactory(classes.PDFCrossRefStream, "create", (dictionary, stream) => {
|
|
150
|
+
const context = (dictionary as { context?: unknown } | undefined)?.context;
|
|
151
|
+
if (typeof context === "object" && context !== null && timedSaves.has(context)) appendInOrder(stream);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Adds an entry that goes after the last one to the end of `stream` at once. Entries are kept by object number. */
|
|
156
|
+
function appendInOrder(stream: unknown): void {
|
|
157
|
+
const references = stream as CrossReferences | undefined;
|
|
158
|
+
const append = references?.appendEntry;
|
|
159
|
+
if (!references || typeof append !== "function" || !Array.isArray(references.entries)) return;
|
|
160
|
+
references.appendEntry = (entry: CrossReference) => {
|
|
161
|
+
const entries = references.entries as CrossReference[];
|
|
162
|
+
const last = entries.at(-1)?.ref?.objectNumber;
|
|
163
|
+
const number = entry?.ref?.objectNumber;
|
|
164
|
+
if (typeof last === "number" && typeof number === "number" && last <= number) entries.push(entry);
|
|
165
|
+
else append.call(references, entry);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Reads a PDF into objects with pdf-lib, which cannot be stopped once it has started, and pauses
|
|
171
|
+
* after every 12 to 40 ms of work so that other requests get a turn. pdf-lib itself pauses by a
|
|
172
|
+
* count of objects, and objects differ in cost a hundred times: a count of 500 held the server for
|
|
173
|
+
* 100 to 180 ms on a file of large arrays, and a file of 150,000 objects, parsed 1,500 at a time,
|
|
174
|
+
* for 0.2 to 0.55 s. What pdf-lib reads in one step still holds the server for as long as it
|
|
175
|
+
* takes, and grows with the file: one object (about 0.15 s for each MB of an array of numbers,
|
|
176
|
+
* about 0.03 s for each MB of a stream whose length the file does not give directly), and a
|
|
177
|
+
* cross-reference table written as text (0.15 s for 150,000 objects).
|
|
178
|
+
*
|
|
179
|
+
* The file is read with an empty password, which opens the many PDFs that are encrypted only to
|
|
180
|
+
* restrict printing or copying. Throws what pdf-lib throws.
|
|
181
|
+
*/
|
|
182
|
+
export async function loadPdf(library: PdfLibrary, bytes: Uint8Array): Promise<import("@cantoo/pdf-lib").PDFDocument> {
|
|
183
|
+
timeParsers(library);
|
|
184
|
+
timedFiles.set(bytes, (timedFiles.get(bytes) ?? 0) + 1);
|
|
185
|
+
try {
|
|
186
|
+
// parseSpeed pauses the parse by count, when it could not be timed.
|
|
187
|
+
return await library.PDFDocument.load(bytes, { updateMetadata: false, parseSpeed: objectsPerTick(bytes), password: "" });
|
|
188
|
+
} finally {
|
|
189
|
+
const reads = (timedFiles.get(bytes) ?? 1) - 1;
|
|
190
|
+
if (reads > 0) timedFiles.set(bytes, reads);
|
|
191
|
+
else timedFiles.delete(bytes);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
29
195
|
/** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
|
|
30
196
|
const BYTES_PER_OBJECT = 1_700;
|
|
31
197
|
/** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
|
|
@@ -101,15 +267,27 @@ export function tooManyObjects(original: Uint8Array, most = MAX_OBJECTS): number
|
|
|
101
267
|
return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
|
|
102
268
|
}
|
|
103
269
|
|
|
104
|
-
/**
|
|
105
|
-
|
|
270
|
+
/**
|
|
271
|
+
* Decodings that may still change a name. A library may keep an escape it did not decode as
|
|
272
|
+
* literal characters, so a name is decoded again; no writer escapes a name more deeply than that.
|
|
273
|
+
*/
|
|
274
|
+
const NAME_DECODINGS = 3;
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* A PDF name as the characters it stands for, so that "#20" and a space are the same name.
|
|
278
|
+
* Undefined for a name that still changes after `NAME_DECODINGS` decodings: only a file built to
|
|
279
|
+
* hold the server writes one ("#2323...2341" loses one level a decoding, and decoding it until
|
|
280
|
+
* nothing changed took 20 s for 400,000 characters). Callers treat it as a name they cannot read.
|
|
281
|
+
*/
|
|
282
|
+
export function canonicalName(raw: string): string | undefined {
|
|
106
283
|
let name = raw;
|
|
107
|
-
|
|
108
|
-
|
|
284
|
+
for (let decoding = 0; decoding <= NAME_DECODINGS; decoding++) {
|
|
285
|
+
if (!name.includes("#")) return name;
|
|
109
286
|
const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
110
287
|
if (next === name) return name;
|
|
111
288
|
name = next;
|
|
112
289
|
}
|
|
290
|
+
return undefined;
|
|
113
291
|
}
|
|
114
292
|
|
|
115
293
|
const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
|
|
@@ -133,14 +311,21 @@ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPag
|
|
|
133
311
|
if (!(xobjects instanceof PDFDict)) return;
|
|
134
312
|
const entries = xobjects.entries();
|
|
135
313
|
if (entries.length < 2) return;
|
|
136
|
-
const
|
|
314
|
+
const names = entries.map(([name]) => canonicalName(name.asString().slice(1)));
|
|
315
|
+
// A name that cannot be read cannot be matched with what the content paints: keep every image.
|
|
316
|
+
if (names.includes(undefined)) return;
|
|
317
|
+
const byName = new Map(entries.map(([, value], index) => [names[index]!, value]));
|
|
137
318
|
|
|
138
319
|
let readable = true;
|
|
139
320
|
/** Names found in content that looks them up in this page's dictionary, still to be followed. */
|
|
140
321
|
const found: string[] = [];
|
|
141
322
|
const decode = (stream: PDFObject | undefined) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
|
|
142
323
|
const read = (text: string) => {
|
|
143
|
-
for (const match of text.matchAll(PAINTED))
|
|
324
|
+
for (const match of text.matchAll(PAINTED)) {
|
|
325
|
+
const name = canonicalName(match[1]!);
|
|
326
|
+
if (name === undefined) readable = false;
|
|
327
|
+
else found.push(name);
|
|
328
|
+
}
|
|
144
329
|
};
|
|
145
330
|
const readStream = (stream: PDFObject | undefined) => {
|
|
146
331
|
const text = decode(stream);
|
|
@@ -223,7 +408,7 @@ function dropUnusedImages(library: PdfLibrary, context: PDFContext, page: PDFPag
|
|
|
223
408
|
}
|
|
224
409
|
if (!readable) return;
|
|
225
410
|
|
|
226
|
-
const kept = entries.filter((
|
|
411
|
+
const kept = entries.filter((_entry, index) => painted.has(names[index]!));
|
|
227
412
|
if (kept.length === entries.length) return;
|
|
228
413
|
const fewer = context.obj({});
|
|
229
414
|
for (const [name, value] of kept) fewer.set(name, value);
|
|
@@ -256,18 +441,87 @@ async function copyPages(library: PdfLibrary, source: import("@cantoo/pdf-lib").
|
|
|
256
441
|
// One copier for everything, and each page copied through its reference: an annotation's /P then
|
|
257
442
|
// points at the copied page, and the layer settings below name the layers the pages use.
|
|
258
443
|
const copier = PDFObjectCopier.for(context, target.context);
|
|
444
|
+
// Without these, a layer that the file hides would be shown.
|
|
445
|
+
const layers = source.catalog.get(PDFName.of("OCProperties"));
|
|
446
|
+
const roots: PDFObject[] = wanted.map((page) => page.ref);
|
|
447
|
+
await copyInTurns(library, copier, context, target.context, layers ? [...roots, layers] : roots);
|
|
259
448
|
for (const page of wanted) {
|
|
260
449
|
const reference = copier.copy(page.ref);
|
|
261
450
|
const node = target.context.lookup(reference);
|
|
262
451
|
if (!(node instanceof Leaf)) throw new Error("A page of this PDF is not a page object.");
|
|
263
452
|
target.addPage(Page.of(node, reference, target));
|
|
264
453
|
}
|
|
265
|
-
// Without these, a layer that the file hides would be shown.
|
|
266
|
-
const layers = source.catalog.get(PDFName.of("OCProperties"));
|
|
267
454
|
if (layers) target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
|
|
455
|
+
timeWriters(library);
|
|
456
|
+
timedSaves.add(target.context);
|
|
268
457
|
return target.save();
|
|
269
458
|
}
|
|
270
459
|
|
|
460
|
+
/**
|
|
461
|
+
* Does the work of `copier.copy(root)` for each of `roots`, with pauses so that other requests get
|
|
462
|
+
* a turn. pdf-lib's copier follows every reference at once: a page that refers to 4,000 large
|
|
463
|
+
* arrays held the server for 0.3 s, and one that refers to 20,000 for 0.9 s. So the objects are
|
|
464
|
+
* first numbered in the order the copier would number them, which keeps the cut the same to the
|
|
465
|
+
* byte, then copied one at a time. `copier.copy(root)` afterwards finds them copied. A copier built
|
|
466
|
+
* otherwise is left to copy everything at once.
|
|
467
|
+
*/
|
|
468
|
+
async function copyInTurns(library: PdfLibrary, copier: PDFObjectCopier, source: PDFContext, target: PDFContext, roots: PDFObject[]): Promise<void> {
|
|
469
|
+
const copied = (copier as unknown as { traversedObjects?: unknown }).traversedObjects;
|
|
470
|
+
if (!(copied instanceof Map)) return;
|
|
471
|
+
const { PDFArray, PDFDict, PDFName, PDFPageLeaf: Leaf, PDFRef, PDFStream } = library;
|
|
472
|
+
const slicer = new TimeSlicer();
|
|
473
|
+
/** Each object referred to, with its number in the cut, in the order the copier numbers them. */
|
|
474
|
+
const numbered: [PDFRef, PDFRef][] = [];
|
|
475
|
+
const seen = new Set<PDFObject>();
|
|
476
|
+
/** What the copier copies next, when it copies `object`: undefined when there is nothing more. */
|
|
477
|
+
const inside = (object: PDFObject): PDFObject[] | undefined => {
|
|
478
|
+
if (object instanceof PDFRef) {
|
|
479
|
+
if (copied.has(object)) return undefined;
|
|
480
|
+
const reference = target.nextRef();
|
|
481
|
+
copied.set(object, reference);
|
|
482
|
+
numbered.push([object, reference]);
|
|
483
|
+
const value = source.lookup(object);
|
|
484
|
+
return value ? [value] : undefined;
|
|
485
|
+
}
|
|
486
|
+
if (object instanceof Leaf) {
|
|
487
|
+
// As the copier copies a page: with what it inherits from the page tree, without its parent.
|
|
488
|
+
const page = object.clone();
|
|
489
|
+
for (const name of Leaf.InheritableEntries) {
|
|
490
|
+
const key = PDFName.of(name);
|
|
491
|
+
const value = page.getInheritableAttribute(key);
|
|
492
|
+
if (!page.get(key) && value) page.set(key, value);
|
|
493
|
+
}
|
|
494
|
+
page.delete(PDFName.of("Parent"));
|
|
495
|
+
return page.entries().map(([, value]) => value);
|
|
496
|
+
}
|
|
497
|
+
if (!(object instanceof PDFDict || object instanceof PDFArray || object instanceof PDFStream) || seen.has(object)) return undefined;
|
|
498
|
+
seen.add(object);
|
|
499
|
+
if (object instanceof PDFArray) return object.asArray();
|
|
500
|
+
return (object instanceof PDFStream ? object.dict : object).entries().map(([, value]) => value);
|
|
501
|
+
};
|
|
502
|
+
// Depth first, each object before what it refers to, as the copier goes.
|
|
503
|
+
const stack: { items: PDFObject[]; at: number }[] = [];
|
|
504
|
+
const enter = (object: PDFObject) => {
|
|
505
|
+
const items = inside(object);
|
|
506
|
+
if (items !== undefined && items.length > 0) stack.push({ items, at: 0 });
|
|
507
|
+
};
|
|
508
|
+
let steps = 0;
|
|
509
|
+
for (const root of roots) {
|
|
510
|
+
enter(root);
|
|
511
|
+
while (stack.length > 0) {
|
|
512
|
+
const top = stack[stack.length - 1]!;
|
|
513
|
+
if (top.at === top.items.length) stack.pop();
|
|
514
|
+
else enter(top.items[top.at++]!);
|
|
515
|
+
if (++steps % 1_000 === 0) await slicer.maybePause();
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
for (const [original, reference] of numbered) {
|
|
519
|
+
const value = source.lookup(original);
|
|
520
|
+
if (value) target.assign(reference, copier.copy(value));
|
|
521
|
+
await slicer.maybePause();
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
271
525
|
/**
|
|
272
526
|
* Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
|
|
273
527
|
* `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
|
|
@@ -286,8 +540,7 @@ export async function cutPdfPages(original: Uint8Array, from: number, to: number
|
|
|
286
540
|
let source: import("@cantoo/pdf-lib").PDFDocument;
|
|
287
541
|
let pages: PDFPage[];
|
|
288
542
|
try {
|
|
289
|
-
|
|
290
|
-
source = await library.PDFDocument.load(original, { updateMetadata: false, parseSpeed: OBJECTS_PER_TICK, password: "" });
|
|
543
|
+
source = await loadPdf(library, original);
|
|
291
544
|
pages = source.getPages();
|
|
292
545
|
} catch (error) {
|
|
293
546
|
const needsPassword = /password/i.test(error instanceof Error ? error.message : String(error));
|
package/src/pdf-pictures.ts
CHANGED
|
@@ -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 {
|
|
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,
|
|
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(
|
|
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
|
-
|
|
335
|
-
|
|
336
|
-
const {
|
|
337
|
-
const
|
|
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.
|