diff --git a/docs/quickstart.md b/docs/quickstart.md index 2f0a365..31620ca 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -307,6 +307,68 @@ to the WebSocket handshake (101/upgrade) response. | `cors` | off (same-origin only) | | `security` | ON (HSTS only when the connection is secure) | +## 8. File uploads / multipart + +A request with `Content-Type: multipart/form-data` makes `@body()` resolve to `{ fields, files }` +instead of a plain object: + +```typescript +import { Route, Post, body } from '@green-tea/core'; +import type { MultipartBody } from '@green-tea/core'; + +@Route('/profile') +class ProfileController { + @Post('/avatar') + upload(@body() form: MultipartBody) { + const name = form.fields.name; // string | string[] + const avatar = form.files.avatar; // UploadedFile | UploadedFile[] + return { name, size: Array.isArray(avatar) ? undefined : avatar?.size }; + } +} +``` + +`UploadedFile` is `{ filename, contentType, data: Buffer, size }` — the whole file is buffered +in memory, no temp files. + +> **Access note (asymmetry).** For multipart, `@body('title')` returns `undefined` — the value +> lives at `body.fields.title`, not `body.title`, unlike JSON/urlencoded where `@body('title')` +> picks the value directly. Use `@body()` and read `.fields`/`.files`, or key into the envelope +> itself with `@body('fields')` / `@body('files')`. + +### Repeated fields — `bodyDuplicates` + +By default, a repeated field name keeps the **last** value (`'last'`, matching urlencoded). +Set `bodyDuplicates: 'array'` on `createApp` to accumulate repeats into a `string[]` instead — +this applies to **both** urlencoded and multipart text fields: + +```typescript +const app = createApp({ modules: [ApiModule], bodyDuplicates: 'array' }); +``` + +Files under a repeated field name always become an array (`UploadedFile[]`), regardless of +`bodyDuplicates`. + +### Per-endpoint override + +```typescript +@Post('/upload', { duplicates: 'array' }) +upload(@body() form: MultipartBody) { /* ... */ } +``` + +Precedence: route `duplicates` → app `bodyDuplicates` → `'last'`. + +### Limits + +Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes` limit as any +other request body (over the limit → 413). `maxParts` (default `1000`) caps the number of +multipart parts per request: + +```typescript +const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } }); +``` + +A malformed multipart body (bad boundary, missing headers, truncated part) → 400. + ## Inspect & test the graph ### Visualize with Mermaid diff --git a/src/app.ts b/src/app.ts index ecc64fb..2161e75 100644 --- a/src/app.ts +++ b/src/app.ts @@ -45,6 +45,7 @@ interface RoutePlan { needs: string[]; run: (ctx: any) => unknown; transformer: typeof JsonTransformer; + duplicates?: 'array' | 'last'; } export interface MeshConfig { @@ -53,7 +54,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' }): App { const bus = new Bus(); const container = new Container(); let server: http.Server | undefined; @@ -115,6 +116,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me needs: getHandlerNeeds(argSpecs), run: (c: any) => inst[route.handlerName](...resolveArgs(argSpecs, c)), transformer: getTransformer(C, route.handlerName) ?? JsonTransformer, + duplicates: route.duplicates, }); } } @@ -319,7 +321,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me ...routePlans .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate .map((plan): RouteDef => ({ - method: plan.method, pattern: plan.pattern, transport: plan.transport, + method: plan.method, pattern: plan.pattern, transport: plan.transport, bodyDuplicates: plan.duplicates, handler: async (req) => { const provided = await providedSeed(plan); return runPipeline({ @@ -362,7 +364,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors, bodyDuplicates: opts.bodyDuplicates }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server!.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index abc83a5..4b28355 100644 --- a/src/http.ts +++ b/src/http.ts @@ -10,14 +10,16 @@ import type { Transport } from './metadata'; import type { Bus } from './bus'; import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; +import { parseMultipart, extractBoundary, collapseDuplicates } from './multipart'; export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 requestTimeoutMs?: number; // default 30_000 headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 + maxParts?: number; // default 1000 } -export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions; bodyDuplicates?: 'array' | 'last' } export type RouteHandler = (req: { method: string; url: string; @@ -29,7 +31,7 @@ export type RouteHandler = (req: { ip: string; }) => Promise; -export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler } +export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler; bodyDuplicates?: 'array' | 'last' } export interface MatchedRoute { params: Record; def: RouteDef } export interface WsOpenCtx { @@ -72,7 +74,7 @@ export function parseQuery(url: string): Record { return out; } -async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { +async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { const chunks: Buffer[] = []; let total = 0; for await (const chunk of req) { @@ -80,9 +82,7 @@ async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promis if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); chunks.push(chunk as Buffer); } - if (chunks.length === 0) return undefined; - const raw = Buffer.concat(chunks).toString('utf8'); - return raw === '' ? undefined : raw; + return chunks.length === 0 ? undefined : Buffer.concat(chunks); } function firstToken(v: string | string[] | undefined): string | undefined { @@ -247,26 +247,43 @@ export function createHttpServer( res.end(JSON.stringify({ error: 'Not Found' })); return; } - let raw: string | undefined; + let buf: Buffer | undefined; try { - raw = await readBody(req, maxBody); + buf = await readBody(req, maxBody); } catch (error) { const r = errorToResponse(error); res.writeHead(r.status, { ...r.headers, connection: 'close' }); res.end(r.body); return; } - let body: unknown = raw; + let body: unknown; const ct = String(req.headers['content-type'] ?? ''); - if (raw !== undefined && ct.includes('application/json')) { - try { body = JSON.parse(raw); } + const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'; + if (buf !== undefined && ct.includes('application/json')) { + try { body = JSON.parse(buf.toString('utf8')); } catch { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'Invalid JSON body' })); return; } - } else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) { - body = Object.fromEntries(new URLSearchParams(raw)); + } else if (buf !== undefined && ct.includes('application/x-www-form-urlencoded')) { + body = collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates); + } else if (buf !== undefined && ct.includes('multipart/form-data')) { + const boundary = extractBoundary(ct); + if (!boundary) { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid multipart body' })); + return; + } + try { body = parseMultipart(buf, boundary, { maxParts: opts?.limits?.maxParts ?? 1000, duplicates }); } + catch { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid multipart body' })); + return; + } + } else { + const s = buf?.toString('utf8'); + body = s === '' ? undefined : s; } let result: PipelineResult; try { diff --git a/src/index.ts b/src/index.ts index 28cf546..344a578 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,6 +25,7 @@ export type { StreamEncoder } from './encoders'; export type { MeshConfig } from './app'; export type { RequestLimits } from './http'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; +export type { UploadedFile, MultipartBody } from './multipart'; export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/src/metadata.ts b/src/metadata.ts index 33e48dc..be4efce 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -7,7 +7,7 @@ export interface ProviderMeta { provides: string; needs: string[]; optional: boo export interface StepMeta { provides: string; needs: string[]; optional: boolean; export: boolean } export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export type Transport = 'buffer' | 'sse' | 'ndjson' | 'negotiate' | 'ws'; -export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean } +export interface RouteMeta { method: HttpMethod; path: string; handlerName: string; transport: Transport; export: boolean; duplicates?: 'array' | 'last' } export interface ModuleOptions { mountpoint: string; providers?: Ctor[]; steps?: Ctor[]; controllers?: Ctor[]; } @@ -40,11 +40,11 @@ export function Route(prefix: string): ClassDecorator { } function routeDecorator(method: HttpMethod, transport: Transport) { - return (path: string, opts?: { export?: boolean }): MethodDecorator => + return (path: string, opts?: { export?: boolean; duplicates?: 'array' | 'last' }): MethodDecorator => (target, propertyKey) => { const ctor = target.constructor; const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? []; - routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false }); + routes.push({ method, path, handlerName: String(propertyKey), transport, export: opts?.export ?? false, duplicates: opts?.duplicates }); Reflect.defineMetadata(K.routes, routes, ctor); }; } diff --git a/src/multipart.ts b/src/multipart.ts new file mode 100644 index 0000000..02fad20 --- /dev/null +++ b/src/multipart.ts @@ -0,0 +1,122 @@ +// src/multipart.ts — pure, binary-safe multipart/form-data parser. No server deps. +export interface UploadedFile { filename: string; contentType: string; data: Buffer; size: number } +export interface MultipartBody { + fields: Record; + files: Record; +} +export interface MultipartOpts { maxParts: number; duplicates: 'array' | 'last' } + +const CRLF = Buffer.from('\r\n'); + +// boundary token from a Content-Type value; supports quoted form. +export function extractBoundary(contentType: string): string | undefined { + const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); + const b = (m?.[1] ?? m?.[2])?.trim(); + return b || undefined; +} + +// order-independent, quoted-or-unquoted param lookup within a header value. +// The `(?:^|[;\s])` prefix anchors the key to a param boundary so `name=` does NOT +// match the tail of `filename=`, and `filename=` does not match `filename*=`. +function param(header: string, key: string): string | undefined { + const q = new RegExp(`(?:^|[;\\s])${key}="([^"]*)"`, 'i').exec(header); + if (q) return q[1]; + const u = new RegExp(`(?:^|[;\\s])${key}=([^";]+)`, 'i').exec(header); + return u ? u[1].trim() : undefined; +} + +function addField(fields: MultipartBody['fields'], name: string, value: string, dup: 'array' | 'last'): void { + if (dup === 'array') { + const ex = fields[name]; + if (Array.isArray(ex)) ex.push(value); + else fields[name] = [value]; + } else { + fields[name] = value; // last-wins + } +} + +// Reusable accumulator for any iterable of [key, value] pairs (e.g. URLSearchParams) +// so urlencoded bodies collapse duplicates with the exact same policy as multipart fields. +export function collapseDuplicates( + pairs: Iterable<[string, string]>, dup: 'array' | 'last', +): Record { + const out: Record = {}; + for (const [k, v] of pairs) addField(out, k, v, dup); + return out; +} + +function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void { + const ex = files[name]; + if (ex === undefined) files[name] = file; + else if (Array.isArray(ex)) ex.push(file); + else files[name] = [ex, file]; +} + +// Find the next REAL delimiter at/after `from`: a `\r\n--boundary` occurrence that is +// followed by `\r\n` (a part) or `--` (the terminator). This skips false hits where the +// exact `\r\n--boundary` byte sequence appears INSIDE a file body — the data-integrity case. +function findDelim(buf: Buffer, delim: Buffer, from: number): number { + let i = buf.indexOf(delim, from); + while (i !== -1) { + const a = i + delim.length; + if ((buf[a] === 0x0d && buf[a + 1] === 0x0a) || (buf[a] === 0x2d && buf[a + 1] === 0x2d)) return i; + i = buf.indexOf(delim, i + delim.length); // false hit inside a body — keep searching + } + return -1; +} + +export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): MultipartBody { + const fields: MultipartBody['fields'] = {}; + const files: MultipartBody['files'] = {}; + const delim = Buffer.concat([CRLF, Buffer.from(`--${boundary}`)]); // \r\n--boundary + // Normalize: prepend CRLF so the FIRST boundary (which a browser sends with no + // leading CRLF) is also preceded by the delimiter and isn't dropped as preamble. + const buf = Buffer.concat([CRLF, raw]); + + let pos = findDelim(buf, delim, 0); + if (pos === -1) throw new Error('Invalid multipart body'); + let count = 0; + while (true) { + let start = pos + delim.length; + // terminator "--" immediately after the boundary → done + if (buf[start] === 0x2d && buf[start + 1] === 0x2d) break; + // skip the CRLF that ends the boundary line + if (buf[start] === 0x0d && buf[start + 1] === 0x0a) start += 2; + const next = findDelim(buf, delim, start); + if (next === -1) throw new Error('Invalid multipart body'); + if (++count > opts.maxParts) throw new Error('Invalid multipart body'); + const part = buf.subarray(start, next); + const sep = part.indexOf('\r\n\r\n'); + if (sep === -1) throw new Error('Invalid multipart body'); + const headerText = part.subarray(0, sep).toString('utf8'); + const partBody = part.subarray(sep + 4); + + let disposition = ''; + let contentType = ''; + for (const line of headerText.split('\r\n')) { + const c = line.indexOf(':'); + if (c === -1) continue; + const k = line.slice(0, c).trim().toLowerCase(); + const v = line.slice(c + 1).trim(); + if (k === 'content-disposition') disposition = v; + else if (k === 'content-type') contentType = v; + } + + const name = param(disposition, 'name'); + if (name === undefined) throw new Error('Invalid multipart body'); + const filename = param(disposition, 'filename'); + if (filename !== undefined) { + if (filename === '' && partBody.length === 0) { pos = next; continue; } // unselected file input + addFile(files, name, { + filename, + contentType: contentType || 'application/octet-stream', + data: Buffer.from(partBody), // copy out of the shared buffer + size: partBody.length, + }); + } else { + addField(fields, name, partBody.toString('utf8'), opts.duplicates); + } + pos = next; + } + return { fields, files }; +} diff --git a/test/multipart-http.test.ts b/test/multipart-http.test.ts new file mode 100644 index 0000000..871d157 --- /dev/null +++ b/test/multipart-http.test.ts @@ -0,0 +1,90 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { createApp, Route, Post, Module, body } from '../src'; + +let app: any; +afterEach(async () => { await app?.close(); }); + +describe('multipart over http', () => { + it('parses fields + a binary file round-trip', async () => { + @Route('/') class C { + @Post('/upload') up(@body() b: any) { + const f = b.files.file; + return { name: b.fields.name, filename: f.filename, bytes: [...f.data], type: f.contentType }; + } + } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const fd = new FormData(); + fd.set('name', 'joe'); + const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0x0d, 0x0a]); + fd.set('file', new Blob([bytes], { type: 'image/png' }), 'p.png'); + const r = await fetch(`http://127.0.0.1:${port}/upload`, { method: 'POST', body: fd }); + const out = (await r.json()) as any; + expect(out.name).toBe('joe'); + expect(out.filename).toBe('p.png'); + expect(out.type).toBe('image/png'); + expect(out.bytes).toEqual([...bytes]); + }); + + it('text/plain body still arrives as a string (fallthrough preserved)', async () => { + @Route('/') class C { @Post('/t') t(@body() b: any) { return { isString: typeof b === 'string', b }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/t`, { + method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' }); + expect(await r.json()).toEqual({ isString: true, b: 'hello' }); + }); + + it('malformed multipart → 400', async () => { + @Route('/') class C { @Post('/u') u(@body() b: any) { return b; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/u`, { + method: 'POST', headers: { 'content-type': 'multipart/form-data; boundary=' }, body: 'x' }); + expect(r.status).toBe(400); + }); +}); + +describe('bodyDuplicates', () => { + it('app "array" makes repeated urlencoded fields arrays', async () => { + @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], bodyDuplicates: 'array' }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/f`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2&y=9' }); + expect(await r.json()).toEqual({ x: ['1', '2'], y: ['9'] }); + }); + it('default (no option) keeps urlencoded last-wins', async () => { + @Route('/') class C { @Post('/f') f(@body() b: any) { return b; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/f`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' }); + expect(await r.json()).toEqual({ x: '2' }); + }); + + it('per-endpoint override beats app default', async () => { + @Route('/') class C { + @Post('/a', { duplicates: 'last' }) a(@body() b: any) { return b; } + @Post('/b', { duplicates: 'array' }) b2(@body() b: any) { return b; } + } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], bodyDuplicates: 'last' }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const post = (p: string) => fetch(`http://127.0.0.1:${port}${p}`, { + method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'x=1&x=2' }).then((r) => r.json()); + expect(await post('/a')).toEqual({ x: '2' }); + expect(await post('/b')).toEqual({ x: ['1', '2'] }); + }); +}); diff --git a/test/multipart.test.ts b/test/multipart.test.ts new file mode 100644 index 0000000..e90366c --- /dev/null +++ b/test/multipart.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect } from 'vitest'; +import { parseMultipart, extractBoundary } from '../src/multipart'; + +const B = 'X-BOUND'; +function body(parts: string[]): Buffer { + return Buffer.concat([ + ...parts.map((p) => Buffer.from(`--${B}\r\n${p}\r\n`)), + Buffer.from(`--${B}--\r\n`), + ]); +} +const field = (name: string, val: string) => `Content-Disposition: form-data; name="${name}"\r\n\r\n${val}`; +const file = (name: string, fn: string, ct: string, data: string) => + `Content-Disposition: form-data; name="${name}"; filename="${fn}"\r\nContent-Type: ${ct}\r\n\r\n${data}`; +const opts = { maxParts: 1000, duplicates: 'last' as const }; + +describe('extractBoundary', () => { + it('plain and quoted', () => { + expect(extractBoundary('multipart/form-data; boundary=abc')).toBe('abc'); + expect(extractBoundary('multipart/form-data; boundary="a b"')).toBe('a b'); + expect(extractBoundary('multipart/form-data')).toBeUndefined(); + }); +}); + +describe('parseMultipart', () => { + it('single text field is NOT lost (first-part off-by-one guard)', () => { + const r = parseMultipart(body([field('title', 'hello')]), B, opts); + expect(r.fields.title).toBe('hello'); + }); + it('multiple distinct fields', () => { + const r = parseMultipart(body([field('a', '1'), field('b', '2')]), B, opts); + expect(r.fields).toEqual({ a: '1', b: '2' }); + }); + it("duplicates 'last' vs 'array'", () => { + const b = body([field('t', 'x'), field('t', 'y')]); + expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'last' }).fields.t).toBe('y'); + expect(parseMultipart(b, B, { maxParts: 1000, duplicates: 'array' }).fields.t).toEqual(['x', 'y']); + }); + it('single file: metadata + exact bytes incl. embedded CRLF and boundary-like text', () => { + const payload = 'ab\r\n--X-BOUNDnope\r\ncd'; + const r = parseMultipart(body([file('doc', 'a.txt', 'text/plain', payload)]), B, opts); + const f = r.files.doc as any; + expect(f.filename).toBe('a.txt'); + expect(f.contentType).toBe('text/plain'); + expect(f.size).toBe(Buffer.byteLength(payload)); + expect(f.data.toString()).toBe(payload); + }); + it('multiple files same name → array', () => { + const r = parseMultipart(body([file('f', '1', 'text/plain', 'a'), file('f', '2', 'text/plain', 'b')]), B, opts); + expect(Array.isArray(r.files.f)).toBe(true); + expect((r.files.f as any).length).toBe(2); + }); + it('mixed fields + files', () => { + const r = parseMultipart(body([field('name', 'joe'), file('avatar', 'p.png', 'image/png', 'PNG')]), B, opts); + expect(r.fields.name).toBe('joe'); + expect((r.files.avatar as any).filename).toBe('p.png'); + }); + it('case-insensitive headers + filename-before-name (order independent)', () => { + const part = `content-disposition: form-data; filename="z.bin"; name="up"\r\ncontent-type: application/octet-stream\r\n\r\nDATA`; + const r = parseMultipart(body([part]), B, opts); + expect((r.files.up as any).filename).toBe('z.bin'); + }); + it('filename="" with empty body is skipped', () => { + const part = `Content-Disposition: form-data; name="up"; filename=""\r\n\r\n`; + const r = parseMultipart(body([part]), B, opts); + expect(r.files.up).toBeUndefined(); + }); + it('malformed → throws: no boundary present', () => { + expect(() => parseMultipart(Buffer.from('garbage'), B, opts)).toThrow(); + }); + it('malformed → throws: part without name', () => { + const part = `Content-Disposition: form-data\r\n\r\nx`; + expect(() => parseMultipart(body([part]), B, opts)).toThrow(); + }); + it('malformed → throws: part with no header/body separator', () => { + const raw = Buffer.from(`--${B}\r\nContent-Disposition: form-data; name="a"\r\n--${B}--\r\n`); + expect(() => parseMultipart(raw, B, opts)).toThrow(); + }); + it('parts over maxParts → throws', () => { + const b = body([field('a', '1'), field('b', '2'), field('c', '3')]); + expect(() => parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).toThrow(); + }); +});