@orpc/server 0.0.0-next.b42ba03 → 0.0.0-next.b45a533

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.
Files changed (82) hide show
  1. package/README.md +120 -0
  2. package/dist/adapters/fetch/index.d.mts +26 -0
  3. package/dist/adapters/fetch/index.d.ts +26 -0
  4. package/dist/adapters/fetch/index.mjs +9 -0
  5. package/dist/adapters/hono/index.d.mts +19 -0
  6. package/dist/adapters/hono/index.d.ts +19 -0
  7. package/dist/{hono.js → adapters/hono/index.mjs} +11 -19
  8. package/dist/adapters/next/index.d.mts +26 -0
  9. package/dist/adapters/next/index.d.ts +26 -0
  10. package/dist/{next.js → adapters/next/index.mjs} +11 -19
  11. package/dist/adapters/node/index.d.mts +34 -0
  12. package/dist/adapters/node/index.d.ts +34 -0
  13. package/dist/adapters/node/index.mjs +31 -0
  14. package/dist/adapters/standard/index.d.mts +25 -0
  15. package/dist/adapters/standard/index.d.ts +25 -0
  16. package/dist/adapters/standard/index.mjs +6 -0
  17. package/dist/index.d.mts +278 -0
  18. package/dist/index.d.ts +278 -0
  19. package/dist/{index.js → index.mjs} +93 -151
  20. package/dist/plugins/index.d.mts +31 -0
  21. package/dist/plugins/index.d.ts +31 -0
  22. package/dist/{chunk-XFBAK67J.js → plugins/index.mjs} +18 -43
  23. package/dist/shared/server.3mOimouH.mjs +158 -0
  24. package/dist/{chunk-EDQKEHUX.js → shared/server.B_5ZADvP.mjs} +181 -195
  25. package/dist/shared/server.BgDZnmUZ.mjs +28 -0
  26. package/dist/shared/server.CL84X8p4.d.mts +75 -0
  27. package/dist/shared/server.DnmJuN02.d.mts +144 -0
  28. package/dist/shared/server.DnmJuN02.d.ts +144 -0
  29. package/dist/shared/server.Q6ZmnTgO.mjs +12 -0
  30. package/dist/shared/server.hqPWnakL.d.ts +75 -0
  31. package/package.json +29 -31
  32. package/dist/chunk-2OH4QMZ4.js +0 -145
  33. package/dist/chunk-BFGSRNYZ.js +0 -319
  34. package/dist/fetch.js +0 -16
  35. package/dist/node.js +0 -170
  36. package/dist/plugins.js +0 -11
  37. package/dist/src/adapters/fetch/index.d.ts +0 -4
  38. package/dist/src/adapters/fetch/rpc-handler.d.ts +0 -10
  39. package/dist/src/adapters/fetch/types.d.ts +0 -13
  40. package/dist/src/adapters/fetch/utils.d.ts +0 -5
  41. package/dist/src/adapters/hono/index.d.ts +0 -3
  42. package/dist/src/adapters/hono/middleware.d.ts +0 -13
  43. package/dist/src/adapters/next/index.d.ts +0 -3
  44. package/dist/src/adapters/next/serve.d.ts +0 -20
  45. package/dist/src/adapters/node/index.d.ts +0 -4
  46. package/dist/src/adapters/node/rpc-handler.d.ts +0 -10
  47. package/dist/src/adapters/node/types.d.ts +0 -21
  48. package/dist/src/adapters/node/utils.d.ts +0 -5
  49. package/dist/src/adapters/standard/handler.d.ts +0 -51
  50. package/dist/src/adapters/standard/index.d.ts +0 -7
  51. package/dist/src/adapters/standard/rpc-codec.d.ts +0 -15
  52. package/dist/src/adapters/standard/rpc-handler.d.ts +0 -8
  53. package/dist/src/adapters/standard/rpc-matcher.d.ts +0 -10
  54. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -16
  55. package/dist/src/adapters/standard/types.d.ts +0 -44
  56. package/dist/src/builder-variants.d.ts +0 -74
  57. package/dist/src/builder.d.ts +0 -57
  58. package/dist/src/config.d.ts +0 -6
  59. package/dist/src/context.d.ts +0 -9
  60. package/dist/src/hidden.d.ts +0 -8
  61. package/dist/src/implementer-procedure.d.ts +0 -30
  62. package/dist/src/implementer-variants.d.ts +0 -17
  63. package/dist/src/implementer.d.ts +0 -28
  64. package/dist/src/index.d.ts +0 -23
  65. package/dist/src/lazy-utils.d.ts +0 -6
  66. package/dist/src/lazy.d.ts +0 -22
  67. package/dist/src/middleware-decorated.d.ts +0 -10
  68. package/dist/src/middleware-utils.d.ts +0 -5
  69. package/dist/src/middleware.d.ts +0 -37
  70. package/dist/src/plugins/base.d.ts +0 -13
  71. package/dist/src/plugins/cors.d.ts +0 -19
  72. package/dist/src/plugins/index.d.ts +0 -4
  73. package/dist/src/plugins/response-headers.d.ts +0 -10
  74. package/dist/src/procedure-client.d.ts +0 -31
  75. package/dist/src/procedure-decorated.d.ts +0 -21
  76. package/dist/src/procedure-utils.d.ts +0 -17
  77. package/dist/src/procedure.d.ts +0 -29
  78. package/dist/src/router-accessible-lazy.d.ts +0 -8
  79. package/dist/src/router-client.d.ts +0 -11
  80. package/dist/src/router.d.ts +0 -29
  81. package/dist/src/utils.d.ts +0 -24
  82. package/dist/standard.js +0 -17
