@orpc/server 2.0.0-beta.34 → 2.0.0-beta.36

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 (43) hide show
  1. package/README.md +30 -20
  2. package/dist/adapters/aws-lambda/index.mjs +3 -3
  3. package/dist/adapters/crossws/index.d.mts +2 -2
  4. package/dist/adapters/crossws/index.d.ts +2 -2
  5. package/dist/adapters/crossws/index.mjs +5 -4
  6. package/dist/adapters/fastify/index.mjs +3 -3
  7. package/dist/adapters/fetch/index.d.mts +1 -1
  8. package/dist/adapters/fetch/index.d.ts +1 -1
  9. package/dist/adapters/fetch/index.mjs +3 -3
  10. package/dist/adapters/message-port/index.d.mts +3 -3
  11. package/dist/adapters/message-port/index.d.ts +3 -3
  12. package/dist/adapters/message-port/index.mjs +5 -4
  13. package/dist/adapters/node/index.d.mts +1 -1
  14. package/dist/adapters/node/index.d.ts +1 -1
  15. package/dist/adapters/node/index.mjs +3 -3
  16. package/dist/adapters/standard/index.d.mts +91 -17
  17. package/dist/adapters/standard/index.d.ts +91 -17
  18. package/dist/adapters/standard/index.mjs +3 -3
  19. package/dist/adapters/standard-peer/index.d.mts +4 -9
  20. package/dist/adapters/standard-peer/index.d.ts +4 -9
  21. package/dist/adapters/standard-peer/index.mjs +10 -2
  22. package/dist/adapters/websocket/index.d.mts +3 -3
  23. package/dist/adapters/websocket/index.d.ts +3 -3
  24. package/dist/adapters/websocket/index.mjs +5 -4
  25. package/dist/extensions/callable.mjs +2 -2
  26. package/dist/index.mjs +7 -9
  27. package/dist/plugins/index.d.mts +2 -2
  28. package/dist/plugins/index.d.ts +2 -2
  29. package/dist/plugins/index.mjs +3 -3
  30. package/dist/shared/{server.BNfuzVqH.mjs → server.24nXyhbl.mjs} +1 -1
  31. package/dist/shared/{server.BrURRtO7.d.mts → server.B5K1CViq.d.mts} +21 -10
  32. package/dist/shared/{server.gXC5UaAH.mjs → server.BynNaBBA.mjs} +8 -10
  33. package/dist/shared/{server.CGQ3M7fX.d.mts → server.C7xllBNN.d.mts} +1 -1
  34. package/dist/shared/server.CFqSIFnT.d.mts +14 -0
  35. package/dist/shared/{server.D23TTT5i.d.ts → server.Cxranw-8.d.ts} +21 -10
  36. package/dist/shared/{server.C-hqoApz.d.ts → server.D0dr-F8u.d.ts} +1 -1
  37. package/dist/shared/{server.CDOFCg6A.mjs → server.Djb_ebJT.mjs} +3 -4
  38. package/dist/shared/server.RRVK1xTV.d.ts +14 -0
  39. package/dist/shared/{server.ozO1TILY.mjs → server.vUIzQiOP.mjs} +82 -21
  40. package/package.json +4 -4
  41. package/dist/shared/server.ByvwIMbH.d.mts +0 -91
  42. package/dist/shared/server.CAmrY_mX.d.ts +0 -91
  43. package/dist/shared/server.CX4vUnDk.mjs +0 -11
@@ -1,8 +1,8 @@
1
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, getOwn } from '@orpc/shared';
3
- import { flattenStandardHeader, parseStandardUrl } from '@standard-server/core';
4
- import { c as createProcedureClient, u as unlazy, P as Procedure } from './server.CDOFCg6A.mjs';
5
- import { w as walkProcedureContractsSync, g as getRouter, c as createContractProcedure, D as DEFAULT_SUCCESS_STATUS, a as DEFAULT_ERROR_STATUS } from './server.gXC5UaAH.mjs';
2
+ import { sortPlugins, toArray, matchesHttpPathPrefix, value, intercept, getTracer, runWithSpan, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, traceReadableStream, recordSpanError, toTracingException, wrapAsyncIterator, wrapReadableStream, pathToHttpPath, normalizeHttpPath, parseEmptyableJSON, getOwn } from '@orpc/shared';
3
+ import { flattenStandardHeader, parseStandardUrl, ErrorEvent } from '@standard-server/core';
4
+ import { c as createProcedureClient, u as unlazy, P as Procedure } from './server.Djb_ebJT.mjs';
5
+ import { w as walkProcedureContractsSync, g as getRouter, c as createContractProcedure, D as DEFAULT_SUCCESS_STATUS, a as DEFAULT_ERROR_STATUS } from './server.BynNaBBA.mjs';
6
6
 
