@vesk/plugin-multipart 0.2.69 → 0.2.71
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/README.md +201 -0
- package/dist/index.d.ts +79 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +99 -0
- package/dist/parser.d.ts +114 -0
- package/dist/parser.d.ts.map +1 -0
- package/dist/parser.js +502 -0
- package/package.json +7 -3
- package/src/index.ts +0 -125
- package/src/parser.test.ts +0 -263
- package/src/parser.ts +0 -479
- package/tsconfig.build.json +0 -12
- package/tsconfig.json +0 -8
package/README.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# @vesk/plugin-multipart
|
|
2
|
+
|
|
3
|
+
Streaming `multipart/form-data` for Vesk route handlers: real `File` values,
|
|
4
|
+
limits enforced as bytes arrive, and no whole-body buffering.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @vesk/plugin-multipart
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Why not `request.formData()`
|
|
11
|
+
|
|
12
|
+
It works, and it returns a real `File`. What it does not do is **bound** the
|
|
13
|
+
upload. `request.formData()` reads the whole body before you see any of it, so
|
|
14
|
+
by the time your handler can check a file's size or type, the bytes are already
|
|
15
|
+
in memory. The only limit in the path is the server's global body cap — 1 MiB by
|
|
16
|
+
default — which is the *total*, not the per-file size, and which nothing in
|
|
17
|
+
your handler can influence.
|
|
18
|
+
|
|
19
|
+
The one thing that does silently destroy uploads is the spread:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
const fd = await request.formData();
|
|
23
|
+
const fields = { ...fd }; // {} — FormData has no own enumerable props
|
|
24
|
+
const entries = Object.fromEntries(fd.entries()); // this one IS fine
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Use `fd.get(name)` or `Object.fromEntries(fd.entries())`. This plugin exists for
|
|
28
|
+
the limits, not for the value type.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { parseUploadOrError } from '@vesk/plugin-multipart';
|
|
34
|
+
|
|
35
|
+
export async function POST(request) {
|
|
36
|
+
const upload = await parseUploadOrError(request, {
|
|
37
|
+
maxFileSize: 8 * 1024 * 1024,
|
|
38
|
+
allowedMimeTypes: ['image/png', 'image/jpeg'],
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// A rejection is already a Response with the right status.
|
|
42
|
+
if (upload instanceof Response) return upload;
|
|
43
|
+
|
|
44
|
+
const avatar = upload.files[0];
|
|
45
|
+
if (!avatar) return Response.json({ error: 'no file' }, { status: 400 });
|
|
46
|
+
|
|
47
|
+
const file = avatar.value; // a real File
|
|
48
|
+
await storage.put(file.name, await file.arrayBuffer());
|
|
49
|
+
|
|
50
|
+
return Response.json({ ok: true, size: file.size, type: file.type });
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
A rejection is a protocol-level outcome — every call site has to answer with it
|
|
55
|
+
— so `parseUploadOrError` is the function to reach for by default. Use
|
|
56
|
+
`parseMultipartRequest` when you want the `MultipartError` and will handle it
|
|
57
|
+
yourself.
|
|
58
|
+
|
|
59
|
+
## Options
|
|
60
|
+
|
|
61
|
+
| Option | Default | Rejection |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `maxFileSize` | 10 MiB | 413 when a single file part exceeds it |
|
|
64
|
+
| `maxTotalSize` | 100 MiB | 413 across all parts |
|
|
65
|
+
| `maxFiles` | 20 | 413 on the 21st file part |
|
|
66
|
+
| `maxFields` | 100 | 413 on the 101st non-file field |
|
|
67
|
+
| `allowedMimeTypes` | — (any) | 415 on a type outside the list; `type/*` wildcards work |
|
|
68
|
+
| `allowedExtensions` | — (any) | 415 on an extension outside the list, with or without the dot |
|
|
69
|
+
|
|
70
|
+
`allowedExtensions` is checked **as well as** the MIME list, not instead of it,
|
|
71
|
+
so a `.php` upload cannot be waved through by a permissive content type.
|
|
72
|
+
|
|
73
|
+
## What you get back
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
interface ParsedMultipart {
|
|
77
|
+
parts: MultipartPart[]; // everything, in wire order
|
|
78
|
+
files: MultipartPart[]; // parts that carried a filename
|
|
79
|
+
fields: MultipartPart[]; // the rest
|
|
80
|
+
totalSize: number; // sum of part bodies
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface MultipartPart {
|
|
84
|
+
name: string; // the form field name
|
|
85
|
+
filename?: string;
|
|
86
|
+
contentType?: string; // lowercased
|
|
87
|
+
headers: Record<string, string>;
|
|
88
|
+
value: string | File; // text parts decode to a string, files stay File
|
|
89
|
+
size: number;
|
|
90
|
+
isFile: boolean;
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A text part is a `string` and a file part is a `File` — check `isFile` or use
|
|
95
|
+
`files` / `fields` rather than guessing from `value`'s type.
|
|
96
|
+
|
|
97
|
+
Repeated field names collapse if you flatten them, so use `toRecord`:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { toRecord } from '@vesk/plugin-multipart';
|
|
101
|
+
|
|
102
|
+
const fields = toRecord(upload);
|
|
103
|
+
// { title: 'Holiday', tags: ['a', 'b'] }
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Errors
|
|
107
|
+
|
|
108
|
+
Every rejection throws `MultipartError` with a `status` and a `code`:
|
|
109
|
+
|
|
110
|
+
| `status` | When |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `400` | malformed body, missing boundary, no body |
|
|
113
|
+
| `413` | any size or count limit passed |
|
|
114
|
+
| `415` | disallowed MIME type or extension |
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { MultipartError } from '@vesk/plugin-multipart';
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
await parseMultipartRequest(request);
|
|
121
|
+
} catch (e) {
|
|
122
|
+
if (e instanceof MultipartError) return Response.json(
|
|
123
|
+
{ error: e.message, code: e.code }, { status: e.status });
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Parsing every upload up front
|
|
129
|
+
|
|
130
|
+
Off by default — a handler that never parses pays nothing. Opt in with the
|
|
131
|
+
plugin and read the result from the request:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
// vesk.config.ts
|
|
135
|
+
import { multipart } from '@vesk/plugin-multipart';
|
|
136
|
+
import tailwind from '@vesk/plugin-tailwind';
|
|
137
|
+
|
|
138
|
+
export default {
|
|
139
|
+
plugins: [multipart({ maxFileSize: 32 * 1024 * 1024, autoParse: true })],
|
|
140
|
+
};
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// app/api/upload/route.ts
|
|
145
|
+
export async function POST(request) {
|
|
146
|
+
// No configuration needed here — the plugin's limits already ran, and this
|
|
147
|
+
// call returns that same parse. A request body can only be read once, so
|
|
148
|
+
// asking for it twice must not throw.
|
|
149
|
+
const upload = await parseUploadOrError(request);
|
|
150
|
+
if (upload instanceof Response) return upload;
|
|
151
|
+
return Response.json({ files: upload.files.length });
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
A rejection short-circuits the request with the same status codes as above, so a
|
|
156
|
+
limit configured here is enforced before any handler runs.
|
|
157
|
+
|
|
158
|
+
`multipartResult(request)` returns that parse directly, or `null`, for the one
|
|
159
|
+
place you cannot fail — an error page, say:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { multipartResult } from '@vesk/plugin-multipart';
|
|
163
|
+
|
|
164
|
+
const upload = multipartResult(request); // ParsedMultipart | null, never throws
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
The result is held on a private `Symbol`, not a property name: nothing is added
|
|
168
|
+
to what `Object.keys(request)` reports, and nothing can collide with your own
|
|
169
|
+
fields.
|
|
170
|
+
|
|
171
|
+
## Requirements
|
|
172
|
+
|
|
173
|
+
- **The body must be a stream.** `vesk dev` and `vesk start` both provide
|
|
174
|
+
`request.body` as a real `ReadableStream`
|
|
175
|
+
(`packages/adapter/src/web-request.ts`). A host that constructs a `Request`
|
|
176
|
+
with a null body — including a hand-rolled `new Request(url, { body: null })`
|
|
177
|
+
— will make every call fail with `NO_BODY`.
|
|
178
|
+
- **Server-side only.** This parses an inbound request; it has nothing to do in
|
|
179
|
+
a browser. If a client bundle reaches it, the build now refuses it and says
|
|
180
|
+
why.
|
|
181
|
+
- **Node 18+**, for `File`, `Blob` and web streams.
|
|
182
|
+
|
|
183
|
+
## API
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
parseMultipartRequest(request, options?): Promise<ParsedMultipart> // throws MultipartError
|
|
187
|
+
parseUploadOrError(request, options?): Promise<ParsedMultipart | Response>
|
|
188
|
+
parseMultipart(stream, boundary, options?): Promise<ParsedMultipart> // raw stream + boundary
|
|
189
|
+
boundaryFromContentType(contentType): string | null
|
|
190
|
+
multipartResult(request): ParsedMultipart | null // never throws
|
|
191
|
+
toRecord(parsed): Record<string, string | File | Array<string | File>>
|
|
192
|
+
multipart(options?): VeskPlugin
|
|
193
|
+
MiB
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
All of the above are exported from the package root; `parseMultipart`,
|
|
197
|
+
`parseMultipartRequest`, `boundaryFromContentType`, `toRecord` and
|
|
198
|
+
`MultipartError` are also available from `@vesk/plugin-multipart/parser`.
|
|
199
|
+
|
|
200
|
+
There is deliberately **no** bare `parseUpload`. Earlier versions of this
|
|
201
|
+
README showed one, and it did not exist.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vesk/plugin-multipart — streaming `multipart/form-data` uploads for Vesk.
|
|
3
|
+
*
|
|
4
|
+
* Core Vesk can parse multipart through `request.formData()`, but the body is
|
|
5
|
+
* buffered whole under the 1 MiB `DEFAULT_MAX_BODY_BYTES` cap and
|
|
6
|
+
* `Object.fromEntries(fd.entries())` collapses `File` values into opaque
|
|
7
|
+
* strings — so an upload could not be inspected, validated or persisted. That
|
|
8
|
+
* work belongs here rather than in core: most apps never accept a file, and the
|
|
9
|
+
* parser is a few hundred lines that should not ship to everyone.
|
|
10
|
+
*
|
|
11
|
+
* Usage — in a route or API handler:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { parseUploadOrError } from '@vesk/plugin-multipart';
|
|
15
|
+
*
|
|
16
|
+
* export async function POST(request) {
|
|
17
|
+
* const upload = await parseUploadOrError(request, {
|
|
18
|
+
* maxFileSize: 8 * 1024 * 1024,
|
|
19
|
+
* allowedMimeTypes: ['image/png', 'image/jpeg'],
|
|
20
|
+
* });
|
|
21
|
+
* if (upload instanceof Response) return upload; // already a 413/415/400
|
|
22
|
+
* const avatar = upload.files[0]?.value;
|
|
23
|
+
* if (avatar instanceof File) console.log(avatar.name, avatar.size);
|
|
24
|
+
* return Response.json({ ok: true });
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* There is deliberately no bare `parseUpload`: a rejection is a protocol-level
|
|
29
|
+
* outcome (413 / 415 / 400) and every call site has to answer with it, so the
|
|
30
|
+
* function that can return a ready `Response` is the one to reach for. Use
|
|
31
|
+
* `parseMultipartRequest` when you want the throw, to handle it yourself.
|
|
32
|
+
*
|
|
33
|
+
* `request.body` must be a real stream. `vesk dev` and `vesk start` both provide
|
|
34
|
+
* one (see `packages/adapter/src/web-request.ts`); a handler that reaches for
|
|
35
|
+
* `request.formData()` instead is buffered whole under the core 1 MiB body cap
|
|
36
|
+
* and has no per-file, per-type or count limits to enforce.
|
|
37
|
+
*
|
|
38
|
+
* Rejections throw `MultipartError`, whose `status` is 413 (too large / too
|
|
39
|
+
* many), 415 (disallowed type) or 400 (malformed). Nothing is buffered beyond
|
|
40
|
+
* `maxFileSize` per part, so an oversized upload is cut off after the first few
|
|
41
|
+
* KB instead of after the whole body has been read.
|
|
42
|
+
*
|
|
43
|
+
* @module plugin-multipart
|
|
44
|
+
*/
|
|
45
|
+
import type { VeskPlugin } from '@vesk/types';
|
|
46
|
+
import { parseMultipart, parseMultipartRequest, boundaryFromContentType, toRecord, multipartResult, MultipartError, type MultipartPart, type MultipartOptions, type ParsedMultipart } from './parser.js';
|
|
47
|
+
export { parseMultipart, parseMultipartRequest, boundaryFromContentType, toRecord, multipartResult, MultipartError, };
|
|
48
|
+
export type { MultipartPart, MultipartOptions, ParsedMultipart };
|
|
49
|
+
declare const MiB: number;
|
|
50
|
+
export interface MultipartPluginOptions extends MultipartOptions {
|
|
51
|
+
/** Skip parsing requests below this content-length (default 1). */
|
|
52
|
+
minBytes?: number;
|
|
53
|
+
/**
|
|
54
|
+
* Parse every multipart request before it reaches the handler, so a
|
|
55
|
+
* configured limit is enforced before any of your code runs.
|
|
56
|
+
*
|
|
57
|
+
* Off by default: a handler that never parses an upload pays nothing.
|
|
58
|
+
*
|
|
59
|
+
* You rarely read the result yourself — `parseUploadOrError` and
|
|
60
|
+
* `parseMultipartRequest` reuse a body that has already been parsed, since a
|
|
61
|
+
* request body cannot be read twice. Reach for `multipartResult(request)`
|
|
62
|
+
* only where you cannot fail, such as an error page.
|
|
63
|
+
*/
|
|
64
|
+
autoParse?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* `parseMultipartRequest` that returns the JSON error `Response` itself on
|
|
68
|
+
* rejection — the ergonomic form for a route handler.
|
|
69
|
+
*
|
|
70
|
+
* ```ts
|
|
71
|
+
* const upload = await parseUploadOrError(req, { maxFileSize: 8 * MiB });
|
|
72
|
+
* if (upload instanceof Response) return upload; // already a 413/415/400
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export declare function parseUploadOrError(request: Request, options?: MultipartOptions): Promise<ParsedMultipart | Response>;
|
|
76
|
+
export declare function multipart(options?: MultipartPluginOptions): VeskPlugin;
|
|
77
|
+
export default multipart;
|
|
78
|
+
export { MiB };
|
|
79
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACN,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,QAAQ,EACR,eAAe,EAEf,cAAc,EACd,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,MAAM,aAAa,CAAC;AAErB,OAAO,EACN,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,QAAQ,EACR,eAAe,EACf,cAAc,GACd,CAAC;AACF,YAAY,EAAE,aAAa,EAAE,gBAAgB,EAAE,eAAe,EAAE,CAAC;AAEjE,QAAA,MAAM,GAAG,QAAc,CAAC;AAExB,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;IAC/D,mEAAmE;IACnE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACvC,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,eAAe,GAAG,QAAQ,CAAC,CAYrC;AAED,wBAAgB,SAAS,CAAC,OAAO,GAAE,sBAA2B,GAAG,UAAU,CA0B1E;AAED,eAAe,SAAS,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vesk/plugin-multipart — streaming `multipart/form-data` uploads for Vesk.
|
|
3
|
+
*
|
|
4
|
+
* Core Vesk can parse multipart through `request.formData()`, but the body is
|
|
5
|
+
* buffered whole under the 1 MiB `DEFAULT_MAX_BODY_BYTES` cap and
|
|
6
|
+
* `Object.fromEntries(fd.entries())` collapses `File` values into opaque
|
|
7
|
+
* strings — so an upload could not be inspected, validated or persisted. That
|
|
8
|
+
* work belongs here rather than in core: most apps never accept a file, and the
|
|
9
|
+
* parser is a few hundred lines that should not ship to everyone.
|
|
10
|
+
*
|
|
11
|
+
* Usage — in a route or API handler:
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { parseUploadOrError } from '@vesk/plugin-multipart';
|
|
15
|
+
*
|
|
16
|
+
* export async function POST(request) {
|
|
17
|
+
* const upload = await parseUploadOrError(request, {
|
|
18
|
+
* maxFileSize: 8 * 1024 * 1024,
|
|
19
|
+
* allowedMimeTypes: ['image/png', 'image/jpeg'],
|
|
20
|
+
* });
|
|
21
|
+
* if (upload instanceof Response) return upload; // already a 413/415/400
|
|
22
|
+
* const avatar = upload.files[0]?.value;
|
|
23
|
+
* if (avatar instanceof File) console.log(avatar.name, avatar.size);
|
|
24
|
+
* return Response.json({ ok: true });
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* There is deliberately no bare `parseUpload`: a rejection is a protocol-level
|
|
29
|
+
* outcome (413 / 415 / 400) and every call site has to answer with it, so the
|
|
30
|
+
* function that can return a ready `Response` is the one to reach for. Use
|
|
31
|
+
* `parseMultipartRequest` when you want the throw, to handle it yourself.
|
|
32
|
+
*
|
|
33
|
+
* `request.body` must be a real stream. `vesk dev` and `vesk start` both provide
|
|
34
|
+
* one (see `packages/adapter/src/web-request.ts`); a handler that reaches for
|
|
35
|
+
* `request.formData()` instead is buffered whole under the core 1 MiB body cap
|
|
36
|
+
* and has no per-file, per-type or count limits to enforce.
|
|
37
|
+
*
|
|
38
|
+
* Rejections throw `MultipartError`, whose `status` is 413 (too large / too
|
|
39
|
+
* many), 415 (disallowed type) or 400 (malformed). Nothing is buffered beyond
|
|
40
|
+
* `maxFileSize` per part, so an oversized upload is cut off after the first few
|
|
41
|
+
* KB instead of after the whole body has been read.
|
|
42
|
+
*
|
|
43
|
+
* @module plugin-multipart
|
|
44
|
+
*/
|
|
45
|
+
import { parseMultipart, parseMultipartRequest, boundaryFromContentType, toRecord, multipartResult, attachMultipartResult, MultipartError, } from './parser.js';
|
|
46
|
+
export { parseMultipart, parseMultipartRequest, boundaryFromContentType, toRecord, multipartResult, MultipartError, };
|
|
47
|
+
const MiB = 1024 * 1024;
|
|
48
|
+
/**
|
|
49
|
+
* `parseMultipartRequest` that returns the JSON error `Response` itself on
|
|
50
|
+
* rejection — the ergonomic form for a route handler.
|
|
51
|
+
*
|
|
52
|
+
* ```ts
|
|
53
|
+
* const upload = await parseUploadOrError(req, { maxFileSize: 8 * MiB });
|
|
54
|
+
* if (upload instanceof Response) return upload; // already a 413/415/400
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export async function parseUploadOrError(request, options = {}) {
|
|
58
|
+
try {
|
|
59
|
+
return await parseMultipartRequest(request, options);
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (e instanceof MultipartError) {
|
|
63
|
+
return new Response(JSON.stringify({ error: e.message, code: e.code }), { status: e.status, headers: { 'Content-Type': 'application/json' } });
|
|
64
|
+
}
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function multipart(options = {}) {
|
|
69
|
+
const { autoParse = false, minBytes = 1, ...parseOptions } = options;
|
|
70
|
+
return {
|
|
71
|
+
name: 'multipart',
|
|
72
|
+
async onRequest(ctx) {
|
|
73
|
+
if (!autoParse)
|
|
74
|
+
return;
|
|
75
|
+
const request = ctx.request;
|
|
76
|
+
if (!request)
|
|
77
|
+
return;
|
|
78
|
+
const length = Number(request.headers.get('content-length') || '0');
|
|
79
|
+
if (Number.isFinite(length) && length < minBytes)
|
|
80
|
+
return;
|
|
81
|
+
if (!boundaryFromContentType(request.headers.get('content-type')))
|
|
82
|
+
return;
|
|
83
|
+
try {
|
|
84
|
+
const parsed = await parseMultipartRequest(request, parseOptions);
|
|
85
|
+
attachMultipartResult(request, parsed);
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
if (e instanceof MultipartError) {
|
|
89
|
+
ctx.response = new Response(JSON.stringify({ error: e.message, code: e.code }), { status: e.status, headers: { 'Content-Type': 'application/json' } });
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
throw e;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export default multipart;
|
|
99
|
+
export { MiB };
|
package/dist/parser.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming `multipart/form-data` parser for Vesk.
|
|
3
|
+
*
|
|
4
|
+
* Why this exists instead of `await request.formData()`:
|
|
5
|
+
*
|
|
6
|
+
* 1. **It buffered the whole body in memory.** The core servers cap request
|
|
7
|
+
* bodies at 1 MiB (`DEFAULT_MAX_BODY_BYTES`) and hand the buffer to
|
|
8
|
+
* undici, which then re-parses it. A 40 MB upload could not be accepted
|
|
9
|
+
* at all, and the process held every byte before rejecting anything.
|
|
10
|
+
* 2. **`Object.fromEntries(fd.entries())` destroys files.** A `File` value
|
|
11
|
+
* collapses to an opaque string, so `useBody()` / `withValidation()` could
|
|
12
|
+
* never see a real upload, and nothing could enforce type or size.
|
|
13
|
+
* 3. **No limits could be applied per field.** Validation had to happen after
|
|
14
|
+
* the entire body was resident.
|
|
15
|
+
*
|
|
16
|
+
* This parser consumes the request stream incrementally and enforces the
|
|
17
|
+
* limits as bytes arrive, so an over-limit upload is aborted after the first
|
|
18
|
+
* few KB rather than after buffering all of it.
|
|
19
|
+
*
|
|
20
|
+
* No regex is used for parsing (see the repo's no-regex rule): this is a byte
|
|
21
|
+
* state machine over an incremental buffer.
|
|
22
|
+
*/
|
|
23
|
+
/** A single parsed multipart part. */
|
|
24
|
+
export interface MultipartPart {
|
|
25
|
+
/** The `name` attribute of the part's Content-Disposition. */
|
|
26
|
+
name: string;
|
|
27
|
+
/** Raw filename from the part, when it was a file upload. */
|
|
28
|
+
filename?: string;
|
|
29
|
+
/** Lowercased MIME type from the part's Content-Type, when present. */
|
|
30
|
+
contentType?: string;
|
|
31
|
+
/** Every header on the part. */
|
|
32
|
+
headers: Record<string, string>;
|
|
33
|
+
/** The part body. Text parts get a decoded string; files a `File`. */
|
|
34
|
+
value: string | File;
|
|
35
|
+
/** Byte length of the part body. */
|
|
36
|
+
size: number;
|
|
37
|
+
/** True when the part carried a filename (i.e. is an upload). */
|
|
38
|
+
isFile: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface MultipartLimits {
|
|
41
|
+
/** Max bytes for a single file part. Default 10 MiB. */
|
|
42
|
+
maxFileSize?: number;
|
|
43
|
+
/** Max bytes across the whole body. Default 100 MiB. */
|
|
44
|
+
maxTotalSize?: number;
|
|
45
|
+
/** Max number of file parts. Default 20. */
|
|
46
|
+
maxFiles?: number;
|
|
47
|
+
/** Max number of non-file fields. Default 100. */
|
|
48
|
+
maxFields?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface MultipartOptions extends MultipartLimits {
|
|
51
|
+
/**
|
|
52
|
+
* When set, any file whose content type is not in this list is rejected
|
|
53
|
+
* with a 415. Matching is on the full type or a `type/*` wildcard.
|
|
54
|
+
*/
|
|
55
|
+
allowedMimeTypes?: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Extension allowlist (with or without the leading dot), checked against
|
|
58
|
+
* the filename. Applied even when `allowedMimeTypes` is unset.
|
|
59
|
+
*/
|
|
60
|
+
allowedExtensions?: string[];
|
|
61
|
+
}
|
|
62
|
+
/** Thrown for any rejection. `status` maps onto an HTTP response. */
|
|
63
|
+
export declare class MultipartError extends Error {
|
|
64
|
+
status: number;
|
|
65
|
+
code: string;
|
|
66
|
+
constructor(message: string, code: string, status: number);
|
|
67
|
+
}
|
|
68
|
+
declare const ZERO = 48;
|
|
69
|
+
export interface ParsedMultipart {
|
|
70
|
+
parts: MultipartPart[];
|
|
71
|
+
files: MultipartPart[];
|
|
72
|
+
fields: MultipartPart[];
|
|
73
|
+
/** Sum of every part body, excluding part headers and boundaries. */
|
|
74
|
+
totalSize: number;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Parse a multipart body from a `ReadableStream`, enforcing limits as bytes
|
|
78
|
+
* arrive. Rejects with `MultipartError` (413/415/400) on the first violation.
|
|
79
|
+
*/
|
|
80
|
+
export declare function parseMultipart(stream: ReadableStream<Uint8Array>, boundary: string, options?: MultipartOptions): Promise<ParsedMultipart>;
|
|
81
|
+
/**
|
|
82
|
+
* Extract the boundary token from a `Content-Type` header. Returns null when
|
|
83
|
+
* the header is not multipart or carries no boundary.
|
|
84
|
+
*/
|
|
85
|
+
export declare function boundaryFromContentType(contentType: string | null | undefined): string | null;
|
|
86
|
+
/**
|
|
87
|
+
* The upload a `multipart({ autoParse: true })` plugin already parsed for this
|
|
88
|
+
* request, or null if none did.
|
|
89
|
+
*
|
|
90
|
+
* You rarely need this: `parseUploadOrError` / `parseMultipartRequest` reuse
|
|
91
|
+
* the auto-parsed body on their own. It exists for a handler that wants the
|
|
92
|
+
* result without being able to fail — an error page, say.
|
|
93
|
+
*/
|
|
94
|
+
export declare function multipartResult(request: Request): ParsedMultipart | null;
|
|
95
|
+
/** @internal — used by the plugin's `onRequest` hook. */
|
|
96
|
+
export declare function attachMultipartResult(request: Request, parsed: ParsedMultipart): void;
|
|
97
|
+
/**
|
|
98
|
+
* Apply `options` to an already-parsed upload.
|
|
99
|
+
*
|
|
100
|
+
* Only correct after the fact — the whole point of `parseMultipart` is that it
|
|
101
|
+
* stops a hostile body mid-stream — but the only alternative when a plugin has
|
|
102
|
+
* already read the body is to serve the result with the caller's limits silently
|
|
103
|
+
* ignored, which is worse.
|
|
104
|
+
*/
|
|
105
|
+
export declare function recheckLimits(parsed: ParsedMultipart, options?: MultipartOptions): ParsedMultipart;
|
|
106
|
+
export declare function parseMultipartRequest(request: Request, options?: MultipartOptions): Promise<ParsedMultipart>;
|
|
107
|
+
/**
|
|
108
|
+
* Shape a parsed upload for `withValidation()`-style code and for
|
|
109
|
+
* `Object.fromEntries`-style flattening WITHOUT destroying `File` values.
|
|
110
|
+
* Repeated field names collect into an array.
|
|
111
|
+
*/
|
|
112
|
+
export declare function toRecord(parsed: ParsedMultipart): Record<string, string | File | Array<string | File>>;
|
|
113
|
+
export { ZERO as _ZERO };
|
|
114
|
+
//# sourceMappingURL=parser.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,sCAAsC;AACtC,MAAM,WAAW,aAAa;IAC7B,8DAA8D;IAC9D,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gCAAgC;IAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,sEAAsE;IACtE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,oCAAoC;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,MAAM,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC/B,wDAAwD;IACxD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wDAAwD;IACxD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,gBAAiB,SAAQ,eAAe;IACxD;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,qEAAqE;AACrE,qBAAa,cAAe,SAAQ,KAAK;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;gBACD,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAMzD;AAUD,QAAA,MAAM,IAAI,KAAO,CAAC;AAgGlB,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;CAClB;AASD;;;GAGG;AACH,wBAAsB,cAAc,CACnC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,EAClC,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,eAAe,CAAC,CA8K1B;AA6CD;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAgB7F;AAiBD;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAExE;AAED,yDAAyD;AACzD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,GAAG,IAAI,CAErF;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,EAAE,OAAO,GAAE,gBAAqB,GAAG,eAAe,CAwCtG;AAED,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,eAAe,CAAC,CAc1B;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAatG;AAED,OAAO,EAAE,IAAI,IAAI,KAAK,EAAE,CAAC"}
|