@temporary-name/server 1.9.3-alpha.0d2fa3247b6b23bbc2e3097a95f631b86740e4d8 → 1.9.3-alpha.0f2e1f4d66464608b85c66977bff51174cbb238f

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 (39) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +12 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +12 -7
  3. package/dist/adapters/aws-lambda/index.mjs +12 -4
  4. package/dist/adapters/fetch/index.d.mts +12 -7
  5. package/dist/adapters/fetch/index.d.ts +12 -7
  6. package/dist/adapters/fetch/index.mjs +12 -11
  7. package/dist/adapters/node/index.d.mts +12 -7
  8. package/dist/adapters/node/index.d.ts +12 -7
  9. package/dist/adapters/node/index.mjs +12 -11
  10. package/dist/adapters/standard/index.d.mts +27 -13
  11. package/dist/adapters/standard/index.d.ts +27 -13
  12. package/dist/adapters/standard/index.mjs +8 -100
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +82 -459
  15. package/dist/index.d.ts +82 -459
  16. package/dist/index.mjs +213 -366
  17. package/dist/openapi/index.d.mts +220 -0
  18. package/dist/openapi/index.d.ts +220 -0
  19. package/dist/openapi/index.mjs +709 -0
  20. package/dist/plugins/index.d.mts +5 -83
  21. package/dist/plugins/index.d.ts +5 -83
  22. package/dist/plugins/index.mjs +17 -189
  23. package/dist/shared/{server.Btxrgkj5.d.ts → server.25yUS-xw.d.mts} +7 -25
  24. package/dist/shared/server.BKwU5-Ea.d.mts +23 -0
  25. package/dist/shared/server.C1RJffw4.mjs +30 -0
  26. package/dist/shared/{server.Bo94xDTv.d.mts → server.Co-zpS8Y.d.ts} +7 -25
  27. package/dist/shared/server.DRYRuXpK.mjs +254 -0
  28. package/dist/shared/server.DV_PWBS2.d.ts +23 -0
  29. package/dist/shared/server.DWEp52Gx.mjs +379 -0
  30. package/dist/shared/server.JtIZ8YG7.mjs +237 -0
  31. package/dist/shared/server.VtI8pLxV.d.mts +242 -0
  32. package/dist/shared/server.VtI8pLxV.d.ts +242 -0
  33. package/package.json +18 -23
  34. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  35. package/dist/shared/server.C1YnHvvf.d.mts +0 -192
  36. package/dist/shared/server.C1YnHvvf.d.ts +0 -192
  37. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  38. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  39. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
