llm-large-files 0.3.0 → 0.3.6
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 +67 -0
- package/README.md +21 -1
- package/dist/extract.d.ts +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +204 -22
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +32 -4
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +65 -15
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +17 -0
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +16 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +1 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/node/handlers.d.ts +9 -0
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +56 -13
- package/dist/node/handlers.js.map +1 -1
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +52 -9
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +6 -3
- package/dist/text.js.map +1 -1
- package/docs/api.md +29 -6
- package/docs/configuration.md +127 -1
- package/docs/getting-started.md +19 -1
- package/docs/how-it-works.md +21 -0
- package/docs/security.md +5 -0
- package/package.json +1 -1
- package/src/extract.ts +198 -19
- package/src/gemini/chat.ts +87 -19
- package/src/gemini/endpoints.ts +34 -2
- package/src/gemini/index.ts +1 -1
- package/src/node/handlers.ts +61 -9
- package/src/pdf-pictures.ts +60 -10
- package/src/text.ts +6 -3
package/src/node/handlers.ts
CHANGED
|
@@ -6,10 +6,19 @@ export type DocumentHandlerOptions = {
|
|
|
6
6
|
/**
|
|
7
7
|
* The signed-in user for this request. When set, uploads are owned by that user and other
|
|
8
8
|
* users cannot read or delete them. Return undefined to allow anonymous access.
|
|
9
|
+
*
|
|
10
|
+
* To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
|
|
11
|
+
* the `http-errors` package makes: the handler answers with that status and the error's message.
|
|
12
|
+
* Any other error is answered with a 500 that does not repeat its message. It is called before
|
|
13
|
+
* the upload is read, so a refused upload is not buffered.
|
|
9
14
|
*/
|
|
10
15
|
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
11
16
|
};
|
|
12
17
|
|
|
18
|
+
/**
|
|
19
|
+
* The handlers answer every request themselves, errors included, and never reject: they can be
|
|
20
|
+
* called without a `catch`, from `node:http` or from Express 4.
|
|
21
|
+
*/
|
|
13
22
|
export type DocumentHandlers = {
|
|
14
23
|
/** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
|
|
15
24
|
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
@@ -25,6 +34,39 @@ class HttpError extends Error {
|
|
|
25
34
|
}
|
|
26
35
|
}
|
|
27
36
|
|
|
37
|
+
/** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
|
|
38
|
+
function statusOf(error: unknown): number | undefined {
|
|
39
|
+
if (error instanceof HttpError) return error.status;
|
|
40
|
+
if (!(error instanceof Error)) return undefined;
|
|
41
|
+
const { status, statusCode } = error as Error & { status?: unknown; statusCode?: unknown };
|
|
42
|
+
const value = typeof status === "number" ? status : statusCode;
|
|
43
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
|
|
48
|
+
* names server paths or hosts, so only the code is passed on.
|
|
49
|
+
*/
|
|
50
|
+
function systemErrorCode(error: unknown): string | undefined {
|
|
51
|
+
const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
|
|
52
|
+
return typeof code === "string" && typeof syscall === "string" ? code : undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Answers a failed request. An error with a status keeps its status and message. Anything else is
|
|
57
|
+
* the server's trouble: a 500 that says what failed and, for a system error, its code.
|
|
58
|
+
*/
|
|
59
|
+
function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
|
|
60
|
+
const status = statusOf(error);
|
|
61
|
+
if (status !== undefined) {
|
|
62
|
+
const message = status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.`;
|
|
63
|
+
send(response, status, { error: message });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const code = systemErrorCode(error);
|
|
67
|
+
send(response, 500, { error: code ? `${failed} (${code}).` : `${failed}.` });
|
|
68
|
+
}
|
|
69
|
+
|
|
28
70
|
function send(response: ServerResponse, status: number, value: unknown): void {
|
|
29
71
|
if (response.headersSent) return;
|
|
30
72
|
response.statusCode = status;
|
|
@@ -85,10 +127,11 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
85
127
|
const url = new URL(request.url ?? "/", "http://localhost");
|
|
86
128
|
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
87
129
|
if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
130
|
+
// Who is asking comes first: a refused upload is not read into memory.
|
|
131
|
+
const currentOwner = await owner(request);
|
|
88
132
|
const bytes = await readBody(request, files.maxUploadBytes);
|
|
89
133
|
const contentType = header(request, "content-type");
|
|
90
134
|
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
91
|
-
const currentOwner = await owner(request);
|
|
92
135
|
let meta;
|
|
93
136
|
try {
|
|
94
137
|
meta = await files.ingest({
|
|
@@ -98,25 +141,34 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
98
141
|
...(currentOwner !== undefined ? { owner: currentOwner } : {}),
|
|
99
142
|
});
|
|
100
143
|
} catch (error) {
|
|
144
|
+
// A file that cannot be read is the client's 422. A store that fails is the server's 500.
|
|
145
|
+
if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) throw error;
|
|
101
146
|
throw new HttpError(422, error instanceof Error ? error.message : String(error));
|
|
102
147
|
}
|
|
103
148
|
send(response, 201, toDocumentSummary(meta));
|
|
104
149
|
} catch (error) {
|
|
105
|
-
|
|
106
|
-
else send(response, 500, { error: error instanceof Error ? error.message : "Upload failed." });
|
|
150
|
+
fail(response, error, "Upload failed", tooLarge);
|
|
107
151
|
}
|
|
108
152
|
},
|
|
109
153
|
|
|
110
154
|
async get(request, response, id) {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
155
|
+
try {
|
|
156
|
+
const currentOwner = await owner(request);
|
|
157
|
+
const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
|
|
158
|
+
if (meta) send(response, 200, toDocumentSummary(meta));
|
|
159
|
+
else send(response, 404, { error: "This file is no longer available." });
|
|
160
|
+
} catch (error) {
|
|
161
|
+
fail(response, error, "The file could not be looked up", tooLarge);
|
|
162
|
+
}
|
|
115
163
|
},
|
|
116
164
|
|
|
117
165
|
async remove(request, response, id) {
|
|
118
|
-
|
|
119
|
-
|
|
166
|
+
try {
|
|
167
|
+
const currentOwner = await owner(request);
|
|
168
|
+
send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
|
|
169
|
+
} catch (error) {
|
|
170
|
+
fail(response, error, "The file could not be deleted", tooLarge);
|
|
171
|
+
}
|
|
120
172
|
},
|
|
121
173
|
};
|
|
122
174
|
}
|
package/src/pdf-pictures.ts
CHANGED
|
@@ -42,10 +42,50 @@ const FURNITURE_SHARE = 0.3;
|
|
|
42
42
|
const DRAWING_COLOURS = 3;
|
|
43
43
|
const MAX_SHAPES = 20_000;
|
|
44
44
|
const MAX_FORM_DEPTH = 4;
|
|
45
|
+
/** Images painted on one page past which the page is marked without reading further. */
|
|
46
|
+
const MAX_IMAGES = 20_000;
|
|
47
|
+
/**
|
|
48
|
+
* Content read for one page, a form counted each time it is painted. A page of text holds a few
|
|
49
|
+
* kilobytes. A page past this paints so much that it is a drawing, and is marked: forms painted
|
|
50
|
+
* inside forms, many times over, grow to that in a few milliseconds instead of without end.
|
|
51
|
+
*/
|
|
52
|
+
const MAX_PAGE_CONTENT = 16 * 1024 * 1024;
|
|
53
|
+
/** Decoded forms kept for the whole file, so that a letterhead painted on every page is decoded once. */
|
|
54
|
+
const MAX_KEPT_FORMS = 64 * 1024 * 1024;
|
|
45
55
|
|
|
46
56
|
type Image = { id: number; box: Box };
|
|
47
57
|
type Shape = { box: Box; fill: string };
|
|
48
|
-
|
|
58
|
+
/** What a page draws. `read` counts the content run for it, forms each time they are painted. */
|
|
59
|
+
type Graphics = { images: Image[]; shapes: Shape[]; tooLarge: boolean; read: number };
|
|
60
|
+
|
|
61
|
+
/** What one reading of a file shares between its pages. */
|
|
62
|
+
type Reading = {
|
|
63
|
+
library: PdfLibrary;
|
|
64
|
+
context: PDFContext;
|
|
65
|
+
/** The content of each form, decoded once however many times and on however many pages it is painted. */
|
|
66
|
+
forms: Map<PDFObject, string | undefined>;
|
|
67
|
+
/** Characters of content in `forms`. Past `MAX_KEPT_FORMS`, a form is decoded each time instead. */
|
|
68
|
+
kept: number;
|
|
69
|
+
/** When the time for the whole file is up. */
|
|
70
|
+
deadline: number;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** The content of a form, from the forms already decoded for this file when it is there. */
|
|
74
|
+
function formContent(reading: Reading, form: PDFObject): string | undefined {
|
|
75
|
+
if (reading.forms.has(form)) return reading.forms.get(form);
|
|
76
|
+
const content = decodeContent(reading.library, reading.context, form, MAX_CONTENT_BYTES);
|
|
77
|
+
const size = content?.length ?? 0;
|
|
78
|
+
if (reading.kept + size <= MAX_KEPT_FORMS) {
|
|
79
|
+
reading.forms.set(form, content);
|
|
80
|
+
reading.kept += size;
|
|
81
|
+
}
|
|
82
|
+
return content;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A page paints too much to be text: it is marked as showing a drawing. */
|
|
86
|
+
class PaintsTooMuch extends Error {}
|
|
87
|
+
/** The time for the whole file is up: no page is marked. */
|
|
88
|
+
class OutOfTime extends Error {}
|
|
49
89
|
|
|
50
90
|
const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
|
|
51
91
|
/** Applies `first`, then `second`. */
|
|
@@ -69,8 +109,13 @@ const INLINE_IMAGE_END = /[\x00\t\n\f\r ]EI(?![^\x00\t\n\f\r /\[\]<>(){}%])/g;
|
|
|
69
109
|
* Runs the content of a page, or of a form it paints, and adds what it draws to `found`.
|
|
70
110
|
* It understands just enough: the matrix (q, Q, cm), paths and how they are painted, the fill
|
|
71
111
|
* colour, and Do. Text, clipping and everything else pass through unread.
|
|
112
|
+
* Throws `PaintsTooMuch` when the page paints more than a page of text can, and `OutOfTime`.
|
|
72
113
|
*/
|
|
73
|
-
function run(
|
|
114
|
+
function run(reading: Reading, content: string, resources: PDFDict | undefined, matrix: Matrix, found: Graphics, depth: number, open: Set<PDFObject>): void {
|
|
115
|
+
found.read += content.length;
|
|
116
|
+
if (found.read > MAX_PAGE_CONTENT) throw new PaintsTooMuch();
|
|
117
|
+
if (performance.now() > reading.deadline) throw new OutOfTime();
|
|
118
|
+
const { library, context } = reading;
|
|
74
119
|
const { PDFArray, PDFDict, PDFName, PDFNumber, PDFRef, PDFStream } = library;
|
|
75
120
|
const saved: Array<{ ctm: Matrix; fill: string }> = [];
|
|
76
121
|
let ctm = matrix;
|
|
@@ -208,19 +253,20 @@ function run(library: PdfLibrary, context: PDFContext, content: string, resource
|
|
|
208
253
|
if (!(object instanceof PDFStream)) break;
|
|
209
254
|
const subtype = object.dict.lookup(PDFName.of("Subtype"));
|
|
210
255
|
if (subtype === PDFName.of("Image")) {
|
|
256
|
+
if (found.images.length >= MAX_IMAGES) throw new PaintsTooMuch();
|
|
211
257
|
// An image fills the unit square of the space it is painted in.
|
|
212
258
|
const xs = [mapX(ctm, 0, 0), mapX(ctm, 1, 0), mapX(ctm, 0, 1), mapX(ctm, 1, 1)];
|
|
213
259
|
const ys = [mapY(ctm, 0, 0), mapY(ctm, 1, 0), mapY(ctm, 0, 1), mapY(ctm, 1, 1)];
|
|
214
260
|
found.images.push({ id: value instanceof PDFRef ? value.objectNumber : -1, box: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)] });
|
|
215
261
|
} else if (subtype === PDFName.of("Form") && depth < MAX_FORM_DEPTH && !open.has(object)) {
|
|
216
|
-
const inner =
|
|
262
|
+
const inner = formContent(reading, object);
|
|
217
263
|
if (inner === undefined) break;
|
|
218
264
|
const own = object.dict.lookup(PDFName.of("Resources"));
|
|
219
265
|
const formMatrix = object.dict.lookup(PDFName.of("Matrix"));
|
|
220
266
|
const values = formMatrix instanceof PDFArray ? formMatrix.asArray().map((entry) => (entry instanceof PDFNumber ? entry.asNumber() : Number.NaN)) : [];
|
|
221
267
|
open.add(object);
|
|
222
268
|
// A form without resources of its own uses those of the content that paints it.
|
|
223
|
-
run(
|
|
269
|
+
run(reading, inner, own instanceof PDFDict ? own : resources, values.length === 6 && values.every(Number.isFinite) ? multiply(values, ctm) : ctm, found, depth + 1, open);
|
|
224
270
|
open.delete(object);
|
|
225
271
|
}
|
|
226
272
|
break;
|
|
@@ -292,11 +338,11 @@ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGe
|
|
|
292
338
|
const leaves = document.getPages();
|
|
293
339
|
if (leaves.length !== pages.length) return undefined;
|
|
294
340
|
const { context } = document;
|
|
295
|
-
const
|
|
341
|
+
const reading: Reading = { library, context, forms: new Map(), kept: 0, deadline: performance.now() + TIME_LIMIT_MS };
|
|
296
342
|
const graphics: Graphics[] = [];
|
|
297
343
|
for (const leaf of leaves) {
|
|
298
|
-
if (performance.now() > deadline) return undefined;
|
|
299
|
-
const found: Graphics = { images: [], shapes: [], tooLarge: false };
|
|
344
|
+
if (performance.now() > reading.deadline) return undefined;
|
|
345
|
+
const found: Graphics = { images: [], shapes: [], tooLarge: false, read: 0 };
|
|
300
346
|
graphics.push(found);
|
|
301
347
|
try {
|
|
302
348
|
const contents = leaf.node.Contents();
|
|
@@ -307,9 +353,13 @@ export async function findPicturePages(bytes: Uint8Array, pages: readonly PageGe
|
|
|
307
353
|
}
|
|
308
354
|
const parts = streams.map((stream) => decodeContent(library, context, stream, MAX_CONTENT_BYTES));
|
|
309
355
|
// Content that cannot be read is not guessed at: the page stays unmarked.
|
|
310
|
-
if (!parts.includes(undefined)) run(
|
|
311
|
-
} catch {
|
|
312
|
-
//
|
|
356
|
+
if (!parts.includes(undefined)) run(reading, parts.join(" "), leaf.node.Resources(), IDENTITY, found, 0, new Set());
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// The time for the file is up within a page: no page is marked, as between pages.
|
|
359
|
+
if (error instanceof OutOfTime) return undefined;
|
|
360
|
+
// A page that paints more than a page of text can is a drawing. Any other trouble leaves
|
|
361
|
+
// an unusual page unmarked.
|
|
362
|
+
if (error instanceof PaintsTooMuch) found.tooLarge = true;
|
|
313
363
|
}
|
|
314
364
|
}
|
|
315
365
|
// An image painted on many pages is part of the page design, whatever its size.
|
package/src/text.ts
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
export const MAX_LINE_CHARACTERS = 2_000;
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Terminal escape sequences: CSI ("ESC [ 31 m"), OSC ("ESC ]
|
|
6
|
-
* ("ESC ( B"), and two-character escapes
|
|
5
|
+
* Terminal escape sequences: CSI ("ESC [ 31 m"), OSC ("ESC ] 0;title BEL", ended by BEL or
|
|
6
|
+
* "ESC \" on the same line), character-set selection ("ESC ( B"), and two-character escapes
|
|
7
|
+
* ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
|
|
8
|
+
* not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
|
|
9
|
+
* or two bytes in a logged user agent, would take every line after it.
|
|
7
10
|
*/
|
|
8
11
|
// eslint-disable-next-line no-control-regex
|
|
9
|
-
const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)
|
|
12
|
+
const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])/g;
|
|
10
13
|
|
|
11
14
|
/**
|
|
12
15
|
* Strips a BOM, unifies line endings, and removes terminal escape sequences and control characters
|