@orpc/node 2.0.0-beta.48 → 2.0.0-beta.50

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 CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
6
6
  </a>
7
7
  <a href="https://www.npmjs.com/package/@orpc/node">
8
- <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fnode?logo=npm" />
8
+ <img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fnode?logo=npm" />
9
9
  </a>
10
10
  <a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
11
11
  <img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
@@ -41,10 +41,11 @@ export const router = {
41
41
  Then call them from a client that knows every input and output, without generating anything:
42
42
 
43
43
  ```ts
44
- import type { RouterClient } from '@orpc/server'
45
- import type { router } from './router'
46
44
  import { createORPCClient } from '@orpc/client'
47
45
  import { RPCLink } from '@orpc/client/fetch'
46
+ import type { RouterClient } from '@orpc/server'
47
+
48
+ import type { router } from './router'
48
49
 
49
50
  const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
50
51
  const client: RouterClient<typeof router> = createORPCClient(link)
@@ -208,7 +209,6 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
208
209
  <tr>
209
210
  <td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
210
211
  <td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&amp;v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
211
- <td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
212
212
  </tr>
213
213
  </table>
214
214
 
@@ -0,0 +1,47 @@
1
+ import { CompressionEncoding } from "@orpc/shared";
2
+ import { Context } from "@orpc/server";
3
+ import { StandardHandlerOptions, StandardHandlerPlugin } from "@orpc/server/standard";
4
+ export interface BatchResponseCompressionHandlerPluginOptions {
5
+ /**
6
+ * The compression schemes to use for batch responses.
7
+ * Schemes are prioritized by their order in this array and
8
+ * only applied if the client supports them (via Accept-Encoding).
9
+ *
10
+ * @default ['gzip', 'deflate']
11
+ */
12
+ encodings?: readonly CompressionEncoding[] | undefined;
13
+ /**
14
+ * The minimum response size in bytes required to trigger compression.
15
+ * Responses smaller than this threshold will not be compressed to avoid overhead.
16
+ * A streaming batch response has no size until it ends, so it is always compressed.
17
+ *
18
+ * @default 1024 (1KB)
19
+ */
20
+ threshold?: number | undefined;
21
+ }
22
+ /**
23
+ * Compresses every successful [batch](https://orpc.dev/docs/plugins/batch) response, which the
24
+ * runtime-agnostic {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
25
+ * leaves untouched when framed: a batch frames subresponses of mixed content types, so its envelope
26
+ * has none of its own and nothing says whether the contents compress. Registering this plugin
27
+ * states that they do.
28
+ *
29
+ * @remarks
30
+ * Each message is flushed as soon as it is produced, so a streaming batch stays streaming.
31
+ * This is why the plugin lives in the Node.js package: `zlib` can flush mid-stream, while the
32
+ * web `CompressionStream` cannot, and would hold every early message until the batch ends.
33
+ *
34
+ * @see {@link https://orpc.dev/docs/plugins/batch-response-compression | Batch Response Compression Plugin}
35
+ */
36
+ export declare class BatchResponseCompressionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
37
+ name: string;
38
+ /**
39
+ * Compression should be done after batching, to compress the assembled batch response
40
+ * rather than each subresponse inside it.
41
+ */
42
+ after: string[];
43
+ private readonly encodings;
44
+ private readonly threshold;
45
+ constructor(options?: BatchResponseCompressionHandlerPluginOptions);
46
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
47
+ }
@@ -0,0 +1,108 @@
1
+ import { Duplex } from "node:stream";
2
+ import { constants, createDeflate, createDeflateRaw, createGzip } from "node:zlib";
3
+ import { BATCH_HEADER, negotiateResponseCompressionEncoding, toCompressedHeaders } from "@orpc/server/plugins";
4
+ import { toArray } from "@orpc/shared";
5
+ import { flattenStandardHeader } from "@standard-server/core";
6
+ import { toFetchBody } from "@standard-server/fetch";
7
+ // src/batch-response-compression-handler-plugin.ts
8
+ /**
9
+ * Compresses every successful [batch](https://orpc.dev/docs/plugins/batch) response, which the
10
+ * runtime-agnostic {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
11
+ * leaves untouched when framed: a batch frames subresponses of mixed content types, so its envelope
12
+ * has none of its own and nothing says whether the contents compress. Registering this plugin
13
+ * states that they do.
14
+ *
15
+ * @remarks
16
+ * Each message is flushed as soon as it is produced, so a streaming batch stays streaming.
17
+ * This is why the plugin lives in the Node.js package: `zlib` can flush mid-stream, while the
18
+ * web `CompressionStream` cannot, and would hold every early message until the batch ends.
19
+ *
20
+ * @see {@link https://orpc.dev/docs/plugins/batch-response-compression | Batch Response Compression Plugin}
21
+ */
22
+ var BatchResponseCompressionHandlerPlugin = class {
23
+ name = "~batch-response-compression";
24
+ /**
25
+ * Compression should be done after batching, to compress the assembled batch response
26
+ * rather than each subresponse inside it.
27
+ */
28
+ after = ["~batch"];
29
+ encodings;
30
+ threshold;
31
+ constructor(options = {}) {
32
+ this.encodings = options.encodings ?? ["gzip", "deflate"];
33
+ this.threshold = options.threshold ?? 1024;
34
+ }
35
+ init(options) {
36
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
37
+ const result = await next();
38
+ if (!result.matched) return result;
39
+ /**
40
+ * The batch plugin only engages on a request carrying this header, so a response framed like
41
+ * a batch without it belongs to a procedure serving that content type itself, whose own file
42
+ * semantics must survive untouched.
43
+ */
44
+ if (flattenStandardHeader(interceptorOptions.request.headers[BATCH_HEADER]) === void 0) return result;
45
+ const response = result.response;
46
+ const headers = response.headers;
47
+ const body = response.body;
48
+ /**
49
+ * A batch that failed as a whole answers with a plain message instead of subresponses,
50
+ * so only a successful envelope is a batch payload worth compressing.
51
+ */
52
+ if (response.status >= 400) return result;
53
+ const encoding = negotiateResponseCompressionEncoding(response, interceptorOptions.request.headers, this.encodings);
54
+ if (encoding === void 0) return result;
55
+ let stream;
56
+ /**
57
+ * A framed body is opaque bytes, while a json one still has to be parsed as json,
58
+ * so each keeps the hint that tells the client how to read it.
59
+ */
60
+ let bodyHeaders;
61
+ /**
62
+ * A buffered batch with no binary or stream subresponse stays a plain array of messages, serialized
63
+ * as json by the adapter. The header and status above already say this is a batch envelope,
64
+ * so the array itself is the only thing left to recognise.
65
+ */
66
+ if (Array.isArray(body)) {
67
+ const [string, jsonHeaders] = toFetchBody(body, headers);
68
+ const json = new Blob([string]);
69
+ if (json.size < this.threshold) return result;
70
+ stream = json.stream();
71
+ bodyHeaders = {
72
+ "content-type": jsonHeaders["content-type"],
73
+ "standard-server": jsonHeaders["standard-server"] ?? []
74
+ };
75
+ } else if (body instanceof Blob || body instanceof ReadableStream) {
76
+ if (body instanceof Blob && Number.isFinite(body.size) && body.size < this.threshold) return result;
77
+ stream = body instanceof Blob ? body.stream() : body;
78
+ bodyHeaders = { "standard-server": "octet-stream" };
79
+ } else return result;
80
+ return {
81
+ ...result,
82
+ response: {
83
+ ...response,
84
+ body: stream.pipeThrough(createFlushingCompressionStream(encoding)),
85
+ headers: {
86
+ ...toCompressedHeaders(headers, encoding),
87
+ ...bodyHeaders
88
+ }
89
+ }
90
+ };
91
+ };
92
+ return {
93
+ ...options,
94
+ routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)]
95
+ };
96
+ }
97
+ };
98
+ /**
99
+ * A compressor that ends every write with a sync flush, so each batch message reaches the client
100
+ * as soon as the batch produces it instead of waiting in the compressor for the batch to end.
101
+ * The few bytes each flush costs are what keep a streaming batch streaming.
102
+ */
103
+ function createFlushingCompressionStream(encoding) {
104
+ const zlibOptions = { flush: constants.Z_SYNC_FLUSH };
105
+ const compressor = encoding === "gzip" ? createGzip(zlibOptions) : encoding === "deflate" ? createDeflate(zlibOptions) : createDeflateRaw(zlibOptions);
106
+ return Duplex.toWeb(compressor);
107
+ }
108
+ export { BatchResponseCompressionHandlerPlugin };
@@ -0,0 +1,4 @@
1
+ import { BatchResponseCompressionHandlerPlugin, BatchResponseCompressionHandlerPluginOptions } from "./batch-response-compression-handler-plugin.js";
2
+ import { StaticFileHandlerPlugin, StaticFileHandlerPluginOptions } from "./static-file-handler-plugin.js";
3
+ import { TmpFile, TmpFileUploadHandlerPlugin, TmpFileUploadHandlerPluginMaxBodySize, TmpFileUploadHandlerPluginOptions } from "./tmp-file-upload-handler-plugin.js";
4
+ export { BatchResponseCompressionHandlerPlugin, BatchResponseCompressionHandlerPluginOptions, StaticFileHandlerPlugin, StaticFileHandlerPluginOptions, TmpFile, TmpFileUploadHandlerPlugin, TmpFileUploadHandlerPluginMaxBodySize, TmpFileUploadHandlerPluginOptions };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { BatchResponseCompressionHandlerPlugin } from "./batch-response-compression-handler-plugin.js";
2
+ export { StaticFileHandlerPlugin } from "./static-file-handler-plugin.js";
3
+ export { TmpFile, TmpFileUploadHandlerPlugin } from "./tmp-file-upload-handler-plugin.js";
@@ -0,0 +1,170 @@
1
+ import { Buffer } from "node:buffer";
2
+ // src/multipart.ts
3
+ /**
4
+ * Part headers are tiny in practice, so an unterminated header block is cut off
5
+ * long before it can buffer a request-sized payload in memory.
6
+ */
7
+ const MAX_PART_HEADER_SIZE = 16384;
8
+ const CRLF = /* @__PURE__ */ Buffer.from("\r\n");
9
+ const HEADER_BLOCK_END = /* @__PURE__ */ Buffer.from("\r\n\r\n");
10
+ /**
11
+ * Parses a `multipart/form-data` byte stream part by part, so a part's body can be
12
+ * consumed as it arrives instead of being buffered whole. Bodies are delivered to the
13
+ * writer `onPart` returns, with writer promises awaited for backpressure, so parts are
14
+ * processed strictly one at a time.
15
+ *
16
+ * Line endings are strictly CRLF, every part must carry a `form-data` content
17
+ * disposition with a `name` parameter, and a malformed or truncated body throws a
18
+ * `TypeError`, matching the standard parser's strictness.
19
+ *
20
+ * @see https://www.rfc-editor.org/rfc/rfc7578
21
+ * @see https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
22
+ */
23
+ async function parseMultipart(source, boundary, onPart) {
24
+ const delimiter = Buffer.from(`\r\n--${boundary}`);
25
+ /**
26
+ * Seeded with a virtual CRLF so the opening `--boundary` line, which the grammar
27
+ * allows without a preceding line break, matches the same needle as every
28
+ * later delimiter.
29
+ */
30
+ let buffer = CRLF;
31
+ let state = "preamble";
32
+ let writer;
33
+ let done = false;
34
+ const process = async () => {
35
+ while (true) {
36
+ if (state === "preamble" || state === "body") {
37
+ const index = buffer.indexOf(delimiter);
38
+ if (index === -1) {
39
+ const settledLength = buffer.length - delimiter.length + 1;
40
+ if (settledLength > 0) {
41
+ if (state === "body") await writer.write(buffer.subarray(0, settledLength));
42
+ buffer = buffer.subarray(settledLength);
43
+ }
44
+ return;
45
+ }
46
+ if (state === "body") {
47
+ if (index > 0) await writer.write(buffer.subarray(0, index));
48
+ await writer.end();
49
+ writer = void 0;
50
+ }
51
+ buffer = buffer.subarray(index + delimiter.length);
52
+ state = "delimiter-end";
53
+ continue;
54
+ }
55
+ if (state === "delimiter-end") {
56
+ if (buffer.length < 2) return;
57
+ if (buffer[0] === 45 && buffer[1] === 45) {
58
+ done = true;
59
+ buffer = Buffer.alloc(0);
60
+ return;
61
+ }
62
+ state = "transport-padding";
63
+ continue;
64
+ }
65
+ if (state === "transport-padding") {
66
+ let index = 0;
67
+ while (index < buffer.length && (buffer[index] === 32 || buffer[index] === 9)) index++;
68
+ buffer = buffer.subarray(index);
69
+ if (buffer.length < 2) return;
70
+ if (buffer[0] !== 13 || buffer[1] !== 10) throw new TypeError("Invalid multipart body: expected CRLF after a boundary delimiter");
71
+ buffer = buffer.subarray(2);
72
+ state = "headers";
73
+ continue;
74
+ }
75
+ if (buffer[0] === 13 && buffer[1] === 10) throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
76
+ const headerWindow = MAX_PART_HEADER_SIZE + HEADER_BLOCK_END.length;
77
+ const headerEnd = buffer.subarray(0, headerWindow).indexOf(HEADER_BLOCK_END);
78
+ if (headerEnd === -1) {
79
+ if (buffer.length >= headerWindow) throw new TypeError("Invalid multipart body: part headers exceed the maximum allowed size");
80
+ return;
81
+ }
82
+ const headerSize = headerEnd + HEADER_BLOCK_END.length;
83
+ const part = parsePartHeaders(buffer.subarray(0, headerEnd).toString(), headerSize);
84
+ buffer = buffer.subarray(headerSize);
85
+ writer = await onPart(part);
86
+ state = "body";
87
+ }
88
+ };
89
+ for await (const chunk of source) {
90
+ if (done) continue;
91
+ buffer = buffer.length === 0 ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.concat([buffer, chunk]);
92
+ await process();
93
+ }
94
+ if (!done) throw new TypeError("Invalid multipart body: unexpected end of body");
95
+ }
96
+ function parsePartHeaders(block, headerSize) {
97
+ let contentDisposition;
98
+ let contentType;
99
+ for (const line of block.split("\r\n")) {
100
+ const colon = line.indexOf(":");
101
+ if (colon === -1) throw new TypeError("Invalid multipart body: malformed part header");
102
+ const name = line.slice(0, colon).trim().toLowerCase();
103
+ if (name === "content-disposition") contentDisposition = line.slice(colon + 1).trim();
104
+ else if (name === "content-type") contentType = line.slice(colon + 1).trim();
105
+ }
106
+ if (contentDisposition === void 0) throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
107
+ const semicolon = contentDisposition.indexOf(";");
108
+ if ((semicolon === -1 ? contentDisposition : contentDisposition.slice(0, semicolon)).trim().toLowerCase() !== "form-data") throw new TypeError("Invalid multipart body: content-disposition must be form-data");
109
+ const parameters = parseHeaderParameters(contentDisposition);
110
+ const name = parameters.get("name");
111
+ if (name === void 0) throw new TypeError("Invalid multipart body: content-disposition header is missing the name parameter");
112
+ const filename = parameters.get("filename");
113
+ return {
114
+ name: decodeContentDispositionParameter(name),
115
+ filename: filename === void 0 ? void 0 : decodeContentDispositionParameter(filename),
116
+ type: contentType,
117
+ headerSize
118
+ };
119
+ }
120
+ /**
121
+ * The multipart serialization every spec-compliant client uses escapes `"`, `\r`,
122
+ * and `\n` in content-disposition names and filenames as `%22`, `%0D`, and `%0A`,
123
+ * and the standard parser reverses exactly these three.
124
+ *
125
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
126
+ */
127
+ function decodeContentDispositionParameter(value) {
128
+ return value.replaceAll("%22", "\"").replaceAll("%0D", "\r").replaceAll("%0A", "\n");
129
+ }
130
+ /**
131
+ * Extracts the `key=value` parameters that follow a header's leading token.
132
+ * The first occurrence of a parameter wins.
133
+ *
134
+ * A backslash inside a quoted value is a literal character rather than an
135
+ * escape, matching the standard parser: the multipart serialization escapes
136
+ * `"` as `%22`, so a quote can never occur inside a value, while filenames
137
+ * with literal backslashes are common and must survive verbatim.
138
+ *
139
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
140
+ */
141
+ function parseHeaderParameters(header) {
142
+ const parameters = /* @__PURE__ */ new Map();
143
+ let index = header.indexOf(";");
144
+ while (index !== -1 && index < header.length) {
145
+ index++;
146
+ while (index < header.length && (header[index] === " " || header[index] === " ")) index++;
147
+ let equals = index;
148
+ while (equals < header.length && header[equals] !== "=" && header[equals] !== ";") equals++;
149
+ if (equals === header.length) break;
150
+ if (header[equals] === ";") {
151
+ index = equals;
152
+ continue;
153
+ }
154
+ const key = header.slice(index, equals).trim().toLowerCase();
155
+ index = equals + 1;
156
+ let value;
157
+ if (header[index] === "\"") {
158
+ const closing = header.indexOf("\"", index + 1);
159
+ value = closing === -1 ? header.slice(index + 1) : header.slice(index + 1, closing);
160
+ index = closing === -1 ? -1 : header.indexOf(";", closing + 1);
161
+ } else {
162
+ const semicolon = header.indexOf(";", index);
163
+ value = (semicolon === -1 ? header.slice(index) : header.slice(index, semicolon)).trim();
164
+ index = semicolon;
165
+ }
166
+ if (!parameters.has(key)) parameters.set(key, value);
167
+ }
168
+ return parameters;
169
+ }
170
+ export { parseHeaderParameters, parseMultipart };
@@ -0,0 +1,84 @@
1
+ import { Context } from "@orpc/server";
2
+ import { 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,190 @@
1
+ import { getTracer, isAcceptableEncoding, isCompressibleContentType, matchesHttpPathPrefix, mergeHttpPath, parseAcceptEncodingQualities, safeDecodeURIComponent, toArray } from "@orpc/shared";
2
+ import { flattenStandardHeader, parseStandardUrl } from "@standard-server/core";
3
+ import { createReadStream } from "node:fs";
4
+ import { stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { toWebReadableStream } from "@standard-server/node";
7
+ import mime from "mime";
8
+ // src/static-file-handler-plugin.ts
9
+ const UNSAFE_SEGMENT_REGEX = /^[. ]+$|[\0/\\]/;
10
+ const UNSAFE_OR_DOTFILE_SEGMENT_REGEX = /^[. ]+$|^\.|^[^.]{0,6}~\d|[\0/\\]/;
11
+ const PRECOMPRESSED_ENCODINGS = [
12
+ ["br", ".br"],
13
+ ["zstd", ".zst"],
14
+ ["gzip", ".gz"]
15
+ ];
16
+ /**
17
+ * Serves static files from a directory: index files, `ETag`/`Last-Modified`
18
+ * revalidation, range requests, and precompressed sidecars. Files are served
19
+ * as a fallback, so matched procedures always win.
20
+ *
21
+ * @see {@link https://orpc.dev/docs/plugins/static-file | Static File Plugin}
22
+ */
23
+ var StaticFileHandlerPlugin = class {
24
+ name = "~static-file";
25
+ after = ["~tracing"];
26
+ before = ["~head-method"];
27
+ rootDir;
28
+ path;
29
+ indexFile;
30
+ fallbackFilePath;
31
+ cacheControl;
32
+ unsafeSegmentRegex;
33
+ precompressed;
34
+ mimeTypes;
35
+ constructor(options) {
36
+ this.rootDir = path.resolve(options.rootDir);
37
+ this.path = stripTrailingSlash(options.path ?? "/");
38
+ this.indexFile = options.indexFile ?? "index.html";
39
+ this.fallbackFilePath = options.fallbackFile === void 0 ? void 0 : path.join(this.rootDir, options.fallbackFile);
40
+ this.cacheControl = options.cacheControl ?? "public, max-age=0";
41
+ this.unsafeSegmentRegex = options.dotfiles ? UNSAFE_SEGMENT_REGEX : UNSAFE_OR_DOTFILE_SEGMENT_REGEX;
42
+ this.precompressed = options.precompressed ?? false;
43
+ this.mimeTypes = Object.assign(Object.create(null), options.mimeTypes);
44
+ }
45
+ init(options) {
46
+ const routingInterceptor = async ({ next, request, prefix }) => {
47
+ const result = await next();
48
+ if (result.matched || request.method !== "GET" && request.method !== "HEAD") return result;
49
+ const base = prefix === void 0 ? this.path : stripTrailingSlash(mergeHttpPath(prefix, this.path));
50
+ const response = await this.serve(request, base);
51
+ if (response === void 0) return result;
52
+ getTracer()?.getActiveSpan()?.updateName(`${request.method} ${base === "/" ? "" : base}/* (static file)`);
53
+ return {
54
+ matched: true,
55
+ response
56
+ };
57
+ };
58
+ return {
59
+ ...options,
60
+ routingInterceptors: [...toArray(options.routingInterceptors), routingInterceptor]
61
+ };
62
+ }
63
+ async serve(request, base) {
64
+ const [pathname] = parseStandardUrl(request.url);
65
+ if (base !== "/" && !matchesHttpPathPrefix(pathname, base)) return;
66
+ const segments = [];
67
+ let isDirectoryUrl = false;
68
+ for (const rawSegment of pathname.slice(base.length).split("/")) {
69
+ const segment = safeDecodeURIComponent(rawSegment);
70
+ isDirectoryUrl = segment === "" || segment === ".";
71
+ if (isDirectoryUrl) continue;
72
+ if (this.unsafeSegmentRegex.test(segment)) return;
73
+ segments.push(segment);
74
+ }
75
+ let filePath = path.join(this.rootDir, ...segments);
76
+ let stats = isDirectoryUrl ? void 0 : await getStats(filePath);
77
+ if (isDirectoryUrl || stats?.isDirectory()) {
78
+ stats = void 0;
79
+ if (this.indexFile !== false) {
80
+ filePath = path.join(filePath, this.indexFile);
81
+ stats = await getStats(filePath);
82
+ }
83
+ }
84
+ if (!stats?.isFile() && this.fallbackFilePath !== void 0) {
85
+ filePath = this.fallbackFilePath;
86
+ stats = await getStats(filePath);
87
+ }
88
+ if (!stats?.isFile()) return;
89
+ const contentType = this.resolveContentType(filePath);
90
+ const headers = {};
91
+ let contentEncoding;
92
+ if (this.precompressed && isCompressibleContentType(contentType)) {
93
+ headers.vary = "accept-encoding";
94
+ const qualities = parseAcceptEncodingQualities(flattenStandardHeader(request.headers["accept-encoding"]));
95
+ for (const [encoding, extension] of PRECOMPRESSED_ENCODINGS) {
96
+ if (!isAcceptableEncoding(qualities, encoding)) continue;
97
+ const variantStats = await getStats(filePath + extension);
98
+ if (variantStats?.isFile()) {
99
+ filePath += extension;
100
+ stats = variantStats;
101
+ contentEncoding = encoding;
102
+ break;
103
+ }
104
+ }
105
+ }
106
+ const size = stats.size;
107
+ const etag = `"${size.toString(16)}-${stats.mtime.getTime().toString(16)}"`;
108
+ const lastModifiedTime = Math.floor(stats.mtime.getTime() / 1e3) * 1e3;
109
+ headers.etag = etag;
110
+ headers["last-modified"] = stats.mtime.toUTCString();
111
+ headers["accept-ranges"] = "bytes";
112
+ if (this.cacheControl !== false) headers["cache-control"] = this.cacheControl;
113
+ if (isNotModified(request.headers, etag, lastModifiedTime)) return {
114
+ status: 304,
115
+ headers
116
+ };
117
+ let status = 200;
118
+ let start = 0;
119
+ let end = size - 1;
120
+ const range = request.method === "GET" ? flattenStandardHeader(request.headers.range) : void 0;
121
+ if (range !== void 0 && isRangeApplicable(request.headers, etag, lastModifiedTime)) {
122
+ const parsed = parseByteRange(range, size);
123
+ if (parsed === "unsatisfiable") return {
124
+ status: 416,
125
+ headers: {
126
+ ...headers,
127
+ "content-range": `bytes */${size}`
128
+ }
129
+ };
130
+ if (parsed !== void 0) {
131
+ status = 206;
132
+ [start, end] = parsed;
133
+ headers["content-range"] = `bytes ${start}-${end}/${size}`;
134
+ }
135
+ }
136
+ if (contentEncoding !== void 0) headers["content-encoding"] = contentEncoding;
137
+ headers["content-type"] = contentType;
138
+ headers["content-length"] = `${end - start + 1}`;
139
+ const body = request.method === "HEAD" ? new ReadableStream({ start: (controller) => controller.close() }) : toWebReadableStream(createReadStream(filePath, status === 206 ? {
140
+ start,
141
+ end
142
+ } : void 0));
143
+ return {
144
+ status,
145
+ headers,
146
+ body
147
+ };
148
+ }
149
+ resolveContentType(filePath) {
150
+ const extension = path.extname(filePath).slice(1).toLowerCase();
151
+ const configured = this.mimeTypes[extension];
152
+ if (configured !== void 0) return configured;
153
+ const contentType = mime.getType(extension);
154
+ if (contentType === null) return "application/octet-stream";
155
+ return contentType.startsWith("text/") ? `${contentType}; charset=utf-8` : contentType;
156
+ }
157
+ };
158
+ function getStats(filePath) {
159
+ return stat(filePath).catch(() => void 0);
160
+ }
161
+ function stripTrailingSlash(path) {
162
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
163
+ }
164
+ function isNotModified(requestHeaders, etag, lastModifiedTime) {
165
+ const ifNoneMatch = flattenStandardHeader(requestHeaders["if-none-match"]);
166
+ if (ifNoneMatch !== void 0) return ifNoneMatch.trim() === "*" || ifNoneMatch.split(",").some((tag) => {
167
+ tag = tag.trim();
168
+ return (tag.startsWith("W/") ? tag.slice(2) : tag) === etag;
169
+ });
170
+ const ifModifiedSince = flattenStandardHeader(requestHeaders["if-modified-since"]);
171
+ return ifModifiedSince !== void 0 && lastModifiedTime <= Date.parse(ifModifiedSince);
172
+ }
173
+ function isRangeApplicable(requestHeaders, etag, lastModifiedTime) {
174
+ const ifRange = flattenStandardHeader(requestHeaders["if-range"]);
175
+ if (ifRange === void 0) return true;
176
+ return ifRange.startsWith("\"") || ifRange.startsWith("W/") ? ifRange === etag : Date.parse(ifRange) === lastModifiedTime;
177
+ }
178
+ function parseByteRange(range, size) {
179
+ const match = range.match(/^bytes=\s*(\d*)-(\d*)$/i);
180
+ if (match === null || match[1] === "" && match[2] === "") return;
181
+ if (match[1] === "") {
182
+ const suffixLength = Number(match[2]);
183
+ return suffixLength === 0 || size === 0 ? "unsatisfiable" : [Math.max(0, size - suffixLength), size - 1];
184
+ }
185
+ const start = Number(match[1]);
186
+ if (start >= size) return "unsatisfiable";
187
+ const end = match[2] === "" ? size - 1 : Math.min(Number(match[2]), size - 1);
188
+ return end < start ? void 0 : [start, end];
189
+ }
190
+ export { StaticFileHandlerPlugin };