@orpc/server 0.0.0-next.8f9385e → 0.0.0-next.9125edb

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 (67) hide show
  1. package/dist/chunk-GBEB77SU.js +32 -0
  2. package/dist/chunk-GBL3M2PB.js +325 -0
  3. package/dist/chunk-XI6WGCB3.js +125 -0
  4. package/dist/chunk-XP6YRLY2.js +378 -0
  5. package/dist/fetch.js +6 -102
  6. package/dist/hono.js +34 -0
  7. package/dist/index.js +332 -322
  8. package/dist/next.js +31 -0
  9. package/dist/node.js +31 -0
  10. package/dist/plugins.js +11 -0
  11. package/dist/src/adapters/fetch/index.d.ts +3 -0
  12. package/dist/src/adapters/fetch/rpc-handler.d.ts +11 -0
  13. package/dist/src/adapters/fetch/types.d.ts +14 -0
  14. package/dist/src/adapters/hono/index.d.ts +3 -0
  15. package/dist/src/adapters/hono/middleware.d.ts +12 -0
  16. package/dist/src/adapters/next/index.d.ts +3 -0
  17. package/dist/src/adapters/next/serve.d.ts +19 -0
  18. package/dist/src/adapters/node/index.d.ts +3 -0
  19. package/dist/src/adapters/node/rpc-handler.d.ts +11 -0
  20. package/dist/src/adapters/node/types.d.ts +22 -0
  21. package/dist/src/adapters/standard/handler.d.ts +51 -0
  22. package/dist/src/adapters/standard/index.d.ts +7 -0
  23. package/dist/src/adapters/standard/rpc-codec.d.ts +16 -0
  24. package/dist/src/adapters/standard/rpc-handler.d.ts +8 -0
  25. package/dist/src/adapters/standard/rpc-matcher.d.ts +10 -0
  26. package/dist/src/adapters/standard/rpc-serializer.d.ts +16 -0
  27. package/dist/src/adapters/standard/types.d.ts +20 -0
  28. package/dist/src/builder-variants.d.ts +74 -0
  29. package/dist/src/builder.d.ts +47 -39
  30. package/dist/src/config.d.ts +6 -0
  31. package/dist/src/context.d.ts +9 -0
  32. package/dist/src/hidden.d.ts +8 -0
  33. package/dist/src/implementer-procedure.d.ts +31 -0
  34. package/dist/src/implementer-variants.d.ts +17 -0
  35. package/dist/src/implementer.d.ts +28 -0
  36. package/dist/src/index.d.ts +17 -9
  37. package/dist/src/lazy-utils.d.ts +6 -0
  38. package/dist/src/lazy.d.ts +22 -0
  39. package/dist/src/middleware-decorated.d.ts +10 -0
  40. package/dist/src/middleware-utils.d.ts +5 -0
  41. package/dist/src/middleware.d.ts +28 -18
  42. package/dist/src/plugins/base.d.ts +13 -0
  43. package/dist/src/plugins/cors.d.ts +19 -0
  44. package/dist/src/plugins/index.d.ts +4 -0
  45. package/dist/src/plugins/response-headers.d.ts +10 -0
  46. package/dist/src/procedure-client.d.ts +30 -0
  47. package/dist/src/procedure-decorated.d.ts +22 -0
  48. package/dist/src/procedure-utils.d.ts +18 -0
  49. package/dist/src/procedure.d.ts +25 -25
  50. package/dist/src/router-accessible-lazy.d.ts +8 -0
  51. package/dist/src/router-client.d.ts +11 -0
  52. package/dist/src/router.d.ts +26 -16
  53. package/dist/src/utils.d.ts +23 -2
  54. package/dist/standard.js +17 -0
  55. package/package.json +36 -9
  56. package/dist/chunk-TDFYNRZV.js +0 -190
  57. package/dist/src/fetch/handle.d.ts +0 -7
  58. package/dist/src/fetch/handler.d.ts +0 -3
  59. package/dist/src/fetch/index.d.ts +0 -4
  60. package/dist/src/fetch/types.d.ts +0 -35
  61. package/dist/src/procedure-builder.d.ts +0 -31
  62. package/dist/src/procedure-caller.d.ts +0 -19
  63. package/dist/src/procedure-implementer.d.ts +0 -18
  64. package/dist/src/router-builder.d.ts +0 -22
  65. package/dist/src/router-caller.d.ts +0 -22
  66. package/dist/src/router-implementer.d.ts +0 -20
  67. package/dist/src/types.d.ts +0 -8