@@ -0,0 +1,254 @@
1
+ import { stringifyJSON, isObject, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, ORPCError, toORPCError } from '@temporary-name/shared';
2
+ import { c as createProcedureClient } from './server.DWEp52Gx.mjs';
3
+ import { fallbackContractConfig, standardizeHTTPPath } from '@temporary-name/contract';
4
+ import { d as deserialize, b as bracketNotationDeserialize, s as serialize } from './server.JtIZ8YG7.mjs';
5
+ import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@temporary-name/server';
6
+ import { createRouter, addRoute, findRoute } from 'rou3';
7
+
8
+ async function decode(request, pathParams) {
9
+ return {
10
+ path: pathParams ?? {},
11
+ query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
12
+ headers: request.headers,
13
+ body: deserialize(await request.body()) ?? {}
14
+ };
15
+ }
16
+ function encode(output, procedure) {
17
+ const successStatus = fallbackContractConfig(
18
+ "defaultSuccessStatus",
19
+ procedure["~orpc"].route.successStatus
20
+ );
21
+ const outputStructure = fallbackContractConfig(
22
+ "defaultOutputStructure",
23
+ procedure["~orpc"].route.outputStructure
24
+ );
25
+ if (outputStructure === "compact") {
26
+ return {
27
+ status: successStatus,
28
+ headers: new Headers(),
29
+ body: serialize(output)
30
+ };
31
+ }
32
+ if (!isDetailedOutput(output)) {
33
+ throw new Error(`
34
+ Invalid "detailed" output structure:
35
+ \u2022 Expected an object with optional properties:
36
+ - status (number 200-399)
37
+ - headers (Record<string, string | string[]>)
38
+ - body (any)
39
+ \u2022 No extra keys allowed.
40
+
41
+ Actual value:
42
+ ${stringifyJSON(output)}
43
+ `);
44
+ }
45
+ return {
46
+ status: output.status ?? successStatus,
47
+ headers: output.headers ?? new Headers(),
48
+ body: serialize(output.body)
49
+ };
50
+ }
51
+ function encodeError(error) {
52
+ return {
53
+ status: error.status,
54
+ headers: new Headers(),
55
+ body: serialize(error.toJSON(), { outputFormat: "plain" })
56
+ };
57
+ }
58
+ function isDetailedOutput(output) {
59
+ if (!isObject(output)) {
60
+ return false;
61
+ }
62
+ if (output.headers && !isObject(output.headers)) {
63
+ return false;
64
+ }
65
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+
71
+ function resolveFriendlyStandardHandleOptions(options) {
72
+ return {
73
+ ...options,
74
+ context: options.context ?? {}
75
+ // Context only optional if all fields are optional
76
+ };
77
+ }
78
+ function toRou3Pattern(path) {
79
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
80
+ }
81
+ function decodeParams(params) {
82
+ return Object.fromEntries(
83
+ Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
84
+ );
85
+ }
86
+
87
+ class StandardOpenAPIMatcher {
88
+ tree = createRouter();
89
+ pendingRouters = [];
90
+ init(router, path = []) {
91
+ const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
92
+ const { path: path2, contract } = traverseOptions;
93
+ const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
94
+ const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
95
+ if (isProcedure(contract)) {
96
+ addRoute(this.tree, method, httpPath, {
97
+ path: path2,
98
+ contract,
99
+ procedure: contract,
100
+ // this mean dev not used contract-first so we can used contract as procedure directly
101
+ router
102
+ });
103
+ } else {
104
+ addRoute(this.tree, method, httpPath, {
105
+ path: path2,
106
+ contract,
107
+ procedure: void 0,
108
+ router
109
+ });
110
+ }
111
+ });
112
+ this.pendingRouters.push(
113
+ ...laziedOptions.map((option) => ({
114
+ ...option,
115
+ httpPathPrefix: toHttpPath(option.path),
116
+ laziedPrefix: getLazyMeta(option.router).prefix
117
+ }))
118
+ );
119
+ }
120
+ async match(method, pathname) {
121
+ if (this.pendingRouters.length) {
122
+ const newPendingRouters = [];
123
+ for (const pendingRouter of this.pendingRouters) {
124
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
125
+ const { default: router } = await unlazy(pendingRouter.router);
126
+ this.init(router, pendingRouter.path);
127
+ } else {
128
+ newPendingRouters.push(pendingRouter);
129
+ }
130
+ }
131
+ this.pendingRouters = newPendingRouters;
132
+ }
133
+ const match = findRoute(this.tree, method, pathname);
134
+ if (!match) {
135
+ return void 0;
136
+ }
137
+ if (!match.data.procedure) {
138
+ const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
139
+ if (!isProcedure(maybeProcedure)) {
140
+ throw new Error(`
141
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
142
+ Ensure that the procedure is correctly defined and matches the expected contract.
143
+ `);
144
+ }
145
+ match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
146
+ }
147
+ return {
148
+ path: match.data.path,
149
+ procedure: match.data.procedure,
150
+ params: match.params ? decodeParams(match.params) : void 0
151
+ };
152
+ }
153
+ }
154
+
155
+ class CompositeStandardHandlerPlugin {
156
+ plugins;
157
+ constructor(plugins = []) {
158
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
159
+ }
160
+ init(options, router) {
161
+ for (const plugin of this.plugins) {
162
+ plugin.init?.(options, router);
163
+ }
164
+ }
165
+ }
166
+
167
+ class StandardHandler {
168
+ interceptors;
169
+ clientInterceptors;
170
+ rootInterceptors;
171
+ matcher;
172
+ constructor(router, options) {
173
+ this.matcher = new StandardOpenAPIMatcher();
174
+ const plugins = new CompositeStandardHandlerPlugin(options.plugins);
175
+ plugins.init(options, router);
176
+ this.interceptors = toArray(options.interceptors);
177
+ this.clientInterceptors = toArray(options.clientInterceptors);
178
+ this.rootInterceptors = toArray(options.rootInterceptors);
179
+ this.matcher.init(router);
180
+ }
181
+ async handle(request, options) {
182
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
183
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
184
+ return { matched: false, response: void 0 };
185
+ }
186
+ return intercept(this.rootInterceptors, { ...options, request, prefix }, async (interceptorOptions) => {
187
+ return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
188
+ let step;
189
+ try {
190
+ return await intercept(
191
+ this.interceptors,
192
+ interceptorOptions,
193
+ async ({ request: request2, context, prefix: prefix2 }) => {
194
+ const method = request2.method;
195
+ const url = request2.url;
196
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
197
+ const match = await runWithSpan(
198
+ { name: "find_procedure" },
199
+ () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
200
+ );
201
+ if (!match) {
202
+ return { matched: false, response: void 0 };
203
+ }
204
+ span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
205
+ span?.setAttribute("rpc.system", ORPC_NAME);
206
+ span?.setAttribute("rpc.method", match.path.join("."));
207
+ step = "decode_input";
208
+ const input = await runWithSpan({ name: "decode_input" }, () => decode(request2, match.params));
209
+ step = void 0;
210
+ if (isAsyncIteratorObject(input.body)) {
211
+ input.body = asyncIteratorWithSpan(
212
+ { name: "consume_event_iterator_input", signal: request2.signal },
213
+ input.body
214
+ );
215
+ }
216
+ const client = createProcedureClient(match.procedure, {
217
+ context,
218
+ path: match.path,
219
+ interceptors: this.clientInterceptors
220
+ });
221
+ step = "call_procedure";
222
+ const output = await client(input, {
223
+ request: request2,
224
+ signal: request2.signal,
225
+ lastEventId: request2.headers.get("last-event-id") ?? void 0
226
+ });
227
+ step = void 0;
228
+ const response = encode(output, match.procedure);
229
+ return {
230
+ matched: true,
231
+ response
232
+ };
233
+ }
234
+ );
235
+ } catch (e) {
236
+ if (step !== "call_procedure") {
237
+ setSpanError(span, e);
238
+ }
239
+ const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
240
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
241
+ cause: e
242
+ }) : toORPCError(e);
243
+ const response = encodeError(error);
244
+ return {
245
+ matched: true,
246
+ response
247
+ };
248
+ }
249
+ });
250
+ });
251
+ }
252
+ }
253
+
254
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
@@ -0,0 +1,23 @@
1
+ import { HTTPPath } from '@temporary-name/shared';
2
+ import { C as Context } from './server.VtI8pLxV.js';
3
+ import { c as StandardHandleOptions } from './server.Co-zpS8Y.js';
4
+
5
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
6
+ context?: T;
7
+ } : {
8
+ context: T;
9
+ });
10
+ declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
11
+ /**
12
+ * {@link https://github.com/unjs/rou3}
13
+ *
14
+ * @internal
15
+ */
16
+ declare function toRou3Pattern(path: HTTPPath): string;
17
+ /**
18
+ * @internal
19
+ */
20
+ declare function decodeParams(params: Record<string, string>): Record<string, string>;
21
+
22
+ export { decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
23
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,379 @@
1
+ import { isContractProcedure, mergePrefix, enhanceRoute, ValidationError } from '@temporary-name/contract';
2
+ import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan, ORPCError } from '@temporary-name/shared';
3
+ import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
4
+ import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
5
+
6
+ function isStartWithMiddlewares(middlewares, compare) {
7
+ if (compare.length > middlewares.length) {
8
+ return false;
9
+ }
10
+ for (let i = 0; i < middlewares.length; i++) {
11
+ if (compare[i] === void 0) {
12
+ return true;
13
+ }
14
+ if (middlewares[i] !== compare[i]) {
15
+ return false;
16
+ }
17
+ }
18
+ return true;
19
+ }
20
+ function mergeMiddlewares(first, second, options) {
21
+ if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
22
+ return second;
23
+ }
24
+ return [...first, ...second];
25
+ }
26
+ function addMiddleware(middlewares, addition) {
27
+ return [...middlewares, addition];
28
+ }
29
+
30
+ class Procedure {
31
+ /**
32
+ * This property holds the defined options.
33
+ */
34
+ "~orpc";
35
+ constructor(def) {
36
+ this["~orpc"] = def;
37
+ }
38
+ }
39
+ function isProcedure(item) {
40
+ if (item instanceof Procedure) {
41
+ return true;
42
+ }
43
+ return isContractProcedure(item) && "middlewares" in item["~orpc"] && "handler" in item["~orpc"];
44
+ }
45
+
46
+ function mergeCurrentContext(context, other) {
47
+ return { ...context, ...other };
48
+ }
49
+
50
+ const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
51
+ function setHiddenRouterContract(router, contract) {
52
+ return new Proxy(router, {
53
+ get(target, key) {
54
+ if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
55
+ return contract;
56
+ }
57
+ return Reflect.get(target, key);
58
+ }
59
+ });
60
+ }
61
+ function getHiddenRouterContract(router) {
62
+ return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
63
+ }
64
+
65
+ function getRouter(router, path) {
66
+ let current = router;
67
+ for (let i = 0; i < path.length; i++) {
68
+ const segment = path[i];
69
+ if (!current) {
70
+ return void 0;
71
+ }
72
+ if (isProcedure(current)) {
73
+ return void 0;
74
+ }
75
+ if (!isLazy(current)) {
76
+ current = current[segment];
77
+ continue;
78
+ }
79
+ const lazied = current;
80
+ const rest = path.slice(i);
81
+ return lazyInternal(async () => {
82
+ const unwrapped = await unlazy(lazied);
83
+ const next = getRouter(unwrapped.default, rest);
84
+ return unlazy(next);
85
+ }, getLazyMeta(lazied));
86
+ }
87
+ return current;
88
+ }
89
+ function createAccessibleLazyRouter(lazied) {
90
+ const recursive = new Proxy(lazied, {
91
+ get(target, key) {
92
+ if (typeof key !== "string") {
93
+ return Reflect.get(target, key);
94
+ }
95
+ const next = getRouter(lazied, [key]);
96
+ return createAccessibleLazyRouter(next);
97
+ }
98
+ });
99
+ return recursive;
100
+ }
101
+ function enhanceRouter(router, options) {
102
+ if (isLazy(router)) {
103
+ const laziedMeta = getLazyMeta(router);
104
+ const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
105
+ const enhanced2 = lazyInternal(
106
+ async () => {
107
+ const { default: unlaziedRouter } = await unlazy(router);
108
+ const enhanced3 = enhanceRouter(unlaziedRouter, options);
109
+ return unlazy(enhanced3);
110
+ },
111
+ {
112
+ ...laziedMeta,
113
+ prefix: enhancedPrefix
114
+ }
115
+ );
116
+ const accessible = createAccessibleLazyRouter(enhanced2);
117
+ return accessible;
118
+ }
119
+ if (isProcedure(router)) {
120
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
121
+ dedupeLeading: options.dedupeLeadingMiddlewares
122
+ });
123
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
124
+ const enhanced2 = new Procedure({
125
+ ...router["~orpc"],
126
+ route: enhanceRoute(router["~orpc"].route, options),
127
+ middlewares: newMiddlewares,
128
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
129
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
130
+ });
131
+ return enhanced2;
132
+ }
133
+ const enhanced = {};
134
+ for (const key in router) {
135
+ enhanced[key] = enhanceRouter(router[key], options);
136
+ }
137
+ return enhanced;
138
+ }
139
+ function traverseContractProcedures(options, callback, lazyOptions = []) {
140
+ let currentRouter = options.router;
141
+ const hiddenContract = getHiddenRouterContract(options.router);
142
+ if (hiddenContract !== void 0) {
143
+ currentRouter = hiddenContract;
144
+ }
145
+ if (isLazy(currentRouter)) {
146
+ lazyOptions.push({
147
+ router: currentRouter,
148
+ path: options.path
149
+ });
150
+ } else if (isContractProcedure(currentRouter)) {
151
+ callback({
152
+ contract: currentRouter,
153
+ path: options.path
154
+ });
155
+ } else {
156
+ for (const key in currentRouter) {
157
+ traverseContractProcedures(
158
+ {
159
+ router: currentRouter[key],
160
+ path: [...options.path, key]
161
+ },
162
+ callback,
163
+ lazyOptions
164
+ );
165
+ }
166
+ }
167
+ return lazyOptions;
168
+ }
169
+ async function resolveContractProcedures(options, callback) {
170
+ const pending = [options];
171
+ for (const options2 of pending) {
172
+ const lazyOptions = traverseContractProcedures(options2, callback);
173
+ for (const options3 of lazyOptions) {
174
+ const { default: router } = await unlazy(options3.router);
175
+ pending.push({
176
+ router,
177
+ path: options3.path
178
+ });
179
+ }
180
+ }
181
+ }
182
+ async function unlazyRouter(router) {
183
+ if (isProcedure(router)) {
184
+ return router;
185
+ }
186
+ const unlazied = {};
187
+ for (const key in router) {
188
+ const item = router[key];
189
+ const { default: unlaziedRouter } = await unlazy(item);
190
+ unlazied[key] = await unlazyRouter(unlaziedRouter);
191
+ }
192
+ return unlazied;
193
+ }
194
+
195
+ const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
196
+ function lazyInternal(loader, meta = {}) {
197
+ return {
198
+ [LAZY_SYMBOL]: {
199
+ loader,
200
+ meta
201
+ }
202
+ };
203
+ }
204
+ function lazy(prefix, loader) {
205
+ return enhanceRouter(lazyInternal(loader), {
206
+ middlewares: [],
207
+ dedupeLeadingMiddlewares: true,
208
+ prefix
209
+ });
210
+ }
211
+ function isLazy(item) {
212
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
213
+ }
214
+ function getLazyMeta(lazied) {
215
+ return lazied[LAZY_SYMBOL].meta;
216
+ }
217
+ function unlazy(lazied) {
218
+ return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
219
+ }
220
+
221
+ function middlewareOutputFn(output) {
222
+ return { output, context: {} };
223
+ }
224
+
225
+ function createProcedureClient(lazyableProcedure, ...rest) {
226
+ const options = resolveMaybeOptionalOptions(rest);
227
+ return async (...[input, callerOptions]) => {
228
+ const path = toArray(options.path);
229
+ const { default: procedure } = await unlazy(lazyableProcedure);
230
+ const clientContext = callerOptions?.context ?? {};
231
+ const context = await value(options.context ?? {}, clientContext);
232
+ const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
233
+ span?.setAttribute("procedure.path", [...path]);
234
+ return intercept(
235
+ toArray(options.interceptors),
236
+ {
237
+ context,
238
+ input,
239
+ path,
240
+ procedure,
241
+ request: callerOptions?.request,
242
+ signal: callerOptions?.signal,
243
+ lastEventId: callerOptions?.lastEventId
244
+ },
245
+ (interceptorOptions) => {
246
+ const { input: input2, ...opts } = interceptorOptions;
247
+ return executeProcedureInternal(interceptorOptions.procedure, input2, opts);
248
+ }
249
+ );
250
+ });
251
+ if (isAsyncIteratorObject(output)) {
252
+ if (output instanceof HibernationEventIterator) {
253
+ return output;
254
+ }
255
+ return overlayProxy(
256
+ output,
257
+ mapEventIterator(
258
+ asyncIteratorWithSpan(
259
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
260
+ output
261
+ ),
262
+ {
263
+ value: (v) => v,
264
+ error: async (e) => e
265
+ }
266
+ )
267
+ );
268
+ }
269
+ return output;
270
+ };
271
+ }
272
+ async function validateInput(procedure, input) {
273
+ const schemas = procedure["~orpc"].schemas;
274
+ return runWithSpan({ name: "validate_input" }, async () => {
275
+ const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, { parseType: "body" });
276
+ const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, { parseType: "path" });
277
+ const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, { parseType: "query" });
278
+ const issues = [];
279
+ if (!resultBody.success) {
280
+ issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
281
+ }
282
+ if (!resultPath.success) {
283
+ issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
284
+ }
285
+ if (!resultQuery.success) {
286
+ issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
287
+ }
288
+ if (issues.length > 0) {
289
+ throw new ORPCError("BAD_REQUEST", {
290
+ message: "Input validation failed",
291
+ data: {
292
+ issues
293
+ },
294
+ cause: new ValidationError({
295
+ message: "Input validation failed",
296
+ issues,
297
+ data: input
298
+ })
299
+ });
300
+ }
301
+ const results = {
302
+ body: resultBody.data,
303
+ path: resultPath.data,
304
+ query: resultQuery.data
305
+ };
306
+ return results;
307
+ });
308
+ }
309
+ async function validateOutput(procedure, output) {
310
+ const schema = procedure["~orpc"].schemas.outputSchema;
311
+ if (!schema) {
312
+ return output;
313
+ }
314
+ return runWithSpan({ name: "validate_output" }, async () => {
315
+ const result = await safeEncodeAsync(schema, output, { parseType: "output" });
316
+ if (!result.success) {
317
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
318
+ message: "Output validation failed",
319
+ cause: new ValidationError({
320
+ message: "Output validation failed",
321
+ issues: result.error.issues,
322
+ data: output
323
+ })
324
+ });
325
+ }
326
+ return result.data;
327
+ });
328
+ }
329
+ async function executeProcedureInternal(procedure, input, options) {
330
+ const middlewares = procedure["~orpc"].middlewares;
331
+ const inputValidationIndex = Math.min(
332
+ Math.max(0, procedure["~orpc"].inputValidationIndex),
333
+ middlewares.length
334
+ );
335
+ const outputValidationIndex = Math.min(
336
+ Math.max(0, procedure["~orpc"].outputValidationIndex),
337
+ middlewares.length
338
+ );
339
+ const next = async (index, context, input2) => {
340
+ let currentInput = input2;
341
+ if (index === inputValidationIndex) {
342
+ currentInput = await validateInput(procedure, currentInput);
343
+ }
344
+ const mid = middlewares[index];
345
+ const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
346
+ span?.setAttribute("middleware.index", index);
347
+ span?.setAttribute("middleware.name", mid.name);
348
+ const result = await mid(
349
+ {
350
+ ...options,
351
+ context,
352
+ next: async (...[nextOptions]) => {
353
+ const nextContext = nextOptions?.context ?? {};
354
+ return {
355
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
356
+ // NB: Pretty sure this isn't used (or meant to be used) at runtime, it's just there
357
+ // to get type inference in the builder (via the caller returning the output of next() in
358
+ // the middleware function)
359
+ context: nextContext
360
+ };
361
+ }
362
+ },
363
+ currentInput,
364
+ middlewareOutputFn
365
+ );
366
+ return result.output;
367
+ }) : await runWithSpan(
368
+ { name: "handler", signal: options.signal },
369
+ () => procedure["~orpc"].handler(currentInput, { ...options, context })
370
+ );
371
+ if (index === outputValidationIndex) {
372
+ return await validateOutput(procedure, output);
373
+ }
374
+ return output;
375
+ };
376
+ return next(0, options.context, input);
377
+ }
378
+
379
+ export { LAZY_SYMBOL as L, Procedure as P, addMiddleware as a, isLazy as b, createProcedureClient as c, getRouter as d, enhanceRouter as e, lazy as f, getLazyMeta as g, middlewareOutputFn as h, isProcedure as i, isStartWithMiddlewares as j, mergeMiddlewares as k, lazyInternal as l, mergeCurrentContext as m, getHiddenRouterContract as n, createAccessibleLazyRouter as o, unlazyRouter as p, resolveContractProcedures as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u };