@orpc/server 1.14.11 → 1.14.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +98 -52
  2. package/dist/adapters/aws-lambda/index.d.mts +46 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +46 -0
  4. package/dist/adapters/aws-lambda/index.mjs +40 -0
  5. package/dist/adapters/bun-ws/index.d.mts +36 -0
  6. package/dist/adapters/bun-ws/index.d.ts +36 -0
  7. package/dist/adapters/bun-ws/index.mjs +47 -0
  8. package/dist/adapters/crossws/index.d.mts +21 -45
  9. package/dist/adapters/crossws/index.d.ts +21 -45
  10. package/dist/adapters/crossws/index.mjs +18 -40
  11. package/dist/adapters/fastify/index.d.mts +53 -0
  12. package/dist/adapters/fastify/index.d.ts +53 -0
  13. package/dist/adapters/fastify/index.mjs +52 -0
  14. package/dist/adapters/fetch/index.d.mts +96 -64
  15. package/dist/adapters/fetch/index.d.ts +96 -64
  16. package/dist/adapters/fetch/index.mjs +139 -34
  17. package/dist/adapters/message-port/index.d.mts +34 -49
  18. package/dist/adapters/message-port/index.d.ts +34 -49
  19. package/dist/adapters/message-port/index.mjs +37 -68
  20. package/dist/adapters/node/index.d.mts +71 -63
  21. package/dist/adapters/node/index.d.ts +71 -63
  22. package/dist/adapters/node/index.mjs +113 -36
  23. package/dist/adapters/standard/index.d.mts +18 -16
  24. package/dist/adapters/standard/index.d.ts +18 -16
  25. package/dist/adapters/standard/index.mjs +5 -5
  26. package/dist/adapters/standard-peer/index.d.mts +14 -12
  27. package/dist/adapters/standard-peer/index.d.ts +14 -12
  28. package/dist/adapters/standard-peer/index.mjs +21 -2
  29. package/dist/adapters/websocket/index.d.mts +38 -53
  30. package/dist/adapters/websocket/index.d.ts +38 -53
  31. package/dist/adapters/websocket/index.mjs +42 -59
  32. package/dist/adapters/ws/index.d.mts +31 -0
  33. package/dist/adapters/ws/index.d.ts +31 -0
  34. package/dist/adapters/ws/index.mjs +41 -0
  35. package/dist/helpers/index.d.mts +4 -4
  36. package/dist/helpers/index.d.ts +4 -4
  37. package/dist/helpers/index.mjs +5 -13
  38. package/dist/hibernation/index.d.mts +44 -0
  39. package/dist/hibernation/index.d.ts +44 -0
  40. package/dist/hibernation/index.mjs +65 -0
  41. package/dist/index.d.mts +770 -166
  42. package/dist/index.d.ts +770 -166
  43. package/dist/index.mjs +399 -306
  44. package/dist/plugins/index.d.mts +121 -214
  45. package/dist/plugins/index.d.ts +121 -214
  46. package/dist/plugins/index.mjs +214 -576
  47. package/dist/shared/server.7cEtMB30.d.ts +74 -0
  48. package/dist/shared/server.B8gYOD5g.d.mts +12 -0
  49. package/dist/shared/server.BqadksTP.d.mts +74 -0
  50. package/dist/shared/server.C8_sRzQB.d.mts +42 -0
  51. package/dist/shared/server.CMf4nKky.mjs +230 -0
  52. package/dist/shared/server.ChyoA9XY.d.ts +42 -0
  53. package/dist/shared/server.D8IXzfqT.d.ts +32 -0
  54. package/dist/shared/server.DEBcqOjg.mjs +418 -0
  55. package/dist/shared/{server.W91HSRkE.mjs → server.DZ5BIITo.mjs} +2 -2
  56. package/dist/shared/server.DzE6WeuY.d.mts +32 -0
  57. package/dist/shared/server.EfTOZ2Q7.d.ts +12 -0
  58. package/dist/shared/server.TEVCLCFC.mjs +39 -0
  59. package/dist/shared/server.qKsRrdxW.d.mts +193 -0
  60. package/dist/shared/server.qKsRrdxW.d.ts +193 -0
  61. package/package.json +56 -26
  62. package/dist/extensions/callable.d.mts +0 -10
  63. package/dist/extensions/callable.d.ts +0 -10
  64. package/dist/extensions/callable.mjs +0 -11
  65. package/dist/shared/server.15O7oC1p.d.mts +0 -61
  66. package/dist/shared/server.B4BnEWWm.d.mts +0 -67
  67. package/dist/shared/server.BhsVw7m7.d.ts +0 -104
  68. package/dist/shared/server.BoiFpNT7.mjs +0 -224
  69. package/dist/shared/server.COPVXhDG.mjs +0 -271
  70. package/dist/shared/server.CX4vUnDk.mjs +0 -11
  71. package/dist/shared/server.CcR4kgje.d.mts +0 -206
  72. package/dist/shared/server.CcR4kgje.d.ts +0 -206
  73. package/dist/shared/server.CnN50DHH.d.ts +0 -67
  74. package/dist/shared/server.DBs0rrf9.mjs +0 -41
  75. package/dist/shared/server.DDFizwfU.d.mts +0 -104
  76. package/dist/shared/server.D_QauotT.mjs +0 -30
  77. package/dist/shared/server.DofEOwf-.mjs +0 -237
  78. package/dist/shared/server.m3szVJGU.d.ts +0 -61