@@ -0,0 +1,378 @@
1
+ // src/lazy.ts
2
+ var LAZY_LOADER_SYMBOL = Symbol("ORPC_LAZY_LOADER");
3
+ function lazy(loader) {
4
+ return {
5
+ [LAZY_LOADER_SYMBOL]: loader
6
+ };
7
+ }
8
+ function isLazy(item) {
9
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_LOADER_SYMBOL in item && typeof item[LAZY_LOADER_SYMBOL] === "function";
10
+ }
11
+ function unlazy(lazied) {
12
+ return isLazy(lazied) ? lazied[LAZY_LOADER_SYMBOL]() : Promise.resolve({ default: lazied });
13
+ }
14
+
15
+ // src/procedure.ts
16
+ import { isContractProcedure } from "@orpc/contract";
17
+ var Procedure = class {
18
+ "~orpc";
19
+ constructor(def) {
20
+ this["~orpc"] = def;
21
+ }
22
+ };
23
+ function isProcedure(item) {
24
+ if (item instanceof Procedure) {
25
+ return true;
26
+ }
27
+ return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
28
+ }
29
+
30
+ // src/lazy-utils.ts
31
+ function flatLazy(lazied) {
32
+ const flattenLoader = async () => {
33
+ let current = await unlazy(lazied);
34
+ while (true) {
35
+ if (!isLazy(current.default)) {
36
+ break;
37
+ }
38
+ current = await unlazy(current.default);
39
+ }
40
+ return current;
41
+ };
42
+ return lazy(flattenLoader);
43
+ }
44
+ function createLazyProcedureFormAnyLazy(lazied) {
45
+ const lazyProcedure = lazy(async () => {
46
+ const { default: maybeProcedure } = await unlazy(flatLazy(lazied));
47
+ if (!isProcedure(maybeProcedure)) {
48
+ throw new Error(`
49
+ Expected a lazy<procedure> but got lazy<unknown>.
50
+ This should be caught by TypeScript compilation.
51
+ Please report this issue if this makes you feel uncomfortable.
52
+ `);
53
+ }
54
+ return { default: maybeProcedure };
55
+ });
56
+ return lazyProcedure;
57
+ }
58
+
59
+ // src/middleware.ts
60
+ function middlewareOutputFn(output) {
61
+ return { output, context: {} };
62
+ }
63
+
64
+ // src/procedure-client.ts
65
+ import { createORPCErrorConstructorMap, ORPCError, validateORPCError, ValidationError } from "@orpc/contract";
66
+ import { intercept, toError, value } from "@orpc/shared";
67
+ function createProcedureClient(lazyableProcedure, ...[options]) {
68
+ return async (...[input, callerOptions]) => {
69
+ const path = options?.path ?? [];
70
+ const { default: procedure } = await unlazy(lazyableProcedure);
71
+ const clientContext = callerOptions?.context ?? {};
72
+ const context = await value(options?.context ?? {}, clientContext);
73
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
74
+ try {
75
+ return await intercept(
76
+ options?.interceptors ?? [],
77
+ {
78
+ context,
79
+ input,
80
+ // input only optional when it undefinable so we can safely cast it
81
+ errors,
82
+ path,
83
+ procedure,
84
+ signal: callerOptions?.signal
85
+ },
86
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
87
+ );
88
+ } catch (e) {
89
+ if (!(e instanceof ORPCError)) {
90
+ throw toError(e);
91
+ }
92
+ const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
93
+ throw validated;
94
+ }
95
+ };
96
+ }
97
+ async function validateInput(procedure, input) {
98
+ const schema = procedure["~orpc"].inputSchema;
99
+ if (!schema) {
100
+ return input;
101
+ }
102
+ const result = await schema["~standard"].validate(input);
103
+ if (result.issues) {
104
+ throw new ORPCError("BAD_REQUEST", {
105
+ message: "Input validation failed",
106
+ data: {
107
+ issues: result.issues
108
+ },
109
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
110
+ });
111
+ }
112
+ return result.value;
113
+ }
114
+ async function validateOutput(procedure, output) {
115
+ const schema = procedure["~orpc"].outputSchema;
116
+ if (!schema) {
117
+ return output;
118
+ }
119
+ const result = await schema["~standard"].validate(output);
120
+ if (result.issues) {
121
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
122
+ message: "Output validation failed",
123
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
124
+ });
125
+ }
126
+ return result.value;
127
+ }
128
+ async function executeProcedureInternal(procedure, options) {
129
+ const middlewares = procedure["~orpc"].middlewares;
130
+ const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
131
+ const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
132
+ let currentIndex = 0;
133
+ let currentContext = options.context;
134
+ let currentInput = options.input;
135
+ const next = async (...[nextOptions]) => {
136
+ const index = currentIndex;
137
+ currentIndex += 1;
138
+ currentContext = { ...currentContext, ...nextOptions?.context };
139
+ if (index === inputValidationIndex) {
140
+ currentInput = await validateInput(procedure, currentInput);
141
+ }
142
+ const mid = middlewares[index];
143
+ const result = mid ? await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn) : { output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput }), context: currentContext };
144
+ if (index === outputValidationIndex) {
145
+ const validatedOutput = await validateOutput(procedure, result.output);
146
+ return {
147
+ ...result,
148
+ output: validatedOutput
149
+ };
150
+ }
151
+ return result;
152
+ };
153
+ return (await next({})).output;
154
+ }
155
+
156
+ // src/hidden.ts
157
+ var ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_ROUTER_CONTRACT");
158
+ function setRouterContract(obj, contract) {
159
+ return new Proxy(obj, {
160
+ get(target, key) {
161
+ if (key === ROUTER_CONTRACT_SYMBOL) {
162
+ return contract;
163
+ }
164
+ return Reflect.get(target, key);
165
+ }
166
+ });
167
+ }
168
+ function getRouterContract(obj) {
169
+ return obj[ROUTER_CONTRACT_SYMBOL];
170
+ }
171
+ var LAZY_ROUTER_PREFIX_SYMBOL = Symbol("ORPC_LAZY_ROUTER_PREFIX");
172
+ function deepSetLazyRouterPrefix(router, prefix) {
173
+ return new Proxy(router, {
174
+ get(target, key) {
175
+ if (key !== LAZY_ROUTER_PREFIX_SYMBOL) {
176
+ const val = Reflect.get(target, key);
177
+ if (isLazy(val)) {
178
+ return deepSetLazyRouterPrefix(val, prefix);
179
+ }
180
+ return val;
181
+ }
182
+ return prefix;
183
+ }
184
+ });
185
+ }
186
+ function getLazyRouterPrefix(obj) {
187
+ return obj[LAZY_ROUTER_PREFIX_SYMBOL];
188
+ }
189
+
190
+ // src/router.ts
191
+ import { adaptRoute, mergeErrorMap, mergePrefix } from "@orpc/contract";
192
+
193
+ // src/middleware-utils.ts
194
+ function dedupeMiddlewares(compare, middlewares) {
195
+ let min = 0;
196
+ for (let i = 0; i < middlewares.length; i++) {
197
+ const index = compare.indexOf(middlewares[i], min);
198
+ if (index === -1) {
199
+ return middlewares.slice(i);
200
+ }
201
+ min = index + 1;
202
+ }
203
+ return [];
204
+ }
205
+ function mergeMiddlewares(first, second) {
206
+ return [...first, ...dedupeMiddlewares(first, second)];
207
+ }
208
+ function addMiddleware(middlewares, addition) {
209
+ return [...middlewares, addition];
210
+ }
211
+
212
+ // src/router.ts
213
+ function adaptRouter(router, options) {
214
+ if (isLazy(router)) {
215
+ const adapted2 = lazy(async () => {
216
+ const unlaziedRouter = (await unlazy(router)).default;
217
+ const adapted3 = adaptRouter(unlaziedRouter, options);
218
+ return { default: adapted3 };
219
+ });
220
+ const accessible = createAccessibleLazyRouter(adapted2);
221
+ const currentPrefix = getLazyRouterPrefix(router);
222
+ const prefix = currentPrefix ? mergePrefix(options.prefix, currentPrefix) : options.prefix;
223
+ if (prefix) {
224
+ return deepSetLazyRouterPrefix(accessible, prefix);
225
+ }
226
+ return accessible;
227
+ }
228
+ if (isProcedure(router)) {
229
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares);
230
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
231
+ const adapted2 = new Procedure({
232
+ ...router["~orpc"],
233
+ route: adaptRoute(router["~orpc"].route, options),
234
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
235
+ middlewares: newMiddlewares,
236
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
237
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
238
+ });
239
+ return adapted2;
240
+ }
241
+ const adapted = {};
242
+ for (const key in router) {
243
+ adapted[key] = adaptRouter(router[key], options);
244
+ }
245
+ return adapted;
246
+ }
247
+ function getRouterChild(router, ...path) {
248
+ let current = router;
249
+ for (let i = 0; i < path.length; i++) {
250
+ const segment = path[i];
251
+ if (!current) {
252
+ return void 0;
253
+ }
254
+ if (isProcedure(current)) {
255
+ return void 0;
256
+ }
257
+ if (!isLazy(current)) {
258
+ current = current[segment];
259
+ continue;
260
+ }
261
+ const lazied = current;
262
+ const rest = path.slice(i);
263
+ const newLazy = lazy(async () => {
264
+ const unwrapped = await unlazy(lazied);
265
+ if (!unwrapped.default) {
266
+ return unwrapped;
267
+ }
268
+ const next = getRouterChild(unwrapped.default, ...rest);
269
+ return { default: next };
270
+ });
271
+ return flatLazy(newLazy);
272
+ }
273
+ return current;
274
+ }
275
+
276
+ // src/router-accessible-lazy.ts
277
+ function createAccessibleLazyRouter(lazied) {
278
+ const flattenLazy = flatLazy(lazied);
279
+ const recursive = new Proxy(flattenLazy, {
280
+ get(target, key) {
281
+ if (typeof key !== "string") {
282
+ return Reflect.get(target, key);
283
+ }
284
+ const next = getRouterChild(flattenLazy, key);
285
+ return createAccessibleLazyRouter(next);
286
+ }
287
+ });
288
+ return recursive;
289
+ }
290
+
291
+ // src/utils.ts
292
+ import { isContractProcedure as isContractProcedure2 } from "@orpc/contract";
293
+ function eachContractProcedure(options, callback, laziedOptions = []) {
294
+ const hiddenContract = getRouterContract(options.router);
295
+ if (hiddenContract) {
296
+ return eachContractProcedure(
297
+ {
298
+ router: hiddenContract,
299
+ path: options.path
300
+ },
301
+ callback,
302
+ laziedOptions
303
+ );
304
+ }
305
+ if (isLazy(options.router)) {
306
+ laziedOptions.push({
307
+ lazied: options.router,
308
+ path: options.path
309
+ });
310
+ } else if (isContractProcedure2(options.router)) {
311
+ callback({
312
+ contract: options.router,
313
+ path: options.path
314
+ });
315
+ } else {
316
+ for (const key in options.router) {
317
+ eachContractProcedure(
318
+ {
319
+ router: options.router[key],
320
+ path: [...options.path, key]
321
+ },
322
+ callback,
323
+ laziedOptions
324
+ );
325
+ }
326
+ }
327
+ return laziedOptions;
328
+ }
329
+ async function eachAllContractProcedure(options, callback) {
330
+ const pending = [options];
331
+ for (const item of pending) {
332
+ const lazies = eachContractProcedure(item, callback);
333
+ for (const lazy2 of lazies) {
334
+ const { default: router } = await unlazy(lazy2.lazied);
335
+ pending.push({
336
+ path: lazy2.path,
337
+ router
338
+ });
339
+ }
340
+ }
341
+ }
342
+ function convertPathToHttpPath(path) {
343
+ return `/${path.map(encodeURIComponent).join("/")}`;
344
+ }
345
+ function createContractedProcedure(contract, procedure) {
346
+ return new Procedure({
347
+ ...procedure["~orpc"],
348
+ errorMap: contract["~orpc"].errorMap,
349
+ route: contract["~orpc"].route,
350
+ meta: contract["~orpc"].meta
351
+ });
352
+ }
353
+
354
+ export {
355
+ LAZY_LOADER_SYMBOL,
356
+ lazy,
357
+ isLazy,
358
+ unlazy,
359
+ Procedure,
360
+ isProcedure,
361
+ flatLazy,
362
+ createLazyProcedureFormAnyLazy,
363
+ addMiddleware,
364
+ middlewareOutputFn,
365
+ createProcedureClient,
366
+ setRouterContract,
367
+ getRouterContract,
368
+ deepSetLazyRouterPrefix,
369
+ getLazyRouterPrefix,
370
+ createAccessibleLazyRouter,
371
+ adaptRouter,
372
+ getRouterChild,
373
+ eachContractProcedure,
374
+ eachAllContractProcedure,
375
+ convertPathToHttpPath,
376
+ createContractedProcedure
377
+ };
378
+ //# sourceMappingURL=chunk-XP6YRLY2.js.map
package/dist/fetch.js CHANGED
@@ -1,106 +1,10 @@
1
1
  import {
2
- createProcedureCaller,
3
- isProcedure
4
- } from "./chunk-TDFYNRZV.js";
5
-
6
- // src/fetch/handle.ts
7
- import { ORPCError } from "@orpc/shared/error";
8
- async function handleFetchRequest(options) {
9
- for (const handler of options.handlers) {
10
- const response = await handler(options);
11
- if (response) {
12
- return response;
13
- }
14
- }
15
- const error = new ORPCError({ code: "NOT_FOUND", message: "Not found" });
16
- return new Response(JSON.stringify(error.toJSON()), {
17
- status: error.status,
18
- headers: {
19
- "Content-Type": "application/json"
20
- }
21
- });
22
- }
23
-
24
- // src/fetch/handler.ts
25
- import { ORPC_HEADER, ORPC_HEADER_VALUE } from "@orpc/contract";
26
- import { trim, value } from "@orpc/shared";
27
- import { ORPCError as ORPCError2 } from "@orpc/shared/error";
28
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
29
- var serializer = new ORPCSerializer();
30
- var deserializer = new ORPCDeserializer();
31
- function createORPCHandler() {
32
- return async (options) => {
33
- if (options.request.headers.get(ORPC_HEADER) !== ORPC_HEADER_VALUE) {
34
- return void 0;
35
- }
36
- const context = await value(options.context);
37
- const handler = async () => {
38
- const url = new URL(options.request.url);
39
- const pathname = `/${trim(url.pathname.replace(options.prefix ?? "", ""), "/")}`;
40
- const match = resolveORPCRouter(options.router, pathname);
41
- if (!match) {
42
- throw new ORPCError2({ code: "NOT_FOUND", message: "Not found" });
43
- }
44
- const input = await deserializeRequest(options.request);
45
- const caller = createProcedureCaller({
46
- context,
47
- procedure: match.procedure,
48
- path: match.path
49
- });
50
- const output = await caller(input);
51
- const { body, headers } = serializer.serialize(output);
52
- return new Response(body, {
53
- status: 200,
54
- headers
55
- });
56
- };
57
- try {
58
- return await options.hooks?.(
59
- context,
60
- { next: handler, response: (response) => response }
61
- ) ?? await handler();
62
- } catch (e) {
63
- const error = e instanceof ORPCError2 ? e : new ORPCError2({
64
- code: "INTERNAL_SERVER_ERROR",
65
- message: "Internal server error",
66
- cause: e
67
- });
68
- const { body, headers } = serializer.serialize(error.toJSON());
69
- return new Response(body, {
70
- status: error.status,
71
- headers
72
- });
73
- }
74
- };
75
- }
76
- function resolveORPCRouter(router, pathname) {
77
- const path = trim(pathname, "/").split("/").map(decodeURIComponent);
78
- let current = router;
79
- for (const segment of path) {
80
- if ((typeof current !== "object" || current === null) && typeof current !== "function") {
81
- current = void 0;
82
- break;
83
- }
84
- current = current[segment];
85
- }
86
- return isProcedure(current) ? {
87
- procedure: current,
88
- path
89
- } : void 0;
90
- }
91
- async function deserializeRequest(request) {
92
- try {
93
- return await deserializer.deserialize(request);
94
- } catch (e) {
95
- throw new ORPCError2({
96
- code: "BAD_REQUEST",
97
- message: "Cannot parse request. Please check the request body and Content-Type header.",
98
- cause: e
99
- });
100
- }
101
- }
2
+ RPCHandler
3
+ } from "./chunk-GBEB77SU.js";
4
+ import "./chunk-GBL3M2PB.js";
5
+ import "./chunk-XP6YRLY2.js";
6
+ import "./chunk-XI6WGCB3.js";
102
7
  export {
103
- createORPCHandler,
104
- handleFetchRequest
8
+ RPCHandler
105
9
  };