@@ -1,145 +0,0 @@
1
- import {
2
- RPCCodec,
3
- RPCMatcher,
4
- StandardHandler
5
- } from "./chunk-BFGSRNYZ.js";
6
-
7
- // src/adapters/fetch/utils.ts
8
- import { once } from "@orpc/shared";
9
- import { contentDisposition, parse as parseContentDisposition } from "@tinyhttp/content-disposition";
10
- function fetchHeadersToStandardHeaders(headers) {
11
- const standardHeaders = {};
12
- for (const [key, value] of headers) {
13
- if (Array.isArray(standardHeaders[key])) {
14
- standardHeaders[key].push(value);
15
- } else if (standardHeaders[key] !== void 0) {
16
- standardHeaders[key] = [standardHeaders[key], value];
17
- } else {
18
- standardHeaders[key] = value;
19
- }
20
- }
21
- return standardHeaders;
22
- }
23
- async function fetchReToStandardBody(re) {
24
- if (!re.body) {
25
- return void 0;
26
- }
27
- const contentDisposition2 = re.headers.get("content-disposition");
28
- if (contentDisposition2) {
29
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
30
- if (typeof fileName === "string") {
31
- const blob2 = await re.blob();
32
- return new File([blob2], fileName, {
33
- type: blob2.type
34
- });
35
- }
36
- }
37
- const contentType = re.headers.get("content-type");
38
- if (!contentType || contentType.startsWith("application/json")) {
39
- const text = await re.text();
40
- if (!text) {
41
- return void 0;
42
- }
43
- return JSON.parse(text);
44
- }
45
- if (contentType.startsWith("multipart/form-data")) {
46
- return await re.formData();
47
- }
48
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
49
- return new URLSearchParams(await re.text());
50
- }
51
- if (contentType.startsWith("text/")) {
52
- return await re.text();
53
- }
54
- const blob = await re.blob();
55
- return new File([blob], "blob", {
56
- type: blob.type
57
- });
58
- }
59
- function fetchRequestToStandardRequest(request) {
60
- const url = new URL(request.url);
61
- return {
62
- raw: { request },
63
- url,
64
- signal: request.signal,
65
- method: request.method,
66
- body: once(() => {
67
- return fetchReToStandardBody(request);
68
- }),
69
- get headers() {
70
- const headers = fetchHeadersToStandardHeaders(request.headers);
71
- Object.defineProperty(this, "headers", { value: headers, writable: true });
72
- return headers;
73
- },
74
- set headers(value) {
75
- Object.defineProperty(this, "headers", { value, writable: true });
76
- }
77
- };
78
- }
79
- function standardResponseToFetchHeaders(response) {
80
- const fetchHeaders = new Headers();
81
- for (const [key, value] of Object.entries(response.headers)) {
82
- if (Array.isArray(value)) {
83
- for (const v of value) {
84
- fetchHeaders.append(key, v);
85
- }
86
- } else if (value !== void 0) {
87
- fetchHeaders.append(key, value);
88
- }
89
- }
90
- return fetchHeaders;
91
- }
92
- function standardResponseToFetchResponse(response) {
93
- const resHeaders = standardResponseToFetchHeaders(response);
94
- resHeaders.delete("content-type");
95
- resHeaders.delete("content-disposition");
96
- if (response.body === void 0) {
97
- return new Response(void 0, { headers: resHeaders, status: response.status });
98
- }
99
- if (response.body instanceof Blob) {
100
- resHeaders.set("content-type", response.body.type);
101
- resHeaders.set("content-length", response.body.size.toString());
102
- resHeaders.set(
103
- "content-disposition",
104
- contentDisposition(response.body instanceof File ? response.body.name : "blob", { type: "inline" })
105
- );
106
- return new Response(response.body, { headers: resHeaders, status: response.status });
107
- }
108
- if (response.body instanceof FormData) {
109
- return new Response(response.body, { headers: resHeaders, status: response.status });
110
- }
111
- if (response.body instanceof URLSearchParams) {
112
- return new Response(response.body, { headers: resHeaders, status: response.status });
113
- }
114
- resHeaders.set("content-type", "application/json");
115
- return new Response(JSON.stringify(response.body), { headers: resHeaders, status: response.status });
116
- }
117
-
118
- // src/adapters/fetch/rpc-handler.ts
119
- var RPCHandler = class {
120
- standardHandler;
121
- constructor(router, options) {
122
- const matcher = options?.matcher ?? new RPCMatcher();
123
- const codec = options?.codec ?? new RPCCodec();
124
- this.standardHandler = new StandardHandler(router, matcher, codec, options);
125
- }
126
- async handle(request, ...rest) {
127
- const standardRequest = fetchRequestToStandardRequest(request);
128
- const result = await this.standardHandler.handle(standardRequest, ...rest);
129
- if (!result.matched) {
130
- return result;
131
- }
132
- return {
133
- matched: true,
134
- response: standardResponseToFetchResponse(result.response)
135
- };
136
- }
137
- };
138
-
139
- export {
140
- fetchReToStandardBody,
141
- fetchRequestToStandardRequest,
142
- standardResponseToFetchResponse,
143
- RPCHandler
144
- };
145
- //# sourceMappingURL=chunk-2OH4QMZ4.js.map
@@ -1,319 +0,0 @@
1
- import {
2
- convertPathToHttpPath,
3
- createContractedProcedure,
4
- createProcedureClient,
5
- eachContractProcedure,
6
- getRouterChild,
7
- isProcedure,
8
- unlazy
9
- } from "./chunk-EDQKEHUX.js";
10
- import {
11
- CompositePlugin
12
- } from "./chunk-XFBAK67J.js";
13
-
14
- // src/adapters/standard/handler.ts
15
- import { toORPCError } from "@orpc/contract";
16
- import { intercept, trim } from "@orpc/shared";
17
- var StandardHandler = class {
18
- constructor(router, matcher, codec, options = {}) {
19
- this.matcher = matcher;
20
- this.codec = codec;
21
- this.options = options;
22
- this.plugin = new CompositePlugin(options?.plugins);
23
- this.plugin.init(this.options);
24
- this.matcher.init(router);
25
- }
26
- plugin;
27
- handle(request, ...[options]) {
28
- return intercept(
29
- this.options.interceptorsRoot ?? [],
30
- {
31
- request,
32
- ...options,
33
- context: options?.context ?? {}
34
- // context is optional only when all fields are optional so we can safely force it to have a context
35
- },
36
- async (interceptorOptions) => {
37
- try {
38
- return await intercept(
39
- this.options.interceptors ?? [],
40
- interceptorOptions,
41
- async (interceptorOptions2) => {
42
- const method = interceptorOptions2.request.method;
43
- const url = interceptorOptions2.request.url;
44
- const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
45
- const match = await this.matcher.match(method, pathname);
46
- if (!match) {
47
- return { matched: false, response: void 0 };
48
- }
49
- const clientOptions = {
50
- context: interceptorOptions2.context,
51
- path: match.path
52
- };
53
- this.plugin.beforeCreateProcedureClient(clientOptions, interceptorOptions2);
54
- const client = createProcedureClient(match.procedure, clientOptions);
55
- const input = await this.codec.decode(request, match.params, match.procedure);
56
- const output = await client(input, { signal: request.signal });
57
- const response = this.codec.encode(output, match.procedure);
58
- return {
59
- matched: true,
60
- response
61
- };
62
- }
63
- );
64
- } catch (e) {
65
- const error = toORPCError(e);
66
- const response = this.codec.encodeError(error);
67
- return {
68
- matched: true,
69
- response
70
- };
71
- }
72
- }
73
- );
74
- }
75
- };
76
-
77
- // src/adapters/standard/rpc-serializer.ts
78
- import { findDeepMatches, isObject, set } from "@orpc/shared";
79
- var RPCSerializer = class {
80
- serialize(data) {
81
- if (data === void 0) {
82
- return void 0;
83
- }
84
- if (data instanceof Blob) {
85
- return data;
86
- }
87
- const serializedJSON = serializeRPCJson(data);
88
- const { maps, values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON.json);
89
- if (blobs.length === 0) {
90
- return serializedJSON;
91
- }
92
- const form = new FormData();
93
- form.set("data", JSON.stringify(serializedJSON));
94
- form.set("maps", JSON.stringify(maps));
95
- for (const i in blobs) {
96
- form.set(i, blobs[i]);
97
- }
98
- return form;
99
- }
100
- deserialize(serialized) {
101
- if (serialized === void 0) {
102
- return void 0;
103
- }
104
- if (serialized instanceof Blob) {
105
- return serialized;
106
- }
107
- if (!(serialized instanceof FormData)) {
108
- return deserializeRPCJson(serialized);
109
- }
110
- const data = JSON.parse(serialized.get("data"));
111
- const maps = JSON.parse(serialized.get("maps"));
112
- for (const i in maps) {
113
- data.json = set(data.json, maps[i], serialized.get(i));
114
- }
115
- return deserializeRPCJson(data);
116
- }
117
- };
118
- function serializeRPCJson(value, segments = [], meta = []) {
119
- if (typeof value === "bigint") {
120
- meta.push(["bigint", segments]);
121
- return { json: value.toString(), meta };
122
- }
123
- if (value instanceof Date) {
124
- meta.push(["date", segments]);
125
- const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
126
- return { json: data, meta };
127
- }
128
- if (Number.isNaN(value)) {
129
- meta.push(["nan", segments]);
130
- return { json: "NaN", meta };
131
- }
132
- if (value instanceof RegExp) {
133
- meta.push(["regexp", segments]);
134
- return { json: value.toString(), meta };
135
- }
136
- if (value instanceof URL) {
137
- meta.push(["url", segments]);
138
- return { json: value.toString(), meta };
139
- }
140
- if (isObject(value)) {
141
- const json = {};
142
- for (const k in value) {
143
- json[k] = serializeRPCJson(value[k], [...segments, k], meta).json;
144
- }
145
- return { json, meta };
146
- }
147
- if (Array.isArray(value)) {
148
- const json = value.map((v, i) => {
149
- if (v === void 0) {
150
- meta.push(["undefined", [...segments, i]]);
151
- return null;
152
- }
153
- return serializeRPCJson(v, [...segments, i], meta).json;
154
- });
155
- return { json, meta };
156
- }
157
- if (value instanceof Set) {
158
- const result = serializeRPCJson(Array.from(value), segments, meta);
159
- meta.push(["set", segments]);
160
- return result;
161
- }
162
- if (value instanceof Map) {
163
- const result = serializeRPCJson(Array.from(value.entries()), segments, meta);
164
- meta.push(["map", segments]);
165
- return result;
166
- }
167
- return { json: value, meta };
168
- }
169
- function deserializeRPCJson({
170
- json,
171
- meta
172
- }) {
173
- if (meta.length === 0) {
174
- return json;
175
- }
176
- const ref = { data: json };
177
- for (const [type, segments] of meta) {
178
- let currentRef = ref;
179
- let preSegment = "data";
180
- for (let i = 0; i < segments.length; i++) {
181
- currentRef = currentRef[preSegment];
182
- preSegment = segments[i];
183
- }
184
- switch (type) {
185
- case "nan":
186
- currentRef[preSegment] = Number.NaN;
187
- break;
188
- case "bigint":
189
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
190
- break;
191
- case "date":
192
- currentRef[preSegment] = new Date(currentRef[preSegment]);
193
- break;
194
- case "regexp": {
195
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
196
- currentRef[preSegment] = new RegExp(pattern, flags);
197
- break;
198
- }
199
- case "url":
200
- currentRef[preSegment] = new URL(currentRef[preSegment]);
201
- break;
202
- case "undefined":
203
- currentRef[preSegment] = void 0;
204
- break;
205
- case "map":
206
- currentRef[preSegment] = new Map(currentRef[preSegment]);
207
- break;
208
- case "set":
209
- currentRef[preSegment] = new Set(currentRef[preSegment]);
210
- break;
211
- /* v8 ignore next 3 */
212
- default: {
213
- const _expected = type;
214
- }
215
- }
216
- }
217
- return ref.data;
218
- }
219
-
220
- // src/adapters/standard/rpc-codec.ts
221
- var RPCCodec = class {
222
- serializer;
223
- constructor(options = {}) {
224
- this.serializer = options.serializer ?? new RPCSerializer();
225
- }
226
- async decode(request, _params, _procedure) {
227
- const serialized = request.method === "GET" ? JSON.parse(request.url.searchParams.getAll("data").at(-1)) : await request.body();
228
- return this.serializer.deserialize(serialized);
229
- }
230
- encode(output, _procedure) {
231
- return {
232
- status: 200,
233
- headers: {},
234
- body: this.serializer.serialize(output)
235
- };
236
- }
237
- encodeError(error) {
238
- return {
239
- status: error.status,
240
- headers: {},
241
- body: this.serializer.serialize(error.toJSON())
242
- };
243
- }
244
- };
245
-
246
- // src/adapters/standard/rpc-matcher.ts
247
- var RPCMatcher = class {
248
- tree = {};
249
- pendingRouters = [];
250
- init(router, path = []) {
251
- const laziedOptions = eachContractProcedure({
252
- router,
253
- path
254
- }, ({ path: path2, contract }) => {
255
- const httpPath = convertPathToHttpPath(path2);
256
- if (isProcedure(contract)) {
257
- this.tree[httpPath] = {
258
- path: path2,
259
- contract,
260
- procedure: contract,
261
- // this mean dev not used contract-first so we can used contract as procedure directly
262
- router
263
- };
264
- } else {
265
- this.tree[httpPath] = {
266
- path: path2,
267
- contract,
268
- procedure: void 0,
269
- router
270
- };
271
- }
272
- });
273
- this.pendingRouters.push(...laziedOptions.map((option) => ({
274
- ...option,
275
- httpPathPrefix: convertPathToHttpPath(option.path)
276
- })));
277
- }
278
- async match(_method, pathname) {
279
- if (this.pendingRouters.length) {
280
- const newPendingRouters = [];
281
- for (const pendingRouter of this.pendingRouters) {
282
- if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
283
- const { default: router } = await unlazy(pendingRouter.lazied);
284
- this.init(router, pendingRouter.path);
285
- } else {
286
- newPendingRouters.push(pendingRouter);
287
- }
288
- }
289
- this.pendingRouters = newPendingRouters;
290
- }
291
- const match = this.tree[pathname];
292
- if (!match) {
293
- return void 0;
294
- }
295
- if (!match.procedure) {
296
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
297
- if (!isProcedure(maybeProcedure)) {
298
- throw new Error(`
299
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
300
- Ensure that the procedure is correctly defined and matches the expected contract.
301
- `);
302
- }
303
- match.procedure = createContractedProcedure(match.contract, maybeProcedure);
304
- }
305
- return {
306
- path: match.path,
307
- procedure: match.procedure
308
- };
309
- }
310
- };
311
-
312
- export {
313
- StandardHandler,
314
- RPCSerializer,
315
- serializeRPCJson,
316
- RPCCodec,
317
- RPCMatcher
318
- };
319
- //# sourceMappingURL=chunk-BFGSRNYZ.js.map
package/dist/fetch.js DELETED
@@ -1,16 +0,0 @@
1
- import {
2
- RPCHandler,
3
- fetchReToStandardBody,
4
- fetchRequestToStandardRequest,
5
- standardResponseToFetchResponse
6
- } from "./chunk-2OH4QMZ4.js";
7
- import "./chunk-BFGSRNYZ.js";
8
- import "./chunk-EDQKEHUX.js";
9
- import "./chunk-XFBAK67J.js";
10
- export {
11
- RPCHandler,
12
- fetchReToStandardBody,
13
- fetchRequestToStandardRequest,
14
- standardResponseToFetchResponse
15
- };
16
- //# sourceMappingURL=fetch.js.map
package/dist/node.js DELETED
@@ -1,170 +0,0 @@
1
- import {
2
- RPCCodec,
3
- RPCMatcher,
4
- StandardHandler
5
- } from "./chunk-BFGSRNYZ.js";
6
- import "./chunk-EDQKEHUX.js";
7
- import "./chunk-XFBAK67J.js";
8
-
9
- // src/adapters/node/utils.ts
10
- import { Buffer, File } from "node:buffer";
11
- import { Readable } from "node:stream";
12
- import { once } from "@orpc/shared";
13
- import { contentDisposition, parse as parseContentDisposition } from "@tinyhttp/content-disposition";
14
- function nodeHttpToStandardRequest(req, res) {
15
- const method = req.method ?? "GET";
16
- const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
17
- const host = req.headers.host ?? "localhost";
18
- const url = new URL(req.originalUrl ?? req.url ?? "/", `${protocol}//${host}`);
19
- return {
20
- raw: { request: req, response: res },
21
- method,
22
- url,
23
- headers: req.headers,
24
- body: once(() => {
25
- return nodeHttpRequestToStandardBody(req);
26
- }),
27
- get signal() {
28
- const signal = nodeHttpResponseToAbortSignal(res);
29
- Object.defineProperty(this, "signal", { value: signal, writable: true });
30
- return signal;
31
- },
32
- set signal(value) {
33
- Object.defineProperty(this, "signal", { value, writable: true });
34
- }
35
- };
36
- }
37
- function nodeHttpResponseSendStandardResponse(res, standardResponse) {
38
- return new Promise((resolve, reject) => {
39
- res.on("error", reject);
40
- res.on("finish", resolve);
41
- const resHeaders = standardResponse.headers;
42
- delete resHeaders["content-type"];
43
- delete resHeaders["content-disposition"];
44
- if (standardResponse.body === void 0) {
45
- res.writeHead(standardResponse.status, standardResponse.headers);
46
- res.end();
47
- return;
48
- }
49
- if (standardResponse.body instanceof Blob) {
50
- resHeaders["content-type"] = standardResponse.body.type;
51
- resHeaders["content-length"] = standardResponse.body.size.toString();
52
- resHeaders["content-disposition"] = contentDisposition(
53
- standardResponse.body instanceof File ? standardResponse.body.name : "blob",
54
- { type: "inline" }
55
- );
56
- res.writeHead(standardResponse.status, resHeaders);
57
- Readable.fromWeb(
58
- standardResponse.body.stream()
59
- // Conflict between types=node and lib=dom so we need to cast it
60
- ).pipe(res);
61
- return;
62
- }
63
- if (standardResponse.body instanceof FormData) {
64
- const response = new Response(standardResponse.body);
65
- resHeaders["content-type"] = response.headers.get("content-type");
66
- res.writeHead(standardResponse.status, resHeaders);
67
- Readable.fromWeb(
68
- response.body
69
- // Conflict between types=node and lib=dom so we need to cast it
70
- ).pipe(res);
71
- return;
72
- }
73
- if (standardResponse.body instanceof URLSearchParams) {
74
- resHeaders["content-type"] = "application/x-www-form-urlencoded";
75
- res.writeHead(standardResponse.status, resHeaders);
76
- res.end(standardResponse.body.toString());
77
- return;
78
- }
79
- resHeaders["content-type"] = "application/json";
80
- res.writeHead(standardResponse.status, resHeaders);
81
- res.end(JSON.stringify(standardResponse.body));
82
- });
83
- }
84
- async function nodeHttpRequestToStandardBody(req) {
85
- const method = req.method ?? "GET";
86
- if (method === "GET" || method === "HEAD") {
87
- return void 0;
88
- }
89
- const contentDisposition2 = req.headers["content-disposition"];
90
- const contentType = req.headers["content-type"];
91
- if (contentDisposition2) {
92
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
93
- if (typeof fileName === "string") {
94
- return await streamToFile(req, fileName, contentType || "application/octet-stream");
95
- }
96
- }
97
- if (!contentType || contentType.startsWith("application/json")) {
98
- const text = await streamToString(req);
99
- if (!text) {
100
- return void 0;
101
- }
102
- return JSON.parse(text);
103
- }
104
- if (contentType.startsWith("multipart/form-data")) {
105
- return await streamToFormData(req, contentType);
106
- }
107
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
108
- const text = await streamToString(req);
109
- return new URLSearchParams(text);
110
- }
111
- if (contentType.startsWith("text/")) {
112
- return await streamToString(req);
113
- }
114
- return streamToFile(req, "blob", contentType);
115
- }
116
- function streamToFormData(stream, contentType) {
117
- const response = new Response(stream, {
118
- // Conflict between types=node and lib=dom so we need to cast it
119
- headers: {
120
- "content-type": contentType
121
- }
122
- });
123
- return response.formData();
124
- }
125
- async function streamToString(stream) {
126
- let string = "";
127
- for await (const chunk of stream) {
128
- string += chunk.toString();
129
- }
130
- return string;
131
- }
132
- async function streamToFile(stream, fileName, contentType) {
133
- const chunks = [];
134
- for await (const chunk of stream) {
135
- chunks.push(chunk);
136
- }
137
- return new File([Buffer.concat(chunks)], fileName, { type: contentType });
138
- }
139
- function nodeHttpResponseToAbortSignal(res) {
140
- const controller = new AbortController();
141
- res.on("close", () => {
142
- controller.abort();
143
- });
144
- return controller.signal;
145
- }
146
-
147
- // src/adapters/node/rpc-handler.ts
148
- var RPCHandler = class {
149
- standardHandler;
150
- constructor(router, options) {
151
- const codec = options?.codec ?? new RPCCodec();
152
- const matcher = options?.matcher ?? new RPCMatcher();
153
- this.standardHandler = new StandardHandler(router, matcher, codec, options);
154
- }
155
- async handle(req, res, ...rest) {
156
- const standardRequest = nodeHttpToStandardRequest(req, res);
157
- const result = await this.standardHandler.handle(standardRequest, ...rest);
158
- if (!result.matched) {
159
- return { matched: false };
160
- }
161
- await nodeHttpResponseSendStandardResponse(res, result.response);
162
- return { matched: true };
163
- }
164
- };
165
- export {
166
- RPCHandler,
167
- nodeHttpResponseSendStandardResponse,
168
- nodeHttpToStandardRequest
169
- };
170
- //# sourceMappingURL=node.js.map
package/dist/plugins.js DELETED
@@ -1,11 +0,0 @@
1
- import {
2
- CORSPlugin,
3
- CompositePlugin,
4
- ResponseHeadersPlugin
5
- } from "./chunk-XFBAK67J.js";
6
- export {
7
- CORSPlugin,
8
- CompositePlugin,
9
- ResponseHeadersPlugin
10
- };
11
- //# sourceMappingURL=plugins.js.map
@@ -1,4 +0,0 @@
1
- export * from './rpc-handler';
2
- export * from './types';
3
- export * from './utils';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1,10 +0,0 @@
1
- import type { Context } from '../../context';
2
- import type { Router } from '../../router';
3
- import type { RPCHandlerOptions, StandardHandleRest } from '../standard';
4
- import type { FetchHandler, FetchHandleResult } from './types';
5
- export declare class RPCHandler<T extends Context> implements FetchHandler<T> {
6
- private readonly standardHandler;
7
- constructor(router: Router<T, any>, options?: NoInfer<RPCHandlerOptions<T>>);
8
- handle(request: Request, ...rest: StandardHandleRest<T>): Promise<FetchHandleResult>;
9
- }
10
- //# sourceMappingURL=rpc-handler.d.ts.map
@@ -1,13 +0,0 @@
1
- import type { Context } from '../../context';
2
- import type { StandardHandleRest } from '../standard';
3
- export type FetchHandleResult = {
4
- matched: true;
5
- response: Response;
6
- } | {
7
- matched: false;
8
- response: undefined;
9
- };
10
- export interface FetchHandler<T extends Context> {
11
- handle(request: Request, ...rest: StandardHandleRest<T>): Promise<FetchHandleResult>;
12
- }
13
- //# sourceMappingURL=types.d.ts.map
@@ -1,5 +0,0 @@
1
- import type { StandardBody, StandardRequest, StandardResponse } from '../standard';
2
- export declare function fetchReToStandardBody(re: Request | Response): Promise<StandardBody>;
3
- export declare function fetchRequestToStandardRequest(request: Request): StandardRequest;
4
- export declare function standardResponseToFetchResponse(response: StandardResponse): Response;
5
- //# sourceMappingURL=utils.d.ts.map