@orpc/server 0.0.0-next.d74cac4 → 0.0.0-next.d760838

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 (86) hide show
  1. package/README.md +131 -0
  2. package/dist/adapters/fetch/index.d.mts +54 -0
  3. package/dist/adapters/fetch/index.d.ts +54 -0
  4. package/dist/adapters/fetch/index.mjs +9 -0
  5. package/dist/adapters/hono/index.d.mts +22 -0
  6. package/dist/adapters/hono/index.d.ts +22 -0
  7. package/dist/{hono.js → adapters/hono/index.mjs} +11 -13
  8. package/dist/adapters/next/index.d.mts +29 -0
  9. package/dist/adapters/next/index.d.ts +29 -0
  10. package/dist/{next.js → adapters/next/index.mjs} +11 -13
  11. package/dist/adapters/node/index.d.mts +53 -0
  12. package/dist/adapters/node/index.d.ts +53 -0
  13. package/dist/adapters/node/index.mjs +85 -0
  14. package/dist/adapters/standard/index.d.mts +26 -0
  15. package/dist/adapters/standard/index.d.ts +26 -0
  16. package/dist/adapters/standard/index.mjs +6 -0
  17. package/dist/index.d.mts +291 -0
  18. package/dist/index.d.ts +291 -0
  19. package/dist/{index.js → index.mjs} +107 -156
  20. package/dist/plugins/index.d.mts +66 -0
  21. package/dist/plugins/index.d.ts +66 -0
  22. package/dist/plugins/index.mjs +196 -0
  23. package/dist/shared/server.BFt8M4Cr.d.ts +8 -0
  24. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  25. package/dist/shared/server.Bc6jnvPE.d.ts +10 -0
  26. package/dist/shared/server.BlxK0o8R.d.mts +66 -0
  27. package/dist/shared/server.C37gDhSZ.mjs +364 -0
  28. package/dist/shared/server.CCPFkKqC.mjs +98 -0
  29. package/dist/shared/server.CCgy73tk.d.mts +10 -0
  30. package/dist/shared/server.DJrRF9vD.mjs +162 -0
  31. package/dist/shared/server.DLt5njUb.d.mts +143 -0
  32. package/dist/shared/server.DLt5njUb.d.ts +143 -0
  33. package/dist/shared/server.DuTpqr2w.d.ts +66 -0
  34. package/dist/shared/server.JgWzFqlo.d.mts +8 -0
  35. package/package.json +30 -34
  36. package/dist/chunk-L4ESXQX7.js +0 -32
  37. package/dist/chunk-NXEANHUK.js +0 -351
  38. package/dist/chunk-XI6WGCB3.js +0 -125
  39. package/dist/chunk-XXBE6CYD.js +0 -379
  40. package/dist/fetch.js +0 -10
  41. package/dist/node.js +0 -31
  42. package/dist/plugins.js +0 -11
  43. package/dist/src/adapters/fetch/index.d.ts +0 -3
  44. package/dist/src/adapters/fetch/rpc-handler.d.ts +0 -11
  45. package/dist/src/adapters/fetch/types.d.ts +0 -14
  46. package/dist/src/adapters/hono/index.d.ts +0 -3
  47. package/dist/src/adapters/hono/middleware.d.ts +0 -12
  48. package/dist/src/adapters/next/index.d.ts +0 -3
  49. package/dist/src/adapters/next/serve.d.ts +0 -19
  50. package/dist/src/adapters/node/index.d.ts +0 -3
  51. package/dist/src/adapters/node/rpc-handler.d.ts +0 -11
  52. package/dist/src/adapters/node/types.d.ts +0 -22
  53. package/dist/src/adapters/standard/handler.d.ts +0 -51
  54. package/dist/src/adapters/standard/index.d.ts +0 -7
  55. package/dist/src/adapters/standard/rpc-codec.d.ts +0 -16
  56. package/dist/src/adapters/standard/rpc-handler.d.ts +0 -8
  57. package/dist/src/adapters/standard/rpc-matcher.d.ts +0 -10
  58. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -22
  59. package/dist/src/adapters/standard/types.d.ts +0 -20
  60. package/dist/src/builder-variants.d.ts +0 -74
  61. package/dist/src/builder.d.ts +0 -57
  62. package/dist/src/config.d.ts +0 -6
  63. package/dist/src/context.d.ts +0 -8
  64. package/dist/src/hidden.d.ts +0 -8
  65. package/dist/src/implementer-procedure.d.ts +0 -31
  66. package/dist/src/implementer-variants.d.ts +0 -17
  67. package/dist/src/implementer.d.ts +0 -28
  68. package/dist/src/index.d.ts +0 -24
  69. package/dist/src/lazy-utils.d.ts +0 -6
  70. package/dist/src/lazy.d.ts +0 -22
  71. package/dist/src/middleware-decorated.d.ts +0 -10
  72. package/dist/src/middleware-utils.d.ts +0 -5
  73. package/dist/src/middleware.d.ts +0 -37
  74. package/dist/src/plugins/base.d.ts +0 -13
  75. package/dist/src/plugins/cors.d.ts +0 -19
  76. package/dist/src/plugins/index.d.ts +0 -4
  77. package/dist/src/plugins/response-headers.d.ts +0 -10
  78. package/dist/src/procedure-client.d.ts +0 -31
  79. package/dist/src/procedure-decorated.d.ts +0 -22
  80. package/dist/src/procedure-utils.d.ts +0 -18
  81. package/dist/src/procedure.d.ts +0 -30
  82. package/dist/src/router-accessible-lazy.d.ts +0 -8
  83. package/dist/src/router-client.d.ts +0 -11
  84. package/dist/src/router.d.ts +0 -30
  85. package/dist/src/utils.d.ts +0 -24
  86. package/dist/standard.js +0 -17
