@orpc/server 0.0.0-next.d42488d → 0.0.0-next.d452413
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 +120 -0
- package/dist/adapters/fetch/index.d.mts +26 -0
- package/dist/adapters/fetch/index.d.ts +26 -0
- package/dist/adapters/fetch/index.mjs +9 -0
- package/dist/adapters/hono/index.d.mts +19 -0
- package/dist/adapters/hono/index.d.ts +19 -0
- package/dist/adapters/hono/index.mjs +32 -0
- package/dist/adapters/next/index.d.mts +26 -0
- package/dist/adapters/next/index.d.ts +26 -0
- package/dist/adapters/next/index.mjs +29 -0
- package/dist/adapters/node/index.d.mts +34 -0
- package/dist/adapters/node/index.d.ts +34 -0
- package/dist/adapters/node/index.mjs +31 -0
- package/dist/adapters/standard/index.d.mts +25 -0
- package/dist/adapters/standard/index.d.ts +25 -0
- package/dist/adapters/standard/index.mjs +6 -0
- package/dist/index.d.mts +269 -0
- package/dist/index.d.ts +269 -0
- package/dist/index.mjs +343 -0
- package/dist/plugins/index.d.mts +31 -0
- package/dist/plugins/index.d.ts +31 -0
- package/dist/plugins/index.mjs +103 -0
- package/dist/shared/server.CMrS28Go.mjs +346 -0
- package/dist/shared/server.CSZRzcSW.mjs +158 -0
- package/dist/shared/server.Cq3B6PoL.mjs +28 -0
- package/dist/shared/server.Ctc1Ekur.d.mts +75 -0
- package/dist/shared/server.DyteP6Y8.d.ts +75 -0
- package/dist/shared/server.Q6ZmnTgO.mjs +12 -0
- package/dist/shared/server.Zu6nd6jA.d.mts +142 -0
- package/dist/shared/server.Zu6nd6jA.d.ts +142 -0
- package/package.json +43 -15
- package/dist/chunk-FN62GL22.js +0 -182
- package/dist/fetch.js +0 -286
- package/dist/index.js +0 -518
- package/dist/src/builder.d.ts +0 -35
- package/dist/src/fetch/composite-handler.d.ts +0 -8
- package/dist/src/fetch/index.d.ts +0 -6
- package/dist/src/fetch/orpc-handler.d.ts +0 -20
- package/dist/src/fetch/orpc-payload-codec.d.ts +0 -9
- package/dist/src/fetch/orpc-procedure-matcher.d.ts +0 -12
- package/dist/src/fetch/super-json.d.ts +0 -12
- package/dist/src/fetch/types.d.ts +0 -16
- package/dist/src/hidden.d.ts +0 -6
- package/dist/src/implementer-chainable.d.ts +0 -10
- package/dist/src/index.d.ts +0 -23
- package/dist/src/lazy-decorated.d.ts +0 -10
- package/dist/src/lazy-utils.d.ts +0 -4
- package/dist/src/lazy.d.ts +0 -18
- package/dist/src/middleware-decorated.d.ts +0 -8
- package/dist/src/middleware.d.ts +0 -23
- package/dist/src/procedure-builder.d.ts +0 -22
- package/dist/src/procedure-client.d.ts +0 -29
- package/dist/src/procedure-decorated.d.ts +0 -14
- package/dist/src/procedure-implementer.d.ts +0 -18
- package/dist/src/procedure.d.ts +0 -23
- package/dist/src/router-builder.d.ts +0 -29
- package/dist/src/router-client.d.ts +0 -25
- package/dist/src/router-implementer.d.ts +0 -21
- package/dist/src/router.d.ts +0 -16
- package/dist/src/types.d.ts +0 -12
- package/dist/src/utils.d.ts +0 -3
@@ -0,0 +1,346 @@
|
|
1
|
+
import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
|
2
|
+
import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
|
3
|
+
import { value, intercept, toError } 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 mergeMiddlewares(first, second) {
|
25
|
+
return [...first, ...second];
|
26
|
+
}
|
27
|
+
function addMiddleware(middlewares, addition) {
|
28
|
+
return [...middlewares, addition];
|
29
|
+
}
|
30
|
+
|
31
|
+
class Procedure {
|
32
|
+
"~orpc";
|
33
|
+
constructor(def) {
|
34
|
+
this["~orpc"] = def;
|
35
|
+
}
|
36
|
+
}
|
37
|
+
function isProcedure(item) {
|
38
|
+
if (item instanceof Procedure) {
|
39
|
+
return true;
|
40
|
+
}
|
41
|
+
return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
|
42
|
+
}
|
43
|
+
|
44
|
+
function createORPCErrorConstructorMap(errors) {
|
45
|
+
const proxy = new Proxy(errors, {
|
46
|
+
get(target, code) {
|
47
|
+
if (typeof code !== "string") {
|
48
|
+
return Reflect.get(target, code);
|
49
|
+
}
|
50
|
+
const item = (...[options]) => {
|
51
|
+
const config = errors[code];
|
52
|
+
return new ORPCError(code, {
|
53
|
+
defined: Boolean(config),
|
54
|
+
status: config?.status,
|
55
|
+
message: options?.message ?? config?.message,
|
56
|
+
data: options?.data,
|
57
|
+
cause: options?.cause
|
58
|
+
});
|
59
|
+
};
|
60
|
+
return item;
|
61
|
+
}
|
62
|
+
});
|
63
|
+
return proxy;
|
64
|
+
}
|
65
|
+
async function validateORPCError(map, error) {
|
66
|
+
const { code, status, message, data, cause, defined } = error;
|
67
|
+
const config = map?.[error.code];
|
68
|
+
if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
|
69
|
+
return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
|
70
|
+
}
|
71
|
+
if (!config.data) {
|
72
|
+
return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
|
73
|
+
}
|
74
|
+
const validated = await config.data["~standard"].validate(error.data);
|
75
|
+
if (validated.issues) {
|
76
|
+
return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
|
77
|
+
}
|
78
|
+
return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
|
79
|
+
}
|
80
|
+
|
81
|
+
function middlewareOutputFn(output) {
|
82
|
+
return { output, context: {} };
|
83
|
+
}
|
84
|
+
|
85
|
+
function createProcedureClient(lazyableProcedure, ...[options]) {
|
86
|
+
return async (...[input, callerOptions]) => {
|
87
|
+
const path = options?.path ?? [];
|
88
|
+
const { default: procedure } = await unlazy(lazyableProcedure);
|
89
|
+
const clientContext = callerOptions?.context ?? {};
|
90
|
+
const context = await value(options?.context ?? {}, clientContext);
|
91
|
+
const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
|
92
|
+
try {
|
93
|
+
return await intercept(
|
94
|
+
options?.interceptors ?? [],
|
95
|
+
{
|
96
|
+
context,
|
97
|
+
input,
|
98
|
+
// input only optional when it undefinable so we can safely cast it
|
99
|
+
errors,
|
100
|
+
path,
|
101
|
+
procedure,
|
102
|
+
signal: callerOptions?.signal,
|
103
|
+
lastEventId: callerOptions?.lastEventId
|
104
|
+
},
|
105
|
+
(interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
|
106
|
+
);
|
107
|
+
} catch (e) {
|
108
|
+
if (!(e instanceof ORPCError)) {
|
109
|
+
throw toError(e);
|
110
|
+
}
|
111
|
+
const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
|
112
|
+
throw validated;
|
113
|
+
}
|
114
|
+
};
|
115
|
+
}
|
116
|
+
async function validateInput(procedure, input) {
|
117
|
+
const schema = procedure["~orpc"].inputSchema;
|
118
|
+
if (!schema) {
|
119
|
+
return input;
|
120
|
+
}
|
121
|
+
const result = await schema["~standard"].validate(input);
|
122
|
+
if (result.issues) {
|
123
|
+
throw new ORPCError("BAD_REQUEST", {
|
124
|
+
message: "Input validation failed",
|
125
|
+
data: {
|
126
|
+
issues: result.issues
|
127
|
+
},
|
128
|
+
cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
|
129
|
+
});
|
130
|
+
}
|
131
|
+
return result.value;
|
132
|
+
}
|
133
|
+
async function validateOutput(procedure, output) {
|
134
|
+
const schema = procedure["~orpc"].outputSchema;
|
135
|
+
if (!schema) {
|
136
|
+
return output;
|
137
|
+
}
|
138
|
+
const result = await schema["~standard"].validate(output);
|
139
|
+
if (result.issues) {
|
140
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
141
|
+
message: "Output validation failed",
|
142
|
+
cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
|
143
|
+
});
|
144
|
+
}
|
145
|
+
return result.value;
|
146
|
+
}
|
147
|
+
async function executeProcedureInternal(procedure, options) {
|
148
|
+
const middlewares = procedure["~orpc"].middlewares;
|
149
|
+
const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
|
150
|
+
const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
|
151
|
+
let currentIndex = 0;
|
152
|
+
let currentContext = options.context;
|
153
|
+
let currentInput = options.input;
|
154
|
+
const next = async (...[nextOptions]) => {
|
155
|
+
const index = currentIndex;
|
156
|
+
currentIndex += 1;
|
157
|
+
currentContext = { ...currentContext, ...nextOptions?.context };
|
158
|
+
if (index === inputValidationIndex) {
|
159
|
+
currentInput = await validateInput(procedure, currentInput);
|
160
|
+
}
|
161
|
+
const mid = middlewares[index];
|
162
|
+
const result = mid ? await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn) : { output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput }), context: currentContext };
|
163
|
+
if (index === outputValidationIndex) {
|
164
|
+
const validatedOutput = await validateOutput(procedure, result.output);
|
165
|
+
return {
|
166
|
+
...result,
|
167
|
+
output: validatedOutput
|
168
|
+
};
|
169
|
+
}
|
170
|
+
return result;
|
171
|
+
};
|
172
|
+
return (await next({})).output;
|
173
|
+
}
|
174
|
+
|
175
|
+
const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
|
176
|
+
function setHiddenRouterContract(router, contract) {
|
177
|
+
return new Proxy(router, {
|
178
|
+
get(target, key) {
|
179
|
+
if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
|
180
|
+
return contract;
|
181
|
+
}
|
182
|
+
return Reflect.get(target, key);
|
183
|
+
}
|
184
|
+
});
|
185
|
+
}
|
186
|
+
function getHiddenRouterContract(router) {
|
187
|
+
return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
|
188
|
+
}
|
189
|
+
|
190
|
+
function getRouter(router, path) {
|
191
|
+
let current = router;
|
192
|
+
for (let i = 0; i < path.length; i++) {
|
193
|
+
const segment = path[i];
|
194
|
+
if (!current) {
|
195
|
+
return void 0;
|
196
|
+
}
|
197
|
+
if (isProcedure(current)) {
|
198
|
+
return void 0;
|
199
|
+
}
|
200
|
+
if (!isLazy(current)) {
|
201
|
+
current = current[segment];
|
202
|
+
continue;
|
203
|
+
}
|
204
|
+
const lazied = current;
|
205
|
+
const rest = path.slice(i);
|
206
|
+
return lazy(async () => {
|
207
|
+
const unwrapped = await unlazy(lazied);
|
208
|
+
const next = getRouter(unwrapped.default, rest);
|
209
|
+
return unlazy(next);
|
210
|
+
}, getLazyMeta(lazied));
|
211
|
+
}
|
212
|
+
return current;
|
213
|
+
}
|
214
|
+
function createAccessibleLazyRouter(lazied) {
|
215
|
+
const recursive = new Proxy(lazied, {
|
216
|
+
get(target, key) {
|
217
|
+
if (typeof key !== "string") {
|
218
|
+
return Reflect.get(target, key);
|
219
|
+
}
|
220
|
+
const next = getRouter(lazied, [key]);
|
221
|
+
return createAccessibleLazyRouter(next);
|
222
|
+
}
|
223
|
+
});
|
224
|
+
return recursive;
|
225
|
+
}
|
226
|
+
function enhanceRouter(router, options) {
|
227
|
+
if (isLazy(router)) {
|
228
|
+
const laziedMeta = getLazyMeta(router);
|
229
|
+
const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
|
230
|
+
const enhanced2 = lazy(async () => {
|
231
|
+
const { default: unlaziedRouter } = await unlazy(router);
|
232
|
+
const enhanced3 = enhanceRouter(unlaziedRouter, options);
|
233
|
+
return unlazy(enhanced3);
|
234
|
+
}, {
|
235
|
+
...laziedMeta,
|
236
|
+
prefix: enhancedPrefix
|
237
|
+
});
|
238
|
+
const accessible = createAccessibleLazyRouter(enhanced2);
|
239
|
+
return accessible;
|
240
|
+
}
|
241
|
+
if (isProcedure(router)) {
|
242
|
+
const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares);
|
243
|
+
const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
|
244
|
+
const enhanced2 = new Procedure({
|
245
|
+
...router["~orpc"],
|
246
|
+
route: enhanceRoute(router["~orpc"].route, options),
|
247
|
+
errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
|
248
|
+
middlewares: newMiddlewares,
|
249
|
+
inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
|
250
|
+
outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
|
251
|
+
});
|
252
|
+
return enhanced2;
|
253
|
+
}
|
254
|
+
const enhanced = {};
|
255
|
+
for (const key in router) {
|
256
|
+
enhanced[key] = enhanceRouter(router[key], options);
|
257
|
+
}
|
258
|
+
return enhanced;
|
259
|
+
}
|
260
|
+
function traverseContractProcedures(options, callback, lazyOptions = []) {
|
261
|
+
let currentRouter = options.router;
|
262
|
+
const hiddenContract = getHiddenRouterContract(options.router);
|
263
|
+
if (hiddenContract !== void 0) {
|
264
|
+
currentRouter = hiddenContract;
|
265
|
+
}
|
266
|
+
if (isLazy(currentRouter)) {
|
267
|
+
lazyOptions.push({
|
268
|
+
router: currentRouter,
|
269
|
+
path: options.path
|
270
|
+
});
|
271
|
+
} else if (isContractProcedure(currentRouter)) {
|
272
|
+
callback({
|
273
|
+
contract: currentRouter,
|
274
|
+
path: options.path
|
275
|
+
});
|
276
|
+
} else {
|
277
|
+
for (const key in currentRouter) {
|
278
|
+
traverseContractProcedures(
|
279
|
+
{
|
280
|
+
router: currentRouter[key],
|
281
|
+
path: [...options.path, key]
|
282
|
+
},
|
283
|
+
callback,
|
284
|
+
lazyOptions
|
285
|
+
);
|
286
|
+
}
|
287
|
+
}
|
288
|
+
return lazyOptions;
|
289
|
+
}
|
290
|
+
async function resolveContractProcedures(options, callback) {
|
291
|
+
const pending = [options];
|
292
|
+
for (const options2 of pending) {
|
293
|
+
const lazyOptions = traverseContractProcedures(options2, callback);
|
294
|
+
for (const options3 of lazyOptions) {
|
295
|
+
const { default: router } = await unlazy(options3.router);
|
296
|
+
pending.push({
|
297
|
+
router,
|
298
|
+
path: options3.path
|
299
|
+
});
|
300
|
+
}
|
301
|
+
}
|
302
|
+
}
|
303
|
+
async function unlazyRouter(router) {
|
304
|
+
if (isProcedure(router)) {
|
305
|
+
return router;
|
306
|
+
}
|
307
|
+
const unlazied = {};
|
308
|
+
for (const key in router) {
|
309
|
+
const item = router[key];
|
310
|
+
const { default: unlaziedRouter } = await unlazy(item);
|
311
|
+
unlazied[key] = await unlazyRouter(unlaziedRouter);
|
312
|
+
}
|
313
|
+
return unlazied;
|
314
|
+
}
|
315
|
+
|
316
|
+
function createAssertedLazyProcedure(lazied) {
|
317
|
+
const lazyProcedure = lazy(async () => {
|
318
|
+
const { default: maybeProcedure } = await unlazy(lazied);
|
319
|
+
if (!isProcedure(maybeProcedure)) {
|
320
|
+
throw new Error(`
|
321
|
+
Expected a lazy<procedure> but got lazy<unknown>.
|
322
|
+
This should be caught by TypeScript compilation.
|
323
|
+
Please report this issue if this makes you feel uncomfortable.
|
324
|
+
`);
|
325
|
+
}
|
326
|
+
return { default: maybeProcedure };
|
327
|
+
}, getLazyMeta(lazied));
|
328
|
+
return lazyProcedure;
|
329
|
+
}
|
330
|
+
function createContractedProcedure(procedure, contract) {
|
331
|
+
return new Procedure({
|
332
|
+
...procedure["~orpc"],
|
333
|
+
errorMap: contract["~orpc"].errorMap,
|
334
|
+
route: contract["~orpc"].route,
|
335
|
+
meta: contract["~orpc"].meta
|
336
|
+
});
|
337
|
+
}
|
338
|
+
function call(procedure, input, ...rest) {
|
339
|
+
return createProcedureClient(procedure, ...rest)(input);
|
340
|
+
}
|
341
|
+
|
342
|
+
function toHttpPath(path) {
|
343
|
+
return `/${path.map(encodeURIComponent).join("/")}`;
|
344
|
+
}
|
345
|
+
|
346
|
+
export { LAZY_SYMBOL as L, Procedure as P, toHttpPath as a, createContractedProcedure as b, createProcedureClient as c, addMiddleware as d, enhanceRouter as e, isLazy as f, getRouter as g, createAssertedLazyProcedure as h, isProcedure as i, getLazyMeta as j, call as k, lazy as l, middlewareOutputFn as m, getHiddenRouterContract as n, createAccessibleLazyRouter as o, unlazyRouter as p, resolveContractProcedures as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u };
|
@@ -0,0 +1,158 @@
|
|
1
|
+
import { ORPCError, toORPCError } from '@orpc/client';
|
2
|
+
import { intercept, trim, parseEmptyableJSON } from '@orpc/shared';
|
3
|
+
import { C as CompositePlugin } from './server.Q6ZmnTgO.mjs';
|
4
|
+
import { c as createProcedureClient, t as traverseContractProcedures, a as toHttpPath, i as isProcedure, u as unlazy, g as getRouter, b as createContractedProcedure } from './server.CMrS28Go.mjs';
|
5
|
+
|
6
|
+
class StandardHandler {
|
7
|
+
constructor(router, matcher, codec, options) {
|
8
|
+
this.matcher = matcher;
|
9
|
+
this.codec = codec;
|
10
|
+
this.options = options;
|
11
|
+
this.plugin = new CompositePlugin(options.plugins);
|
12
|
+
this.plugin.init(this.options);
|
13
|
+
this.matcher.init(router);
|
14
|
+
}
|
15
|
+
plugin;
|
16
|
+
handle(request, ...[options]) {
|
17
|
+
return intercept(
|
18
|
+
this.options.rootInterceptors ?? [],
|
19
|
+
{
|
20
|
+
request,
|
21
|
+
...options,
|
22
|
+
context: options?.context ?? {}
|
23
|
+
// context is optional only when all fields are optional so we can safely force it to have a context
|
24
|
+
},
|
25
|
+
async (interceptorOptions) => {
|
26
|
+
let isDecoding = false;
|
27
|
+
try {
|
28
|
+
return await intercept(
|
29
|
+
this.options.interceptors ?? [],
|
30
|
+
interceptorOptions,
|
31
|
+
async (interceptorOptions2) => {
|
32
|
+
const method = interceptorOptions2.request.method;
|
33
|
+
const url = interceptorOptions2.request.url;
|
34
|
+
const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
|
35
|
+
const match = await this.matcher.match(method, pathname);
|
36
|
+
if (!match) {
|
37
|
+
return { matched: false, response: void 0 };
|
38
|
+
}
|
39
|
+
const client = createProcedureClient(match.procedure, {
|
40
|
+
context: interceptorOptions2.context,
|
41
|
+
path: match.path,
|
42
|
+
interceptors: this.options.clientInterceptors
|
43
|
+
});
|
44
|
+
isDecoding = true;
|
45
|
+
const input = await this.codec.decode(request, match.params, match.procedure);
|
46
|
+
isDecoding = false;
|
47
|
+
const lastEventId = Array.isArray(request.headers["last-event-id"]) ? request.headers["last-event-id"].at(-1) : request.headers["last-event-id"];
|
48
|
+
const output = await client(input, { signal: request.signal, lastEventId });
|
49
|
+
const response = this.codec.encode(output, match.procedure);
|
50
|
+
return {
|
51
|
+
matched: true,
|
52
|
+
response
|
53
|
+
};
|
54
|
+
}
|
55
|
+
);
|
56
|
+
} catch (e) {
|
57
|
+
const error = isDecoding ? new ORPCError("BAD_REQUEST", {
|
58
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
59
|
+
cause: e
|
60
|
+
}) : toORPCError(e);
|
61
|
+
const response = this.codec.encodeError(error);
|
62
|
+
return {
|
63
|
+
matched: true,
|
64
|
+
response
|
65
|
+
};
|
66
|
+
}
|
67
|
+
}
|
68
|
+
);
|
69
|
+
}
|
70
|
+
}
|
71
|
+
|
72
|
+
class RPCCodec {
|
73
|
+
constructor(serializer) {
|
74
|
+
this.serializer = serializer;
|
75
|
+
}
|
76
|
+
async decode(request, _params, _procedure) {
|
77
|
+
const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
|
78
|
+
return this.serializer.deserialize(serialized);
|
79
|
+
}
|
80
|
+
encode(output, _procedure) {
|
81
|
+
return {
|
82
|
+
status: 200,
|
83
|
+
headers: {},
|
84
|
+
body: this.serializer.serialize(output)
|
85
|
+
};
|
86
|
+
}
|
87
|
+
encodeError(error) {
|
88
|
+
return {
|
89
|
+
status: error.status,
|
90
|
+
headers: {},
|
91
|
+
body: this.serializer.serialize(error.toJSON())
|
92
|
+
};
|
93
|
+
}
|
94
|
+
}
|
95
|
+
|
96
|
+
class RPCMatcher {
|
97
|
+
tree = {};
|
98
|
+
pendingRouters = [];
|
99
|
+
init(router, path = []) {
|
100
|
+
const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
|
101
|
+
const httpPath = toHttpPath(path2);
|
102
|
+
if (isProcedure(contract)) {
|
103
|
+
this.tree[httpPath] = {
|
104
|
+
path: path2,
|
105
|
+
contract,
|
106
|
+
procedure: contract,
|
107
|
+
// this mean dev not used contract-first so we can used contract as procedure directly
|
108
|
+
router
|
109
|
+
};
|
110
|
+
} else {
|
111
|
+
this.tree[httpPath] = {
|
112
|
+
path: path2,
|
113
|
+
contract,
|
114
|
+
procedure: void 0,
|
115
|
+
router
|
116
|
+
};
|
117
|
+
}
|
118
|
+
});
|
119
|
+
this.pendingRouters.push(...laziedOptions.map((option) => ({
|
120
|
+
...option,
|
121
|
+
httpPathPrefix: toHttpPath(option.path)
|
122
|
+
})));
|
123
|
+
}
|
124
|
+
async match(_method, pathname) {
|
125
|
+
if (this.pendingRouters.length) {
|
126
|
+
const newPendingRouters = [];
|
127
|
+
for (const pendingRouter of this.pendingRouters) {
|
128
|
+
if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
129
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
130
|
+
this.init(router, pendingRouter.path);
|
131
|
+
} else {
|
132
|
+
newPendingRouters.push(pendingRouter);
|
133
|
+
}
|
134
|
+
}
|
135
|
+
this.pendingRouters = newPendingRouters;
|
136
|
+
}
|
137
|
+
const match = this.tree[pathname];
|
138
|
+
if (!match) {
|
139
|
+
return void 0;
|
140
|
+
}
|
141
|
+
if (!match.procedure) {
|
142
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
|
143
|
+
if (!isProcedure(maybeProcedure)) {
|
144
|
+
throw new Error(`
|
145
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
|
146
|
+
Ensure that the procedure is correctly defined and matches the expected contract.
|
147
|
+
`);
|
148
|
+
}
|
149
|
+
match.procedure = createContractedProcedure(maybeProcedure, match.contract);
|
150
|
+
}
|
151
|
+
return {
|
152
|
+
path: match.path,
|
153
|
+
procedure: match.procedure
|
154
|
+
};
|
155
|
+
}
|
156
|
+
}
|
157
|
+
|
158
|
+
export { RPCCodec as R, StandardHandler as S, RPCMatcher as a };
|
@@ -0,0 +1,28 @@
|
|
1
|
+
import { RPCSerializer } from '@orpc/client/standard';
|
2
|
+
import { toStandardLazyRequest, toFetchResponse } from '@orpc/standard-server-fetch';
|
3
|
+
import { S as StandardHandler, a as RPCMatcher, R as RPCCodec } from './server.CSZRzcSW.mjs';
|
4
|
+
|
5
|
+
class RPCHandler {
|
6
|
+
standardHandler;
|
7
|
+
constructor(router, options = {}) {
|
8
|
+
const serializer = new RPCSerializer();
|
9
|
+
const matcher = new RPCMatcher();
|
10
|
+
const codec = new RPCCodec(serializer);
|
11
|
+
this.standardHandler = new StandardHandler(router, matcher, codec, options);
|
12
|
+
}
|
13
|
+
async handle(request, ...[
|
14
|
+
options = {}
|
15
|
+
]) {
|
16
|
+
const standardRequest = toStandardLazyRequest(request);
|
17
|
+
const result = await this.standardHandler.handle(standardRequest, options);
|
18
|
+
if (!result.matched) {
|
19
|
+
return result;
|
20
|
+
}
|
21
|
+
return {
|
22
|
+
matched: true,
|
23
|
+
response: toFetchResponse(result.response, options)
|
24
|
+
};
|
25
|
+
}
|
26
|
+
}
|
27
|
+
|
28
|
+
export { RPCHandler as R };
|
@@ -0,0 +1,75 @@
|
|
1
|
+
import { HTTPPath, AnySchema, Meta, InferSchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
|
2
|
+
import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
|
3
|
+
import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
|
4
|
+
import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.Zu6nd6jA.mjs';
|
5
|
+
import { ORPCError } from '@orpc/client';
|
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
|
+
type StandardHandleOptions<T extends Context> = {
|
24
|
+
prefix?: HTTPPath;
|
25
|
+
} & (Record<never, never> extends T ? {
|
26
|
+
context?: T;
|
27
|
+
} : {
|
28
|
+
context: T;
|
29
|
+
});
|
30
|
+
type StandardHandleResult = {
|
31
|
+
matched: true;
|
32
|
+
response: StandardResponse;
|
33
|
+
} | {
|
34
|
+
matched: false;
|
35
|
+
response: undefined;
|
36
|
+
};
|
37
|
+
type StandardHandlerInterceptorOptions<T extends Context> = StandardHandleOptions<T> & {
|
38
|
+
context: T;
|
39
|
+
request: StandardLazyRequest;
|
40
|
+
};
|
41
|
+
interface StandardHandlerOptions<TContext extends Context> {
|
42
|
+
plugins?: HandlerPlugin<TContext>[];
|
43
|
+
/**
|
44
|
+
* Interceptors at the request level, helpful when you want catch errors
|
45
|
+
*/
|
46
|
+
interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
|
47
|
+
/**
|
48
|
+
* Interceptors at the root level, helpful when you want override the request/response
|
49
|
+
*/
|
50
|
+
rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
|
51
|
+
/**
|
52
|
+
*
|
53
|
+
* Interceptors for procedure client.
|
54
|
+
*/
|
55
|
+
clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, AnySchema, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
|
56
|
+
}
|
57
|
+
declare class StandardHandler<T extends Context> {
|
58
|
+
private readonly matcher;
|
59
|
+
private readonly codec;
|
60
|
+
private readonly options;
|
61
|
+
private readonly plugin;
|
62
|
+
constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
|
63
|
+
handle(request: StandardLazyRequest, ...[options]: MaybeOptionalOptions<StandardHandleOptions<T>>): Promise<StandardHandleResult>;
|
64
|
+
}
|
65
|
+
|
66
|
+
interface HandlerPlugin<TContext extends Context> {
|
67
|
+
init?(options: StandardHandlerOptions<TContext>): void;
|
68
|
+
}
|
69
|
+
declare class CompositePlugin<TContext extends Context> implements HandlerPlugin<TContext> {
|
70
|
+
private readonly plugins;
|
71
|
+
constructor(plugins?: HandlerPlugin<TContext>[]);
|
72
|
+
init(options: StandardHandlerOptions<TContext>): void;
|
73
|
+
}
|
74
|
+
|
75
|
+
export { CompositePlugin as C, type HandlerPlugin as H, type StandardHandleOptions as S, type StandardHandlerInterceptorOptions as a, type StandardHandlerOptions as b, type StandardCodec as c, type StandardParams as d, type StandardMatcher as e, type StandardMatchResult as f, type StandardHandleResult as g, StandardHandler as h };
|
@@ -0,0 +1,75 @@
|
|
1
|
+
import { HTTPPath, AnySchema, Meta, InferSchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
|
2
|
+
import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
|
3
|
+
import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
|
4
|
+
import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.Zu6nd6jA.js';
|
5
|
+
import { ORPCError } from '@orpc/client';
|
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
|
+
type StandardHandleOptions<T extends Context> = {
|
24
|
+
prefix?: HTTPPath;
|
25
|
+
} & (Record<never, never> extends T ? {
|
26
|
+
context?: T;
|
27
|
+
} : {
|
28
|
+
context: T;
|
29
|
+
});
|
30
|
+
type StandardHandleResult = {
|
31
|
+
matched: true;
|
32
|
+
response: StandardResponse;
|
33
|
+
} | {
|
34
|
+
matched: false;
|
35
|
+
response: undefined;
|
36
|
+
};
|
37
|
+
type StandardHandlerInterceptorOptions<T extends Context> = StandardHandleOptions<T> & {
|
38
|
+
context: T;
|
39
|
+
request: StandardLazyRequest;
|
40
|
+
};
|
41
|
+
interface StandardHandlerOptions<TContext extends Context> {
|
42
|
+
plugins?: HandlerPlugin<TContext>[];
|
43
|
+
/**
|
44
|
+
* Interceptors at the request level, helpful when you want catch errors
|
45
|
+
*/
|
46
|
+
interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
|
47
|
+
/**
|
48
|
+
* Interceptors at the root level, helpful when you want override the request/response
|
49
|
+
*/
|
50
|
+
rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
|
51
|
+
/**
|
52
|
+
*
|
53
|
+
* Interceptors for procedure client.
|
54
|
+
*/
|
55
|
+
clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, AnySchema, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
|
56
|
+
}
|
57
|
+
declare class StandardHandler<T extends Context> {
|
58
|
+
private readonly matcher;
|
59
|
+
private readonly codec;
|
60
|
+
private readonly options;
|
61
|
+
private readonly plugin;
|
62
|
+
constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
|
63
|
+
handle(request: StandardLazyRequest, ...[options]: MaybeOptionalOptions<StandardHandleOptions<T>>): Promise<StandardHandleResult>;
|
64
|
+
}
|
65
|
+
|
66
|
+
interface HandlerPlugin<TContext extends Context> {
|
67
|
+
init?(options: StandardHandlerOptions<TContext>): void;
|
68
|
+
}
|
69
|
+
declare class CompositePlugin<TContext extends Context> implements HandlerPlugin<TContext> {
|
70
|
+
private readonly plugins;
|
71
|
+
constructor(plugins?: HandlerPlugin<TContext>[]);
|
72
|
+
init(options: StandardHandlerOptions<TContext>): void;
|
73
|
+
}
|
74
|
+
|
75
|
+
export { CompositePlugin as C, type HandlerPlugin as H, type StandardHandleOptions as S, type StandardHandlerInterceptorOptions as a, type StandardHandlerOptions as b, type StandardCodec as c, type StandardParams as d, type StandardMatcher as e, type StandardMatchResult as f, type StandardHandleResult as g, StandardHandler as h };
|