106
10
  //# sourceMappingURL=fetch.js.map
package/dist/hono.js ADDED
@@ -0,0 +1,34 @@
1
+ import {
2
+ RPCHandler
3
+ } from "./chunk-GBEB77SU.js";
4
+ import "./chunk-GBL3M2PB.js";
5
+ import "./chunk-XP6YRLY2.js";
6
+ import "./chunk-XI6WGCB3.js";
7
+
8
+ // src/adapters/hono/middleware.ts
9
+ import { value } from "@orpc/shared";
10
+ function createMiddleware(handler, ...[options]) {
11
+ return async (c, next) => {
12
+ const bodyProps = /* @__PURE__ */ new Set(["arrayBuffer", "blob", "formData", "json", "text"]);
13
+ const request = c.req.method === "GET" || c.req.method === "HEAD" ? c.req.raw : new Proxy(c.req.raw, {
14
+ // https://github.com/honojs/middleware/blob/main/packages/trpc-server/src/index.ts#L39
15
+ get(target, prop) {
16
+ if (bodyProps.has(prop)) {
17
+ return () => c.req[prop]();
18
+ }
19
+ return Reflect.get(target, prop, target);
20
+ }
21
+ });
22
+ const context = await value(options?.context ?? {}, c);
23
+ const { matched, response } = await handler.handle(request, { ...options, context });
24
+ if (matched) {
25
+ return c.newResponse(response.body, response);
26
+ }
27
+ await next();
28
+ };
29
+ }
30
+ export {
31
+ RPCHandler,
32
+ createMiddleware
33
+ };
34
+ //# sourceMappingURL=hono.js.map