@@ -1,67 +0,0 @@
1
- import { RPCSerializer, AnyORPCError } from '@orpc/client';
2
- import { Value, Promisable } from '@orpc/shared';
3
- import { StandardMethod, StandardLazyRequest, StandardResponse } from '@standardserver/core';
4
- import { A as AnyProcedure, C as Context } from './server.CcR4kgje.mjs';
5
- import { A as AnyRouter } from './server.15O7oC1p.mjs';
6
- import { AnyProcedureContract } from '@orpc/contract';
7
- import { b as StandardHandlerHandleOptions, c as StandardHandlerCodec, d as StandardHandlerCodecResolvedProcedure } from './server.DDFizwfU.mjs';
8
-
9
- interface RPCMatcherOptions {
10
- /**
11
- * Filter which procedures are exposed for matching. Return `false` to exclude.
12
- *
13
- * @default true
14
- */
15
- filter?: Value<boolean, [procedure: AnyProcedureContract | AnyProcedure, path: string[]]>;
16
- }
17
- declare class RPCMatcher {
18
- private readonly filter;
19
- private readonly rootRouter;
20
- private readonly tree;
21
- private pendingLazyRouters;
22
- constructor(router: AnyRouter, options?: RPCMatcherOptions);
23
- private index;
24
- match(_method: StandardMethod, pathname: `/${string}`, prefix: `/${string}` | undefined): Promise<{
25
- path: string[];
26
- procedure: AnyProcedure;
27
- } | undefined>;
28
- private matchPathname;
29
- private resolvePendingLazyRouters;
30
- private resolveProcedure;
31
- }
32
-
33
- interface RPCHandlerCodecOptions<T extends Context> extends RPCMatcherOptions {
34
- /**
35
- * Override the default RPC serializer.
36
- */
37
- serializer?: Pick<RPCSerializer, keyof RPCSerializer>;
38
- /**
39
- * Resolve HTTP status for encoded successful outputs.
40
- *
41
- * Value should be in the `2xx` range and must be less than `400`.
42
- * Return `undefined` or `null` to fallback to default
43
- *
44
- * @default DEFAULT_SUCCESS_STATUS (200)
45
- */
46
- outputStatus?: Value<number | undefined | null, [output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>]>;
47
- /**
48
- * Mapping ORPCError Code -> HTTP Status Code
49
- * The status code should be in the `4xx` or `5xx` range (must be greater than or equal to `400`).
50
- *
51
- * @default COMMON_ERROR_STATUS_MAP
52
- */
53
- errorStatusMap?: Record<string, number> | undefined;
54
- }
55
- declare class RPCHandlerCodec<T extends Context> implements StandardHandlerCodec<T> {
56
- private readonly matcher;
57
- private readonly serializer;
58
- private readonly errorStatusMap;
59
- private readonly outputStatus;
60
- constructor(router: AnyRouter, options?: RPCHandlerCodecOptions<T>);
61
- resolveProcedure(request: StandardLazyRequest, options: StandardHandlerHandleOptions<T>): Promise<StandardHandlerCodecResolvedProcedure | undefined>;
62
- encodeOutput(output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
63
- encodeError(error: AnyORPCError, _procedure: AnyProcedure, _path: string[], _options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
64
- }
65
-
66
- export { RPCHandlerCodec as a, RPCMatcher as b };
67
- export type { RPCHandlerCodecOptions as R, RPCMatcherOptions as c };
@@ -1,104 +0,0 @@
1
- import { AnyORPCError } from '@orpc/client';
2
- import { OrderablePlugin, Interceptor, Promisable } from '@orpc/shared';
3
- import { StandardLazyRequest, StandardResponse } from '@standardserver/core';
4
- import { C as Context, c as ProcedureClientInterceptor, A as AnyProcedure } from './server.CcR4kgje.js';
5
- import { Schema, ErrorMap } from '@orpc/contract';
6
-
7
- interface StandardHandlerPlugin<T extends Context> extends OrderablePlugin {
8
- /**
9
- * Initializes the plugin and returns new handler options.
10
- * Called once per plugin instance during composition.
11
- *
12
- * This method allows plugins to wrap, extend, or transform handler options
13
- * such as interceptors, or configuration.
14
- *
15
- * @param options - The current handler options from previous plugins or base configuration
16
- * @returns Transformed handler options with plugin's modifications applied
17
- *
18
- * @example
19
- * ```ts
20
- * init(options) {
21
- * return {
22
- * ...options,
23
- * interceptors: [...(options.interceptors || []), myInterceptor]
24
- * }
25
- * }
26
- * ```
27
- */
28
- init?(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
29
- }
30
- declare class CompositeStandardHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
31
- readonly name = "~composite";
32
- protected readonly plugins: StandardHandlerPlugin<T>[];
33
- constructor(plugins?: StandardHandlerPlugin<T>[]);
34
- init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
35
- }
36
-
37
- interface StandardHandlerHandleOptions<T extends Context> {
38
- prefix?: `/${string}` | undefined;
39
- context: T;
40
- }
41
- type StandardHandlerHandleResult = {
42
- matched: true;
43
- response: StandardResponse;
44
- } | {
45
- matched: false;
46
- response?: undefined;
47
- };
48
- interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandlerCodecResolvedProcedure, StandardHandlerHandleOptions<T> {
49
- request: StandardLazyRequest;
50
- }
51
- type StandardHandlerInterceptor<T extends Context> = Interceptor<StandardHandlerInterceptorOptions<T>, Promise<StandardResponse>>;
52
- interface StandardHandlerRoutingInterceptorOptions<T extends Context> extends StandardHandlerHandleOptions<T> {
53
- request: StandardLazyRequest;
54
- }
55
- type StandardHandlerRoutingInterceptor<T extends Context> = Interceptor<StandardHandlerRoutingInterceptorOptions<T>, Promise<StandardHandlerHandleResult>>;
56
- interface StandardHandlerOptions<TContext extends Context> {
57
- /**
58
- * Fired on every request before routing, useful when you want
59
- * to intercept all requests regardless of whether they match a procedure or not.
60
- *
61
- * @examples
62
- * - batch plugins - separate one request into multiple and call multiple next
63
- * - openapi spec plugin - to intercept a request and early response
64
- */
65
- routingInterceptors?: StandardHandlerRoutingInterceptor<TContext>[];
66
- /**
67
- * interceptor run after routing and before error handler,
68
- * useful for error handling, logging, metrics, etc.
69
- */
70
- interceptors?: StandardHandlerInterceptor<TContext>[];
71
- /**
72
- *
73
- * ClientInterceptor equivalent with createRouterClient.interceptors / createProcedure.interceptors
74
- * useful for error handling, logging, metrics, etc. (not counting encoding/decoding)
75
- */
76
- clientInterceptors?: ProcedureClientInterceptor<TContext, Schema<unknown>, ErrorMap, any>[];
77
- plugins?: StandardHandlerPlugin<TContext>[];
78
- }
79
- declare class StandardHandler<T extends Context> {
80
- private readonly codec;
81
- private readonly routingInterceptors;
82
- private readonly interceptors;
83
- private readonly clientInterceptors;
84
- constructor(codec: StandardHandlerCodec<T>, options: StandardHandlerOptions<T>);
85
- handle(request: StandardLazyRequest, { context, prefix }: StandardHandlerHandleOptions<T>): Promise<StandardHandlerHandleResult>;
86
- }
87
- declare class OtelHandlerPlugin implements StandardHandlerPlugin<any> {
88
- name: string;
89
- init(options: StandardHandlerOptions<any>): StandardHandlerOptions<any>;
90
- }
91
-
92
- interface StandardHandlerCodecResolvedProcedure {
93
- path: string[];
94
- procedure: AnyProcedure;
95
- decodeInput: () => Promise<unknown>;
96
- }
97
- interface StandardHandlerCodec<T extends Context> {
98
- resolveProcedure(request: StandardLazyRequest, options: StandardHandlerHandleOptions<T>): Promisable<StandardHandlerCodecResolvedProcedure | undefined>;
99
- encodeOutput(output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
100
- encodeError(error: AnyORPCError, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
101
- }
102
-
103
- export { CompositeStandardHandlerPlugin as C, OtelHandlerPlugin as O, StandardHandler as S };
104
- export type { StandardHandlerOptions as a, StandardHandlerHandleOptions as b, StandardHandlerCodec as c, StandardHandlerCodecResolvedProcedure as d, StandardHandlerPlugin as e, StandardHandlerRoutingInterceptorOptions as f, StandardHandlerInterceptorOptions as g, StandardHandlerHandleResult as h, StandardHandlerInterceptor as i, StandardHandlerRoutingInterceptor as j };
@@ -1,224 +0,0 @@
1
- import { c as createProcedureClient, P as Procedure, L as Lazy, u as unlazy } from './server.DofEOwf-.mjs';
2
- import { resolveMetaPlugins, mergeErrorMap, ProcedureContract } from '@orpc/contract';
3
- import { getOrBind, omit, isTypescriptObject } from '@orpc/shared';
4
-
5
- const DEFAULT_SUCCESS_STATUS = 200;
6
- const DEFAULT_ERROR_STATUS = 500;
7
-
8
- function createGuardedProcedureLazy(lazy) {
9
- const guarded = new Lazy({
10
- ...lazy["~orpc"],
11
- async loader() {
12
- const { default: maybeProcedure } = await unlazy(lazy);
13
- if (!(maybeProcedure instanceof Procedure)) {
14
- throw new TypeError(`
15
- Expected a lazy<procedure> but got lazy<unknown>.
16
- This should be caught by TypeScript compilation.
17
- Please report this issue if you think this is a bug.
18
- `);
19
- }
20
- return { default: maybeProcedure };
21
- }
22
- });
23
- return guarded;
24
- }
25
- function createContractProcedure(procedure, contract) {
26
- return new Procedure({
27
- ...procedure["~orpc"],
28
- errorMap: contract["~orpc"].errorMap,
29
- meta: contract["~orpc"].meta,
30
- metaPlugins: contract["~orpc"].metaPlugins
31
- });
32
- }
33
- function call(lazyableProcedure, ...[
34
- input = void 0,
35
- options = {}
36
- ]) {
37
- return createProcedureClient(lazyableProcedure, options)(input, options);
38
- }
39
-
40
- const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol.for("ORPC_HIDDEN_ROUTER_CONTRACT");
41
- function withHiddenRouterContract(router, contract) {
42
- return new Proxy(router, {
43
- get(target, key) {
44
- if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
45
- return contract;
46
- }
47
- return getOrBind(target, key);
48
- }
49
- });
50
- }
51
- function getHiddenRouterContract(router) {
52
- return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
53
- }
54
-
55
- function augmentRouter(router, options) {
56
- if (router instanceof Lazy) {
57
- const [meta, metaPlugins] = resolveMetaPlugins(
58
- options.meta,
59
- options.metaPlugins,
60
- router["~orpc"].metaPlugins
61
- );
62
- const enhanced2 = new Lazy({
63
- meta,
64
- metaPlugins,
65
- async loader() {
66
- const { default: unlaziedRouter } = await unlazy(router);
67
- const enhanced3 = augmentRouter(unlaziedRouter, options);
68
- return unlazy(enhanced3);
69
- }
70
- });
71
- return enhanced2;
72
- }
73
- if (router instanceof Procedure) {
74
- const [meta, metaPlugins] = resolveMetaPlugins(
75
- options.meta,
76
- options.metaPlugins,
77
- router["~orpc"].metaPlugins
78
- );
79
- const enhanced2 = new Procedure({
80
- ...omit(options, ["middlewares", "errorMap", "meta", "metaPlugins"]),
81
- ...router["~orpc"],
82
- meta,
83
- metaPlugins,
84
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
85
- orderedMiddlewares: [
86
- ...options.middlewares.map((middleware) => ({ middleware, inputSchemasLengthAtUse: 0, outputSchemasLengthAtUse: 0 })),
87
- ...router["~orpc"].orderedMiddlewares
88
- ]
89
- });
90
- return enhanced2;
91
- }
92
- if (!isTypescriptObject(router)) {
93
- return router;
94
- }
95
- const enhanced = {};
96
- for (const key in router) {
97
- enhanced[key] = augmentRouter(router[key], options);
98
- }
99
- return enhanced;
100
- }
101
- function augmentImplementedRouter(router, options) {
102
- if (router instanceof Lazy) {
103
- const enhanced2 = new Lazy({
104
- ...router["~orpc"],
105
- async loader() {
106
- const { default: unlaziedRouter } = await unlazy(router);
107
- const enhanced3 = augmentImplementedRouter(unlaziedRouter, options);
108
- return unlazy(enhanced3);
109
- }
110
- });
111
- return enhanced2;
112
- }
113
- if (router instanceof Procedure) {
114
- const enhanced2 = new Procedure({
115
- ...omit(options, ["middlewares"]),
116
- ...router["~orpc"],
117
- orderedMiddlewares: [
118
- ...options.middlewares.map((middleware) => ({ middleware, inputSchemasLengthAtUse: 0, outputSchemasLengthAtUse: 0 })),
119
- ...router["~orpc"].orderedMiddlewares
120
- ]
121
- });
122
- return enhanced2;
123
- }
124
- if (!isTypescriptObject(router)) {
125
- return router;
126
- }
127
- const enhanced = {};
128
- for (const key in router) {
129
- enhanced[key] = augmentImplementedRouter(router[key], options);
130
- }
131
- return enhanced;
132
- }
133
- function getRouter(router, path) {
134
- let current = router;
135
- for (let i = 0; i < path.length; i++) {
136
- const segment = path[i];
137
- if (!isTypescriptObject(current)) {
138
- return void 0;
139
- }
140
- if (current instanceof Procedure) {
141
- return void 0;
142
- }
143
- if (!(current instanceof Lazy)) {
144
- current = current[segment];
145
- continue;
146
- }
147
- const lazied = current;
148
- const rest = path.slice(i);
149
- return new Lazy({
150
- ...lazied["~orpc"],
151
- async loader() {
152
- const unwrapped = await unlazy(lazied);
153
- const next = getRouter(unwrapped.default, rest);
154
- return await unlazy(next);
155
- }
156
- });
157
- }
158
- if (!isTypescriptObject(current)) {
159
- return void 0;
160
- }
161
- return current;
162
- }
163
- function walkProcedureContractsSync(router, callback, path = []) {
164
- const hiddenContract = getHiddenRouterContract(router);
165
- if (hiddenContract !== void 0) {
166
- router = hiddenContract;
167
- }
168
- if (router instanceof ProcedureContract) {
169
- callback(router, path);
170
- return [];
171
- }
172
- if (!isTypescriptObject(router)) {
173
- return [];
174
- }
175
- const lazyResults = [];
176
- for (const key in router) {
177
- const value = router[key];
178
- if (value instanceof Lazy) {
179
- lazyResults.push({ router: value, path: [...path, key] });
180
- } else {
181
- lazyResults.push(...walkProcedureContractsSync(value, callback, [...path, key]));
182
- }
183
- }
184
- return lazyResults;
185
- }
186
- async function walkProcedureContractsAsync(router, callback, path = []) {
187
- const hiddenContract = getHiddenRouterContract(router);
188
- if (hiddenContract !== void 0) {
189
- router = hiddenContract;
190
- }
191
- if (router instanceof ProcedureContract) {
192
- await callback(router, path);
193
- return;
194
- }
195
- if (!isTypescriptObject(router)) {
196
- return;
197
- }
198
- for (const key in router) {
199
- const value = router[key];
200
- if (value instanceof Lazy) {
201
- const { default: router2 } = await unlazy(value);
202
- await walkProcedureContractsAsync(router2, callback, [...path, key]);
203
- } else {
204
- await walkProcedureContractsAsync(value, callback, [...path, key]);
205
- }
206
- }
207
- }
208
- async function unlazyRouter(router) {
209
- if (router instanceof Procedure) {
210
- return router;
211
- }
212
- if (!isTypescriptObject(router)) {
213
- return router;
214
- }
215
- const unlazied = {};
216
- for (const key in router) {
217
- const item = router[key];
218
- const { default: unlaziedRouter } = await unlazy(item);
219
- unlazied[key] = await unlazyRouter(unlaziedRouter);
220
- }
221
- return unlazied;
222
- }
223
-
224
- export { DEFAULT_SUCCESS_STATUS as D, DEFAULT_ERROR_STATUS as a, augmentRouter as b, createContractProcedure as c, augmentImplementedRouter as d, withHiddenRouterContract as e, createGuardedProcedureLazy as f, getRouter as g, call as h, getHiddenRouterContract as i, walkProcedureContractsAsync as j, unlazyRouter as u, walkProcedureContractsSync as w };
@@ -1,271 +0,0 @@
1
- import { ORPCError, toORPCError, RPCSerializer, COMMON_ERROR_STATUS_MAP } from '@orpc/client';
2
- import { sortPlugins, getOpenTelemetryConfig, runWithSpan, toArray, matchesHttpPathPrefix, intercept, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, recordSpanError, pathToHttpPath, normalizeHttpPath, value, parseEmptyableJSON } from '@orpc/shared';
3
- import { flattenStandardHeader, parseStandardUrl } from '@standardserver/core';
4
- import { c as createProcedureClient, u as unlazy, P as Procedure } from './server.DofEOwf-.mjs';
5
- import { w as walkProcedureContractsSync, g as getRouter, c as createContractProcedure, D as DEFAULT_SUCCESS_STATUS, a as DEFAULT_ERROR_STATUS } from './server.BoiFpNT7.mjs';
6
-
7
- class CompositeStandardHandlerPlugin {
8
- name = "~composite";
9
- plugins;
10
- constructor(plugins = []) {
11
- this.plugins = sortPlugins(plugins);
12
- }
13
- init(options) {
14
- for (const plugin of this.plugins) {
15
- if (plugin.init) {
16
- options = plugin.init(options);
17
- }
18
- }
19
- return options;
20
- }
21
- }
22
-
23
- class StandardHandler {
24
- constructor(codec, options) {
25
- this.codec = codec;
26
- options = new CompositeStandardHandlerPlugin([
27
- new OtelHandlerPlugin(),
28
- ...toArray(options.plugins)
29
- ]).init(options);
30
- this.routingInterceptors = options.routingInterceptors;
31
- this.interceptors = options.interceptors;
32
- this.clientInterceptors = options.clientInterceptors;
33
- }
34
- routingInterceptors;
35
- interceptors;
36
- clientInterceptors;
37
- async handle(request, { context, prefix }) {
38
- if (prefix && !matchesHttpPathPrefix(request.url, prefix)) {
39
- return { matched: false, response: void 0 };
40
- }
41
- return intercept(
42
- this.routingInterceptors,
43
- { context, prefix, request },
44
- async ({ context: context2, prefix: prefix2, request: request2 }) => {
45
- const span = getOpenTelemetryConfig()?.trace.getActiveSpan();
46
- let step;
47
- const matchedOrNot = await runWithSpan("find_procedure", () => this.codec.resolveProcedure(request2, { context: context2, prefix: prefix2 }));
48
- if (!matchedOrNot) {
49
- span?.updateName(`${ORPC_NAME}_no_match`);
50
- span?.setAttribute("http.request.method", request2.method);
51
- span?.setAttribute("url.path", request2.url);
52
- return { matched: false };
53
- }
54
- const { path, procedure, decodeInput } = matchedOrNot;
55
- span?.updateName(`${ORPC_NAME}.${path.join("/")}`);
56
- span?.setAttribute("rpc.system", ORPC_NAME);
57
- span?.setAttribute("rpc.method", path.join("."));
58
- try {
59
- const response = await intercept(
60
- this.interceptors,
61
- { context: context2, prefix: prefix2, request: request2, path, procedure, decodeInput },
62
- async ({ context: context3, prefix: prefix3, request: request3, path: path2, procedure: procedure2, decodeInput: decodeInput2 }) => {
63
- step = "decode_input";
64
- let input = await runWithSpan("decode_input", decodeInput2);
65
- step = void 0;
66
- if (isAsyncIteratorObject(input)) {
67
- input = override(input, traceAsyncIterator("consume_async_iterator_object_input", input));
68
- }
69
- const client = createProcedureClient(procedure2, {
70
- context: context3,
71
- path: path2,
72
- interceptors: this.clientInterceptors
73
- });
74
- step = "call_procedure";
75
- const output = await client(input, {
76
- signal: request3.signal,
77
- lastEventId: flattenStandardHeader(request3.headers["last-event-id"])
78
- });
79
- step = void 0;
80
- const response2 = await this.codec.encodeOutput(output, procedure2, path2, { context: context3, prefix: prefix3 });
81
- return response2;
82
- }
83
- );
84
- return { matched: true, response };
85
- } catch (e) {
86
- if (step !== "call_procedure") {
87
- recordSpanError(span, e);
88
- }
89
- const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
90
- message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
91
- cause: e
92
- }) : toORPCError(e);
93
- const response = await this.codec.encodeError(error, procedure, path, { context: context2, prefix: prefix2 });
94
- return { matched: true, response };
95
- }
96
- }
97
- );
98
- }
99
- }
100
- class OtelHandlerPlugin {
101
- name = "~opentelemetry";
102
- init(options) {
103
- return {
104
- ...options,
105
- routingInterceptors: [
106
- // Should be placed before user-provided interceptors to help them access the current active context.
107
- async ({ next, request }) => {
108
- const otelConfig = getOpenTelemetryConfig();
109
- let propagationContext;
110
- if (otelConfig?.propagation) {
111
- propagationContext = otelConfig.propagation.extract(otelConfig.context.active(), request.headers);
112
- }
113
- return runWithSpan(
114
- { name: `${request.method} ${request.url}`, context: propagationContext },
115
- () => next()
116
- );
117
- },
118
- ...toArray(options.routingInterceptors)
119
- ]
120
- };
121
- }
122
- }
123
-
124
- class RPCMatcher {
125
- filter;
126
- rootRouter;
127
- tree = /* @__PURE__ */ new Map();
128
- pendingLazyRouters = [];
129
- constructor(router, options = {}) {
130
- this.filter = options.filter ?? true;
131
- this.rootRouter = router;
132
- this.index(router);
133
- }
134
- index(router, path = []) {
135
- const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
136
- if (!value(this.filter, procedure, procedurePath)) {
137
- return;
138
- }
139
- const httpPath = pathToHttpPath(procedurePath);
140
- if (procedure instanceof Procedure) {
141
- this.tree.set(httpPath, {
142
- path: procedurePath,
143
- contract: procedure,
144
- procedure
145
- });
146
- } else {
147
- this.tree.set(httpPath, {
148
- path: procedurePath,
149
- contract: procedure
150
- });
151
- }
152
- }, path);
153
- this.pendingLazyRouters.push(
154
- ...lazyResults.map((result) => ({
155
- ...result,
156
- httpPathPrefix: pathToHttpPath(result.path)
157
- }))
158
- );
159
- }
160
- async match(_method, pathname, prefix) {
161
- if (pathname.length > 1 && pathname.endsWith("/")) {
162
- pathname = pathname.slice(0, -1);
163
- }
164
- if (prefix) {
165
- if (!pathname.startsWith(prefix)) {
166
- return void 0;
167
- }
168
- const charAfterPrefix = pathname[prefix.length];
169
- if (charAfterPrefix === "/") {
170
- pathname = pathname.slice(prefix.length);
171
- } else if (charAfterPrefix === void 0) {
172
- pathname = "/";
173
- } else if (prefix[prefix.length - 1] === "/") {
174
- pathname = pathname.slice(prefix.length - 1);
175
- } else {
176
- return void 0;
177
- }
178
- }
179
- const result = await this.matchPathname(pathname);
180
- if (!result && pathname.includes("%")) {
181
- return this.matchPathname(normalizeHttpPath(pathname));
182
- }
183
- return result;
184
- }
185
- async matchPathname(pathname) {
186
- await this.resolvePendingLazyRouters(pathname);
187
- const entry = this.tree.get(pathname);
188
- if (!entry) {
189
- return void 0;
190
- }
191
- const procedure = await this.resolveProcedure(entry);
192
- return { path: entry.path, procedure };
193
- }
194
- async resolvePendingLazyRouters(pathname) {
195
- if (!this.pendingLazyRouters.length) {
196
- return;
197
- }
198
- const stillPending = [];
199
- for (const pending of this.pendingLazyRouters) {
200
- if (pathname.startsWith(pending.httpPathPrefix)) {
201
- const { default: router } = await unlazy(pending.router);
202
- this.index(router, pending.path);
203
- } else {
204
- stillPending.push(pending);
205
- }
206
- }
207
- this.pendingLazyRouters = stillPending;
208
- }
209
- async resolveProcedure(entry) {
210
- if (entry.procedure) {
211
- return entry.procedure;
212
- }
213
- const { default: maybeProcedure } = await unlazy(getRouter(this.rootRouter, entry.path));
214
- if (!(maybeProcedure instanceof Procedure)) {
215
- throw new TypeError(
216
- `[Contract-First] Missing or invalid implementation for procedure at path: "${entry.path.join(".")}". Ensure the procedure is correctly implemented and matches its contract.`
217
- );
218
- }
219
- entry.procedure = createContractProcedure(maybeProcedure, entry.contract);
220
- return entry.procedure;
221
- }
222
- }
223
-
224
- class RPCHandlerCodec {
225
- matcher;
226
- serializer;
227
- errorStatusMap;
228
- outputStatus;
229
- constructor(router, options = {}) {
230
- this.matcher = new RPCMatcher(router, options);
231
- this.serializer = options.serializer ?? new RPCSerializer();
232
- this.errorStatusMap = options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP;
233
- this.outputStatus = options.outputStatus;
234
- }
235
- async resolveProcedure(request, options) {
236
- const [pathname, query] = parseStandardUrl(request.url);
237
- const matched = await this.matcher.match(request.method, pathname, options.prefix);
238
- if (!matched) {
239
- return void 0;
240
- }
241
- return {
242
- procedure: matched.procedure,
243
- path: matched.path,
244
- decodeInput: async () => {
245
- if (request.method === "GET") {
246
- const dataString = new URLSearchParams(query).getAll("data").at(-1);
247
- return this.serializer.deserialize(parseEmptyableJSON(dataString));
248
- }
249
- const body = await request.resolveBody();
250
- return this.serializer.deserialize(body);
251
- }
252
- };
253
- }
254
- encodeOutput(output, procedure, path, options) {
255
- return {
256
- headers: {},
257
- status: value(this.outputStatus, output, procedure, path, options) ?? DEFAULT_SUCCESS_STATUS,
258
- body: this.serializer.serialize(output)
259
- };
260
- }
261
- encodeError(error, _procedure, _path, _options) {
262
- const status = this.errorStatusMap[error.code] ?? DEFAULT_ERROR_STATUS;
263
- return {
264
- headers: {},
265
- status,
266
- body: this.serializer.serialize(error.toJSON())
267
- };
268
- }
269
- }
270
-
271
- export { CompositeStandardHandlerPlugin as C, OtelHandlerPlugin as O, RPCHandlerCodec as R, StandardHandler as S, RPCMatcher as a };
@@ -1,11 +0,0 @@
1
- import { value } from '@orpc/shared';
2
-
3
- function createStandardPeerRequestHandler(handler, options) {
4
- return async (request) => {
5
- const context = await value(options.context ?? {}, request);
6
- const { response } = await handler.handle(request, { ...options, context });
7
- return response ?? { status: 404, headers: {}, body: "No procedure matched" };
8
- };
9
- }
10
-
11
- export { createStandardPeerRequestHandler as c };