7
7
  class CompositeStandardHandlerPlugin {
8
8
  name = "~composite";
@@ -24,8 +24,8 @@ class StandardHandler {
24
24
  constructor(codec, options) {
25
25
  this.codec = codec;
26
26
  options = new CompositeStandardHandlerPlugin([
27
- new OtelHandlerPlugin(),
28
- ...toArray(options.plugins)
27
+ ...toArray(options.plugins),
28
+ new TracingHandlerPlugin()
29
29
  ]).init(options);
30
30
  this.routingInterceptors = options.routingInterceptors;
31
31
  this.interceptors = options.interceptors;
@@ -34,15 +34,17 @@ class StandardHandler {
34
34
  routingInterceptors;
35
35
  interceptors;
36
36
  clientInterceptors;
37
- async handle(request, { context, prefix }) {
37
+ async handle(request, options) {
38
+ const { prefix } = options;
38
39
  if (prefix && !matchesHttpPathPrefix(request.url, prefix)) {
39
40
  return { matched: false, response: void 0 };
40
41
  }
42
+ const context = await value(options.context, request);
41
43
  return intercept(
42
44
  this.routingInterceptors,
43
45
  { context, prefix, request },
44
46
  async ({ context: context2, prefix: prefix2, request: request2 }) => {
45
- const span = getOpenTelemetryConfig()?.trace.getActiveSpan();
47
+ const span = getTracer()?.getActiveSpan();
46
48
  let step;
47
49
  const matchedOrNot = await runWithSpan("find_procedure", () => this.codec.resolveProcedure(request2, { context: context2, prefix: prefix2 }));
48
50
  if (!matchedOrNot) {
@@ -63,8 +65,10 @@ class StandardHandler {
63
65
  step = "decode_input";
64
66
  let input = await runWithSpan("decode_input", decodeInput2);
65
67
  step = void 0;
66
- if (isAsyncIteratorObject(input)) {
68
+ if (getTracer() && isAsyncIteratorObject(input)) {
67
69
  input = override(input, traceAsyncIterator("consume_async_iterator_object_input", input));
70
+ } else if (getTracer() && input instanceof ReadableStream) {
71
+ input = override(input, traceReadableStream("consume_octet_stream_input", input));
68
72
  }
69
73
  const client = createProcedureClient(procedure2, {
70
74
  context: context3,
@@ -97,23 +101,80 @@ class StandardHandler {
97
101
  );
98
102
  }
99
103
  }
100
- class OtelHandlerPlugin {
101
- name = "~opentelemetry";
104
+ class TracingHandlerPlugin {
105
+ name = "~tracing";
102
106
  init(options) {
103
107
  return {
104
108
  ...options,
105
109
  routingInterceptors: [
106
- // Should be placed before user-provided interceptors to help them access the current active context.
110
+ // Should be placed before user-provided interceptors to help them access the current active span.
107
111
  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
+ const tracer = getTracer();
113
+ if (!tracer) {
114
+ return next();
112
115
  }
113
- return runWithSpan(
114
- { name: `${request.method} ${request.url}`, context: propagationContext },
115
- () => next()
116
- );
116
+ const parent = tracer.extract?.(request.headers);
117
+ const [pathname] = parseStandardUrl(request.url);
118
+ const span = tracer.startSpan(`${request.method} ${pathname}`, parent);
119
+ let result;
120
+ try {
121
+ result = await tracer.withActiveSpan(span, next);
122
+ } catch (e) {
123
+ span.recordException("error", toTracingException(e));
124
+ span.end();
125
+ throw e;
126
+ }
127
+ if (!result.matched) {
128
+ span.end();
129
+ return result;
130
+ }
131
+ const body = result.response.body;
132
+ if (isAsyncIteratorObject(body)) {
133
+ return {
134
+ ...result,
135
+ response: {
136
+ ...result.response,
137
+ /**
138
+ * @remarks
139
+ * **Warning**: Remember use `override` for remaining special properties
140
+ */
141
+ body: override(body, wrapAsyncIterator(body, {
142
+ runWith: (fn) => tracer.withActiveSpan(span, fn),
143
+ onError(error) {
144
+ if (!(error instanceof ErrorEvent)) {
145
+ span.recordException("error", toTracingException(error));
146
+ }
147
+ },
148
+ onFinish() {
149
+ span.end();
150
+ }
151
+ }))
152
+ }
153
+ };
154
+ }
155
+ if (body instanceof ReadableStream) {
156
+ return {
157
+ ...result,
158
+ response: {
159
+ ...result.response,
160
+ /**
161
+ * @remarks
162
+ * **Warning**: Remember use `override` for remaining special properties
163
+ */
164
+ body: override(body, wrapReadableStream(body, {
165
+ runWith: (fn) => tracer.withActiveSpan(span, fn),
166
+ onError(error) {
167
+ span.recordException("error", toTracingException(error));
168
+ },
169
+ onFinish() {
170
+ span.end();
171
+ }
172
+ }))
173
+ }
174
+ };
175
+ }
176
+ span.end();
177
+ return result;
117
178
  },
118
179
  ...toArray(options.routingInterceptors)
119
180
  ]
@@ -301,4 +362,4 @@ class RPCHandlerCodec {
301
362
  }
302
363
  }
303
364
 
304
- export { CompositeStandardHandlerPlugin as C, OtelHandlerPlugin as O, RPCHandlerCodec as R, StandardHandler as S, RPCMatcher as a, RPC_DEFAULT_ALLOW_METHODS as b };
365
+ export { CompositeStandardHandlerPlugin as C, RPCHandlerCodec as R, StandardHandler as S, TracingHandlerPlugin as T, RPCMatcher as a, RPC_DEFAULT_ALLOW_METHODS as b };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/server",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.34",
4
+ "version": "2.0.0-beta.36",
5
5
  "description": "Build typesafe APIs with oRPC: RPC and OpenAPI support, middleware, and adapters for Node.js, Bun, Deno, Fetch, Fastify, WebSocket, AWS Lambda, and more",
6
6
  "license": "MIT",
7
7
  "funding": [
@@ -117,9 +117,9 @@
117
117
  }
118
118
  },
119
119
  "dependencies": {
120
- "@orpc/client": "2.0.0-beta.34",
121
- "@orpc/contract": "2.0.0-beta.34",
122
- "@orpc/shared": "2.0.0-beta.34",
120
+ "@orpc/client": "2.0.0-beta.36",
121
+ "@orpc/contract": "2.0.0-beta.36",
122
+ "@orpc/shared": "2.0.0-beta.36",
123
123
  "@standard-server/aws-lambda": "~0.9.0",
124
124
  "@standard-server/core": "~0.9.0",
125
125
  "@standard-server/fastify": "~0.9.0",
@@ -1,91 +0,0 @@
1
- import { RPCSerializer, AnyORPCError } from '@orpc/client';
2
- import { Value, Promisable } from '@orpc/shared';
3
- import { StandardMethod, StandardLazyRequest, StandardResponse } from '@standard-server/core';
4
- import { A as AnyProcedure, C as Context } from './server.BsujoJoF.mjs';
5
- import { A as AnyRouter } from './server.BpmUhems.mjs';
6
- import { AnyProcedureContract } from '@orpc/contract';
7
- import { c as StandardHandlerHandleOptions, d as StandardHandlerCodec, e as StandardHandlerCodecResolvedProcedure } from './server.BrURRtO7.mjs';
8
-
9
- /**
10
- * Methods that can invoke procedures by default. Browsers cannot trigger them
11
- * cross-site without a CORS preflight or an HTML form, unlike `GET`, which a plain
12
- * `<a>` click or redirect can trigger with `SameSite=Lax` cookies attached. Other
13
- * methods (`HEAD`, `OPTIONS`, `QUERY`, ...) have safe semantics that should not
14
- * invoke a procedure that can modify data.
15
- *
16
- * @see {@link https://orpc.dev/docs/rpc/handler#supported-http-methods | RPC Handler - Supported HTTP Methods}
17
- */
18
- declare const RPC_DEFAULT_ALLOW_METHODS: readonly StandardMethod[];
19
- interface RPCMatcherOptions {
20
- /**
21
- * Filter which procedures are exposed for matching. Return `false` to exclude.
22
- *
23
- * @default true
24
- */
25
- filter?: Value<boolean, [procedure: AnyProcedureContract | AnyProcedure, path: string[]]>;
26
- /**
27
- * Restricts which HTTP methods can invoke procedures, either with a list of allowed
28
- * methods or decided per request via a function. Requests using a disallowed method
29
- * are treated as unmatched. `GET` is excluded by default because it is exposed to
30
- * Cross-Site Request Forgery (CSRF) attacks.
31
- *
32
- * @default RPC_DEFAULT_ALLOW_METHODS (['POST', 'PUT', 'PATCH', 'DELETE'])
33
- * @see {@link https://orpc.dev/docs/rpc/handler#supported-http-methods | RPC Handler - Supported HTTP Methods}
34
- */
35
- allowMethods?: readonly StandardMethod[] | ((method: StandardMethod, procedure: AnyProcedure, path: string[]) => boolean);
36
- }
37
- declare class RPCMatcher {
38
- private readonly filter;
39
- private readonly allowMethodsSet;
40
- private readonly allowMethodsFn;
41
- private readonly rootRouter;
42
- private readonly tree;
43
- private readonly pendingLazyRouters;
44
- constructor(router: AnyRouter, options?: RPCMatcherOptions);
45
- private index;
46
- match(method: StandardMethod, pathname: `/${string}`, prefix: `/${string}` | undefined): Promise<{
47
- path: string[];
48
- procedure: AnyProcedure;
49
- } | undefined>;
50
- private resolvePendingLazyRouters;
51
- private loadPendingLazyRouters;
52
- private loadPendingLazyRouter;
53
- private indexPendingLazyRouter;
54
- private resolveProcedure;
55
- }
56
-
57
- interface RPCHandlerCodecOptions<T extends Context> extends RPCMatcherOptions {
58
- /**
59
- * Override the default RPC serializer.
60
- */
61
- serializer?: Pick<RPCSerializer, keyof RPCSerializer>;
62
- /**
63
- * Resolve HTTP status for encoded successful outputs.
64
- *
65
- * Value should be in the `2xx` range and must be less than `400`.
66
- * Return `undefined` or `null` to fallback to default
67
- *
68
- * @default DEFAULT_SUCCESS_STATUS (200)
69
- */
70
- outputStatus?: Value<number | undefined | null, [output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>]>;
71
- /**
72
- * Mapping ORPCError Code -> HTTP Status Code
73
- * The status code should be in the `4xx` or `5xx` range (must be greater than or equal to `400`).
74
- *
75
- * @default COMMON_ERROR_STATUS_MAP
76
- */
77
- errorStatusMap?: Record<string, number> | undefined;
78
- }
79
- declare class RPCHandlerCodec<T extends Context> implements StandardHandlerCodec<T> {
80
- private readonly matcher;
81
- private readonly serializer;
82
- private readonly errorStatusMap;
83
- private readonly outputStatus;
84
- constructor(router: AnyRouter, options?: RPCHandlerCodecOptions<T>);
85
- resolveProcedure(request: StandardLazyRequest, options: StandardHandlerHandleOptions<T>): Promise<StandardHandlerCodecResolvedProcedure | undefined>;
86
- encodeOutput(output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
87
- encodeError(error: AnyORPCError, _procedure: AnyProcedure, _path: string[], _options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
88
- }
89
-
90
- export { RPCHandlerCodec as a, RPCMatcher as b, RPC_DEFAULT_ALLOW_METHODS as d };
91
- export type { RPCHandlerCodecOptions as R, RPCMatcherOptions as c };
@@ -1,91 +0,0 @@
1
- import { RPCSerializer, AnyORPCError } from '@orpc/client';
2
- import { Value, Promisable } from '@orpc/shared';
3
- import { StandardMethod, StandardLazyRequest, StandardResponse } from '@standard-server/core';
4
- import { A as AnyProcedure, C as Context } from './server.BsujoJoF.js';
5
- import { A as AnyRouter } from './server.CRwPbhLO.js';
6
- import { AnyProcedureContract } from '@orpc/contract';
7
- import { c as StandardHandlerHandleOptions, d as StandardHandlerCodec, e as StandardHandlerCodecResolvedProcedure } from './server.D23TTT5i.js';
8
-
9
- /**
10
- * Methods that can invoke procedures by default. Browsers cannot trigger them
11
- * cross-site without a CORS preflight or an HTML form, unlike `GET`, which a plain
12
- * `<a>` click or redirect can trigger with `SameSite=Lax` cookies attached. Other
13
- * methods (`HEAD`, `OPTIONS`, `QUERY`, ...) have safe semantics that should not
14
- * invoke a procedure that can modify data.
15
- *
16
- * @see {@link https://orpc.dev/docs/rpc/handler#supported-http-methods | RPC Handler - Supported HTTP Methods}
17
- */
18
- declare const RPC_DEFAULT_ALLOW_METHODS: readonly StandardMethod[];
19
- interface RPCMatcherOptions {
20
- /**
21
- * Filter which procedures are exposed for matching. Return `false` to exclude.
22
- *
23
- * @default true
24
- */
25
- filter?: Value<boolean, [procedure: AnyProcedureContract | AnyProcedure, path: string[]]>;
26
- /**
27
- * Restricts which HTTP methods can invoke procedures, either with a list of allowed
28
- * methods or decided per request via a function. Requests using a disallowed method
29
- * are treated as unmatched. `GET` is excluded by default because it is exposed to
30
- * Cross-Site Request Forgery (CSRF) attacks.
31
- *
32
- * @default RPC_DEFAULT_ALLOW_METHODS (['POST', 'PUT', 'PATCH', 'DELETE'])
33
- * @see {@link https://orpc.dev/docs/rpc/handler#supported-http-methods | RPC Handler - Supported HTTP Methods}
34
- */
35
- allowMethods?: readonly StandardMethod[] | ((method: StandardMethod, procedure: AnyProcedure, path: string[]) => boolean);
36
- }
37
- declare class RPCMatcher {
38
- private readonly filter;
39
- private readonly allowMethodsSet;
40
- private readonly allowMethodsFn;
41
- private readonly rootRouter;
42
- private readonly tree;
43
- private readonly pendingLazyRouters;
44
- constructor(router: AnyRouter, options?: RPCMatcherOptions);
45
- private index;
46
- match(method: StandardMethod, pathname: `/${string}`, prefix: `/${string}` | undefined): Promise<{
47
- path: string[];
48
- procedure: AnyProcedure;
49
- } | undefined>;
50
- private resolvePendingLazyRouters;
51
- private loadPendingLazyRouters;
52
- private loadPendingLazyRouter;
53
- private indexPendingLazyRouter;
54
- private resolveProcedure;
55
- }
56
-
57
- interface RPCHandlerCodecOptions<T extends Context> extends RPCMatcherOptions {
58
- /**
59
- * Override the default RPC serializer.
60
- */
61
- serializer?: Pick<RPCSerializer, keyof RPCSerializer>;
62
- /**
63
- * Resolve HTTP status for encoded successful outputs.
64
- *
65
- * Value should be in the `2xx` range and must be less than `400`.
66
- * Return `undefined` or `null` to fallback to default
67
- *
68
- * @default DEFAULT_SUCCESS_STATUS (200)
69
- */
70
- outputStatus?: Value<number | undefined | null, [output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>]>;
71
- /**
72
- * Mapping ORPCError Code -> HTTP Status Code
73
- * The status code should be in the `4xx` or `5xx` range (must be greater than or equal to `400`).
74
- *
75
- * @default COMMON_ERROR_STATUS_MAP
76
- */
77
- errorStatusMap?: Record<string, number> | undefined;
78
- }
79
- declare class RPCHandlerCodec<T extends Context> implements StandardHandlerCodec<T> {
80
- private readonly matcher;
81
- private readonly serializer;
82
- private readonly errorStatusMap;
83
- private readonly outputStatus;
84
- constructor(router: AnyRouter, options?: RPCHandlerCodecOptions<T>);
85
- resolveProcedure(request: StandardLazyRequest, options: StandardHandlerHandleOptions<T>): Promise<StandardHandlerCodecResolvedProcedure | undefined>;
86
- encodeOutput(output: unknown, procedure: AnyProcedure, path: string[], options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
87
- encodeError(error: AnyORPCError, _procedure: AnyProcedure, _path: string[], _options: StandardHandlerHandleOptions<T>): Promisable<StandardResponse>;
88
- }
89
-
90
- export { RPCHandlerCodec as a, RPCMatcher as b, RPC_DEFAULT_ALLOW_METHODS as d };
91
- export type { RPCHandlerCodecOptions as R, RPCMatcherOptions as c };
@@ -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 };