@orpc/server 0.0.0-next.c59d67c → 0.0.0-next.c72b962
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 +131 -0
- package/dist/adapters/fetch/index.d.mts +58 -0
- package/dist/adapters/fetch/index.d.ts +58 -0
- package/dist/adapters/fetch/index.mjs +11 -0
- package/dist/adapters/hono/index.d.mts +22 -0
- package/dist/adapters/hono/index.d.ts +22 -0
- package/dist/adapters/hono/index.mjs +34 -0
- package/dist/adapters/next/index.d.mts +29 -0
- package/dist/adapters/next/index.d.ts +29 -0
- package/dist/adapters/next/index.mjs +31 -0
- package/dist/adapters/node/index.d.mts +57 -0
- package/dist/adapters/node/index.d.ts +57 -0
- package/dist/adapters/node/index.mjs +90 -0
- package/dist/adapters/standard/index.d.mts +26 -0
- package/dist/adapters/standard/index.d.ts +26 -0
- package/dist/adapters/standard/index.mjs +8 -0
- package/dist/index.d.mts +291 -0
- package/dist/index.d.ts +291 -0
- package/dist/index.mjs +363 -0
- package/dist/plugins/index.d.mts +124 -0
- package/dist/plugins/index.d.ts +124 -0
- package/dist/plugins/index.mjs +244 -0
- package/dist/shared/server.BVwwTHyO.mjs +9 -0
- package/dist/shared/server.BW-nUGgA.mjs +36 -0
- package/dist/shared/server.Bm0UqHzd.mjs +103 -0
- package/dist/shared/server.C37gDhSZ.mjs +364 -0
- package/dist/shared/server.C8NkqxHo.d.ts +17 -0
- package/dist/shared/server.CGCwEAt_.d.mts +10 -0
- package/dist/shared/server.DCQgF_JR.d.mts +17 -0
- package/dist/shared/server.DFFT_EZo.d.ts +73 -0
- package/dist/shared/server.DFuJLDuo.mjs +190 -0
- package/dist/shared/server.DLt5njUb.d.mts +143 -0
- package/dist/shared/server.DLt5njUb.d.ts +143 -0
- package/dist/shared/server.DOYDVeMX.d.mts +73 -0
- package/dist/shared/server._2UufoXA.d.ts +10 -0
- package/package.json +41 -18
- package/dist/chunk-TDFYNRZV.js +0 -190
- package/dist/fetch.js +0 -106
- package/dist/index.js +0 -394
- package/dist/src/builder.d.ts +0 -49
- package/dist/src/fetch/handle.d.ts +0 -7
- package/dist/src/fetch/handler.d.ts +0 -3
- package/dist/src/fetch/index.d.ts +0 -4
- package/dist/src/fetch/types.d.ts +0 -35
- package/dist/src/index.d.ts +0 -15
- package/dist/src/middleware.d.ts +0 -26
- package/dist/src/procedure-builder.d.ts +0 -31
- package/dist/src/procedure-caller.d.ts +0 -19
- package/dist/src/procedure-implementer.d.ts +0 -18
- package/dist/src/procedure.d.ts +0 -29
- package/dist/src/router-builder.d.ts +0 -22
- package/dist/src/router-caller.d.ts +0 -22
- package/dist/src/router-implementer.d.ts +0 -20
- package/dist/src/router.d.ts +0 -20
- package/dist/src/types.d.ts +0 -8
- package/dist/src/utils.d.ts +0 -3
@@ -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 };
|
@@ -0,0 +1,17 @@
|
|
1
|
+
import { C as Context, R as Router } from './server.DLt5njUb.js';
|
2
|
+
import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
|
3
|
+
import { a as StandardHandlerOptions, b as StandardHandler } from './server.DFFT_EZo.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,10 @@
|
|
1
|
+
import { C as Context } from './server.DLt5njUb.mjs';
|
2
|
+
import { S as StandardHandleOptions } from './server.DOYDVeMX.mjs';
|
3
|
+
|
4
|
+
type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
|
5
|
+
context?: T;
|
6
|
+
} : {
|
7
|
+
context: T;
|
8
|
+
});
|
9
|
+
|
10
|
+
export type { FriendlyStandardHandleOptions as F };
|
@@ -0,0 +1,17 @@
|
|
1
|
+
import { C as Context, R as Router } from './server.DLt5njUb.mjs';
|
2
|
+
import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
|
3
|
+
import { a as StandardHandlerOptions, b as StandardHandler } from './server.DOYDVeMX.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,73 @@
|
|
1
|
+
import { HTTPPath, ORPCError } from '@orpc/client';
|
2
|
+
import { Meta, InferSchemaOutput, AnySchema, ErrorFromErrorMap } from '@orpc/contract';
|
3
|
+
import { Interceptor, ThrowableError } from '@orpc/shared';
|
4
|
+
import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
|
5
|
+
import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.DLt5njUb.js';
|
6
|
+
|
7
|
+
type StandardParams = Record<string, string>;
|
8
|
+
type StandardMatchResult = {
|
9
|
+
path: readonly string[];
|
10
|
+
procedure: AnyProcedure;
|
11
|
+
params?: StandardParams;
|
12
|
+
} | undefined;
|
13
|
+
interface StandardMatcher {
|
14
|
+
init(router: AnyRouter): void;
|
15
|
+
match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
|
16
|
+
}
|
17
|
+
interface StandardCodec {
|
18
|
+
encode(output: unknown, procedure: AnyProcedure): StandardResponse;
|
19
|
+
encodeError(error: ORPCError<any, any>): StandardResponse;
|
20
|
+
decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
|
21
|
+
}
|
22
|
+
|
23
|
+
interface StandardHandlerPlugin<TContext extends Context> {
|
24
|
+
order?: number;
|
25
|
+
init?(options: StandardHandlerOptions<TContext>): void;
|
26
|
+
}
|
27
|
+
declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
|
28
|
+
protected readonly plugins: TPlugin[];
|
29
|
+
constructor(plugins?: readonly TPlugin[]);
|
30
|
+
init(options: StandardHandlerOptions<T>): void;
|
31
|
+
}
|
32
|
+
|
33
|
+
interface StandardHandleOptions<T extends Context> {
|
34
|
+
prefix?: HTTPPath;
|
35
|
+
context: T;
|
36
|
+
}
|
37
|
+
type StandardHandleResult = {
|
38
|
+
matched: true;
|
39
|
+
response: StandardResponse;
|
40
|
+
} | {
|
41
|
+
matched: false;
|
42
|
+
response: undefined;
|
43
|
+
};
|
44
|
+
interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
|
45
|
+
request: StandardLazyRequest;
|
46
|
+
}
|
47
|
+
interface StandardHandlerOptions<TContext extends Context> {
|
48
|
+
plugins?: StandardHandlerPlugin<TContext>[];
|
49
|
+
/**
|
50
|
+
* Interceptors at the request level, helpful when you want catch errors
|
51
|
+
*/
|
52
|
+
interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
|
53
|
+
/**
|
54
|
+
* Interceptors at the root level, helpful when you want override the request/response
|
55
|
+
*/
|
56
|
+
rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
|
57
|
+
/**
|
58
|
+
*
|
59
|
+
* Interceptors for procedure client.
|
60
|
+
*/
|
61
|
+
clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
|
62
|
+
}
|
63
|
+
declare class StandardHandler<T extends Context> {
|
64
|
+
private readonly matcher;
|
65
|
+
private readonly codec;
|
66
|
+
private readonly interceptors;
|
67
|
+
private readonly clientInterceptors;
|
68
|
+
private readonly rootInterceptors;
|
69
|
+
constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
|
70
|
+
handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
|
71
|
+
}
|
72
|
+
|
73
|
+
export { CompositeStandardHandlerPlugin as C, type StandardHandleOptions as S, type StandardHandlerOptions as a, StandardHandler as b, type StandardCodec as c, type StandardParams as d, type StandardMatcher as e, type StandardMatchResult as f, type StandardHandleResult as g, type StandardHandlerInterceptorOptions as h, type StandardHandlerPlugin as i };
|
@@ -0,0 +1,190 @@
|
|
1
|
+
import { toHttpPath, StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
|
2
|
+
import { toArray, intercept, parseEmptyableJSON } from '@orpc/shared';
|
3
|
+
import '@orpc/standard-server/batch';
|
4
|
+
import { ORPCError, toORPCError } from '@orpc/client';
|
5
|
+
import { S as StrictGetMethodPlugin } from './server.BW-nUGgA.mjs';
|
6
|
+
import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.C37gDhSZ.mjs';
|
7
|
+
|
8
|
+
class CompositeStandardHandlerPlugin {
|
9
|
+
plugins;
|
10
|
+
constructor(plugins = []) {
|
11
|
+
this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
12
|
+
}
|
13
|
+
init(options) {
|
14
|
+
for (const plugin of this.plugins) {
|
15
|
+
plugin.init?.(options);
|
16
|
+
}
|
17
|
+
}
|
18
|
+
}
|
19
|
+
|
20
|
+
class StandardHandler {
|
21
|
+
constructor(router, matcher, codec, options) {
|
22
|
+
this.matcher = matcher;
|
23
|
+
this.codec = codec;
|
24
|
+
const plugins = new CompositeStandardHandlerPlugin(options.plugins);
|
25
|
+
plugins.init(options);
|
26
|
+
this.interceptors = toArray(options.interceptors);
|
27
|
+
this.clientInterceptors = toArray(options.clientInterceptors);
|
28
|
+
this.rootInterceptors = toArray(options.rootInterceptors);
|
29
|
+
this.matcher.init(router);
|
30
|
+
}
|
31
|
+
interceptors;
|
32
|
+
clientInterceptors;
|
33
|
+
rootInterceptors;
|
34
|
+
async handle(request, options) {
|
35
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
36
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
37
|
+
return { matched: false, response: void 0 };
|
38
|
+
}
|
39
|
+
return intercept(
|
40
|
+
this.rootInterceptors,
|
41
|
+
{ ...options, request, prefix },
|
42
|
+
async (interceptorOptions) => {
|
43
|
+
let isDecoding = false;
|
44
|
+
try {
|
45
|
+
return await intercept(
|
46
|
+
this.interceptors,
|
47
|
+
interceptorOptions,
|
48
|
+
async ({ request: request2, context, prefix: prefix2 }) => {
|
49
|
+
const method = request2.method;
|
50
|
+
const url = request2.url;
|
51
|
+
const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
|
52
|
+
const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
|
53
|
+
if (!match) {
|
54
|
+
return { matched: false, response: void 0 };
|
55
|
+
}
|
56
|
+
const client = createProcedureClient(match.procedure, {
|
57
|
+
context,
|
58
|
+
path: match.path,
|
59
|
+
interceptors: this.clientInterceptors
|
60
|
+
});
|
61
|
+
isDecoding = true;
|
62
|
+
const input = await this.codec.decode(request2, match.params, match.procedure);
|
63
|
+
isDecoding = false;
|
64
|
+
const lastEventId = Array.isArray(request2.headers["last-event-id"]) ? request2.headers["last-event-id"].at(-1) : request2.headers["last-event-id"];
|
65
|
+
const output = await client(input, { signal: request2.signal, lastEventId });
|
66
|
+
const response = this.codec.encode(output, match.procedure);
|
67
|
+
return {
|
68
|
+
matched: true,
|
69
|
+
response
|
70
|
+
};
|
71
|
+
}
|
72
|
+
);
|
73
|
+
} catch (e) {
|
74
|
+
const error = isDecoding && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
|
75
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
76
|
+
cause: e
|
77
|
+
}) : toORPCError(e);
|
78
|
+
const response = this.codec.encodeError(error);
|
79
|
+
return {
|
80
|
+
matched: true,
|
81
|
+
response
|
82
|
+
};
|
83
|
+
}
|
84
|
+
}
|
85
|
+
);
|
86
|
+
}
|
87
|
+
}
|
88
|
+
|
89
|
+
class StandardRPCCodec {
|
90
|
+
constructor(serializer) {
|
91
|
+
this.serializer = serializer;
|
92
|
+
}
|
93
|
+
async decode(request, _params, _procedure) {
|
94
|
+
const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
|
95
|
+
return this.serializer.deserialize(serialized);
|
96
|
+
}
|
97
|
+
encode(output, _procedure) {
|
98
|
+
return {
|
99
|
+
status: 200,
|
100
|
+
headers: {},
|
101
|
+
body: this.serializer.serialize(output)
|
102
|
+
};
|
103
|
+
}
|
104
|
+
encodeError(error) {
|
105
|
+
return {
|
106
|
+
status: error.status,
|
107
|
+
headers: {},
|
108
|
+
body: this.serializer.serialize(error.toJSON())
|
109
|
+
};
|
110
|
+
}
|
111
|
+
}
|
112
|
+
|
113
|
+
class StandardRPCMatcher {
|
114
|
+
tree = {};
|
115
|
+
pendingRouters = [];
|
116
|
+
init(router, path = []) {
|
117
|
+
const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
|
118
|
+
const httpPath = toHttpPath(path2);
|
119
|
+
if (isProcedure(contract)) {
|
120
|
+
this.tree[httpPath] = {
|
121
|
+
path: path2,
|
122
|
+
contract,
|
123
|
+
procedure: contract,
|
124
|
+
// this mean dev not used contract-first so we can used contract as procedure directly
|
125
|
+
router
|
126
|
+
};
|
127
|
+
} else {
|
128
|
+
this.tree[httpPath] = {
|
129
|
+
path: path2,
|
130
|
+
contract,
|
131
|
+
procedure: void 0,
|
132
|
+
router
|
133
|
+
};
|
134
|
+
}
|
135
|
+
});
|
136
|
+
this.pendingRouters.push(...laziedOptions.map((option) => ({
|
137
|
+
...option,
|
138
|
+
httpPathPrefix: toHttpPath(option.path)
|
139
|
+
})));
|
140
|
+
}
|
141
|
+
async match(_method, pathname) {
|
142
|
+
if (this.pendingRouters.length) {
|
143
|
+
const newPendingRouters = [];
|
144
|
+
for (const pendingRouter of this.pendingRouters) {
|
145
|
+
if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
146
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
147
|
+
this.init(router, pendingRouter.path);
|
148
|
+
} else {
|
149
|
+
newPendingRouters.push(pendingRouter);
|
150
|
+
}
|
151
|
+
}
|
152
|
+
this.pendingRouters = newPendingRouters;
|
153
|
+
}
|
154
|
+
const match = this.tree[pathname];
|
155
|
+
if (!match) {
|
156
|
+
return void 0;
|
157
|
+
}
|
158
|
+
if (!match.procedure) {
|
159
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
|
160
|
+
if (!isProcedure(maybeProcedure)) {
|
161
|
+
throw new Error(`
|
162
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
|
163
|
+
Ensure that the procedure is correctly defined and matches the expected contract.
|
164
|
+
`);
|
165
|
+
}
|
166
|
+
match.procedure = createContractedProcedure(maybeProcedure, match.contract);
|
167
|
+
}
|
168
|
+
return {
|
169
|
+
path: match.path,
|
170
|
+
procedure: match.procedure
|
171
|
+
};
|
172
|
+
}
|
173
|
+
}
|
174
|
+
|
175
|
+
class StandardRPCHandler extends StandardHandler {
|
176
|
+
constructor(router, options) {
|
177
|
+
options.plugins ??= [];
|
178
|
+
const strictGetMethodPluginEnabled = options.strictGetMethodPluginEnabled ?? true;
|
179
|
+
if (strictGetMethodPluginEnabled) {
|
180
|
+
options.plugins.push(new StrictGetMethodPlugin());
|
181
|
+
}
|
182
|
+
const jsonSerializer = new StandardRPCJsonSerializer(options);
|
183
|
+
const serializer = new StandardRPCSerializer(jsonSerializer);
|
184
|
+
const matcher = new StandardRPCMatcher();
|
185
|
+
const codec = new StandardRPCCodec(serializer);
|
186
|
+
super(router, matcher, codec, options);
|
187
|
+
}
|
188
|
+
}
|
189
|
+
|
190
|
+
export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardRPCCodec as a, StandardRPCHandler as b, StandardRPCMatcher as c };
|