llm-large-files 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +147 -0
- package/README.md +32 -6
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +5 -1
- package/dist/analyze.js.map +1 -1
- package/dist/extract.d.ts +30 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +94 -23
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -2
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +83 -32
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +34 -4
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +51 -8
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +37 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +59 -7
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +7 -0
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +58 -16
- package/dist/map-reduce.js.map +1 -1
- package/dist/pdf-layout.d.ts +39 -0
- package/dist/pdf-layout.d.ts.map +1 -0
- package/dist/pdf-layout.js +820 -0
- package/dist/pdf-layout.js.map +1 -0
- package/dist/pdf-pages.d.ts +45 -0
- package/dist/pdf-pages.d.ts.map +1 -0
- package/dist/pdf-pages.js +336 -0
- package/dist/pdf-pages.js.map +1 -0
- package/dist/pdf-pictures.d.ts +20 -0
- package/dist/pdf-pictures.d.ts.map +1 -0
- package/dist/pdf-pictures.js +336 -0
- package/dist/pdf-pictures.js.map +1 -0
- package/dist/plan.d.ts +13 -3
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +27 -18
- package/dist/plan.js.map +1 -1
- package/dist/search.d.ts +17 -4
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +90 -24
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +7 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +37 -5
- package/dist/stores.js.map +1 -1
- package/dist/text.d.ts +18 -4
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +155 -15
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +156 -16
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +63 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +56 -11
- package/docs/configuration.md +298 -6
- package/docs/getting-started.md +41 -7
- package/docs/how-it-works.md +77 -11
- package/docs/security.md +54 -6
- package/package.json +96 -91
- package/src/analyze.ts +3 -1
- package/src/extract.ts +105 -24
- package/src/gemini/chat.ts +116 -34
- package/src/gemini/generate.ts +66 -10
- package/src/gemini/index.ts +3 -3
- package/src/index.ts +4 -3
- package/src/library.ts +308 -226
- package/src/map-reduce.ts +69 -16
- package/src/node/handlers.ts +122 -122
- package/src/pdf-layout.ts +807 -0
- package/src/pdf-pages.ts +315 -0
- package/src/pdf-pictures.ts +324 -0
- package/src/plan.ts +120 -98
- package/src/search.ts +85 -25
- package/src/stores.ts +165 -132
- package/src/text.ts +131 -14
- package/src/tools.ts +408 -264
- package/src/types.ts +228 -168
package/src/map-reduce.ts
CHANGED
|
@@ -9,8 +9,15 @@ const FINAL_OUTPUT_TOKENS = 8_192;
|
|
|
9
9
|
export type WholeDocumentResult = {
|
|
10
10
|
answer: string;
|
|
11
11
|
parts: number;
|
|
12
|
+
/** Parts that were read and had something relevant. Parts that could not be read are not counted. */
|
|
12
13
|
relevantParts: number;
|
|
13
14
|
failedParts: number;
|
|
15
|
+
/** Parts whose notes stopped at the output limit, so some of what they contain is missing. */
|
|
16
|
+
truncatedParts: number;
|
|
17
|
+
/** Note-merging steps that stopped at the output limit. */
|
|
18
|
+
truncatedMerges: number;
|
|
19
|
+
/** The final answer stopped at the output limit. */
|
|
20
|
+
answerTruncated: boolean;
|
|
14
21
|
};
|
|
15
22
|
|
|
16
23
|
/** Splits a document into line ranges that each fit one model request. */
|
|
@@ -62,6 +69,20 @@ async function withRetry(call: () => Promise<string>, signal?: AbortSignal): Pro
|
|
|
62
69
|
}
|
|
63
70
|
}
|
|
64
71
|
|
|
72
|
+
/** One model call, retried once. `truncated` is true when the reply that was kept hit the output limit. */
|
|
73
|
+
async function ask(
|
|
74
|
+
generate: GenerateText,
|
|
75
|
+
request: { system: string; prompt: string; maxOutputTokens: number },
|
|
76
|
+
signal: AbortSignal | undefined,
|
|
77
|
+
): Promise<{ text: string; truncated: boolean }> {
|
|
78
|
+
let truncated = false;
|
|
79
|
+
const text = await withRetry(() => {
|
|
80
|
+
truncated = false;
|
|
81
|
+
return generate({ ...request, signal, onTruncated: () => { truncated = true; } });
|
|
82
|
+
}, signal);
|
|
83
|
+
return { text: text.trim(), truncated };
|
|
84
|
+
}
|
|
85
|
+
|
|
65
86
|
/**
|
|
66
87
|
* Answers a task that needs the whole document: each part is read separately ("map"),
|
|
67
88
|
* then the notes are combined ("reduce"), in several rounds if the notes are still too large.
|
|
@@ -84,11 +105,14 @@ export async function analyzeWholeDocument(options: {
|
|
|
84
105
|
|
|
85
106
|
let done = 0;
|
|
86
107
|
let failed = 0;
|
|
108
|
+
let firstFailure = "";
|
|
109
|
+
let truncatedParts = 0;
|
|
87
110
|
const notes = await pool(parts.length, options.concurrency ?? 4, async (index) => {
|
|
88
111
|
const { from, to } = parts[index]!;
|
|
89
112
|
let text: string;
|
|
113
|
+
let read = true;
|
|
90
114
|
try {
|
|
91
|
-
|
|
115
|
+
const reply = await ask(generate, {
|
|
92
116
|
system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
|
|
93
117
|
prompt: [
|
|
94
118
|
`Task: ${task}`,
|
|
@@ -101,25 +125,45 @@ export async function analyzeWholeDocument(options: {
|
|
|
101
125
|
"</part>",
|
|
102
126
|
].join("\n"),
|
|
103
127
|
maxOutputTokens: PART_OUTPUT_TOKENS,
|
|
104
|
-
|
|
105
|
-
|
|
128
|
+
}, signal);
|
|
129
|
+
text = reply.text;
|
|
130
|
+
if (reply.truncated) {
|
|
131
|
+
truncatedParts++;
|
|
132
|
+
text += "\n[These notes were cut off at the output limit. This part has more relevant content than is listed here.]";
|
|
133
|
+
}
|
|
106
134
|
} catch (error) {
|
|
107
135
|
if (signal?.aborted) throw error;
|
|
108
136
|
failed++;
|
|
109
|
-
|
|
137
|
+
read = false;
|
|
138
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
139
|
+
firstFailure ||= reason;
|
|
140
|
+
text = `[This part could not be read: ${reason}]`;
|
|
110
141
|
}
|
|
111
142
|
done++;
|
|
112
143
|
onProgress?.({ kind: "map", message: `Reading ${name}: part ${done} of ${parts.length}`, done, total: parts.length });
|
|
113
|
-
return { from, to, text };
|
|
144
|
+
return { from, to, text, read };
|
|
114
145
|
}, signal);
|
|
115
146
|
|
|
147
|
+
// Nothing was read at all: an answer written from here would be invented.
|
|
148
|
+
if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
|
|
149
|
+
|
|
116
150
|
const relevant = notes.filter((note) => !note.text.toUpperCase().startsWith(NOTHING));
|
|
117
|
-
|
|
118
|
-
|
|
151
|
+
const relevantParts = relevant.filter((note) => note.read).length;
|
|
152
|
+
if (relevantParts === 0) {
|
|
153
|
+
return {
|
|
154
|
+
answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${parts.length} parts could not be read.)` : ""}`,
|
|
155
|
+
parts: parts.length,
|
|
156
|
+
relevantParts: 0,
|
|
157
|
+
failedParts: failed,
|
|
158
|
+
truncatedParts,
|
|
159
|
+
truncatedMerges: 0,
|
|
160
|
+
answerTruncated: false,
|
|
161
|
+
};
|
|
119
162
|
}
|
|
120
163
|
|
|
121
164
|
let layer = relevant.map((note) => `### Lines ${note.from}-${note.to}\n${note.text}`);
|
|
122
165
|
let round = 0;
|
|
166
|
+
let truncatedMerges = 0;
|
|
123
167
|
// Combine notes in batches until one batch holds them all. Each merge is capped at
|
|
124
168
|
// PART_OUTPUT_TOKENS, so the layer shrinks every round; the round cap is a safety net.
|
|
125
169
|
while (layer.length > 1 && estimateTokens(layer.join("\n\n")) > budget.mapChunkTokens && round < 8) {
|
|
@@ -145,31 +189,40 @@ export async function analyzeWholeDocument(options: {
|
|
|
145
189
|
}
|
|
146
190
|
let combined = 0;
|
|
147
191
|
layer = await pool(batches.length, options.concurrency ?? 4, async (index) => {
|
|
148
|
-
const
|
|
192
|
+
const reply = await ask(generate, {
|
|
149
193
|
system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
|
|
150
194
|
prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batches[index]!.join("\n\n")}`,
|
|
151
195
|
maxOutputTokens: PART_OUTPUT_TOKENS,
|
|
152
|
-
|
|
153
|
-
|
|
196
|
+
}, signal);
|
|
197
|
+
if (reply.truncated) truncatedMerges++;
|
|
154
198
|
combined++;
|
|
155
199
|
onProgress?.({ kind: "reduce", message: `Combining notes on ${name} (round ${round}): ${combined} of ${batches.length}`, done: combined, total: batches.length });
|
|
156
|
-
return text.
|
|
200
|
+
return reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
|
|
157
201
|
}, signal);
|
|
158
202
|
}
|
|
159
203
|
|
|
160
|
-
onProgress?.({ kind: "reduce", message: `Writing the answer from ${
|
|
161
|
-
const
|
|
204
|
+
onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
|
|
205
|
+
const cutShort = truncatedParts + truncatedMerges;
|
|
206
|
+
const final = await ask(generate, {
|
|
162
207
|
system: "You write a complete answer from notes taken across every part of a document.",
|
|
163
208
|
prompt: [
|
|
164
209
|
`Task: ${task}`,
|
|
165
210
|
"",
|
|
166
211
|
`These notes cover all ${parts.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
|
|
212
|
+
...(cutShort ? [`Some notes were cut off at the output limit (they say so), so the notes are incomplete. Say in the answer that it is incomplete.`] : []),
|
|
167
213
|
"Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
|
|
168
214
|
"",
|
|
169
215
|
layer.join("\n\n"),
|
|
170
216
|
].join("\n"),
|
|
171
217
|
maxOutputTokens: FINAL_OUTPUT_TOKENS,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
218
|
+
}, signal);
|
|
219
|
+
return {
|
|
220
|
+
answer: final.text,
|
|
221
|
+
parts: parts.length,
|
|
222
|
+
relevantParts,
|
|
223
|
+
failedParts: failed,
|
|
224
|
+
truncatedParts,
|
|
225
|
+
truncatedMerges,
|
|
226
|
+
answerTruncated: final.truncated,
|
|
227
|
+
};
|
|
175
228
|
}
|
package/src/node/handlers.ts
CHANGED
|
@@ -1,122 +1,122 @@
|
|
|
1
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import { toDocumentSummary, type LargeFiles } from "../library.js";
|
|
3
|
-
import { formatBytes } from "../plan.js";
|
|
4
|
-
|
|
5
|
-
export type DocumentHandlerOptions = {
|
|
6
|
-
/**
|
|
7
|
-
* The signed-in user for this request. When set, uploads are owned by that user and other
|
|
8
|
-
* users cannot read or delete them. Return undefined to allow anonymous access.
|
|
9
|
-
*/
|
|
10
|
-
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
export type DocumentHandlers = {
|
|
14
|
-
/** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
|
|
15
|
-
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
16
|
-
/** GET: the document's summary, or 404. */
|
|
17
|
-
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
18
|
-
/** DELETE: removes the document. Responds `{ deleted: boolean }`. */
|
|
19
|
-
remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
class HttpError extends Error {
|
|
23
|
-
constructor(readonly status: number, message: string) {
|
|
24
|
-
super(message);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function send(response: ServerResponse, status: number, value: unknown): void {
|
|
29
|
-
if (response.headersSent) return;
|
|
30
|
-
response.statusCode = status;
|
|
31
|
-
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
32
|
-
response.end(JSON.stringify(value));
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function header(request: IncomingMessage, name: string): string {
|
|
36
|
-
const raw = request.headers[name];
|
|
37
|
-
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
38
|
-
if (!value) return "";
|
|
39
|
-
try {
|
|
40
|
-
return decodeURIComponent(value);
|
|
41
|
-
} catch {
|
|
42
|
-
return value;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
|
|
47
|
-
async function readBody(request: IncomingMessage, limit: number): Promise<Uint8Array> {
|
|
48
|
-
const parsed = (request as IncomingMessage & { body?: unknown }).body;
|
|
49
|
-
if (parsed instanceof Uint8Array) {
|
|
50
|
-
if (parsed.byteLength > limit) throw new HttpError(413, "");
|
|
51
|
-
return parsed;
|
|
52
|
-
}
|
|
53
|
-
if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
|
|
54
|
-
throw new HttpError(400, "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.");
|
|
55
|
-
}
|
|
56
|
-
const declared = Number(request.headers["content-length"]);
|
|
57
|
-
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
|
|
58
|
-
const chunks: Buffer[] = [];
|
|
59
|
-
let size = 0;
|
|
60
|
-
for await (const chunk of request) {
|
|
61
|
-
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
|
|
62
|
-
size += buffer.byteLength;
|
|
63
|
-
if (size > limit) {
|
|
64
|
-
// Stop buffering; drain the rest so the client can read the response.
|
|
65
|
-
request.resume();
|
|
66
|
-
throw new HttpError(413, "");
|
|
67
|
-
}
|
|
68
|
-
chunks.push(buffer);
|
|
69
|
-
}
|
|
70
|
-
const body = Buffer.concat(chunks);
|
|
71
|
-
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
|
|
76
|
-
* `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON.
|
|
77
|
-
*/
|
|
78
|
-
export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
|
|
79
|
-
const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
|
|
80
|
-
const owner = async (request: IncomingMessage) => options.getOwner?.(request);
|
|
81
|
-
|
|
82
|
-
return {
|
|
83
|
-
async upload(request, response) {
|
|
84
|
-
try {
|
|
85
|
-
const url = new URL(request.url ?? "/", "http://localhost");
|
|
86
|
-
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
87
|
-
if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
88
|
-
const bytes = await readBody(request, files.maxUploadBytes);
|
|
89
|
-
const contentType = header(request, "content-type");
|
|
90
|
-
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
91
|
-
const currentOwner = await owner(request);
|
|
92
|
-
let meta;
|
|
93
|
-
try {
|
|
94
|
-
meta = await files.ingest({
|
|
95
|
-
name,
|
|
96
|
-
bytes,
|
|
97
|
-
...(mimeType ? { mimeType } : {}),
|
|
98
|
-
...(currentOwner !== undefined ? { owner: currentOwner } : {}),
|
|
99
|
-
});
|
|
100
|
-
} catch (error) {
|
|
101
|
-
throw new HttpError(422, error instanceof Error ? error.message : String(error));
|
|
102
|
-
}
|
|
103
|
-
send(response, 201, toDocumentSummary(meta));
|
|
104
|
-
} catch (error) {
|
|
105
|
-
if (error instanceof HttpError) send(response, error.status, { error: error.status === 413 ? tooLarge : error.message });
|
|
106
|
-
else send(response, 500, { error: error instanceof Error ? error.message : "Upload failed." });
|
|
107
|
-
}
|
|
108
|
-
},
|
|
109
|
-
|
|
110
|
-
async get(request, response, id) {
|
|
111
|
-
const currentOwner = await owner(request);
|
|
112
|
-
const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
|
|
113
|
-
if (meta) send(response, 200, toDocumentSummary(meta));
|
|
114
|
-
else send(response, 404, { error: "This file is no longer available." });
|
|
115
|
-
},
|
|
116
|
-
|
|
117
|
-
async remove(request, response, id) {
|
|
118
|
-
const currentOwner = await owner(request);
|
|
119
|
-
send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
|
|
120
|
-
},
|
|
121
|
-
};
|
|
122
|
-
}
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { toDocumentSummary, type LargeFiles } from "../library.js";
|
|
3
|
+
import { formatBytes } from "../plan.js";
|
|
4
|
+
|
|
5
|
+
export type DocumentHandlerOptions = {
|
|
6
|
+
/**
|
|
7
|
+
* The signed-in user for this request. When set, uploads are owned by that user and other
|
|
8
|
+
* users cannot read or delete them. Return undefined to allow anonymous access.
|
|
9
|
+
*/
|
|
10
|
+
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type DocumentHandlers = {
|
|
14
|
+
/** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
|
|
15
|
+
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
16
|
+
/** GET: the document's summary, or 404. */
|
|
17
|
+
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
18
|
+
/** DELETE: removes the document. Responds `{ deleted: boolean }`. */
|
|
19
|
+
remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
class HttpError extends Error {
|
|
23
|
+
constructor(readonly status: number, message: string) {
|
|
24
|
+
super(message);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function send(response: ServerResponse, status: number, value: unknown): void {
|
|
29
|
+
if (response.headersSent) return;
|
|
30
|
+
response.statusCode = status;
|
|
31
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
32
|
+
response.end(JSON.stringify(value));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function header(request: IncomingMessage, name: string): string {
|
|
36
|
+
const raw = request.headers[name];
|
|
37
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
38
|
+
if (!value) return "";
|
|
39
|
+
try {
|
|
40
|
+
return decodeURIComponent(value);
|
|
41
|
+
} catch {
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
|
|
47
|
+
async function readBody(request: IncomingMessage, limit: number): Promise<Uint8Array> {
|
|
48
|
+
const parsed = (request as IncomingMessage & { body?: unknown }).body;
|
|
49
|
+
if (parsed instanceof Uint8Array) {
|
|
50
|
+
if (parsed.byteLength > limit) throw new HttpError(413, "");
|
|
51
|
+
return parsed;
|
|
52
|
+
}
|
|
53
|
+
if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
|
|
54
|
+
throw new HttpError(400, "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.");
|
|
55
|
+
}
|
|
56
|
+
const declared = Number(request.headers["content-length"]);
|
|
57
|
+
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
|
|
58
|
+
const chunks: Buffer[] = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
for await (const chunk of request) {
|
|
61
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
|
|
62
|
+
size += buffer.byteLength;
|
|
63
|
+
if (size > limit) {
|
|
64
|
+
// Stop buffering; drain the rest so the client can read the response.
|
|
65
|
+
request.resume();
|
|
66
|
+
throw new HttpError(413, "");
|
|
67
|
+
}
|
|
68
|
+
chunks.push(buffer);
|
|
69
|
+
}
|
|
70
|
+
const body = Buffer.concat(chunks);
|
|
71
|
+
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
|
|
76
|
+
* `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON.
|
|
77
|
+
*/
|
|
78
|
+
export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
|
|
79
|
+
const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
|
|
80
|
+
const owner = async (request: IncomingMessage) => options.getOwner?.(request);
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
async upload(request, response) {
|
|
84
|
+
try {
|
|
85
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
86
|
+
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
87
|
+
if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
88
|
+
const bytes = await readBody(request, files.maxUploadBytes);
|
|
89
|
+
const contentType = header(request, "content-type");
|
|
90
|
+
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
91
|
+
const currentOwner = await owner(request);
|
|
92
|
+
let meta;
|
|
93
|
+
try {
|
|
94
|
+
meta = await files.ingest({
|
|
95
|
+
name,
|
|
96
|
+
bytes,
|
|
97
|
+
...(mimeType ? { mimeType } : {}),
|
|
98
|
+
...(currentOwner !== undefined ? { owner: currentOwner } : {}),
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
throw new HttpError(422, error instanceof Error ? error.message : String(error));
|
|
102
|
+
}
|
|
103
|
+
send(response, 201, toDocumentSummary(meta));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error instanceof HttpError) send(response, error.status, { error: error.status === 413 ? tooLarge : error.message });
|
|
106
|
+
else send(response, 500, { error: error instanceof Error ? error.message : "Upload failed." });
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async get(request, response, id) {
|
|
111
|
+
const currentOwner = await owner(request);
|
|
112
|
+
const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
|
|
113
|
+
if (meta) send(response, 200, toDocumentSummary(meta));
|
|
114
|
+
else send(response, 404, { error: "This file is no longer available." });
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
async remove(request, response, id) {
|
|
118
|
+
const currentOwner = await owner(request);
|
|
119
|
+
send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|