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
package/src/pdf-work.ts
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds a page of a PDF that would hold the server for a long time while pdf.js reads its text,
|
|
3
|
+
* before pdf.js reads any page.
|
|
4
|
+
*
|
|
5
|
+
* pdf.js reads the text of a page in one go: until it is done, no timer and no other request runs,
|
|
6
|
+
* and nothing stops it. What it runs for a page:
|
|
7
|
+
* - the content of the page;
|
|
8
|
+
* - each form the content paints, again each time it is painted, with what that form paints. A
|
|
9
|
+
* form that shows no text is skipped after its first paint in the same content;
|
|
10
|
+
* - each font the content sets, the first time any page sets it: the font program and its maps are
|
|
11
|
+
* read, and every glyph program of a Type3 font is run, with the forms, patterns and soft masks
|
|
12
|
+
* it paints (each form again each time). Images in glyphs are not decoded to read text.
|
|
13
|
+
* This adds that up from the structure of the file, read with @cantoo/pdf-lib, without running
|
|
14
|
+
* anything. Where it cannot tell, it counts high: every name before a `Do` may be the one painted,
|
|
15
|
+
* and a form with anything that looks like a text operator shows text. It follows pdf.js 5.4
|
|
16
|
+
* (unpdf 1.4); another version of pdf.js may run more.
|
|
17
|
+
*
|
|
18
|
+
* Units are about one byte of content: pdf.js read 160 MB of text operators in 23 to 29 s, about
|
|
19
|
+
* 0.16 µs a byte. A form costs more than its bytes each time it is run (`TEXT_PAINT`,
|
|
20
|
+
* `GLYPH_PAINT`).
|
|
21
|
+
*/
|
|
22
|
+
import { createInflate, inflateSync } from "node:zlib";
|
|
23
|
+
import type { PDFDict, PDFDocument, PDFObject, PDFRawStream } from "@cantoo/pdf-lib";
|
|
24
|
+
import { TimeSlicer } from "./pause.js";
|
|
25
|
+
import { canonicalName, latin1 } from "./pdf-pages.js";
|
|
26
|
+
|
|
27
|
+
type PdfLibrary = typeof import("@cantoo/pdf-lib");
|
|
28
|
+
type Mode = "text" | "glyph";
|
|
29
|
+
/**
|
|
30
|
+
* What a run of content costs, and whether pdf.js would find text in it. `reach`: the depth of the
|
|
31
|
+
* shallowest open form it paints again, which pdf.js skips (Infinity when none).
|
|
32
|
+
*/
|
|
33
|
+
type Cost = { units: number; text: boolean; reach: number };
|
|
34
|
+
/** The forms being run, each with its depth: pdf.js skips a form that is already open. */
|
|
35
|
+
type Path = Map<PDFObject, number>;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A form run for its text, each time: pdf.js took 75 to 85 µs (one form painted 10,000 times, or
|
|
39
|
+
* forms inside forms 2 to 4 deep), and about 100 µs in an earlier run of forms 3 to 6 deep.
|
|
40
|
+
*/
|
|
41
|
+
export const TEXT_PAINT = 640;
|
|
42
|
+
/** A form run inside a Type3 glyph, each time: about 23 µs measured, and 1.8 KB kept until the page is read. */
|
|
43
|
+
export const GLYPH_PAINT = 256;
|
|
44
|
+
/**
|
|
45
|
+
* A page may run this much whatever the size of its file: about 1 to 1.5 s of pdf.js. The pages
|
|
46
|
+
* of the documents tested run 0.01 to 0.18 million units.
|
|
47
|
+
*/
|
|
48
|
+
export const PAGE_WORK_ALLOWANCE = 8 * 1024 * 1024;
|
|
49
|
+
/**
|
|
50
|
+
* Past the allowance, a page may run this many times the size of the whole file. The content of
|
|
51
|
+
* real pages is packed 3 to 10 times; a page past this draws far more than its file can explain.
|
|
52
|
+
*/
|
|
53
|
+
export const PAGE_WORK_EXPANSION = 32;
|
|
54
|
+
/**
|
|
55
|
+
* The pages of a file together may run this many pages' limits, and no more content is decoded
|
|
56
|
+
* to check it: 60 pages that show one 4 MB stream of a 25 KB file kept pdf.js busy for 40 s.
|
|
57
|
+
*/
|
|
58
|
+
const FILE_WORK_PAGES = 4;
|
|
59
|
+
/**
|
|
60
|
+
* What looking at one entry of a resource dictionary costs the check, against the same budget as
|
|
61
|
+
* the content it decodes: content can make it look through a dictionary of a million entries again
|
|
62
|
+
* and again (a 4 MB file made it fill 4 GB). Real pages look at tens of entries.
|
|
63
|
+
*/
|
|
64
|
+
const VISIT = 16;
|
|
65
|
+
/** A resource dictionary with more entries than this is kept apart: not compared with others. */
|
|
66
|
+
const MAX_COMPARED = 4_096;
|
|
67
|
+
/** Forms inside forms that are followed, at most. Real files nest a few. */
|
|
68
|
+
const MAX_DEPTH = 64;
|
|
69
|
+
/** Content decoded by @cantoo/pdf-lib, which keeps all it decodes: past this one stream is refused. */
|
|
70
|
+
const MAX_KEPT = 64 * 1024 * 1024;
|
|
71
|
+
/** Decoded content is read in pieces of this size, and decoded in one go below `SMALL`. */
|
|
72
|
+
const PIECE = 64 * 1024;
|
|
73
|
+
const SMALL = 1024 * 1024;
|
|
74
|
+
/** Distinct names kept between two `Do`s. Past it, every drawing the content can name may be painted. */
|
|
75
|
+
const MAX_NAMES = 10_000;
|
|
76
|
+
/** A token longer than this is not a name of the file: the content may name any of its drawings. */
|
|
77
|
+
const MAX_TOKEN = 4_096;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Why a file is refused: a page runs more than the limit (`heavy`), the pages together hold far
|
|
81
|
+
* more content than the file (`file`), or a page's content cannot be measured here (`unreadable`).
|
|
82
|
+
*/
|
|
83
|
+
export class HeavyPage extends Error {
|
|
84
|
+
constructor(readonly reason: "heavy" | "file" | "unreadable", readonly page = 0) {
|
|
85
|
+
super(reason);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const REGULAR = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
|
|
90
|
+
/** A name, or the operator `Do`, read with no regard to strings and comments: over, never under. */
|
|
91
|
+
const TOKEN = new RegExp(`/(${REGULAR}*)|(?<!${REGULAR})Do(?!${REGULAR})`, "g");
|
|
92
|
+
/** White space and delimiters of PDF syntax, by character code. */
|
|
93
|
+
const SPECIAL = new Uint8Array(256);
|
|
94
|
+
for (const character of "\x00\t\n\f\r /[]<>(){}%") SPECIAL[character.charCodeAt(0)] = 1;
|
|
95
|
+
/** What pdf.js could turn into text: Tj, TJ, ' and ". */
|
|
96
|
+
const TEXT_OPERATOR = /Tj|TJ|['"]/;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Reads the decoded content of a run a piece at a time: its length, whether it may show text,
|
|
100
|
+
* and the names written before each `Do` (a window). The content is split into tokens at white
|
|
101
|
+
* space and delimiters only, so a `Do` or a name inside a string or a comment counts too: pdf.js
|
|
102
|
+
* paints at most what this finds, whatever the content hides in strings, comments and images.
|
|
103
|
+
*/
|
|
104
|
+
class Scan {
|
|
105
|
+
length = 0;
|
|
106
|
+
text = false;
|
|
107
|
+
/** Names written anywhere: the fonts, patterns and shadings that may be set. Null: any. */
|
|
108
|
+
seen: Set<string> | null = new Set();
|
|
109
|
+
/** The windows closed since `take` was last called. Null: any drawing may be painted. */
|
|
110
|
+
private windows: Array<Set<string> | null> = [];
|
|
111
|
+
private names: Set<string> | null = new Set();
|
|
112
|
+
private carry = "";
|
|
113
|
+
private last = "";
|
|
114
|
+
|
|
115
|
+
feed(piece: string): void {
|
|
116
|
+
this.length += piece.length;
|
|
117
|
+
if (!this.text && TEXT_OPERATOR.test(this.last + piece)) this.text = true;
|
|
118
|
+
this.last = piece.slice(-1);
|
|
119
|
+
const text = this.carry + piece;
|
|
120
|
+
// A token cut at the end of the piece goes on in the next one. A name keeps its "/".
|
|
121
|
+
let cut = text.length;
|
|
122
|
+
while (cut > 0 && SPECIAL[text.charCodeAt(cut - 1)] !== 1) cut--;
|
|
123
|
+
if (cut > 0 && text.charCodeAt(cut - 1) === 47) cut--;
|
|
124
|
+
this.tokens(text.slice(0, cut));
|
|
125
|
+
this.carry = text.slice(cut);
|
|
126
|
+
if (this.carry.length > MAX_TOKEN) {
|
|
127
|
+
this.names = null;
|
|
128
|
+
this.seen = null;
|
|
129
|
+
this.carry = "";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The end of one stream of a page's content. pdf.js joins the next one to it with nothing
|
|
135
|
+
* between, so a token cut here goes on in the next stream; it is also read as ending here.
|
|
136
|
+
*/
|
|
137
|
+
boundary(): void {
|
|
138
|
+
if (this.carry) this.tokens(`${this.carry} `);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
end(): void {
|
|
142
|
+
this.tokens(`${this.carry} `);
|
|
143
|
+
this.carry = "";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Content whose tokens cannot be read (stored with a predictor): it may show text, set anything,
|
|
148
|
+
* and paint any drawing it can name once every 4 bytes ("/ Do" is the shortest paint).
|
|
149
|
+
*/
|
|
150
|
+
blind(length: number): void {
|
|
151
|
+
this.length += length;
|
|
152
|
+
this.text = true;
|
|
153
|
+
this.seen = null;
|
|
154
|
+
this.names = null;
|
|
155
|
+
this.blindPaints += Math.ceil(length / 4);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Paints in content that `blind` counted, since `take` was last called. */
|
|
159
|
+
private blindPaints = 0;
|
|
160
|
+
|
|
161
|
+
/** The windows closed since the last call, each with how many paints it stands for. */
|
|
162
|
+
take(): Array<[Set<string> | null, number]> {
|
|
163
|
+
const taken: Array<[Set<string> | null, number]> = this.windows.map((window) => [window, 1]);
|
|
164
|
+
if (this.blindPaints > 0) taken.push([null, this.blindPaints]);
|
|
165
|
+
this.windows = [];
|
|
166
|
+
this.blindPaints = 0;
|
|
167
|
+
return taken;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private tokens(text: string): void {
|
|
171
|
+
for (const match of text.matchAll(TOKEN)) {
|
|
172
|
+
if (match[1] !== undefined) {
|
|
173
|
+
const name = canonicalName(match[1]);
|
|
174
|
+
if (name === undefined) {
|
|
175
|
+
// A name that cannot be read may be any of them.
|
|
176
|
+
this.names = null;
|
|
177
|
+
this.seen = null;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (this.names && this.names.add(name).size > MAX_NAMES) this.names = null;
|
|
181
|
+
if (this.seen && this.seen.add(name).size > MAX_NAMES) this.seen = null;
|
|
182
|
+
} else {
|
|
183
|
+
this.windows.push(this.names);
|
|
184
|
+
this.names = new Set();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The entries of a resource dictionary of one kind, by name as content writes it, each once. */
|
|
191
|
+
type Named = Map<string, PDFObject[]>;
|
|
192
|
+
const NONE: Named = new Map();
|
|
193
|
+
|
|
194
|
+
/** The resource dictionaries' kinds that change what content costs. */
|
|
195
|
+
const KINDS = ["XObject", "Font", "ExtGState", "Pattern", "Shading"];
|
|
196
|
+
|
|
197
|
+
class PageWork {
|
|
198
|
+
/** The cost of a form (or a pattern) run with resources, by `resourcesKey`. */
|
|
199
|
+
private readonly memo: Record<Mode, Map<PDFObject, Map<string, Cost>>> = { text: new Map(), glyph: new Map() };
|
|
200
|
+
/**
|
|
201
|
+
* The entries of each dictionary of one kind of resource (XObject, Font...), kept by that
|
|
202
|
+
* dictionary: many resource dictionaries can share one, so it is read once, whatever its size.
|
|
203
|
+
*/
|
|
204
|
+
private readonly named = new Map<PDFDict, Named>();
|
|
205
|
+
/** Every entry of a dictionary once: what content that may name anything may use. */
|
|
206
|
+
private readonly every = new WeakMap<Named, PDFObject[]>();
|
|
207
|
+
/** A number for each such dictionary, the same for dictionaries written the same. */
|
|
208
|
+
private readonly groupIds = new Map<PDFDict, number>();
|
|
209
|
+
private readonly groupTexts = new Map<string, number>();
|
|
210
|
+
private readonly keys = new Map<PDFDict, string>();
|
|
211
|
+
private readonly ids = new Map<PDFObject, number>();
|
|
212
|
+
/** The units of the content of pages measured so far, by content stream and `resourcesKey`. */
|
|
213
|
+
private readonly pages = new Map<PDFObject, Map<string, number>>();
|
|
214
|
+
/** Fonts read so far: pdf.js reads a font once for the whole file. */
|
|
215
|
+
private readonly fonts = new Set<PDFObject>();
|
|
216
|
+
/** Content decoded and entries looked at so far, for the whole file, against `budget`. */
|
|
217
|
+
private spent = 0;
|
|
218
|
+
/** Fonts read for the page being measured. */
|
|
219
|
+
private extra = 0;
|
|
220
|
+
|
|
221
|
+
constructor(
|
|
222
|
+
private readonly library: PdfLibrary,
|
|
223
|
+
private readonly document: PDFDocument,
|
|
224
|
+
private readonly limit: number,
|
|
225
|
+
private readonly budget: number,
|
|
226
|
+
private readonly slicer: TimeSlicer,
|
|
227
|
+
) {}
|
|
228
|
+
|
|
229
|
+
/** The units pdf.js would run for the text of a page. Throws `HeavyPage` past the limit. */
|
|
230
|
+
async page(contents: PDFObject[], resources: PDFDict | undefined): Promise<number> {
|
|
231
|
+
this.extra = 0;
|
|
232
|
+
// Pages that show the same content with the same resources cost the same: it is read once here
|
|
233
|
+
// (pdf.js runs it for each page, between which other requests get a turn).
|
|
234
|
+
const single = contents.length === 1 ? this.lookup(contents[0]) : undefined;
|
|
235
|
+
const key = this.resourcesKey(resources);
|
|
236
|
+
const known = single ? this.pages.get(single)?.get(key) : undefined;
|
|
237
|
+
if (known !== undefined) return known;
|
|
238
|
+
const { units } = await this.run(contents, resources, "text", new Map());
|
|
239
|
+
const total = units + this.extra;
|
|
240
|
+
if (total > this.limit) throw new HeavyPage("heavy");
|
|
241
|
+
if (single) {
|
|
242
|
+
let byResources = this.pages.get(single);
|
|
243
|
+
if (!byResources) this.pages.set(single, (byResources = new Map()));
|
|
244
|
+
byResources.set(key, units);
|
|
245
|
+
}
|
|
246
|
+
return total;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Resource dictionaries that name the same objects the same way give content the same cost.
|
|
251
|
+
* Pages often have dictionaries of their own written the same, so this is what costs are kept by.
|
|
252
|
+
*/
|
|
253
|
+
private resourcesKey(resources: PDFDict | undefined): string {
|
|
254
|
+
if (!resources) return "";
|
|
255
|
+
let key = this.keys.get(resources);
|
|
256
|
+
if (key !== undefined) return key;
|
|
257
|
+
key = KINDS.map((kind) => this.groupId(this.group(resources, kind))).join(" ");
|
|
258
|
+
this.keys.set(resources, key);
|
|
259
|
+
return key;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The number of a dictionary of one kind of resource: worked out once for each dictionary. */
|
|
263
|
+
private groupId(group: PDFDict | undefined): number {
|
|
264
|
+
if (!group) return -1;
|
|
265
|
+
let known = this.groupIds.get(group);
|
|
266
|
+
if (known !== undefined) return known;
|
|
267
|
+
if (this.entriesOf(group).size > MAX_COMPARED) {
|
|
268
|
+
// Sorting and writing out every entry would cost more than sharing a cost saves.
|
|
269
|
+
this.groupIds.set(group, (known = -2 - this.groupIds.size));
|
|
270
|
+
return known;
|
|
271
|
+
}
|
|
272
|
+
const id = (object: PDFObject) => {
|
|
273
|
+
let number = this.ids.get(object);
|
|
274
|
+
if (number === undefined) this.ids.set(object, (number = this.ids.size));
|
|
275
|
+
return number;
|
|
276
|
+
};
|
|
277
|
+
const text = JSON.stringify([...this.entriesOf(group)]
|
|
278
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
279
|
+
.map(([name, objects]) => [name, objects.map(id)]));
|
|
280
|
+
known = this.groupTexts.get(text);
|
|
281
|
+
if (known === undefined) this.groupTexts.set(text, (known = this.groupTexts.size));
|
|
282
|
+
this.groupIds.set(group, known);
|
|
283
|
+
return known;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private over(units: number): void {
|
|
287
|
+
if (units + this.extra > this.limit) throw new HeavyPage("heavy");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Spends `amount` of the file's budget. Throws `HeavyPage` past it. */
|
|
291
|
+
private spend(amount: number): void {
|
|
292
|
+
this.spent += amount;
|
|
293
|
+
if (this.spent > this.budget) throw new HeavyPage("file");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** One entry of a resource dictionary looked at: it costs `VISIT`, and others get their turn. */
|
|
297
|
+
private async visit(): Promise<void> {
|
|
298
|
+
this.spend(VISIT);
|
|
299
|
+
await this.slicer.maybePause();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private lookup(object: PDFObject | undefined): PDFObject | undefined {
|
|
303
|
+
return object === undefined ? undefined : this.document.context.lookup(object);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
/** The dictionary of `kind` (XObject, Font, Pattern, Shading, ExtGState) in a resource dictionary. */
|
|
308
|
+
private group(resources: PDFDict | undefined, kind: string): PDFDict | undefined {
|
|
309
|
+
const group = resources ? this.lookup(resources.get(this.library.PDFName.of(kind))) : undefined;
|
|
310
|
+
return group instanceof this.library.PDFDict ? group : undefined;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The entries of `kind` in a resource dictionary. */
|
|
314
|
+
private entries(resources: PDFDict | undefined, kind: string): Named {
|
|
315
|
+
const group = this.group(resources, kind);
|
|
316
|
+
return group ? this.entriesOf(group) : NONE;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private entriesOf(group: PDFDict): Named {
|
|
320
|
+
let named = this.named.get(group);
|
|
321
|
+
if (named) return named;
|
|
322
|
+
// Names written apart can be one name ("/a" and "/#61"); an object listed many times counts once.
|
|
323
|
+
const sets = new Map<string, Set<PDFObject>>();
|
|
324
|
+
for (const [key, value] of group.entries()) {
|
|
325
|
+
const object = this.lookup(value);
|
|
326
|
+
if (object === undefined) continue;
|
|
327
|
+
// A key that cannot be read keeps its escapes: no name read from content (which has none
|
|
328
|
+
// left) can be the same, so only content that may name anything reaches it.
|
|
329
|
+
const raw = key.asString().slice(1);
|
|
330
|
+
const name = canonicalName(raw) ?? raw;
|
|
331
|
+
let set = sets.get(name);
|
|
332
|
+
if (!set) sets.set(name, (set = new Set()));
|
|
333
|
+
set.add(object);
|
|
334
|
+
}
|
|
335
|
+
named = new Map([...sets].map(([name, set]) => [name, [...set]]));
|
|
336
|
+
this.named.set(group, named);
|
|
337
|
+
return named;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The entries of `kind` that `names` may name: all of them, each once, when `names` is null. */
|
|
341
|
+
private pick(named: Named, names: Set<string> | null): PDFObject[] {
|
|
342
|
+
if (names === null) {
|
|
343
|
+
let all = this.every.get(named);
|
|
344
|
+
if (!all) this.every.set(named, (all = [...new Set([...named.values()].flat())]));
|
|
345
|
+
return all;
|
|
346
|
+
}
|
|
347
|
+
const picked: PDFObject[] = [];
|
|
348
|
+
for (const name of names) {
|
|
349
|
+
const objects = named.get(name);
|
|
350
|
+
if (objects) picked.push(...objects);
|
|
351
|
+
}
|
|
352
|
+
return picked;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* The decoded content of a stream, a piece at a time, as pdf.js reads it: a stream it cannot
|
|
357
|
+
* decode from the start is empty to it, and one damaged on the way gives what came before the
|
|
358
|
+
* damage. Throws `HeavyPage` for content stored in a way pdf-lib does not decode.
|
|
359
|
+
*/
|
|
360
|
+
private async *pieces(object: PDFObject | undefined): AsyncGenerator<string> {
|
|
361
|
+
const { PDFArray, PDFName, PDFRawStream, UnsupportedEncodingError, decodePDFRawStream } = this.library;
|
|
362
|
+
const stream = this.lookup(object);
|
|
363
|
+
if (!(stream instanceof PDFRawStream)) return;
|
|
364
|
+
const filter = this.lookup(stream.dict.get(PDFName.of("Filter")));
|
|
365
|
+
const filters = filter instanceof PDFArray ? filter.asArray().map((entry) => this.lookup(entry)) : filter ? [filter] : [];
|
|
366
|
+
const count = (piece: { length: number }) => this.spend(piece.length);
|
|
367
|
+
const flate = filters.length === 1 && (filters[0] === PDFName.of("FlateDecode") || filters[0] === PDFName.of("Fl"));
|
|
368
|
+
if (filters.length === 0 || flate) {
|
|
369
|
+
let data = stream.contents;
|
|
370
|
+
if (stream.transform) {
|
|
371
|
+
// An encrypted file: decrypted first, with nothing else undone.
|
|
372
|
+
data = decodePDFRawStream(PDFRawStream.of(this.document.context.obj({}), stream.contents, stream.transform)).decode();
|
|
373
|
+
}
|
|
374
|
+
if (!flate) {
|
|
375
|
+
for (let at = 0; at < data.length; at += PIECE) {
|
|
376
|
+
const piece = data.subarray(at, at + PIECE);
|
|
377
|
+
count(piece);
|
|
378
|
+
yield latin1(piece);
|
|
379
|
+
await this.slicer.maybePause();
|
|
380
|
+
}
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
let whole: Buffer | undefined;
|
|
384
|
+
try {
|
|
385
|
+
whole = inflateSync(data, { maxOutputLength: SMALL });
|
|
386
|
+
} catch {
|
|
387
|
+
// Larger than SMALL, or damaged: in pieces below.
|
|
388
|
+
}
|
|
389
|
+
if (whole) {
|
|
390
|
+
count(whole);
|
|
391
|
+
yield latin1(whole);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const inflate = createInflate({ chunkSize: PIECE });
|
|
395
|
+
inflate.end(data);
|
|
396
|
+
const output = (inflate as AsyncIterable<Buffer>)[Symbol.asyncIterator]();
|
|
397
|
+
try {
|
|
398
|
+
for (;;) {
|
|
399
|
+
let next: IteratorResult<Buffer>;
|
|
400
|
+
try {
|
|
401
|
+
next = await output.next();
|
|
402
|
+
} catch {
|
|
403
|
+
return; // Damaged: pdf.js runs what came before.
|
|
404
|
+
}
|
|
405
|
+
if (next.done) return;
|
|
406
|
+
count(next.value);
|
|
407
|
+
yield latin1(next.value);
|
|
408
|
+
await this.slicer.maybePause();
|
|
409
|
+
}
|
|
410
|
+
} finally {
|
|
411
|
+
inflate.destroy();
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
let decoder: ReturnType<typeof decodePDFRawStream>;
|
|
415
|
+
try {
|
|
416
|
+
decoder = decodePDFRawStream(stream);
|
|
417
|
+
} catch (error) {
|
|
418
|
+
// A filter pdf-lib does not have (pdf.js has more): the content cannot be measured.
|
|
419
|
+
if (error instanceof UnsupportedEncodingError) throw new HeavyPage("unreadable");
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
let kept = 0;
|
|
423
|
+
for (;;) {
|
|
424
|
+
let piece: Uint8Array;
|
|
425
|
+
try {
|
|
426
|
+
const bytes = decoder.getBytes(PIECE);
|
|
427
|
+
piece = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
428
|
+
} catch {
|
|
429
|
+
// Damaged on the way: what was decoded before it, as pdf.js runs it.
|
|
430
|
+
const state = decoder as unknown as { buffer?: Uint8Array; bufferLength?: number; pos?: number };
|
|
431
|
+
if (state.buffer && typeof state.bufferLength === "number" && typeof state.pos === "number" && state.bufferLength > state.pos) {
|
|
432
|
+
const rest = state.buffer.subarray(state.pos, state.bufferLength);
|
|
433
|
+
count(rest);
|
|
434
|
+
yield latin1(rest);
|
|
435
|
+
}
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (piece.length === 0) return;
|
|
439
|
+
count(piece);
|
|
440
|
+
kept += piece.length;
|
|
441
|
+
if (kept > MAX_KEPT) throw new HeavyPage("unreadable");
|
|
442
|
+
yield latin1(piece);
|
|
443
|
+
await this.slicer.maybePause();
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Whether a stream is stored with a predictor. pdf-lib does not undo one (pdf.js does): what it
|
|
449
|
+
* decodes is about as long as the content, but its tokens are not those of the content.
|
|
450
|
+
*/
|
|
451
|
+
private predicted(object: PDFObject | undefined): boolean {
|
|
452
|
+
const { PDFArray, PDFDict, PDFName, PDFNumber, PDFRawStream } = this.library;
|
|
453
|
+
const stream = this.lookup(object);
|
|
454
|
+
if (!(stream instanceof PDFRawStream)) return false;
|
|
455
|
+
const parameters = this.lookup(stream.dict.get(PDFName.of("DecodeParms")));
|
|
456
|
+
const list = parameters instanceof PDFArray ? parameters.asArray().map((entry) => this.lookup(entry)) : [parameters];
|
|
457
|
+
return list.some((entry) => {
|
|
458
|
+
const value = entry instanceof PDFDict ? this.lookup(entry.get(PDFName.of("Predictor"))) : undefined;
|
|
459
|
+
return value instanceof PDFNumber && value.asNumber() > 1;
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private async length(stream: PDFObject | undefined): Promise<number> {
|
|
464
|
+
let length = 0;
|
|
465
|
+
for await (const piece of this.pieces(stream)) length += piece.length;
|
|
466
|
+
return length;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Runs content as pdf.js would for text (`text`), or for a glyph of a Type3 font (`glyph`), and
|
|
471
|
+
* returns what it costs. `path` holds the forms being run, each with its depth.
|
|
472
|
+
*/
|
|
473
|
+
private async run(contents: PDFObject[], resources: PDFDict | undefined, mode: Mode, path: Path): Promise<Cost> {
|
|
474
|
+
const { PDFName, PDFRawStream } = this.library;
|
|
475
|
+
const scan = new Scan();
|
|
476
|
+
const drawings = this.entries(resources, "XObject");
|
|
477
|
+
const form = PDFName.of("Form");
|
|
478
|
+
const subtype = PDFName.of("Subtype");
|
|
479
|
+
let units = 0;
|
|
480
|
+
let text = false;
|
|
481
|
+
let reach = Number.POSITIVE_INFINITY;
|
|
482
|
+
/** Forms without text painted so far: pdf.js skips them after their first paint. */
|
|
483
|
+
const once = new Set<PDFObject>();
|
|
484
|
+
/**
|
|
485
|
+
* What a paint that may be of any drawing costs, once worked out for this content: the same each
|
|
486
|
+
* time, as the forms without text are already counted.
|
|
487
|
+
*/
|
|
488
|
+
let anyPaint: number | undefined;
|
|
489
|
+
const charge = async () => {
|
|
490
|
+
for (const [window, times] of scan.take()) {
|
|
491
|
+
let best = window === null ? anyPaint : undefined;
|
|
492
|
+
if (best === undefined) {
|
|
493
|
+
best = 0;
|
|
494
|
+
// An image painted costs nothing here: pdf.js does not decode it to read text.
|
|
495
|
+
for (const object of this.pick(drawings, window)) {
|
|
496
|
+
await this.visit();
|
|
497
|
+
if (!(object instanceof PDFRawStream) || this.lookup(object.dict.get(subtype)) !== form) continue;
|
|
498
|
+
const pending = this.form(object, resources, mode, path);
|
|
499
|
+
const cost = pending instanceof Promise ? await pending : pending;
|
|
500
|
+
reach = Math.min(reach, cost.reach);
|
|
501
|
+
if (mode === "glyph") best = Math.max(best, GLYPH_PAINT + cost.units);
|
|
502
|
+
else if (cost.text) {
|
|
503
|
+
text = true;
|
|
504
|
+
best = Math.max(best, TEXT_PAINT + cost.units);
|
|
505
|
+
} else if (!once.has(object)) {
|
|
506
|
+
once.add(object);
|
|
507
|
+
units += TEXT_PAINT + cost.units;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
if (window === null) anyPaint = best;
|
|
511
|
+
}
|
|
512
|
+
units += best * times;
|
|
513
|
+
this.over(units + scan.length);
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
for (const stream of contents) {
|
|
517
|
+
const blind = this.predicted(stream);
|
|
518
|
+
for await (const piece of this.pieces(stream)) {
|
|
519
|
+
if (blind) scan.blind(piece.length);
|
|
520
|
+
else scan.feed(piece);
|
|
521
|
+
await charge();
|
|
522
|
+
this.over(units + scan.length);
|
|
523
|
+
}
|
|
524
|
+
scan.boundary();
|
|
525
|
+
}
|
|
526
|
+
scan.end();
|
|
527
|
+
await charge();
|
|
528
|
+
units += scan.length;
|
|
529
|
+
this.over(units);
|
|
530
|
+
text ||= scan.text;
|
|
531
|
+
await this.fontsOf(resources, scan.seen);
|
|
532
|
+
if (mode === "glyph") {
|
|
533
|
+
const extras = await this.glyphExtras(resources, scan.seen, path);
|
|
534
|
+
units += extras.units;
|
|
535
|
+
reach = Math.min(reach, extras.reach);
|
|
536
|
+
}
|
|
537
|
+
this.over(units);
|
|
538
|
+
return { units, text, reach };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* The cost of running a form once: known at once when it has been run with the same resources.
|
|
543
|
+
* A form that is already being run is skipped by pdf.js, which costs nothing.
|
|
544
|
+
*/
|
|
545
|
+
private form(object: PDFRawStream, painter: PDFDict | undefined, mode: Mode, path: Path): Cost | Promise<Cost> {
|
|
546
|
+
const open = path.get(object);
|
|
547
|
+
if (open !== undefined) return { units: 0, text: false, reach: open };
|
|
548
|
+
const own = this.lookup(object.dict.get(this.library.PDFName.of("Resources")));
|
|
549
|
+
// A form without resources of its own uses those of the content that paints it.
|
|
550
|
+
const resources = own instanceof this.library.PDFDict ? own : painter;
|
|
551
|
+
const key = this.resourcesKey(resources);
|
|
552
|
+
return this.memo[mode].get(object)?.get(key) ?? this.firstRun(object, resources, key, mode, path);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private async firstRun(object: PDFRawStream, resources: PDFDict | undefined, key: string, mode: Mode, path: Path): Promise<Cost> {
|
|
556
|
+
const depth = path.size;
|
|
557
|
+
if (depth >= MAX_DEPTH) throw new HeavyPage("heavy");
|
|
558
|
+
path.set(object, depth);
|
|
559
|
+
let cost: Cost;
|
|
560
|
+
try {
|
|
561
|
+
cost = await this.run([object], resources, mode, path);
|
|
562
|
+
} finally {
|
|
563
|
+
path.delete(object);
|
|
564
|
+
}
|
|
565
|
+
// A form that paints a form open further up costs what it costs only on this path: pdf.js
|
|
566
|
+
// skips that form here, and may run it in full where it is not open. Such a cost is not kept,
|
|
567
|
+
// so it is worked out again on each path (forms that all paint each other soon pass the limit).
|
|
568
|
+
if (cost.reach < depth) return cost;
|
|
569
|
+
const kept = { ...cost, reach: Number.POSITIVE_INFINITY };
|
|
570
|
+
let byResources = this.memo[mode].get(object);
|
|
571
|
+
if (!byResources) this.memo[mode].set(object, (byResources = new Map()));
|
|
572
|
+
byResources.set(key, kept);
|
|
573
|
+
return kept;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Reads the fonts the content may set that no page has set yet: the units go to the page. */
|
|
577
|
+
private async fontsOf(resources: PDFDict | undefined, seen: Set<string> | null): Promise<void> {
|
|
578
|
+
const { PDFArray, PDFDict } = this.library;
|
|
579
|
+
const fonts = [...this.pick(this.entries(resources, "Font"), seen)];
|
|
580
|
+
// A graphics state can set a font too.
|
|
581
|
+
for (const state of this.pick(this.entries(resources, "ExtGState"), seen)) {
|
|
582
|
+
await this.visit();
|
|
583
|
+
const entry = state instanceof PDFDict ? this.lookup(state.get(this.library.PDFName.of("Font"))) : undefined;
|
|
584
|
+
const font = entry instanceof PDFArray && entry.size() > 0 ? this.lookup(entry.get(0)) : undefined;
|
|
585
|
+
if (font) fonts.push(font);
|
|
586
|
+
}
|
|
587
|
+
for (const font of fonts) {
|
|
588
|
+
await this.visit();
|
|
589
|
+
if (!(font instanceof PDFDict) || this.fonts.has(font)) continue;
|
|
590
|
+
this.fonts.add(font);
|
|
591
|
+
this.extra += await this.font(font, resources);
|
|
592
|
+
this.over(0);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** What pdf.js reads to load a font: its programs and maps, and every glyph program of a Type3 font. */
|
|
597
|
+
private async font(font: PDFDict, listed: PDFDict | undefined): Promise<number> {
|
|
598
|
+
const { PDFArray, PDFDict, PDFName } = this.library;
|
|
599
|
+
const get = (dict: PDFDict, key: string) => this.lookup(dict.get(PDFName.of(key)));
|
|
600
|
+
let units = 0;
|
|
601
|
+
if (get(font, "Subtype") === PDFName.of("Type3")) {
|
|
602
|
+
const procs = get(font, "CharProcs");
|
|
603
|
+
const own = get(font, "Resources");
|
|
604
|
+
const resources = own instanceof PDFDict ? own : listed;
|
|
605
|
+
if (procs instanceof PDFDict) {
|
|
606
|
+
for (const [, value] of procs.entries()) {
|
|
607
|
+
await this.visit();
|
|
608
|
+
// Each glyph program is run on its own, with no forms open.
|
|
609
|
+
units += (await this.run([value], resources, "glyph", new Map())).units;
|
|
610
|
+
this.over(units);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const descendants = get(font, "DescendantFonts");
|
|
615
|
+
const parts = [font, ...(descendants instanceof PDFArray ? descendants.asArray().map((entry) => this.lookup(entry)) : [])];
|
|
616
|
+
for (const part of parts) {
|
|
617
|
+
await this.visit();
|
|
618
|
+
if (!(part instanceof PDFDict)) continue;
|
|
619
|
+
const descriptor = get(part, "FontDescriptor");
|
|
620
|
+
const streams = [get(part, "ToUnicode"), get(part, "Encoding"), get(part, "CIDToGIDMap")];
|
|
621
|
+
if (descriptor instanceof PDFDict) streams.push(get(descriptor, "FontFile"), get(descriptor, "FontFile2"), get(descriptor, "FontFile3"));
|
|
622
|
+
for (const stream of streams) units += await this.length(stream);
|
|
623
|
+
}
|
|
624
|
+
return units;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** What a glyph may paint besides its forms: patterns, shadings, and soft masks. */
|
|
628
|
+
private async glyphExtras(resources: PDFDict | undefined, seen: Set<string> | null, path: Path): Promise<{ units: number; reach: number }> {
|
|
629
|
+
const { PDFArray, PDFDict, PDFName, PDFRawStream } = this.library;
|
|
630
|
+
let units = 0;
|
|
631
|
+
let reach = Number.POSITIVE_INFINITY;
|
|
632
|
+
const paint = async (object: PDFRawStream) => {
|
|
633
|
+
const cost = await this.form(object, resources, "glyph", path);
|
|
634
|
+
reach = Math.min(reach, cost.reach);
|
|
635
|
+
return GLYPH_PAINT + cost.units;
|
|
636
|
+
};
|
|
637
|
+
const shading = async (object: PDFObject | undefined) => {
|
|
638
|
+
let sum = await this.length(object);
|
|
639
|
+
const dict = object instanceof PDFRawStream ? object.dict : object;
|
|
640
|
+
const functions = dict instanceof PDFDict ? this.lookup(dict.get(PDFName.of("Function"))) : undefined;
|
|
641
|
+
for (const entry of functions instanceof PDFArray ? functions.asArray() : [functions]) {
|
|
642
|
+
await this.visit();
|
|
643
|
+
sum += await this.length(this.lookup(entry));
|
|
644
|
+
}
|
|
645
|
+
return sum;
|
|
646
|
+
};
|
|
647
|
+
for (const pattern of this.pick(this.entries(resources, "Pattern"), seen)) {
|
|
648
|
+
await this.visit();
|
|
649
|
+
if (pattern instanceof PDFRawStream) units += await paint(pattern);
|
|
650
|
+
else if (pattern instanceof PDFDict) units += await shading(this.lookup(pattern.get(PDFName.of("Shading"))));
|
|
651
|
+
this.over(units);
|
|
652
|
+
}
|
|
653
|
+
for (const object of this.pick(this.entries(resources, "Shading"), seen)) {
|
|
654
|
+
await this.visit();
|
|
655
|
+
units += await shading(object);
|
|
656
|
+
this.over(units);
|
|
657
|
+
}
|
|
658
|
+
for (const state of this.pick(this.entries(resources, "ExtGState"), seen)) {
|
|
659
|
+
await this.visit();
|
|
660
|
+
const mask = state instanceof PDFDict ? this.lookup(state.get(PDFName.of("SMask"))) : undefined;
|
|
661
|
+
const group = mask instanceof PDFDict ? this.lookup(mask.get(PDFName.of("G"))) : undefined;
|
|
662
|
+
if (group instanceof PDFRawStream) units += await paint(group);
|
|
663
|
+
this.over(units);
|
|
664
|
+
}
|
|
665
|
+
return { units, reach };
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** The most a page of a file of `fileBytes` may run before it is refused. */
|
|
670
|
+
export function pageWorkLimit(fileBytes: number): number {
|
|
671
|
+
return Math.max(PAGE_WORK_ALLOWANCE, fileBytes * PAGE_WORK_EXPANSION);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Throws `HeavyPage` (with the page number) for the first page of a PDF whose text would take
|
|
676
|
+
* pdf.js more than `pageWorkLimit` of the file's size to read, or whose content cannot be measured
|
|
677
|
+
* here, and for a file whose pages together take more than `FILE_WORK_PAGES` such pages. Other
|
|
678
|
+
* requests get a turn every few milliseconds, and an aborted `signal` stops it. Returns the work
|
|
679
|
+
* of the heaviest page, in units. `onProgress` is told the pages checked so far, after each page.
|
|
680
|
+
*/
|
|
681
|
+
export async function checkPageWork(
|
|
682
|
+
library: PdfLibrary,
|
|
683
|
+
document: PDFDocument,
|
|
684
|
+
fileBytes: number,
|
|
685
|
+
signal?: AbortSignal,
|
|
686
|
+
onProgress?: (done: number, total: number) => void,
|
|
687
|
+
): Promise<number> {
|
|
688
|
+
const limit = pageWorkLimit(fileBytes);
|
|
689
|
+
const budget = limit * FILE_WORK_PAGES;
|
|
690
|
+
const slicer = new TimeSlicer(signal);
|
|
691
|
+
const work = new PageWork(library, document, limit, budget, slicer);
|
|
692
|
+
const { PDFArray } = library;
|
|
693
|
+
const measured = new Set<PDFObject>();
|
|
694
|
+
let heaviest = 0;
|
|
695
|
+
let total = 0;
|
|
696
|
+
const leaves = document.getPages().map((page) => page.node);
|
|
697
|
+
for (let index = 0; index < leaves.length; index++) {
|
|
698
|
+
const leaf = leaves[index]!;
|
|
699
|
+
// A page listed twice is refused by the text extractor, with its own message.
|
|
700
|
+
if (measured.has(leaf)) {
|
|
701
|
+
onProgress?.(index + 1, leaves.length);
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
measured.add(leaf);
|
|
705
|
+
const contents = leaf.Contents();
|
|
706
|
+
const streams = contents instanceof PDFArray ? contents.asArray() : contents ? [contents] : [];
|
|
707
|
+
try {
|
|
708
|
+
const units = await work.page(streams, leaf.Resources());
|
|
709
|
+
heaviest = Math.max(heaviest, units);
|
|
710
|
+
// Pages that are each within the limit can still add up to far more than the file holds:
|
|
711
|
+
// one stream of 4 MB shown by 60 pages of a 25 KB file kept pdf.js busy for 40 s.
|
|
712
|
+
total += units;
|
|
713
|
+
if (total > budget) throw new HeavyPage("file");
|
|
714
|
+
} catch (error) {
|
|
715
|
+
if (error instanceof HeavyPage) throw new HeavyPage(error.reason, index + 1);
|
|
716
|
+
throw error;
|
|
717
|
+
}
|
|
718
|
+
onProgress?.(index + 1, leaves.length);
|
|
719
|
+
await slicer.maybePause();
|
|
720
|
+
}
|
|
721
|
+
return heaviest;
|
|
722
|
+
}
|