@orpc/server 0.0.0-next.9ada823 → 0.0.0-next.9b13466

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 (59) hide show
  1. package/README.md +131 -0
  2. package/dist/adapters/fetch/index.d.mts +58 -0
  3. package/dist/adapters/fetch/index.d.ts +58 -0
  4. package/dist/adapters/fetch/index.mjs +105 -0
  5. package/dist/adapters/node/index.d.mts +57 -0
  6. package/dist/adapters/node/index.d.ts +57 -0
  7. package/dist/adapters/node/index.mjs +90 -0
  8. package/dist/adapters/standard/index.d.mts +26 -0
  9. package/dist/adapters/standard/index.d.ts +26 -0
  10. package/dist/adapters/standard/index.mjs +8 -0
  11. package/dist/index.d.mts +291 -0
  12. package/dist/index.d.ts +291 -0
  13. package/dist/index.mjs +363 -0
  14. package/dist/plugins/index.d.mts +124 -0
  15. package/dist/plugins/index.d.ts +124 -0
  16. package/dist/plugins/index.mjs +252 -0
  17. package/dist/shared/server.B5yVxwZh.d.mts +17 -0
  18. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  19. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  20. package/dist/shared/server.By38lRwX.d.ts +17 -0
  21. package/dist/shared/server.C37gDhSZ.mjs +364 -0
  22. package/dist/shared/server.ClO23hLW.d.mts +73 -0
  23. package/dist/shared/server.Cqam9L0P.d.mts +10 -0
  24. package/dist/shared/server.CuXY46Yy.d.ts +10 -0
  25. package/dist/shared/server.DFuJLDuo.mjs +190 -0
  26. package/dist/shared/server.DQJX4Gnf.d.mts +143 -0
  27. package/dist/shared/server.DQJX4Gnf.d.ts +143 -0
  28. package/dist/shared/server.DsVSuKTu.d.ts +73 -0
  29. package/package.json +29 -15
  30. package/dist/chunk-37HIYNDO.js +0 -182
  31. package/dist/fetch.js +0 -303
  32. package/dist/index.js +0 -518
  33. package/dist/src/builder.d.ts +0 -35
  34. package/dist/src/fetch/composite-handler.d.ts +0 -8
  35. package/dist/src/fetch/index.d.ts +0 -6
  36. package/dist/src/fetch/orpc-handler.d.ts +0 -20
  37. package/dist/src/fetch/orpc-payload-codec.d.ts +0 -11
  38. package/dist/src/fetch/orpc-procedure-matcher.d.ts +0 -12
  39. package/dist/src/fetch/super-json.d.ts +0 -12
  40. package/dist/src/fetch/types.d.ts +0 -16
  41. package/dist/src/hidden.d.ts +0 -6
  42. package/dist/src/implementer-chainable.d.ts +0 -10
  43. package/dist/src/index.d.ts +0 -23
  44. package/dist/src/lazy-decorated.d.ts +0 -10
  45. package/dist/src/lazy-utils.d.ts +0 -4
  46. package/dist/src/lazy.d.ts +0 -18
  47. package/dist/src/middleware-decorated.d.ts +0 -8
  48. package/dist/src/middleware.d.ts +0 -23
  49. package/dist/src/procedure-builder.d.ts +0 -22
  50. package/dist/src/procedure-client.d.ts +0 -34
  51. package/dist/src/procedure-decorated.d.ts +0 -14
  52. package/dist/src/procedure-implementer.d.ts +0 -18
  53. package/dist/src/procedure.d.ts +0 -23
  54. package/dist/src/router-builder.d.ts +0 -29
  55. package/dist/src/router-client.d.ts +0 -25
  56. package/dist/src/router-implementer.d.ts +0 -21
  57. package/dist/src/router.d.ts +0 -16
  58. package/dist/src/types.d.ts +0 -12
  59. package/dist/src/utils.d.ts +0 -3