@@ -0,0 +1,196 @@
1
+ import { value } from '@orpc/shared';
2
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
3
+
4
+ class BatchHandlerPlugin {
5
+ maxSize;
6
+ mapRequestItem;
7
+ successStatus;
8
+ headers;
9
+ constructor(options = {}) {
10
+ this.maxSize = options.maxSize ?? 10;
11
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
12
+ ...request,
13
+ headers: {
14
+ ...batchRequest.headers,
15
+ ...request.headers
16
+ }
17
+ }));
18
+ this.successStatus = options.successStatus ?? 207;
19
+ this.headers = options.headers ?? {};
20
+ }
21
+ init(options) {
22
+ options.rootInterceptors ??= [];
23
+ options.rootInterceptors.unshift(async (options2) => {
24
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
25
+ return options2.next();
26
+ }
27
+ let isParsing = false;
28
+ try {
29
+ isParsing = true;
30
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
31
+ isParsing = false;
32
+ const maxSize = await value(this.maxSize, options2);
33
+ if (parsed.length > maxSize) {
34
+ return {
35
+ matched: true,
36
+ response: {
37
+ status: 413,
38
+ headers: {},
39
+ body: "Batch request size exceeds the maximum allowed size"
40
+ }
41
+ };
42
+ }
43
+ const responses = parsed.map(
44
+ (request, index) => {
45
+ const mapped = this.mapRequestItem(request, options2);
46
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
47
+ if (matched) {
48
+ return { ...response2, index };
49
+ }
50
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
51
+ }).catch(() => {
52
+ return { index, status: 500, headers: {}, body: "Internal server error" };
53
+ });
54
+ }
55
+ );
56
+ await Promise.race(responses);
57
+ const status = await value(this.successStatus, responses, options2);
58
+ const headers = await value(this.headers, responses, options2);
59
+ const response = toBatchResponse({
60
+ status,
61
+ headers,
62
+ body: async function* () {
63
+ const promises = [...responses];
64
+ while (true) {
65
+ const handling = promises.filter((p) => p !== void 0);
66
+ if (handling.length === 0) {
67
+ return;
68
+ }
69
+ const result = await Promise.race(handling);
70
+ promises[result.index] = void 0;
71
+ yield result;
72
+ }
73
+ }()
74
+ });
75
+ return {
76
+ matched: true,
77
+ response
78
+ };
79
+ } catch (cause) {
80
+ if (isParsing) {
81
+ return {
82
+ matched: true,
83
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
84
+ };
85
+ }
86
+ throw cause;
87
+ }
88
+ });
89
+ }
90
+ }
91
+
92
+ class CORSPlugin {
93
+ options;
94
+ constructor(options = {}) {
95
+ const defaults = {
96
+ origin: (origin) => origin,
97
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
98
+ };
99
+ this.options = {
100
+ ...defaults,
101
+ ...options
102
+ };
103
+ }
104
+ init(options) {
105
+ options.rootInterceptors ??= [];
106
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
107
+ if (interceptorOptions.request.method === "OPTIONS") {
108
+ const resHeaders = {};
109
+ if (this.options.maxAge !== void 0) {
110
+ resHeaders["access-control-max-age"] = this.options.maxAge.toString();
111
+ }
112
+ if (this.options.allowMethods?.length) {
113
+ resHeaders["access-control-allow-methods"] = this.options.allowMethods.join(",");
114
+ }
115
+ const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
116
+ if (Array.isArray(allowHeaders) && allowHeaders.length) {
117
+ resHeaders["access-control-allow-headers"] = allowHeaders.join(",");
118
+ } else if (typeof allowHeaders === "string") {
119
+ resHeaders["access-control-allow-headers"] = allowHeaders;
120
+ }
121
+ return {
122
+ matched: true,
123
+ response: {
124
+ status: 204,
125
+ headers: resHeaders,
126
+ body: void 0
127
+ }
128
+ };
129
+ }
130
+ return interceptorOptions.next();
131
+ });
132
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
133
+ const result = await interceptorOptions.next();
134
+ if (!result.matched) {
135
+ return result;
136
+ }
137
+ const origin = Array.isArray(interceptorOptions.request.headers.origin) ? interceptorOptions.request.headers.origin.join(",") : interceptorOptions.request.headers.origin || "";
138
+ const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
139
+ const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
140
+ if (allowedOriginArr.includes("*")) {
141
+ result.response.headers["access-control-allow-origin"] = "*";
142
+ } else {
143
+ if (allowedOriginArr.includes(origin)) {
144
+ result.response.headers["access-control-allow-origin"] = origin;
145
+ }
146
+ result.response.headers.vary = interceptorOptions.request.headers.vary ?? "origin";
147
+ }
148
+ const allowedTimingOrigin = await value(this.options.timingOrigin, origin, interceptorOptions);
149
+ const allowedTimingOriginArr = Array.isArray(allowedTimingOrigin) ? allowedTimingOrigin : [allowedTimingOrigin];
150
+ if (allowedTimingOriginArr.includes("*")) {
151
+ result.response.headers["timing-allow-origin"] = "*";
152
+ } else if (allowedTimingOriginArr.includes(origin)) {
153
+ result.response.headers["timing-allow-origin"] = origin;
154
+ }
155
+ if (this.options.credentials) {
156
+ result.response.headers["access-control-allow-credentials"] = "true";
157
+ }
158
+ if (this.options.exposeHeaders?.length) {
159
+ result.response.headers["access-control-expose-headers"] = this.options.exposeHeaders.join(",");
160
+ }
161
+ return result;
162
+ });
163
+ }
164
+ }
165
+
166
+ class ResponseHeadersPlugin {
167
+ init(options) {
168
+ options.rootInterceptors ??= [];
169
+ options.rootInterceptors.push(async (interceptorOptions) => {
170
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
171
+ const result = await interceptorOptions.next({
172
+ ...interceptorOptions,
173
+ context: {
174
+ ...interceptorOptions.context,
175
+ resHeaders
176
+ }
177
+ });
178
+ if (!result.matched) {
179
+ return result;
180
+ }
181
+ const responseHeaders = result.response.headers;
182
+ for (const [key, value] of resHeaders) {
183
+ if (Array.isArray(responseHeaders[key])) {
184
+ responseHeaders[key].push(value);
185
+ } else if (responseHeaders[key] !== void 0) {
186
+ responseHeaders[key] = [responseHeaders[key], value];
187
+ } else {
188
+ responseHeaders[key] = value;
189
+ }
190
+ }
191
+ return result;
192
+ });
193
+ }
194
+ }
195
+
196
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin };
@@ -0,0 +1,8 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { C as Context } from './server.DLt5njUb.js';
3
+ import { a as StandardHandlerOptions } from './server.DuTpqr2w.js';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ }
7
+
8
+ export type { StandardRPCHandlerOptions as S };
@@ -0,0 +1,9 @@
1
+ function resolveFriendlyStandardHandleOptions(options) {
2
+ return {
3
+ ...options,
4
+ context: options?.context ?? {}
5
+ // Context only optional if all fields are optional
6
+ };
7
+ }
8
+
9
+ export { resolveFriendlyStandardHandleOptions as r };
@@ -0,0 +1,10 @@
1
+ import { C as Context } from './server.DLt5njUb.js';
2
+ import { S as StandardHandleOptions } from './server.DuTpqr2w.js';
3
+
4
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
5
+ context?: T;
6
+ } : {
7
+ context: T;
8
+ });
9
+
10
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,66 @@
1
+ import { HTTPPath, ORPCError } from '@orpc/client';
2
+ import { Meta, InferSchemaOutput, AnySchema, ErrorFromErrorMap } from '@orpc/contract';
3
+ import { Interceptor, ThrowableError } from '@orpc/shared';
4
+ import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
5
+ import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.DLt5njUb.mjs';
6
+
7
+ type StandardParams = Record<string, string>;
8
+ type StandardMatchResult = {
9
+ path: readonly string[];
10
+ procedure: AnyProcedure;
11
+ params?: StandardParams;
12
+ } | undefined;
13
+ interface StandardMatcher {
14
+ init(router: AnyRouter): void;
15
+ match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
16
+ }
17
+ interface StandardCodec {
18
+ encode(output: unknown, procedure: AnyProcedure): StandardResponse;
19
+ encodeError(error: ORPCError<any, any>): StandardResponse;
20
+ decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
21
+ }
22
+
23
+ interface StandardHandleOptions<T extends Context> {
24
+ prefix?: HTTPPath;
25
+ context: T;
26
+ }
27
+ type StandardHandleResult = {
28
+ matched: true;
29
+ response: StandardResponse;
30
+ } | {
31
+ matched: false;
32
+ response: undefined;
33
+ };
34
+ interface StandardHandlerPlugin<TContext extends Context> {
35
+ init?(options: StandardHandlerOptions<TContext>): void;
36
+ }
37
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
38
+ request: StandardLazyRequest;
39
+ }
40
+ interface StandardHandlerOptions<TContext extends Context> {
41
+ plugins?: StandardHandlerPlugin<TContext>[];
42
+ /**
43
+ * Interceptors at the request level, helpful when you want catch errors
44
+ */
45
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
46
+ /**
47
+ * Interceptors at the root level, helpful when you want override the request/response
48
+ */
49
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
50
+ /**
51
+ *
52
+ * Interceptors for procedure client.
53
+ */
54
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
55
+ }
56
+ declare class StandardHandler<T extends Context> {
57
+ private readonly matcher;
58
+ private readonly codec;
59
+ private readonly interceptors;
60
+ private readonly clientInterceptors;
61
+ private readonly rootInterceptors;
62
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
63
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
64
+ }
65
+
66
+ export { type StandardHandleOptions as S, type StandardHandlerOptions as a, type StandardCodec as b, type StandardParams as c, type StandardMatcher as d, type StandardMatchResult as e, type StandardHandleResult as f, type StandardHandlerPlugin as g, type StandardHandlerInterceptorOptions as h, StandardHandler as i };
@@ -0,0 +1,364 @@
1
+ import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
+ import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
+ import { value, intercept } from '@orpc/shared';
4
+
5
+ const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
+ function lazy(loader, meta = {}) {
7
+ return {
8
+ [LAZY_SYMBOL]: {
9
+ loader,
10
+ meta
11
+ }
12
+ };
13
+ }
14
+ function isLazy(item) {
15
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
16
+ }
17
+ function getLazyMeta(lazied) {
18
+ return lazied[LAZY_SYMBOL].meta;
19
+ }
20
+ function unlazy(lazied) {
21
+ return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
22
+ }
23
+
24
+ function isStartWithMiddlewares(middlewares, compare) {
25
+ if (compare.length > middlewares.length) {
26
+ return false;
27
+ }
28
+ for (let i = 0; i < middlewares.length; i++) {
29
+ if (compare[i] === void 0) {
30
+ return true;
31
+ }
32
+ if (middlewares[i] !== compare[i]) {
33
+ return false;
34
+ }
35
+ }
36
+ return true;
37
+ }
38
+ function mergeMiddlewares(first, second, options) {
39
+ if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
40
+ return second;
41
+ }
42
+ return [...first, ...second];
43
+ }
44
+ function addMiddleware(middlewares, addition) {
45
+ return [...middlewares, addition];
46
+ }
47
+
48
+ class Procedure {
49
+ "~orpc";
50
+ constructor(def) {
51
+ this["~orpc"] = def;
52
+ }
53
+ }
54
+ function isProcedure(item) {
55
+ if (item instanceof Procedure) {
56
+ return true;
57
+ }
58
+ return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
59
+ }
60
+
61
+ function mergeCurrentContext(context, other) {
62
+ return { ...context, ...other };
63
+ }
64
+
65
+ function createORPCErrorConstructorMap(errors) {
66
+ const proxy = new Proxy(errors, {
67
+ get(target, code) {
68
+ if (typeof code !== "string") {
69
+ return Reflect.get(target, code);
70
+ }
71
+ const item = (...[options]) => {
72
+ const config = errors[code];
73
+ return new ORPCError(code, {
74
+ defined: Boolean(config),
75
+ status: config?.status,
76
+ message: options?.message ?? config?.message,
77
+ data: options?.data,
78
+ cause: options?.cause
79
+ });
80
+ };
81
+ return item;
82
+ }
83
+ });
84
+ return proxy;
85
+ }
86
+ async function validateORPCError(map, error) {
87
+ const { code, status, message, data, cause, defined } = error;
88
+ const config = map?.[error.code];
89
+ if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
90
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
91
+ }
92
+ if (!config.data) {
93
+ return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
94
+ }
95
+ const validated = await config.data["~standard"].validate(error.data);
96
+ if (validated.issues) {
97
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
98
+ }
99
+ return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
100
+ }
101
+
102
+ function middlewareOutputFn(output) {
103
+ return { output, context: {} };
104
+ }
105
+
106
+ function createProcedureClient(lazyableProcedure, ...[options]) {
107
+ return async (...[input, callerOptions]) => {
108
+ const path = options?.path ?? [];
109
+ const { default: procedure } = await unlazy(lazyableProcedure);
110
+ const clientContext = callerOptions?.context ?? {};
111
+ const context = await value(options?.context ?? {}, clientContext);
112
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
113
+ try {
114
+ return await intercept(
115
+ options?.interceptors ?? [],
116
+ {
117
+ context,
118
+ input,
119
+ // input only optional when it undefinable so we can safely cast it
120
+ errors,
121
+ path,
122
+ procedure,
123
+ signal: callerOptions?.signal,
124
+ lastEventId: callerOptions?.lastEventId
125
+ },
126
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
127
+ );
128
+ } catch (e) {
129
+ if (!(e instanceof ORPCError)) {
130
+ throw e;
131
+ }
132
+ const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
+ throw validated;
134
+ }
135
+ };
136
+ }
137
+ async function validateInput(procedure, input) {
138
+ const schema = procedure["~orpc"].inputSchema;
139
+ if (!schema) {
140
+ return input;
141
+ }
142
+ const result = await schema["~standard"].validate(input);
143
+ if (result.issues) {
144
+ throw new ORPCError("BAD_REQUEST", {
145
+ message: "Input validation failed",
146
+ data: {
147
+ issues: result.issues
148
+ },
149
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
150
+ });
151
+ }
152
+ return result.value;
153
+ }
154
+ async function validateOutput(procedure, output) {
155
+ const schema = procedure["~orpc"].outputSchema;
156
+ if (!schema) {
157
+ return output;
158
+ }
159
+ const result = await schema["~standard"].validate(output);
160
+ if (result.issues) {
161
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
162
+ message: "Output validation failed",
163
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
164
+ });
165
+ }
166
+ return result.value;
167
+ }
168
+ async function executeProcedureInternal(procedure, options) {
169
+ const middlewares = procedure["~orpc"].middlewares;
170
+ const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
+ const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
172
+ const next = async (index, context, input) => {
173
+ let currentInput = input;
174
+ if (index === inputValidationIndex) {
175
+ currentInput = await validateInput(procedure, currentInput);
176
+ }
177
+ const mid = middlewares[index];
178
+ const output = mid ? (await mid({
179
+ ...options,
180
+ context,
181
+ next: async (...[nextOptions]) => {
182
+ const nextContext = nextOptions?.context ?? {};
183
+ return {
184
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
185
+ context: nextContext
186
+ };
187
+ }
188
+ }, currentInput, middlewareOutputFn)).output : await procedure["~orpc"].handler({ ...options, context, input: currentInput });
189
+ if (index === outputValidationIndex) {
190
+ return await validateOutput(procedure, output);
191
+ }
192
+ return output;
193
+ };
194
+ return next(0, options.context, options.input);
195
+ }
196
+
197
+ const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
198
+ function setHiddenRouterContract(router, contract) {
199
+ return new Proxy(router, {
200
+ get(target, key) {
201
+ if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
202
+ return contract;
203
+ }
204
+ return Reflect.get(target, key);
205
+ }
206
+ });
207
+ }
208
+ function getHiddenRouterContract(router) {
209
+ return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
210
+ }
211
+
212
+ function getRouter(router, path) {
213
+ let current = router;
214
+ for (let i = 0; i < path.length; i++) {
215
+ const segment = path[i];
216
+ if (!current) {
217
+ return void 0;
218
+ }
219
+ if (isProcedure(current)) {
220
+ return void 0;
221
+ }
222
+ if (!isLazy(current)) {
223
+ current = current[segment];
224
+ continue;
225
+ }
226
+ const lazied = current;
227
+ const rest = path.slice(i);
228
+ return lazy(async () => {
229
+ const unwrapped = await unlazy(lazied);
230
+ const next = getRouter(unwrapped.default, rest);
231
+ return unlazy(next);
232
+ }, getLazyMeta(lazied));
233
+ }
234
+ return current;
235
+ }
236
+ function createAccessibleLazyRouter(lazied) {
237
+ const recursive = new Proxy(lazied, {
238
+ get(target, key) {
239
+ if (typeof key !== "string") {
240
+ return Reflect.get(target, key);
241
+ }
242
+ const next = getRouter(lazied, [key]);
243
+ return createAccessibleLazyRouter(next);
244
+ }
245
+ });
246
+ return recursive;
247
+ }
248
+ function enhanceRouter(router, options) {
249
+ if (isLazy(router)) {
250
+ const laziedMeta = getLazyMeta(router);
251
+ const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
252
+ const enhanced2 = lazy(async () => {
253
+ const { default: unlaziedRouter } = await unlazy(router);
254
+ const enhanced3 = enhanceRouter(unlaziedRouter, options);
255
+ return unlazy(enhanced3);
256
+ }, {
257
+ ...laziedMeta,
258
+ prefix: enhancedPrefix
259
+ });
260
+ const accessible = createAccessibleLazyRouter(enhanced2);
261
+ return accessible;
262
+ }
263
+ if (isProcedure(router)) {
264
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, { dedupeLeading: options.dedupeLeadingMiddlewares });
265
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
266
+ const enhanced2 = new Procedure({
267
+ ...router["~orpc"],
268
+ route: enhanceRoute(router["~orpc"].route, options),
269
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
270
+ middlewares: newMiddlewares,
271
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
272
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
273
+ });
274
+ return enhanced2;
275
+ }
276
+ const enhanced = {};
277
+ for (const key in router) {
278
+ enhanced[key] = enhanceRouter(router[key], options);
279
+ }
280
+ return enhanced;
281
+ }
282
+ function traverseContractProcedures(options, callback, lazyOptions = []) {
283
+ let currentRouter = options.router;
284
+ const hiddenContract = getHiddenRouterContract(options.router);
285
+ if (hiddenContract !== void 0) {
286
+ currentRouter = hiddenContract;
287
+ }
288
+ if (isLazy(currentRouter)) {
289
+ lazyOptions.push({
290
+ router: currentRouter,
291
+ path: options.path
292
+ });
293
+ } else if (isContractProcedure(currentRouter)) {
294
+ callback({
295
+ contract: currentRouter,
296
+ path: options.path
297
+ });
298
+ } else {
299
+ for (const key in currentRouter) {
300
+ traverseContractProcedures(
301
+ {
302
+ router: currentRouter[key],
303
+ path: [...options.path, key]
304
+ },
305
+ callback,
306
+ lazyOptions
307
+ );
308
+ }
309
+ }
310
+ return lazyOptions;
311
+ }
312
+ async function resolveContractProcedures(options, callback) {
313
+ const pending = [options];
314
+ for (const options2 of pending) {
315
+ const lazyOptions = traverseContractProcedures(options2, callback);
316
+ for (const options3 of lazyOptions) {
317
+ const { default: router } = await unlazy(options3.router);
318
+ pending.push({
319
+ router,
320
+ path: options3.path
321
+ });
322
+ }
323
+ }
324
+ }
325
+ async function unlazyRouter(router) {
326
+ if (isProcedure(router)) {
327
+ return router;
328
+ }
329
+ const unlazied = {};
330
+ for (const key in router) {
331
+ const item = router[key];
332
+ const { default: unlaziedRouter } = await unlazy(item);
333
+ unlazied[key] = await unlazyRouter(unlaziedRouter);
334
+ }
335
+ return unlazied;
336
+ }
337
+
338
+ function createAssertedLazyProcedure(lazied) {
339
+ const lazyProcedure = lazy(async () => {
340
+ const { default: maybeProcedure } = await unlazy(lazied);
341
+ if (!isProcedure(maybeProcedure)) {
342
+ throw new Error(`
343
+ Expected a lazy<procedure> but got lazy<unknown>.
344
+ This should be caught by TypeScript compilation.
345
+ Please report this issue if this makes you feel uncomfortable.
346
+ `);
347
+ }
348
+ return { default: maybeProcedure };
349
+ }, getLazyMeta(lazied));
350
+ return lazyProcedure;
351
+ }
352
+ function createContractedProcedure(procedure, contract) {
353
+ return new Procedure({
354
+ ...procedure["~orpc"],
355
+ errorMap: contract["~orpc"].errorMap,
356
+ route: contract["~orpc"].route,
357
+ meta: contract["~orpc"].meta
358
+ });
359
+ }
360
+ function call(procedure, input, ...rest) {
361
+ return createProcedureClient(procedure, ...rest)(input);
362
+ }
363
+
364
+ export { LAZY_SYMBOL as L, Procedure as P, createContractedProcedure as a, addMiddleware as b, createProcedureClient as c, isLazy as d, enhanceRouter as e, createAssertedLazyProcedure as f, getRouter as g, createORPCErrorConstructorMap as h, isProcedure as i, getLazyMeta as j, middlewareOutputFn as k, lazy as l, mergeCurrentContext as m, isStartWithMiddlewares as n, mergeMiddlewares as o, call as p, getHiddenRouterContract as q, createAccessibleLazyRouter as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, validateORPCError as v, resolveContractProcedures as w, unlazyRouter as x };