@orpc/server 0.0.0-next.83ec2e8 → 0.0.0-next.842d6b5
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.
- package/README.md +127 -0
- package/dist/adapters/aws-lambda/index.d.mts +46 -0
- package/dist/adapters/aws-lambda/index.d.ts +46 -0
- package/dist/adapters/aws-lambda/index.mjs +42 -0
- package/dist/adapters/bun-ws/index.d.mts +36 -0
- package/dist/adapters/bun-ws/index.d.ts +36 -0
- package/dist/adapters/bun-ws/index.mjs +47 -0
- package/dist/adapters/crossws/index.d.mts +33 -0
- package/dist/adapters/crossws/index.d.ts +33 -0
- package/dist/adapters/crossws/index.mjs +45 -0
- package/dist/adapters/fetch/index.d.mts +79 -0
- package/dist/adapters/fetch/index.d.ts +79 -0
- package/dist/adapters/fetch/index.mjs +110 -0
- package/dist/adapters/message-port/index.d.mts +31 -0
- package/dist/adapters/message-port/index.d.ts +31 -0
- package/dist/adapters/message-port/index.mjs +39 -0
- package/dist/adapters/node/index.d.mts +78 -0
- package/dist/adapters/node/index.d.ts +78 -0
- package/dist/adapters/node/index.mjs +96 -0
- package/dist/adapters/standard/index.d.mts +21 -0
- package/dist/adapters/standard/index.d.ts +21 -0
- package/dist/adapters/standard/index.mjs +8 -0
- package/dist/adapters/standard-peer/index.d.mts +18 -0
- package/dist/adapters/standard-peer/index.d.ts +18 -0
- package/dist/adapters/standard-peer/index.mjs +7 -0
- package/dist/adapters/websocket/index.d.mts +54 -0
- package/dist/adapters/websocket/index.d.ts +54 -0
- package/dist/adapters/websocket/index.mjs +67 -0
- package/dist/adapters/ws/index.d.mts +31 -0
- package/dist/adapters/ws/index.d.ts +31 -0
- package/dist/adapters/ws/index.mjs +37 -0
- package/dist/helpers/index.d.mts +134 -0
- package/dist/helpers/index.d.ts +134 -0
- package/dist/helpers/index.mjs +188 -0
- package/dist/hibernation/index.d.mts +44 -0
- package/dist/hibernation/index.d.ts +44 -0
- package/dist/hibernation/index.mjs +65 -0
- package/dist/index.d.mts +803 -0
- package/dist/index.d.ts +803 -0
- package/dist/index.mjs +489 -0
- package/dist/plugins/index.d.mts +169 -0
- package/dist/plugins/index.d.ts +169 -0
- package/dist/plugins/index.mjs +285 -0
- package/dist/shared/server.B7b2w3_i.d.ts +12 -0
- package/dist/shared/server.BEFBl-Cb.d.mts +12 -0
- package/dist/shared/server.BU4WI18A.d.mts +32 -0
- package/dist/shared/server.BW-nUGgA.mjs +36 -0
- package/dist/shared/server.Bmh5xd4n.d.ts +74 -0
- package/dist/shared/server.BohymmQ6.mjs +219 -0
- package/dist/shared/server.CQr6WNc2.mjs +408 -0
- package/dist/shared/server.CYNGeoCm.d.mts +194 -0
- package/dist/shared/server.CYNGeoCm.d.ts +194 -0
- package/dist/shared/server.D0H-iaY3.d.ts +32 -0
- package/dist/shared/server.DZ5BIITo.mjs +9 -0
- package/dist/shared/server.DhJj-1X9.d.mts +42 -0
- package/dist/shared/server.UVMTOWrk.mjs +26 -0
- package/dist/shared/server.gqRxT-yN.d.mts +74 -0
- package/dist/shared/server.jMTkVNIb.d.ts +42 -0
- package/package.json +94 -19
- package/dist/chunk-TDFYNRZV.js +0 -190
- package/dist/chunk-TDFYNRZV.js.map +0 -1
- package/dist/fetch.js +0 -681
- package/dist/fetch.js.map +0 -1
- package/dist/index.js +0 -394
- package/dist/index.js.map +0 -1
- package/dist/src/adapters/fetch.d.ts +0 -42
- package/dist/src/adapters/fetch.d.ts.map +0 -1
- package/dist/src/builder.d.ts +0 -49
- package/dist/src/builder.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -15
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/middleware.d.ts +0 -26
- package/dist/src/middleware.d.ts.map +0 -1
- package/dist/src/procedure-builder.d.ts +0 -31
- package/dist/src/procedure-builder.d.ts.map +0 -1
- package/dist/src/procedure-caller.d.ts +0 -19
- package/dist/src/procedure-caller.d.ts.map +0 -1
- package/dist/src/procedure-implementer.d.ts +0 -18
- package/dist/src/procedure-implementer.d.ts.map +0 -1
- package/dist/src/procedure.d.ts +0 -29
- package/dist/src/procedure.d.ts.map +0 -1
- package/dist/src/router-builder.d.ts +0 -22
- package/dist/src/router-builder.d.ts.map +0 -1
- package/dist/src/router-caller.d.ts +0 -22
- package/dist/src/router-caller.d.ts.map +0 -1
- package/dist/src/router-implementer.d.ts +0 -20
- package/dist/src/router-implementer.d.ts.map +0 -1
- package/dist/src/router.d.ts +0 -20
- package/dist/src/router.d.ts.map +0 -1
- package/dist/src/types.d.ts +0 -8
- package/dist/src/types.d.ts.map +0 -1
- package/dist/src/utils.d.ts +0 -3
- package/dist/src/utils.d.ts.map +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
- package/src/adapters/fetch.test.ts +0 -629
- package/src/adapters/fetch.ts +0 -290
- package/src/builder.test.ts +0 -371
- package/src/builder.ts +0 -238
- package/src/index.ts +0 -16
- package/src/middleware.test.ts +0 -260
- package/src/middleware.ts +0 -136
- package/src/procedure-builder.test.ts +0 -223
- package/src/procedure-builder.ts +0 -158
- package/src/procedure-caller.test.ts +0 -171
- package/src/procedure-caller.ts +0 -138
- package/src/procedure-implementer.test.ts +0 -220
- package/src/procedure-implementer.ts +0 -102
- package/src/procedure.test.ts +0 -317
- package/src/procedure.ts +0 -237
- package/src/router-builder.test.ts +0 -106
- package/src/router-builder.ts +0 -122
- package/src/router-caller.test.ts +0 -126
- package/src/router-caller.ts +0 -64
- package/src/router-implementer.test.ts +0 -116
- package/src/router-implementer.ts +0 -113
- package/src/router.test-d.ts +0 -48
- package/src/router.test.ts +0 -142
- package/src/router.ts +0 -91
- package/src/types.test.ts +0 -18
- package/src/types.ts +0 -13
- package/src/utils.test.ts +0 -16
- package/src/utils.ts +0 -16
@@ -0,0 +1,219 @@
|
|
1
|
+
import { toHttpPath, StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
|
2
|
+
import { ORPCError, toORPCError } from '@orpc/client';
|
3
|
+
import { toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, parseEmptyableJSON, NullProtoObj, value } from '@orpc/shared';
|
4
|
+
import { flattenHeader } from '@orpc/standard-server';
|
5
|
+
import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.CQr6WNc2.mjs';
|
6
|
+
|
7
|
+
class CompositeStandardHandlerPlugin {
|
8
|
+
plugins;
|
9
|
+
constructor(plugins = []) {
|
10
|
+
this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
11
|
+
}
|
12
|
+
init(options, router) {
|
13
|
+
for (const plugin of this.plugins) {
|
14
|
+
plugin.init?.(options, router);
|
15
|
+
}
|
16
|
+
}
|
17
|
+
}
|
18
|
+
|
19
|
+
class StandardHandler {
|
20
|
+
constructor(router, matcher, codec, options) {
|
21
|
+
this.matcher = matcher;
|
22
|
+
this.codec = codec;
|
23
|
+
const plugins = new CompositeStandardHandlerPlugin(options.plugins);
|
24
|
+
plugins.init(options, router);
|
25
|
+
this.interceptors = toArray(options.interceptors);
|
26
|
+
this.clientInterceptors = toArray(options.clientInterceptors);
|
27
|
+
this.rootInterceptors = toArray(options.rootInterceptors);
|
28
|
+
this.matcher.init(router);
|
29
|
+
}
|
30
|
+
interceptors;
|
31
|
+
clientInterceptors;
|
32
|
+
rootInterceptors;
|
33
|
+
async handle(request, options) {
|
34
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
35
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
36
|
+
return { matched: false, response: void 0 };
|
37
|
+
}
|
38
|
+
return intercept(
|
39
|
+
this.rootInterceptors,
|
40
|
+
{ ...options, request, prefix },
|
41
|
+
async (interceptorOptions) => {
|
42
|
+
return runWithSpan(
|
43
|
+
{ name: `${request.method} ${request.url.pathname}` },
|
44
|
+
async (span) => {
|
45
|
+
let step;
|
46
|
+
try {
|
47
|
+
return await intercept(
|
48
|
+
this.interceptors,
|
49
|
+
interceptorOptions,
|
50
|
+
async ({ request: request2, context, prefix: prefix2 }) => {
|
51
|
+
const method = request2.method;
|
52
|
+
const url = request2.url;
|
53
|
+
const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
|
54
|
+
const match = await runWithSpan(
|
55
|
+
{ name: "find_procedure" },
|
56
|
+
() => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
|
57
|
+
);
|
58
|
+
if (!match) {
|
59
|
+
return { matched: false, response: void 0 };
|
60
|
+
}
|
61
|
+
span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
|
62
|
+
span?.setAttribute("rpc.system", ORPC_NAME);
|
63
|
+
span?.setAttribute("rpc.method", match.path.join("."));
|
64
|
+
step = "decode_input";
|
65
|
+
let input = await runWithSpan(
|
66
|
+
{ name: "decode_input" },
|
67
|
+
() => this.codec.decode(request2, match.params, match.procedure)
|
68
|
+
);
|
69
|
+
step = void 0;
|
70
|
+
if (isAsyncIteratorObject(input)) {
|
71
|
+
input = asyncIteratorWithSpan(
|
72
|
+
{ name: "consume_event_iterator_input", signal: request2.signal },
|
73
|
+
input
|
74
|
+
);
|
75
|
+
}
|
76
|
+
const client = createProcedureClient(match.procedure, {
|
77
|
+
context,
|
78
|
+
path: match.path,
|
79
|
+
interceptors: this.clientInterceptors
|
80
|
+
});
|
81
|
+
step = "call_procedure";
|
82
|
+
const output = await client(input, {
|
83
|
+
signal: request2.signal,
|
84
|
+
lastEventId: flattenHeader(request2.headers["last-event-id"])
|
85
|
+
});
|
86
|
+
step = void 0;
|
87
|
+
const response = this.codec.encode(output, match.procedure);
|
88
|
+
return {
|
89
|
+
matched: true,
|
90
|
+
response
|
91
|
+
};
|
92
|
+
}
|
93
|
+
);
|
94
|
+
} catch (e) {
|
95
|
+
if (step !== "call_procedure") {
|
96
|
+
setSpanError(span, e);
|
97
|
+
}
|
98
|
+
const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
|
99
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
100
|
+
cause: e
|
101
|
+
}) : toORPCError(e);
|
102
|
+
const response = this.codec.encodeError(error);
|
103
|
+
return {
|
104
|
+
matched: true,
|
105
|
+
response
|
106
|
+
};
|
107
|
+
}
|
108
|
+
}
|
109
|
+
);
|
110
|
+
}
|
111
|
+
);
|
112
|
+
}
|
113
|
+
}
|
114
|
+
|
115
|
+
class StandardRPCCodec {
|
116
|
+
constructor(serializer) {
|
117
|
+
this.serializer = serializer;
|
118
|
+
}
|
119
|
+
async decode(request, _params, _procedure) {
|
120
|
+
const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
|
121
|
+
return this.serializer.deserialize(serialized);
|
122
|
+
}
|
123
|
+
encode(output, _procedure) {
|
124
|
+
return {
|
125
|
+
status: 200,
|
126
|
+
headers: {},
|
127
|
+
body: this.serializer.serialize(output)
|
128
|
+
};
|
129
|
+
}
|
130
|
+
encodeError(error) {
|
131
|
+
return {
|
132
|
+
status: error.status,
|
133
|
+
headers: {},
|
134
|
+
body: this.serializer.serialize(error.toJSON())
|
135
|
+
};
|
136
|
+
}
|
137
|
+
}
|
138
|
+
|
139
|
+
class StandardRPCMatcher {
|
140
|
+
filter;
|
141
|
+
tree = new NullProtoObj();
|
142
|
+
pendingRouters = [];
|
143
|
+
constructor(options = {}) {
|
144
|
+
this.filter = options.filter ?? true;
|
145
|
+
}
|
146
|
+
init(router, path = []) {
|
147
|
+
const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
|
148
|
+
if (!value(this.filter, traverseOptions)) {
|
149
|
+
return;
|
150
|
+
}
|
151
|
+
const { path: path2, contract } = traverseOptions;
|
152
|
+
const httpPath = toHttpPath(path2);
|
153
|
+
if (isProcedure(contract)) {
|
154
|
+
this.tree[httpPath] = {
|
155
|
+
path: path2,
|
156
|
+
contract,
|
157
|
+
procedure: contract,
|
158
|
+
// this mean dev not used contract-first so we can used contract as procedure directly
|
159
|
+
router
|
160
|
+
};
|
161
|
+
} else {
|
162
|
+
this.tree[httpPath] = {
|
163
|
+
path: path2,
|
164
|
+
contract,
|
165
|
+
procedure: void 0,
|
166
|
+
router
|
167
|
+
};
|
168
|
+
}
|
169
|
+
});
|
170
|
+
this.pendingRouters.push(...laziedOptions.map((option) => ({
|
171
|
+
...option,
|
172
|
+
httpPathPrefix: toHttpPath(option.path)
|
173
|
+
})));
|
174
|
+
}
|
175
|
+
async match(_method, pathname) {
|
176
|
+
if (this.pendingRouters.length) {
|
177
|
+
const newPendingRouters = [];
|
178
|
+
for (const pendingRouter of this.pendingRouters) {
|
179
|
+
if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
180
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
181
|
+
this.init(router, pendingRouter.path);
|
182
|
+
} else {
|
183
|
+
newPendingRouters.push(pendingRouter);
|
184
|
+
}
|
185
|
+
}
|
186
|
+
this.pendingRouters = newPendingRouters;
|
187
|
+
}
|
188
|
+
const match = this.tree[pathname];
|
189
|
+
if (!match) {
|
190
|
+
return void 0;
|
191
|
+
}
|
192
|
+
if (!match.procedure) {
|
193
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
|
194
|
+
if (!isProcedure(maybeProcedure)) {
|
195
|
+
throw new Error(`
|
196
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
|
197
|
+
Ensure that the procedure is correctly defined and matches the expected contract.
|
198
|
+
`);
|
199
|
+
}
|
200
|
+
match.procedure = createContractedProcedure(maybeProcedure, match.contract);
|
201
|
+
}
|
202
|
+
return {
|
203
|
+
path: match.path,
|
204
|
+
procedure: match.procedure
|
205
|
+
};
|
206
|
+
}
|
207
|
+
}
|
208
|
+
|
209
|
+
class StandardRPCHandler extends StandardHandler {
|
210
|
+
constructor(router, options = {}) {
|
211
|
+
const jsonSerializer = new StandardRPCJsonSerializer(options);
|
212
|
+
const serializer = new StandardRPCSerializer(jsonSerializer);
|
213
|
+
const matcher = new StandardRPCMatcher(options);
|
214
|
+
const codec = new StandardRPCCodec(serializer);
|
215
|
+
super(router, matcher, codec, options);
|
216
|
+
}
|
217
|
+
}
|
218
|
+
|
219
|
+
export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardRPCCodec as a, StandardRPCHandler as b, StandardRPCMatcher as c };
|
@@ -0,0 +1,408 @@
|
|
1
|
+
import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
|
2
|
+
import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, asyncIteratorWithSpan } from '@orpc/shared';
|
3
|
+
import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
|
4
|
+
import { experimental_HibernationEventIterator } from '@orpc/standard-server';
|
5
|
+
|
6
|
+
const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
|
7
|
+
function lazy(loader, meta = {}) {
|
8
|
+
return {
|
9
|
+
[LAZY_SYMBOL]: {
|
10
|
+
loader,
|
11
|
+
meta
|
12
|
+
}
|
13
|
+
};
|
14
|
+
}
|
15
|
+
function isLazy(item) {
|
16
|
+
return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
|
17
|
+
}
|
18
|
+
function getLazyMeta(lazied) {
|
19
|
+
return lazied[LAZY_SYMBOL].meta;
|
20
|
+
}
|
21
|
+
function unlazy(lazied) {
|
22
|
+
return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
|
23
|
+
}
|
24
|
+
|
25
|
+
function isStartWithMiddlewares(middlewares, compare) {
|
26
|
+
if (compare.length > middlewares.length) {
|
27
|
+
return false;
|
28
|
+
}
|
29
|
+
for (let i = 0; i < middlewares.length; i++) {
|
30
|
+
if (compare[i] === void 0) {
|
31
|
+
return true;
|
32
|
+
}
|
33
|
+
if (middlewares[i] !== compare[i]) {
|
34
|
+
return false;
|
35
|
+
}
|
36
|
+
}
|
37
|
+
return true;
|
38
|
+
}
|
39
|
+
function mergeMiddlewares(first, second, options) {
|
40
|
+
if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
|
41
|
+
return second;
|
42
|
+
}
|
43
|
+
return [...first, ...second];
|
44
|
+
}
|
45
|
+
function addMiddleware(middlewares, addition) {
|
46
|
+
return [...middlewares, addition];
|
47
|
+
}
|
48
|
+
|
49
|
+
class Procedure {
|
50
|
+
/**
|
51
|
+
* This property holds the defined options.
|
52
|
+
*/
|
53
|
+
"~orpc";
|
54
|
+
constructor(def) {
|
55
|
+
this["~orpc"] = def;
|
56
|
+
}
|
57
|
+
}
|
58
|
+
function isProcedure(item) {
|
59
|
+
if (item instanceof Procedure) {
|
60
|
+
return true;
|
61
|
+
}
|
62
|
+
return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
|
63
|
+
}
|
64
|
+
|
65
|
+
function mergeCurrentContext(context, other) {
|
66
|
+
return { ...context, ...other };
|
67
|
+
}
|
68
|
+
|
69
|
+
function createORPCErrorConstructorMap(errors) {
|
70
|
+
const proxy = new Proxy(errors, {
|
71
|
+
get(target, code) {
|
72
|
+
if (typeof code !== "string") {
|
73
|
+
return Reflect.get(target, code);
|
74
|
+
}
|
75
|
+
const item = (...rest) => {
|
76
|
+
const options = resolveMaybeOptionalOptions(rest);
|
77
|
+
const config = errors[code];
|
78
|
+
return new ORPCError(code, {
|
79
|
+
defined: Boolean(config),
|
80
|
+
status: config?.status,
|
81
|
+
message: options.message ?? config?.message,
|
82
|
+
data: options.data,
|
83
|
+
cause: options.cause
|
84
|
+
});
|
85
|
+
};
|
86
|
+
return item;
|
87
|
+
}
|
88
|
+
});
|
89
|
+
return proxy;
|
90
|
+
}
|
91
|
+
async function validateORPCError(map, error) {
|
92
|
+
const { code, status, message, data, cause, defined } = error;
|
93
|
+
const config = map?.[error.code];
|
94
|
+
if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
|
95
|
+
return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
|
96
|
+
}
|
97
|
+
if (!config.data) {
|
98
|
+
return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
|
99
|
+
}
|
100
|
+
const validated = await config.data["~standard"].validate(error.data);
|
101
|
+
if (validated.issues) {
|
102
|
+
return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
|
103
|
+
}
|
104
|
+
return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
|
105
|
+
}
|
106
|
+
|
107
|
+
function middlewareOutputFn(output) {
|
108
|
+
return { output, context: {} };
|
109
|
+
}
|
110
|
+
|
111
|
+
function createProcedureClient(lazyableProcedure, ...rest) {
|
112
|
+
const options = resolveMaybeOptionalOptions(rest);
|
113
|
+
return async (...[input, callerOptions]) => {
|
114
|
+
const path = toArray(options.path);
|
115
|
+
const { default: procedure } = await unlazy(lazyableProcedure);
|
116
|
+
const clientContext = callerOptions?.context ?? {};
|
117
|
+
const context = await value(options.context ?? {}, clientContext);
|
118
|
+
const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
|
119
|
+
try {
|
120
|
+
const output = await runWithSpan(
|
121
|
+
{ name: "call_procedure", signal: callerOptions?.signal },
|
122
|
+
(span) => {
|
123
|
+
span?.setAttribute("procedure.path", [...path]);
|
124
|
+
return intercept(
|
125
|
+
toArray(options.interceptors),
|
126
|
+
{
|
127
|
+
context,
|
128
|
+
input,
|
129
|
+
// input only optional when it undefinable so we can safely cast it
|
130
|
+
errors,
|
131
|
+
path,
|
132
|
+
procedure,
|
133
|
+
signal: callerOptions?.signal,
|
134
|
+
lastEventId: callerOptions?.lastEventId
|
135
|
+
},
|
136
|
+
(interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
|
137
|
+
);
|
138
|
+
}
|
139
|
+
);
|
140
|
+
if (isAsyncIteratorObject(output)) {
|
141
|
+
if (output instanceof experimental_HibernationEventIterator) {
|
142
|
+
return output;
|
143
|
+
}
|
144
|
+
return asyncIteratorWithSpan(
|
145
|
+
{ name: "consume_event_iterator_output", signal: callerOptions?.signal },
|
146
|
+
output
|
147
|
+
);
|
148
|
+
}
|
149
|
+
return output;
|
150
|
+
} catch (e) {
|
151
|
+
if (!(e instanceof ORPCError)) {
|
152
|
+
throw e;
|
153
|
+
}
|
154
|
+
const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
|
155
|
+
throw validated;
|
156
|
+
}
|
157
|
+
};
|
158
|
+
}
|
159
|
+
async function validateInput(procedure, input) {
|
160
|
+
const schema = procedure["~orpc"].inputSchema;
|
161
|
+
if (!schema) {
|
162
|
+
return input;
|
163
|
+
}
|
164
|
+
return runWithSpan(
|
165
|
+
{ name: "validate_input" },
|
166
|
+
async () => {
|
167
|
+
const result = await schema["~standard"].validate(input);
|
168
|
+
if (result.issues) {
|
169
|
+
throw new ORPCError("BAD_REQUEST", {
|
170
|
+
message: "Input validation failed",
|
171
|
+
data: {
|
172
|
+
issues: result.issues
|
173
|
+
},
|
174
|
+
cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
|
175
|
+
});
|
176
|
+
}
|
177
|
+
return result.value;
|
178
|
+
}
|
179
|
+
);
|
180
|
+
}
|
181
|
+
async function validateOutput(procedure, output) {
|
182
|
+
const schema = procedure["~orpc"].outputSchema;
|
183
|
+
if (!schema) {
|
184
|
+
return output;
|
185
|
+
}
|
186
|
+
return runWithSpan(
|
187
|
+
{ name: "validate_output" },
|
188
|
+
async () => {
|
189
|
+
const result = await schema["~standard"].validate(output);
|
190
|
+
if (result.issues) {
|
191
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
192
|
+
message: "Output validation failed",
|
193
|
+
cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
|
194
|
+
});
|
195
|
+
}
|
196
|
+
return result.value;
|
197
|
+
}
|
198
|
+
);
|
199
|
+
}
|
200
|
+
async function executeProcedureInternal(procedure, options) {
|
201
|
+
const middlewares = procedure["~orpc"].middlewares;
|
202
|
+
const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
|
203
|
+
const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
|
204
|
+
const next = async (index, context, input) => {
|
205
|
+
let currentInput = input;
|
206
|
+
if (index === inputValidationIndex) {
|
207
|
+
currentInput = await validateInput(procedure, currentInput);
|
208
|
+
}
|
209
|
+
const mid = middlewares[index];
|
210
|
+
const output = mid ? await runWithSpan(
|
211
|
+
{ name: `middleware.${mid.name}`, signal: options.signal },
|
212
|
+
async (span) => {
|
213
|
+
span?.setAttribute("middleware.index", index);
|
214
|
+
span?.setAttribute("middleware.name", mid.name);
|
215
|
+
const result = await mid({
|
216
|
+
...options,
|
217
|
+
context,
|
218
|
+
next: async (...[nextOptions]) => {
|
219
|
+
const nextContext = nextOptions?.context ?? {};
|
220
|
+
return {
|
221
|
+
output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
|
222
|
+
context: nextContext
|
223
|
+
};
|
224
|
+
}
|
225
|
+
}, currentInput, middlewareOutputFn);
|
226
|
+
return result.output;
|
227
|
+
}
|
228
|
+
) : await runWithSpan(
|
229
|
+
{ name: "handler", signal: options.signal },
|
230
|
+
() => procedure["~orpc"].handler({ ...options, context, input: currentInput })
|
231
|
+
);
|
232
|
+
if (index === outputValidationIndex) {
|
233
|
+
return await validateOutput(procedure, output);
|
234
|
+
}
|
235
|
+
return output;
|
236
|
+
};
|
237
|
+
return next(0, options.context, options.input);
|
238
|
+
}
|
239
|
+
|
240
|
+
const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
|
241
|
+
function setHiddenRouterContract(router, contract) {
|
242
|
+
return new Proxy(router, {
|
243
|
+
get(target, key) {
|
244
|
+
if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
|
245
|
+
return contract;
|
246
|
+
}
|
247
|
+
return Reflect.get(target, key);
|
248
|
+
}
|
249
|
+
});
|
250
|
+
}
|
251
|
+
function getHiddenRouterContract(router) {
|
252
|
+
return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
|
253
|
+
}
|
254
|
+
|
255
|
+
function getRouter(router, path) {
|
256
|
+
let current = router;
|
257
|
+
for (let i = 0; i < path.length; i++) {
|
258
|
+
const segment = path[i];
|
259
|
+
if (!current) {
|
260
|
+
return void 0;
|
261
|
+
}
|
262
|
+
if (isProcedure(current)) {
|
263
|
+
return void 0;
|
264
|
+
}
|
265
|
+
if (!isLazy(current)) {
|
266
|
+
current = current[segment];
|
267
|
+
continue;
|
268
|
+
}
|
269
|
+
const lazied = current;
|
270
|
+
const rest = path.slice(i);
|
271
|
+
return lazy(async () => {
|
272
|
+
const unwrapped = await unlazy(lazied);
|
273
|
+
const next = getRouter(unwrapped.default, rest);
|
274
|
+
return unlazy(next);
|
275
|
+
}, getLazyMeta(lazied));
|
276
|
+
}
|
277
|
+
return current;
|
278
|
+
}
|
279
|
+
function createAccessibleLazyRouter(lazied) {
|
280
|
+
const recursive = new Proxy(lazied, {
|
281
|
+
get(target, key) {
|
282
|
+
if (typeof key !== "string") {
|
283
|
+
return Reflect.get(target, key);
|
284
|
+
}
|
285
|
+
const next = getRouter(lazied, [key]);
|
286
|
+
return createAccessibleLazyRouter(next);
|
287
|
+
}
|
288
|
+
});
|
289
|
+
return recursive;
|
290
|
+
}
|
291
|
+
function enhanceRouter(router, options) {
|
292
|
+
if (isLazy(router)) {
|
293
|
+
const laziedMeta = getLazyMeta(router);
|
294
|
+
const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
|
295
|
+
const enhanced2 = lazy(async () => {
|
296
|
+
const { default: unlaziedRouter } = await unlazy(router);
|
297
|
+
const enhanced3 = enhanceRouter(unlaziedRouter, options);
|
298
|
+
return unlazy(enhanced3);
|
299
|
+
}, {
|
300
|
+
...laziedMeta,
|
301
|
+
prefix: enhancedPrefix
|
302
|
+
});
|
303
|
+
const accessible = createAccessibleLazyRouter(enhanced2);
|
304
|
+
return accessible;
|
305
|
+
}
|
306
|
+
if (isProcedure(router)) {
|
307
|
+
const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, { dedupeLeading: options.dedupeLeadingMiddlewares });
|
308
|
+
const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
|
309
|
+
const enhanced2 = new Procedure({
|
310
|
+
...router["~orpc"],
|
311
|
+
route: enhanceRoute(router["~orpc"].route, options),
|
312
|
+
errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
|
313
|
+
middlewares: newMiddlewares,
|
314
|
+
inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
|
315
|
+
outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
|
316
|
+
});
|
317
|
+
return enhanced2;
|
318
|
+
}
|
319
|
+
const enhanced = {};
|
320
|
+
for (const key in router) {
|
321
|
+
enhanced[key] = enhanceRouter(router[key], options);
|
322
|
+
}
|
323
|
+
return enhanced;
|
324
|
+
}
|
325
|
+
function traverseContractProcedures(options, callback, lazyOptions = []) {
|
326
|
+
let currentRouter = options.router;
|
327
|
+
const hiddenContract = getHiddenRouterContract(options.router);
|
328
|
+
if (hiddenContract !== void 0) {
|
329
|
+
currentRouter = hiddenContract;
|
330
|
+
}
|
331
|
+
if (isLazy(currentRouter)) {
|
332
|
+
lazyOptions.push({
|
333
|
+
router: currentRouter,
|
334
|
+
path: options.path
|
335
|
+
});
|
336
|
+
} else if (isContractProcedure(currentRouter)) {
|
337
|
+
callback({
|
338
|
+
contract: currentRouter,
|
339
|
+
path: options.path
|
340
|
+
});
|
341
|
+
} else {
|
342
|
+
for (const key in currentRouter) {
|
343
|
+
traverseContractProcedures(
|
344
|
+
{
|
345
|
+
router: currentRouter[key],
|
346
|
+
path: [...options.path, key]
|
347
|
+
},
|
348
|
+
callback,
|
349
|
+
lazyOptions
|
350
|
+
);
|
351
|
+
}
|
352
|
+
}
|
353
|
+
return lazyOptions;
|
354
|
+
}
|
355
|
+
async function resolveContractProcedures(options, callback) {
|
356
|
+
const pending = [options];
|
357
|
+
for (const options2 of pending) {
|
358
|
+
const lazyOptions = traverseContractProcedures(options2, callback);
|
359
|
+
for (const options3 of lazyOptions) {
|
360
|
+
const { default: router } = await unlazy(options3.router);
|
361
|
+
pending.push({
|
362
|
+
router,
|
363
|
+
path: options3.path
|
364
|
+
});
|
365
|
+
}
|
366
|
+
}
|
367
|
+
}
|
368
|
+
async function unlazyRouter(router) {
|
369
|
+
if (isProcedure(router)) {
|
370
|
+
return router;
|
371
|
+
}
|
372
|
+
const unlazied = {};
|
373
|
+
for (const key in router) {
|
374
|
+
const item = router[key];
|
375
|
+
const { default: unlaziedRouter } = await unlazy(item);
|
376
|
+
unlazied[key] = await unlazyRouter(unlaziedRouter);
|
377
|
+
}
|
378
|
+
return unlazied;
|
379
|
+
}
|
380
|
+
|
381
|
+
function createAssertedLazyProcedure(lazied) {
|
382
|
+
const lazyProcedure = lazy(async () => {
|
383
|
+
const { default: maybeProcedure } = await unlazy(lazied);
|
384
|
+
if (!isProcedure(maybeProcedure)) {
|
385
|
+
throw new Error(`
|
386
|
+
Expected a lazy<procedure> but got lazy<unknown>.
|
387
|
+
This should be caught by TypeScript compilation.
|
388
|
+
Please report this issue if this makes you feel uncomfortable.
|
389
|
+
`);
|
390
|
+
}
|
391
|
+
return { default: maybeProcedure };
|
392
|
+
}, getLazyMeta(lazied));
|
393
|
+
return lazyProcedure;
|
394
|
+
}
|
395
|
+
function createContractedProcedure(procedure, contract) {
|
396
|
+
return new Procedure({
|
397
|
+
...procedure["~orpc"],
|
398
|
+
errorMap: contract["~orpc"].errorMap,
|
399
|
+
route: contract["~orpc"].route,
|
400
|
+
meta: contract["~orpc"].meta
|
401
|
+
});
|
402
|
+
}
|
403
|
+
function call(procedure, input, ...rest) {
|
404
|
+
const options = resolveMaybeOptionalOptions(rest);
|
405
|
+
return createProcedureClient(procedure, options)(input, options);
|
406
|
+
}
|
407
|
+
|
408
|
+
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 };
|