llm-large-files 0.4.1 → 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 +1400 -338
- package/README.md +217 -49
- 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 +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- 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 +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- 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 +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- 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 +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- 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 +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- 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 +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- 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 +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- 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 +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- 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 +1022 -138
- 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 +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- 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 +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- 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 +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// A plain completion on a model that may think its output limit away: shared by the part readers
|
|
2
|
+
// of every adapter.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A model that thinks counts its thoughts in its output limit. Asked for 4,096 tokens of notes on
|
|
6
|
+
* a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and Gemini 4
|
|
7
|
+
* wrote nothing at all (November 2026). A reply that was cut off that way is asked for again with
|
|
8
|
+
* this limit, the least Google recommends for a Gemini 4 model. OpenAI says to keep at least
|
|
9
|
+
* 25,000 for its reasoning models.
|
|
10
|
+
*/
|
|
11
|
+
export const THINKING_OUTPUT_TOKENS = 32_768;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* What has been learned about a model, so that a whole-file read does not pay for the wasted
|
|
15
|
+
* request with every part: the output limit it needs, or 0 when it refused that limit.
|
|
16
|
+
*/
|
|
17
|
+
const learnedLimits = new Map<string, number>();
|
|
18
|
+
/** The first request to a model that is still on its way. Others wait for what it learns. */
|
|
19
|
+
const firstRequests = new Map<string, Promise<void>>();
|
|
20
|
+
/** Models that have answered at least once. */
|
|
21
|
+
const answered = new Set<string>();
|
|
22
|
+
const MOST_REMEMBERED = 200;
|
|
23
|
+
|
|
24
|
+
function remember(model: string, limit: number): void {
|
|
25
|
+
if (learnedLimits.size >= MOST_REMEMBERED && !learnedLimits.has(model)) learnedLimits.clear();
|
|
26
|
+
learnedLimits.set(model, limit);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The errors `completeWithinLimit` threw for a reply with no text, with why the reply stopped, in
|
|
31
|
+
* the provider's word ("" when it did not say).
|
|
32
|
+
*/
|
|
33
|
+
const noTextErrors = new WeakMap<object, string>();
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Why a reply had no text, when this error is the one `completeWithinLimit` throws for it: the
|
|
37
|
+
* provider's word for why it stopped ("SAFETY", "refusal"), or "" when it did not say. Undefined
|
|
38
|
+
* for any other error. The message of that error is the package's own.
|
|
39
|
+
*/
|
|
40
|
+
export function noTextReason(error: unknown): string | undefined {
|
|
41
|
+
return typeof error === "object" && error !== null ? noTextErrors.get(error) : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A reply to a plain completion. */
|
|
45
|
+
export type LimitedReply = {
|
|
46
|
+
text: string;
|
|
47
|
+
/** True when the model stopped because it reached the output limit. */
|
|
48
|
+
cutOff: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* True when the provider stopped the reply before its end for another reason (its safety
|
|
51
|
+
* filters): what it wrote is kept, and said to be incomplete, as a reply cut off at the limit is.
|
|
52
|
+
*/
|
|
53
|
+
stopped?: boolean;
|
|
54
|
+
/** Why it stopped, in the provider's word, for the message when there is no text. */
|
|
55
|
+
reason?: string;
|
|
56
|
+
/** Tokens the model spent thinking, when the provider says. */
|
|
57
|
+
thoughts: number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
|
|
62
|
+
* reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
|
|
63
|
+
* was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
|
|
64
|
+
* the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
|
|
65
|
+
* window with it) is not asked for it again, nor is one whose window, or allowance a minute, is no
|
|
66
|
+
* larger than that limit. Requests that arrive while the first one to a model is on its way wait for it.
|
|
67
|
+
*/
|
|
68
|
+
export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
|
|
69
|
+
signal?: AbortSignal | undefined;
|
|
70
|
+
onTruncated?: (() => void) | undefined;
|
|
71
|
+
} = {}): Promise<string> {
|
|
72
|
+
const { signal } = options;
|
|
73
|
+
// The first request to a model finds out whether it thinks its limit away. The parts of a
|
|
74
|
+
// whole-file read are sent four at a time: the others wait for it, and one request is wasted
|
|
75
|
+
// on such a model, not four.
|
|
76
|
+
let learned = () => undefined as void;
|
|
77
|
+
if (!answered.has(model)) {
|
|
78
|
+
const first = firstRequests.get(model);
|
|
79
|
+
if (first) {
|
|
80
|
+
await first;
|
|
81
|
+
signal?.throwIfAborted();
|
|
82
|
+
} else {
|
|
83
|
+
firstRequests.set(model, new Promise<void>((resolve) => {
|
|
84
|
+
learned = () => {
|
|
85
|
+
if (answered.size >= MOST_REMEMBERED) answered.clear();
|
|
86
|
+
answered.add(model);
|
|
87
|
+
firstRequests.delete(model);
|
|
88
|
+
resolve();
|
|
89
|
+
};
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const known = learnedLimits.get(model);
|
|
95
|
+
const limit = Math.max(maxOutputTokens, known ?? 0);
|
|
96
|
+
let reply = await send(limit);
|
|
97
|
+
// Cut off, with nothing written or with at least half of the limit gone on thoughts: the
|
|
98
|
+
// limit was too low for this model, not the notes too long.
|
|
99
|
+
const starved = reply.cutOff && (!reply.text.trim() || reply.thoughts >= limit / 2);
|
|
100
|
+
if (starved && known !== 0 && limit < THINKING_OUTPUT_TOKENS) {
|
|
101
|
+
remember(model, THINKING_OUTPUT_TOKENS);
|
|
102
|
+
try {
|
|
103
|
+
reply = await send(THINKING_OUTPUT_TOKENS);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (signal?.aborted) throw error;
|
|
106
|
+
// A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
|
|
107
|
+
// A refusal of this request as too large for the window with that limit is no such refusal,
|
|
108
|
+
// unless the window is no larger than the limit itself: a smaller part may fit. Nothing is
|
|
109
|
+
// learned from it, and the next request starts as this one did. A request too large for
|
|
110
|
+
// what the provider allows in a minute (OpenAI's or Groq's TPM, HTTP 429 or 413) is too
|
|
111
|
+
// large the same way, with that allowance as the window. Any other failure says nothing
|
|
112
|
+
// about the limit: the next request starts with it. What the first reply had is kept; with
|
|
113
|
+
// nothing in it, this error is the one to report.
|
|
114
|
+
const { status, kind, limitTokens } = (error ?? {}) as { status?: unknown; kind?: unknown; limitTokens?: unknown };
|
|
115
|
+
if (status === 400 || kind === "context_overflow") {
|
|
116
|
+
const tooLarge = kind === "context_overflow" && !(typeof limitTokens === "number" && limitTokens <= THINKING_OUTPUT_TOKENS);
|
|
117
|
+
if (!tooLarge) remember(model, 0);
|
|
118
|
+
else if (learnedLimits.get(model) === THINKING_OUTPUT_TOKENS) learnedLimits.delete(model);
|
|
119
|
+
}
|
|
120
|
+
if (!reply.text.trim()) throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!reply.text.trim()) {
|
|
124
|
+
const error = new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
|
|
125
|
+
noTextErrors.set(error, reply.reason ?? "");
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
// The text stops mid-list when the output limit is reached, or when a filter stopped it. Say so
|
|
129
|
+
// instead of passing it off as complete.
|
|
130
|
+
if (reply.cutOff || reply.stopped) options.onTruncated?.();
|
|
131
|
+
return reply.text;
|
|
132
|
+
} finally {
|
|
133
|
+
learned();
|
|
134
|
+
}
|
|
135
|
+
}
|
package/src/pause.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Lets other work on the server run (an answer streaming to another user) before going on. */
|
|
2
|
+
export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
|
|
3
|
+
|
|
4
|
+
let turn: Promise<void> = Promise.resolve();
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `pause`, taken in turns: each caller waits for the pause before it, so one slice of work runs in
|
|
8
|
+
* a turn of the event loop. Ten uploads that pause at once then hold the server for one slice
|
|
9
|
+
* between two turns, not ten.
|
|
10
|
+
*/
|
|
11
|
+
export const fairPause = (): Promise<void> => (turn = turn.then(pause));
|
|
12
|
+
|
|
13
|
+
/** Work done between two pauses of a long loop, in milliseconds: short enough that nobody waits. */
|
|
14
|
+
const SLICE_MS = 12;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Splits a long piece of synchronous work into slices, so that one upload does not hold the whole
|
|
18
|
+
* server: call `maybePause()` now and then (every few thousand items), and it pauses once the
|
|
19
|
+
* current slice has run for about 12 ms. It also stops the work when `signal` is aborted.
|
|
20
|
+
*/
|
|
21
|
+
export class TimeSlicer {
|
|
22
|
+
private sliceStart = performance.now();
|
|
23
|
+
|
|
24
|
+
constructor(private readonly signal?: AbortSignal) {}
|
|
25
|
+
|
|
26
|
+
/** Whether the current slice has run its time: `maybePause` would pause now. */
|
|
27
|
+
get due(): boolean {
|
|
28
|
+
return performance.now() - this.sliceStart >= SLICE_MS;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async maybePause(): Promise<void> {
|
|
32
|
+
if (this.due) await this.pauseNow();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Pauses, then starts a new slice. Throws the reason of `signal` when it was aborted meanwhile. */
|
|
36
|
+
async pauseNow(): Promise<void> {
|
|
37
|
+
await fairPause();
|
|
38
|
+
this.signal?.throwIfAborted();
|
|
39
|
+
this.sliceStart = performance.now();
|
|
40
|
+
}
|
|
41
|
+
}
|
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.
|