@@ -0,0 +1,252 @@
1
+ import { value, isAsyncIteratorObject } from '@orpc/shared';
2
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
3
+ import { ORPCError } from '@orpc/client';
4
+ export { S as StrictGetMethodPlugin } from '../shared/server.BW-nUGgA.mjs';
5
+ import '@orpc/contract';
6
+
7
+ class BatchHandlerPlugin {
8
+ maxSize;
9
+ mapRequestItem;
10
+ successStatus;
11
+ headers;
12
+ order = 5e6;
13
+ constructor(options = {}) {
14
+ this.maxSize = options.maxSize ?? 10;
15
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
16
+ ...request,
17
+ headers: {
18
+ ...batchRequest.headers,
19
+ ...request.headers
20
+ }
21
+ }));
22
+ this.successStatus = options.successStatus ?? 207;
23
+ this.headers = options.headers ?? {};
24
+ }
25
+ init(options) {
26
+ options.rootInterceptors ??= [];
27
+ options.rootInterceptors.unshift(async (options2) => {
28
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
29
+ return options2.next();
30
+ }
31
+ let isParsing = false;
32
+ try {
33
+ isParsing = true;
34
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
35
+ isParsing = false;
36
+ const maxSize = await value(this.maxSize, options2);
37
+ if (parsed.length > maxSize) {
38
+ return {
39
+ matched: true,
40
+ response: {
41
+ status: 413,
42
+ headers: {},
43
+ body: "Batch request size exceeds the maximum allowed size"
44
+ }
45
+ };
46
+ }
47
+ const responses = parsed.map(
48
+ (request, index) => {
49
+ const mapped = this.mapRequestItem(request, options2);
50
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
51
+ if (matched) {
52
+ if (response2.body instanceof Blob || response2.body instanceof FormData || isAsyncIteratorObject(response2.body)) {
53
+ return {
54
+ index,
55
+ status: 500,
56
+ headers: {},
57
+ body: "Batch responses do not support file/blob, or event-iterator. Please call this procedure separately outside of the batch request."
58
+ };
59
+ }
60
+ return { ...response2, index };
61
+ }
62
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
63
+ }).catch(() => {
64
+ return { index, status: 500, headers: {}, body: "Internal server error" };
65
+ });
66
+ }
67
+ );
68
+ await Promise.race(responses);
69
+ const status = await value(this.successStatus, responses, options2);
70
+ const headers = await value(this.headers, responses, options2);
71
+ const response = toBatchResponse({
72
+ status,
73
+ headers,
74
+ body: async function* () {
75
+ const promises = [...responses];
76
+ while (true) {
77
+ const handling = promises.filter((p) => p !== void 0);
78
+ if (handling.length === 0) {
79
+ return;
80
+ }
81
+ const result = await Promise.race(handling);
82
+ promises[result.index] = void 0;
83
+ yield result;
84
+ }
85
+ }()
86
+ });
87
+ return {
88
+ matched: true,
89
+ response
90
+ };
91
+ } catch (cause) {
92
+ if (isParsing) {
93
+ return {
94
+ matched: true,
95
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
96
+ };
97
+ }
98
+ throw cause;
99
+ }
100
+ });
101
+ }
102
+ }
103
+
104
+ class CORSPlugin {
105
+ options;
106
+ order = 9e6;
107
+ constructor(options = {}) {
108
+ const defaults = {
109
+ origin: (origin) => origin,
110
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
111
+ };
112
+ this.options = {
113
+ ...defaults,
114
+ ...options
115
+ };
116
+ }
117
+ init(options) {
118
+ options.rootInterceptors ??= [];
119
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
120
+ if (interceptorOptions.request.method === "OPTIONS") {
121
+ const resHeaders = {};
122
+ if (this.options.maxAge !== void 0) {
123
+ resHeaders["access-control-max-age"] = this.options.maxAge.toString();
124
+ }
125
+ if (this.options.allowMethods?.length) {
126
+ resHeaders["access-control-allow-methods"] = this.options.allowMethods.join(",");
127
+ }
128
+ const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
129
+ if (Array.isArray(allowHeaders) && allowHeaders.length) {
130
+ resHeaders["access-control-allow-headers"] = allowHeaders.join(",");
131
+ } else if (typeof allowHeaders === "string") {
132
+ resHeaders["access-control-allow-headers"] = allowHeaders;
133
+ }
134
+ return {
135
+ matched: true,
136
+ response: {
137
+ status: 204,
138
+ headers: resHeaders,
139
+ body: void 0
140
+ }
141
+ };
142
+ }
143
+ return interceptorOptions.next();
144
+ });
145
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
146
+ const result = await interceptorOptions.next();
147
+ if (!result.matched) {
148
+ return result;
149
+ }
150
+ const origin = Array.isArray(interceptorOptions.request.headers.origin) ? interceptorOptions.request.headers.origin.join(",") : interceptorOptions.request.headers.origin || "";
151
+ const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
152
+ const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
153
+ if (allowedOriginArr.includes("*")) {
154
+ result.response.headers["access-control-allow-origin"] = "*";
155
+ } else {
156
+ if (allowedOriginArr.includes(origin)) {
157
+ result.response.headers["access-control-allow-origin"] = origin;
158
+ }
159
+ result.response.headers.vary = interceptorOptions.request.headers.vary ?? "origin";
160
+ }
161
+ const allowedTimingOrigin = await value(this.options.timingOrigin, origin, interceptorOptions);
162
+ const allowedTimingOriginArr = Array.isArray(allowedTimingOrigin) ? allowedTimingOrigin : [allowedTimingOrigin];
163
+ if (allowedTimingOriginArr.includes("*")) {
164
+ result.response.headers["timing-allow-origin"] = "*";
165
+ } else if (allowedTimingOriginArr.includes(origin)) {
166
+ result.response.headers["timing-allow-origin"] = origin;
167
+ }
168
+ if (this.options.credentials) {
169
+ result.response.headers["access-control-allow-credentials"] = "true";
170
+ }
171
+ if (this.options.exposeHeaders?.length) {
172
+ result.response.headers["access-control-expose-headers"] = this.options.exposeHeaders.join(",");
173
+ }
174
+ return result;
175
+ });
176
+ }
177
+ }
178
+
179
+ class ResponseHeadersPlugin {
180
+ init(options) {
181
+ options.rootInterceptors ??= [];
182
+ options.rootInterceptors.push(async (interceptorOptions) => {
183
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
184
+ const result = await interceptorOptions.next({
185
+ ...interceptorOptions,
186
+ context: {
187
+ ...interceptorOptions.context,
188
+ resHeaders
189
+ }
190
+ });
191
+ if (!result.matched) {
192
+ return result;
193
+ }
194
+ const responseHeaders = result.response.headers;
195
+ for (const [key, value] of resHeaders) {
196
+ if (Array.isArray(responseHeaders[key])) {
197
+ responseHeaders[key].push(value);
198
+ } else if (responseHeaders[key] !== void 0) {
199
+ responseHeaders[key] = [responseHeaders[key], value];
200
+ } else {
201
+ responseHeaders[key] = value;
202
+ }
203
+ }
204
+ return result;
205
+ });
206
+ }
207
+ }
208
+
209
+ const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
210
+ class SimpleCsrfProtectionHandlerPlugin {
211
+ headerName;
212
+ headerValue;
213
+ exclude;
214
+ error;
215
+ constructor(options = {}) {
216
+ this.headerName = options.headerName ?? "x-csrf-token";
217
+ this.headerValue = options.headerValue ?? "orpc";
218
+ this.exclude = options.exclude ?? false;
219
+ this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
220
+ status: 403,
221
+ message: "Invalid CSRF token"
222
+ });
223
+ }
224
+ order = 8e6;
225
+ init(options) {
226
+ options.rootInterceptors ??= [];
227
+ options.clientInterceptors ??= [];
228
+ options.rootInterceptors.unshift(async (options2) => {
229
+ const headerName = await value(this.headerName, options2);
230
+ const headerValue = await value(this.headerValue, options2);
231
+ return options2.next({
232
+ ...options2,
233
+ context: {
234
+ ...options2.context,
235
+ [SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers[headerName] === headerValue
236
+ }
237
+ });
238
+ });
239
+ options.clientInterceptors.unshift(async (options2) => {
240
+ if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
241
+ throw new TypeError("[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor");
242
+ }
243
+ const excluded = await value(this.exclude, options2);
244
+ if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
245
+ throw this.error;
246
+ }
247
+ return options2.next();
248
+ });
249
+ }
250
+ }
251
+
252
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin };
@@ -0,0 +1,17 @@
1
+ import { C as Context, R as Router } from './server.DQJX4Gnf.mjs';
2
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
3
+ import { b as StandardHandlerOptions, i as StandardHandler } from './server.ClO23hLW.mjs';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ /**
7
+ * Enables or disables the StrictGetMethodPlugin.
8
+ *
9
+ * @default true
10
+ */
11
+ strictGetMethodPluginEnabled?: boolean;
12
+ }
13
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
14
+ constructor(router: Router<any, T>, options: StandardRPCHandlerOptions<T>);
15
+ }
16
+
17
+ export { type StandardRPCHandlerOptions as S, StandardRPCHandler as a };
@@ -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,36 @@
1
+ import { ORPCError, fallbackContractConfig } from '@orpc/contract';
2
+
3
+ const STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL = Symbol("STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT");
4
+ class StrictGetMethodPlugin {
5
+ error;
6
+ order = 7e6;
7
+ constructor(options = {}) {
8
+ this.error = options.error ?? new ORPCError("METHOD_NOT_SUPPORTED");
9
+ }
10
+ init(options) {
11
+ options.rootInterceptors ??= [];
12
+ options.clientInterceptors ??= [];
13
+ options.rootInterceptors.unshift((options2) => {
14
+ const isGetMethod = options2.request.method === "GET";
15
+ return options2.next({
16
+ ...options2,
17
+ context: {
18
+ ...options2.context,
19
+ [STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL]: isGetMethod
20
+ }
21
+ });
22
+ });
23
+ options.clientInterceptors.unshift((options2) => {
24
+ if (typeof options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] !== "boolean") {
25
+ throw new TypeError("[StrictGetMethodPlugin] strict GET method context has been corrupted or modified by another plugin or interceptor");
26
+ }
27
+ const procedureMethod = fallbackContractConfig("defaultMethod", options2.procedure["~orpc"].route.method);
28
+ if (options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] && procedureMethod !== "GET") {
29
+ throw this.error;
30
+ }
31
+ return options2.next();
32
+ });
33
+ }
34
+ }
35
+
36
+ export { StrictGetMethodPlugin as S };
@@ -0,0 +1,17 @@
1
+ import { C as Context, R as Router } from './server.DQJX4Gnf.js';
2
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
3
+ import { b as StandardHandlerOptions, i as StandardHandler } from './server.DsVSuKTu.js';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ /**
7
+ * Enables or disables the StrictGetMethodPlugin.
8
+ *
9
+ * @default true
10
+ */
11
+ strictGetMethodPluginEnabled?: boolean;
12
+ }
13
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
14
+ constructor(router: Router<any, T>, options: StandardRPCHandlerOptions<T>);
15
+ }
16
+
17
+ export { type StandardRPCHandlerOptions as S, StandardRPCHandler as a };
@@ -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 };