@orpc/node 2.0.0-beta.47 → 2.0.0-beta.49

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.
@@ -0,0 +1,221 @@
1
+ import { Buffer } from 'node:buffer';
2
+ /**
3
+ * Part headers are tiny in practice, so an unterminated header block is cut off
4
+ * long before it can buffer a request-sized payload in memory.
5
+ */
6
+ const MAX_PART_HEADER_SIZE = 16 * 1024;
7
+ const CRLF = /* @__PURE__ */ Buffer.from('\r\n');
8
+ const HEADER_BLOCK_END = /* @__PURE__ */ Buffer.from('\r\n\r\n');
9
+ /**
10
+ * Parses a `multipart/form-data` byte stream part by part, so a part's body can be
11
+ * consumed as it arrives instead of being buffered whole. Bodies are delivered to the
12
+ * writer `onPart` returns, with writer promises awaited for backpressure, so parts are
13
+ * processed strictly one at a time.
14
+ *
15
+ * Line endings are strictly CRLF, every part must carry a `form-data` content
16
+ * disposition with a `name` parameter, and a malformed or truncated body throws a
17
+ * `TypeError`, matching the standard parser's strictness.
18
+ *
19
+ * @see https://www.rfc-editor.org/rfc/rfc7578
20
+ * @see https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
21
+ */
22
+ export async function parseMultipart(source, boundary, onPart) {
23
+ const delimiter = Buffer.from(`\r\n--${boundary}`);
24
+ /**
25
+ * Seeded with a virtual CRLF so the opening `--boundary` line, which the grammar
26
+ * allows without a preceding line break, matches the same needle as every
27
+ * later delimiter.
28
+ */
29
+ let buffer = CRLF;
30
+ let state = 'preamble';
31
+ let writer;
32
+ let done = false;
33
+ const process = async () => {
34
+ while (true) {
35
+ if (state === 'preamble' || state === 'body') {
36
+ const index = buffer.indexOf(delimiter);
37
+ if (index === -1) {
38
+ // All bytes except a possible delimiter prefix are settled and can be flushed
39
+ const settledLength = buffer.length - delimiter.length + 1;
40
+ if (settledLength > 0) {
41
+ if (state === 'body') {
42
+ await writer.write(buffer.subarray(0, settledLength));
43
+ }
44
+ buffer = buffer.subarray(settledLength);
45
+ }
46
+ return;
47
+ }
48
+ if (state === 'body') {
49
+ if (index > 0) {
50
+ await writer.write(buffer.subarray(0, index));
51
+ }
52
+ await writer.end();
53
+ writer = undefined;
54
+ }
55
+ buffer = buffer.subarray(index + delimiter.length);
56
+ state = 'delimiter-end';
57
+ continue;
58
+ }
59
+ if (state === 'delimiter-end') {
60
+ if (buffer.length < 2) {
61
+ return;
62
+ }
63
+ // A close delimiter is `--` immediately after the boundary, everything after it is epilogue
64
+ if (buffer[0] === 0x2d && buffer[1] === 0x2d) {
65
+ done = true;
66
+ buffer = Buffer.alloc(0);
67
+ return;
68
+ }
69
+ state = 'transport-padding';
70
+ continue;
71
+ }
72
+ if (state === 'transport-padding') {
73
+ let index = 0;
74
+ while (index < buffer.length && (buffer[index] === 0x20 || buffer[index] === 0x09)) {
75
+ index++;
76
+ }
77
+ buffer = buffer.subarray(index);
78
+ if (buffer.length < 2) {
79
+ return;
80
+ }
81
+ if (buffer[0] !== 0x0d || buffer[1] !== 0x0a) {
82
+ throw new TypeError('Invalid multipart body: expected CRLF after a boundary delimiter');
83
+ }
84
+ buffer = buffer.subarray(2);
85
+ state = 'headers';
86
+ continue;
87
+ }
88
+ // A part without headers can never carry the required content-disposition
89
+ if (buffer[0] === 0x0d && buffer[1] === 0x0a) {
90
+ throw new TypeError('Invalid multipart body: part is missing the content-disposition header');
91
+ }
92
+ const headerWindow = MAX_PART_HEADER_SIZE + HEADER_BLOCK_END.length;
93
+ const headerEnd = buffer.subarray(0, headerWindow).indexOf(HEADER_BLOCK_END);
94
+ if (headerEnd === -1) {
95
+ if (buffer.length >= headerWindow) {
96
+ throw new TypeError('Invalid multipart body: part headers exceed the maximum allowed size');
97
+ }
98
+ return;
99
+ }
100
+ const headerSize = headerEnd + HEADER_BLOCK_END.length;
101
+ const part = parsePartHeaders(buffer.subarray(0, headerEnd).toString(), headerSize);
102
+ buffer = buffer.subarray(headerSize);
103
+ writer = await onPart(part);
104
+ state = 'body';
105
+ }
106
+ };
107
+ for await (const chunk of source) {
108
+ if (done) {
109
+ continue;
110
+ }
111
+ // A bare view suffices when nothing is retained, skipping a copy
112
+ buffer =
113
+ buffer.length === 0
114
+ ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
115
+ : Buffer.concat([buffer, chunk]);
116
+ await process();
117
+ }
118
+ if (!done) {
119
+ throw new TypeError('Invalid multipart body: unexpected end of body');
120
+ }
121
+ }
122
+ function parsePartHeaders(block, headerSize) {
123
+ let contentDisposition;
124
+ let contentType;
125
+ for (const line of block.split('\r\n')) {
126
+ const colon = line.indexOf(':');
127
+ if (colon === -1) {
128
+ throw new TypeError('Invalid multipart body: malformed part header');
129
+ }
130
+ const name = line.slice(0, colon).trim().toLowerCase();
131
+ if (name === 'content-disposition') {
132
+ contentDisposition = line.slice(colon + 1).trim();
133
+ }
134
+ else if (name === 'content-type') {
135
+ contentType = line.slice(colon + 1).trim();
136
+ }
137
+ }
138
+ if (contentDisposition === undefined) {
139
+ throw new TypeError('Invalid multipart body: part is missing the content-disposition header');
140
+ }
141
+ // The standard parser accepts no disposition type other than form-data, case-insensitively
142
+ const semicolon = contentDisposition.indexOf(';');
143
+ const dispositionType = (semicolon === -1 ? contentDisposition : contentDisposition.slice(0, semicolon))
144
+ .trim()
145
+ .toLowerCase();
146
+ if (dispositionType !== 'form-data') {
147
+ throw new TypeError('Invalid multipart body: content-disposition must be form-data');
148
+ }
149
+ const parameters = parseHeaderParameters(contentDisposition);
150
+ const name = parameters.get('name');
151
+ if (name === undefined) {
152
+ throw new TypeError('Invalid multipart body: content-disposition header is missing the name parameter');
153
+ }
154
+ const filename = parameters.get('filename');
155
+ return {
156
+ name: decodeContentDispositionParameter(name),
157
+ filename: filename === undefined ? undefined : decodeContentDispositionParameter(filename),
158
+ type: contentType,
159
+ headerSize,
160
+ };
161
+ }
162
+ /**
163
+ * The multipart serialization every spec-compliant client uses escapes `"`, `\r`,
164
+ * and `\n` in content-disposition names and filenames as `%22`, `%0D`, and `%0A`,
165
+ * and the standard parser reverses exactly these three.
166
+ *
167
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
168
+ */
169
+ function decodeContentDispositionParameter(value) {
170
+ return value.replaceAll('%22', '"').replaceAll('%0D', '\r').replaceAll('%0A', '\n');
171
+ }
172
+ /**
173
+ * Extracts the `key=value` parameters that follow a header's leading token.
174
+ * The first occurrence of a parameter wins.
175
+ *
176
+ * A backslash inside a quoted value is a literal character rather than an
177
+ * escape, matching the standard parser: the multipart serialization escapes
178
+ * `"` as `%22`, so a quote can never occur inside a value, while filenames
179
+ * with literal backslashes are common and must survive verbatim.
180
+ *
181
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
182
+ */
183
+ export function parseHeaderParameters(header) {
184
+ const parameters = new Map();
185
+ let index = header.indexOf(';');
186
+ while (index !== -1 && index < header.length) {
187
+ index++;
188
+ while (index < header.length && (header[index] === ' ' || header[index] === '\t')) {
189
+ index++;
190
+ }
191
+ let equals = index;
192
+ while (equals < header.length && header[equals] !== '=' && header[equals] !== ';') {
193
+ equals++;
194
+ }
195
+ if (equals === header.length) {
196
+ break;
197
+ }
198
+ // A parameter without a value ends at the next semicolon and is skipped
199
+ if (header[equals] === ';') {
200
+ index = equals;
201
+ continue;
202
+ }
203
+ const key = header.slice(index, equals).trim().toLowerCase();
204
+ index = equals + 1;
205
+ let value;
206
+ if (header[index] === '"') {
207
+ const closing = header.indexOf('"', index + 1);
208
+ value = closing === -1 ? header.slice(index + 1) : header.slice(index + 1, closing);
209
+ index = closing === -1 ? -1 : header.indexOf(';', closing + 1);
210
+ }
211
+ else {
212
+ const semicolon = header.indexOf(';', index);
213
+ value = (semicolon === -1 ? header.slice(index) : header.slice(index, semicolon)).trim();
214
+ index = semicolon;
215
+ }
216
+ if (!parameters.has(key)) {
217
+ parameters.set(key, value);
218
+ }
219
+ }
220
+ return parameters;
221
+ }
@@ -0,0 +1,84 @@
1
+ import type { Context } from '@orpc/server';
2
+ import type { StandardHandlerOptions, StandardHandlerPlugin } from '@orpc/server/standard';
3
+ export interface StaticFileHandlerPluginOptions {
4
+ /**
5
+ * The directory files are served from. Resolved against the working
6
+ * directory when relative.
7
+ */
8
+ rootDir: string;
9
+ /**
10
+ * The URL path files are served under, appended to the handler prefix
11
+ * when one is set.
12
+ *
13
+ * @default '/'
14
+ */
15
+ path?: `/${string}` | undefined;
16
+ /**
17
+ * The file served when the request path resolves to a directory.
18
+ * Set to `false` to disable directory index files.
19
+ *
20
+ * @default 'index.html'
21
+ */
22
+ indexFile?: string | false | undefined;
23
+ /**
24
+ * A file served with status 200 when no file matches the request path,
25
+ * relative to `rootDir`. Useful for single-page application routing.
26
+ *
27
+ * @default undefined
28
+ */
29
+ fallbackFile?: string | undefined;
30
+ /**
31
+ * The `Cache-Control` response header value. Set to `false` to omit the header.
32
+ *
33
+ * @default 'public, max-age=0'
34
+ */
35
+ cacheControl?: string | false | undefined;
36
+ /**
37
+ * Whether files and directories whose name starts with a dot can be served.
38
+ * This is a request path policy, so it does not apply to a configured `indexFile`
39
+ * or `fallbackFile`, nor to the target of a symbolic link.
40
+ * When disabled, names shaped like 8.3 short names, such as `ENV~1`, are refused too,
41
+ * since NTFS and FAT resolve them to dotfiles.
42
+ *
43
+ * @default false
44
+ */
45
+ dotfiles?: boolean | undefined;
46
+ /**
47
+ * Whether precompressed sidecar files (`.br`, `.zst`, `.gz`) can be served
48
+ * when the client accepts their encoding and the content type is compressible.
49
+ *
50
+ * @default false
51
+ */
52
+ precompressed?: boolean | undefined;
53
+ /**
54
+ * Content types keyed by lowercase file extension without the dot, taking precedence over
55
+ * the type detected from the extension. Values are sent verbatim, so a text type needs its
56
+ * own charset. Extensions that neither this nor the detection recognises are served as
57
+ * `application/octet-stream`.
58
+ */
59
+ mimeTypes?: Record<string, string> | undefined;
60
+ }
61
+ /**
62
+ * Serves static files from a directory: index files, `ETag`/`Last-Modified`
63
+ * revalidation, range requests, and precompressed sidecars. Files are served
64
+ * as a fallback, so matched procedures always win.
65
+ *
66
+ * @see {@link https://orpc.dev/docs/plugins/static-file | Static File Plugin}
67
+ */
68
+ export declare class StaticFileHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
69
+ name: string;
70
+ after: string[];
71
+ before: string[];
72
+ private readonly rootDir;
73
+ private readonly path;
74
+ private readonly indexFile;
75
+ private readonly fallbackFilePath;
76
+ private readonly cacheControl;
77
+ private readonly unsafeSegmentRegex;
78
+ private readonly precompressed;
79
+ private readonly mimeTypes;
80
+ constructor(options: StaticFileHandlerPluginOptions);
81
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
82
+ private serve;
83
+ private resolveContentType;
84
+ }
@@ -0,0 +1,215 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { getTracer, isAcceptableEncoding, isCompressibleContentType, matchesHttpPathPrefix, mergeHttpPath, parseAcceptEncodingQualities, safeDecodeURIComponent, toArray, } from '@orpc/shared';
5
+ import { flattenStandardHeader, parseStandardUrl } from '@standard-server/core';
6
+ import { toWebReadableStream } from '@standard-server/node';
7
+ import mime from 'mime';
8
+ const UNSAFE_SEGMENT_REGEX = /^[. ]+$|[\0/\\]/;
9
+ const UNSAFE_OR_DOTFILE_SEGMENT_REGEX = /^[. ]+$|^\.|^[^.]{0,6}~\d|[\0/\\]/;
10
+ const PRECOMPRESSED_ENCODINGS = [
11
+ ['br', '.br'],
12
+ ['zstd', '.zst'],
13
+ ['gzip', '.gz'],
14
+ ];
15
+ /**
16
+ * Serves static files from a directory: index files, `ETag`/`Last-Modified`
17
+ * revalidation, range requests, and precompressed sidecars. Files are served
18
+ * as a fallback, so matched procedures always win.
19
+ *
20
+ * @see {@link https://orpc.dev/docs/plugins/static-file | Static File Plugin}
21
+ */
22
+ export class StaticFileHandlerPlugin {
23
+ name = '~static-file';
24
+ after = ['~tracing'];
25
+ before = ['~head-method'];
26
+ rootDir;
27
+ path;
28
+ indexFile;
29
+ fallbackFilePath;
30
+ cacheControl;
31
+ unsafeSegmentRegex;
32
+ precompressed;
33
+ mimeTypes;
34
+ constructor(options) {
35
+ this.rootDir = path.resolve(options.rootDir);
36
+ this.path = stripTrailingSlash(options.path ?? '/');
37
+ this.indexFile = options.indexFile ?? 'index.html';
38
+ this.fallbackFilePath =
39
+ options.fallbackFile === undefined ? undefined : path.join(this.rootDir, options.fallbackFile);
40
+ this.cacheControl = options.cacheControl ?? 'public, max-age=0';
41
+ this.unsafeSegmentRegex = options.dotfiles
42
+ ? UNSAFE_SEGMENT_REGEX
43
+ : UNSAFE_OR_DOTFILE_SEGMENT_REGEX;
44
+ this.precompressed = options.precompressed ?? false;
45
+ this.mimeTypes = Object.assign(Object.create(null), options.mimeTypes);
46
+ }
47
+ init(options) {
48
+ const routingInterceptor = async ({ next, request, prefix, }) => {
49
+ const result = await next();
50
+ if (result.matched || (request.method !== 'GET' && request.method !== 'HEAD')) {
51
+ return result;
52
+ }
53
+ const base = prefix === undefined ? this.path : stripTrailingSlash(mergeHttpPath(prefix, this.path));
54
+ const response = await this.serve(request, base);
55
+ if (response === undefined) {
56
+ return result;
57
+ }
58
+ getTracer()
59
+ ?.getActiveSpan()
60
+ ?.updateName(`${request.method} ${base === '/' ? '' : base}/* (static file)`);
61
+ return { matched: true, response };
62
+ };
63
+ return {
64
+ ...options,
65
+ routingInterceptors: [...toArray(options.routingInterceptors), routingInterceptor],
66
+ };
67
+ }
68
+ async serve(request, base) {
69
+ const [pathname] = parseStandardUrl(request.url);
70
+ if (base !== '/' && !matchesHttpPathPrefix(pathname, base)) {
71
+ return undefined;
72
+ }
73
+ const segments = [];
74
+ let isDirectoryUrl = false;
75
+ for (const rawSegment of pathname.slice(base.length).split('/')) {
76
+ const segment = safeDecodeURIComponent(rawSegment);
77
+ isDirectoryUrl = segment === '' || segment === '.';
78
+ if (isDirectoryUrl) {
79
+ continue;
80
+ }
81
+ if (this.unsafeSegmentRegex.test(segment)) {
82
+ return undefined;
83
+ }
84
+ segments.push(segment);
85
+ }
86
+ let filePath = path.join(this.rootDir, ...segments);
87
+ let stats = isDirectoryUrl ? undefined : await getStats(filePath);
88
+ if (isDirectoryUrl || stats?.isDirectory()) {
89
+ stats = undefined;
90
+ if (this.indexFile !== false) {
91
+ filePath = path.join(filePath, this.indexFile);
92
+ stats = await getStats(filePath);
93
+ }
94
+ }
95
+ if (!stats?.isFile() && this.fallbackFilePath !== undefined) {
96
+ filePath = this.fallbackFilePath;
97
+ stats = await getStats(filePath);
98
+ }
99
+ if (!stats?.isFile()) {
100
+ return undefined;
101
+ }
102
+ const contentType = this.resolveContentType(filePath);
103
+ const headers = {};
104
+ let contentEncoding;
105
+ if (this.precompressed && isCompressibleContentType(contentType)) {
106
+ headers.vary = 'accept-encoding';
107
+ const qualities = parseAcceptEncodingQualities(flattenStandardHeader(request.headers['accept-encoding']));
108
+ for (const [encoding, extension] of PRECOMPRESSED_ENCODINGS) {
109
+ if (!isAcceptableEncoding(qualities, encoding)) {
110
+ continue;
111
+ }
112
+ const variantStats = await getStats(filePath + extension);
113
+ if (variantStats?.isFile()) {
114
+ filePath += extension;
115
+ stats = variantStats;
116
+ contentEncoding = encoding;
117
+ break;
118
+ }
119
+ }
120
+ }
121
+ const size = stats.size;
122
+ const etag = `"${size.toString(16)}-${stats.mtime.getTime().toString(16)}"`;
123
+ const lastModifiedTime = Math.floor(stats.mtime.getTime() / 1000) * 1000;
124
+ headers.etag = etag;
125
+ headers['last-modified'] = stats.mtime.toUTCString();
126
+ headers['accept-ranges'] = 'bytes';
127
+ if (this.cacheControl !== false) {
128
+ headers['cache-control'] = this.cacheControl;
129
+ }
130
+ if (isNotModified(request.headers, etag, lastModifiedTime)) {
131
+ return { status: 304, headers };
132
+ }
133
+ let status = 200;
134
+ let start = 0;
135
+ let end = size - 1;
136
+ const range = request.method === 'GET' ? flattenStandardHeader(request.headers.range) : undefined;
137
+ if (range !== undefined && isRangeApplicable(request.headers, etag, lastModifiedTime)) {
138
+ const parsed = parseByteRange(range, size);
139
+ if (parsed === 'unsatisfiable') {
140
+ return { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } };
141
+ }
142
+ if (parsed !== undefined) {
143
+ status = 206;
144
+ [start, end] = parsed;
145
+ headers['content-range'] = `bytes ${start}-${end}/${size}`;
146
+ }
147
+ }
148
+ if (contentEncoding !== undefined) {
149
+ headers['content-encoding'] = contentEncoding;
150
+ }
151
+ headers['content-type'] = contentType;
152
+ headers['content-length'] = `${end - start + 1}`;
153
+ const body = request.method === 'HEAD'
154
+ ? new ReadableStream({ start: (controller) => controller.close() })
155
+ : toWebReadableStream(createReadStream(filePath, status === 206 ? { start, end } : undefined));
156
+ return { status, headers, body };
157
+ }
158
+ resolveContentType(filePath) {
159
+ const extension = path.extname(filePath).slice(1).toLowerCase();
160
+ const configured = this.mimeTypes[extension];
161
+ if (configured !== undefined) {
162
+ return configured;
163
+ }
164
+ const contentType = mime.getType(extension);
165
+ if (contentType === null) {
166
+ return 'application/octet-stream';
167
+ }
168
+ return contentType.startsWith('text/') ? `${contentType}; charset=utf-8` : contentType;
169
+ }
170
+ }
171
+ function getStats(filePath) {
172
+ return stat(filePath).catch(() => undefined);
173
+ }
174
+ function stripTrailingSlash(path) {
175
+ return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
176
+ }
177
+ function isNotModified(requestHeaders, etag, lastModifiedTime) {
178
+ const ifNoneMatch = flattenStandardHeader(requestHeaders['if-none-match']);
179
+ if (ifNoneMatch !== undefined) {
180
+ return (ifNoneMatch.trim() === '*' ||
181
+ ifNoneMatch.split(',').some((tag) => {
182
+ tag = tag.trim();
183
+ return (tag.startsWith('W/') ? tag.slice(2) : tag) === etag;
184
+ }));
185
+ }
186
+ const ifModifiedSince = flattenStandardHeader(requestHeaders['if-modified-since']);
187
+ return ifModifiedSince !== undefined && lastModifiedTime <= Date.parse(ifModifiedSince);
188
+ }
189
+ function isRangeApplicable(requestHeaders, etag, lastModifiedTime) {
190
+ const ifRange = flattenStandardHeader(requestHeaders['if-range']);
191
+ if (ifRange === undefined) {
192
+ return true;
193
+ }
194
+ return ifRange.startsWith('"') || ifRange.startsWith('W/')
195
+ ? ifRange === etag
196
+ : Date.parse(ifRange) === lastModifiedTime;
197
+ }
198
+ function parseByteRange(range, size) {
199
+ const match = range.match(/^bytes=\s*(\d*)-(\d*)$/i);
200
+ if (match === null || (match[1] === '' && match[2] === '')) {
201
+ return undefined;
202
+ }
203
+ if (match[1] === '') {
204
+ const suffixLength = Number(match[2]);
205
+ return suffixLength === 0 || size === 0
206
+ ? 'unsatisfiable'
207
+ : [Math.max(0, size - suffixLength), size - 1];
208
+ }
209
+ const start = Number(match[1]);
210
+ if (start >= size) {
211
+ return 'unsatisfiable';
212
+ }
213
+ const end = match[2] === '' ? size - 1 : Math.min(Number(match[2]), size - 1);
214
+ return end < start ? undefined : [start, end];
215
+ }
@@ -0,0 +1,142 @@
1
+ import type { FilePropertyBag } from 'node:buffer';
2
+ import type { Context } from '@orpc/server';
3
+ import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from '@orpc/server/standard';
4
+ import type { Promisable, Value } from '@orpc/shared';
5
+ export interface TmpFileUploadHandlerPluginMaxBodySize {
6
+ /**
7
+ * The maximum size in bytes of request body content buffered into memory:
8
+ * JSON, URL-encoded forms, and the fields, part headers, and in-memory files
9
+ * of a multipart body in total, and each event of an event stream on its
10
+ * own. Exceeding it rejects with `PAYLOAD_TOO_LARGE`, except for uploads,
11
+ * which spool to disk instead once they no longer fit. Usually the lowest of
12
+ * the three limits, because this content cannot stream anywhere.
13
+ */
14
+ memory: number;
15
+ /**
16
+ * The maximum total size in bytes of uploaded file content: file bodies and
17
+ * the file parts of a multipart body combined, whether held in memory or
18
+ * spooled to temporary files. A larger body rejects the request with
19
+ * `PAYLOAD_TOO_LARGE`.
20
+ */
21
+ file: number;
22
+ /**
23
+ * The maximum total size in bytes of a request body that is consumed as a
24
+ * stream: event streams and raw binary streams. Enforced while the stream is
25
+ * consumed, so an oversized stream fails at the reader. Usually the highest
26
+ * of the three limits, but keep it finite so no client can stream
27
+ * indefinitely.
28
+ */
29
+ stream: number;
30
+ }
31
+ export interface TmpFileUploadHandlerPluginOptions<T extends Context> {
32
+ /**
33
+ * The directory temporary files are created under. Each request that spools
34
+ * an upload gets its own subdirectory inside it, removed when the request
35
+ * finishes.
36
+ *
37
+ * @default os.tmpdir()
38
+ */
39
+ tmpDir?: string | undefined;
40
+ /**
41
+ * The size limit for each kind of request body, either fixed or resolved
42
+ * per request, so limits can follow the request itself, such as a larger
43
+ * allowance for an authenticated user than for a guest. Every kind is
44
+ * required when the option is given, so none is left unbounded by accident;
45
+ * set a kind to `Number.POSITIVE_INFINITY` to deliberately leave it
46
+ * unlimited.
47
+ *
48
+ * A resolver runs only when a body is parsed, so a request without one never
49
+ * pays for it, and it receives the request as it arrived, before this plugin
50
+ * wraps its body resolution.
51
+ *
52
+ * @default unlimited for every kind
53
+ */
54
+ maxBodySize?: Value<Promisable<TmpFileUploadHandlerPluginMaxBodySize>, [
55
+ options: StandardHandlerRoutingInterceptorOptions<T>
56
+ ]> | undefined;
57
+ /**
58
+ * The size in bytes an uploaded file must exceed before it is spooled to a
59
+ * temporary file. Smaller files stay in memory as plain `File`s, counted
60
+ * against `maxBodySize.memory`, and spool anyway once they no longer fit.
61
+ * Set to `0` to spool every non-empty upload.
62
+ *
63
+ * @default 64 * 1024
64
+ */
65
+ spoolThreshold?: number | undefined;
66
+ }
67
+ /**
68
+ * A `File` whose content lives in a temporary file on disk and is read lazily,
69
+ * so it can represent an upload far larger than available memory.
70
+ *
71
+ * @remarks
72
+ * Node's `fs.openAsBlob`, which backs this class, has known bugs with files
73
+ * over 2 GiB ({@link https://github.com/nodejs/node/issues/52585}): `size` is
74
+ * truncated above 4 GiB and `slice()` is unreliable above 2 GiB, while
75
+ * whole-file reads like `stream()` stay correct. When size or random access
76
+ * matters for such a file, stat or read {@link path} directly.
77
+ *
78
+ * @see {@link https://orpc.dev/docs/plugins/tmp-file-upload | Tmp File Upload Plugin}
79
+ */
80
+ export declare class TmpFile extends File {
81
+ /**
82
+ * Absolute path of the temporary file holding this file's content.
83
+ * The file is removed when the request finishes, so move or copy it
84
+ * to keep the content. The `File` reads from this path, so it must
85
+ * not be read after the file is moved or removed.
86
+ */
87
+ readonly path: string;
88
+ constructor(blob: Blob,
89
+ /**
90
+ * Absolute path of the temporary file holding this file's content.
91
+ * The file is removed when the request finishes, so move or copy it
92
+ * to keep the content. The `File` reads from this path, so it must
93
+ * not be read after the file is moved or removed.
94
+ */
95
+ path: string, name: string, options?: FilePropertyBag);
96
+ }
97
+ /**
98
+ * Parses file uploads into temporary files instead of memory. Bodies the standard
99
+ * body parser would buffer into an in-memory `File`, and multipart file parts, are
100
+ * streamed to disk once they outgrow the spool threshold and surfaced as lazily read
101
+ * {@link TmpFile} instances, so requests far larger than available memory parse in
102
+ * constant memory. Smaller uploads stay in memory as plain `File`s. Every other body is
103
+ * left to the standard parser.
104
+ *
105
+ * Request body sizes are limited per content category: buffered in memory, uploaded
106
+ * files, and streamed, each limit fixed or resolved per request. This subsumes the
107
+ * request limit plugin while sizing each kind of body to what it actually costs.
108
+ *
109
+ * @remarks
110
+ * Temporary files are removed when the request finishes. A streaming response body,
111
+ * an event iterator or a raw stream, keeps them alive until it completes, so
112
+ * responses that read the upload while streaming work. Any other response is
113
+ * transmitted after removal, so one that embeds the upload itself, as a `File` or
114
+ * inside `FormData`, needs the content copied or the file moved first.
115
+ *
116
+ * @see {@link https://orpc.dev/docs/plugins/tmp-file-upload | Tmp File Upload Plugin}
117
+ */
118
+ export declare class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
119
+ name: string;
120
+ /**
121
+ * Should parse the original request body instead of batched sub-requests.
122
+ */
123
+ after: string[];
124
+ /**
125
+ * Should run inside the limit and compression plugins, so spooling receives
126
+ * the size-checked, decompressed bytes.
127
+ */
128
+ before: string[];
129
+ private readonly tmpDir;
130
+ private readonly maxBodySize;
131
+ private readonly spoolThreshold;
132
+ constructor(options?: TmpFileUploadHandlerPluginOptions<T>);
133
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
134
+ private resolveBody;
135
+ /**
136
+ * Enforces size limits on a body the standard parser handles, counting the
137
+ * raw bytes before handing them back for regular parsing.
138
+ */
139
+ private parseLimitedBody;
140
+ private parseFileBody;
141
+ private parseMultipartBody;
142
+ }