@orpc/server 0.0.0-next.33ca37d → 0.0.0-next.350a165

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 (37) hide show
  1. package/README.md +11 -0
  2. package/dist/adapters/fetch/index.d.mts +41 -11
  3. package/dist/adapters/fetch/index.d.ts +41 -11
  4. package/dist/adapters/fetch/index.mjs +6 -6
  5. package/dist/adapters/hono/index.d.mts +5 -4
  6. package/dist/adapters/hono/index.d.ts +5 -4
  7. package/dist/adapters/hono/index.mjs +6 -6
  8. package/dist/adapters/next/index.d.mts +5 -4
  9. package/dist/adapters/next/index.d.ts +5 -4
  10. package/dist/adapters/next/index.mjs +6 -6
  11. package/dist/adapters/node/index.d.mts +43 -22
  12. package/dist/adapters/node/index.d.ts +43 -22
  13. package/dist/adapters/node/index.mjs +81 -21
  14. package/dist/adapters/standard/index.d.mts +6 -6
  15. package/dist/adapters/standard/index.d.ts +6 -6
  16. package/dist/adapters/standard/index.mjs +3 -3
  17. package/dist/index.d.mts +56 -43
  18. package/dist/index.d.ts +56 -43
  19. package/dist/index.mjs +27 -6
  20. package/dist/plugins/index.d.mts +51 -14
  21. package/dist/plugins/index.d.ts +51 -14
  22. package/dist/plugins/index.mjs +101 -6
  23. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  24. package/dist/shared/{server.BtxZnWJ9.mjs → server.C37gDhSZ.mjs} +19 -29
  25. package/dist/shared/server.C56IpPNj.d.mts +10 -0
  26. package/dist/shared/{server.jG7ZuX3S.mjs → server.C78d5yfh.mjs} +43 -28
  27. package/dist/shared/server.CSIDw0mq.mjs +106 -0
  28. package/dist/shared/{server.EhgR_5_I.d.ts → server.CyrwhzzU.d.ts} +2 -2
  29. package/dist/shared/{server.BYTulgUc.d.mts → server.DLt5njUb.d.mts} +9 -10
  30. package/dist/shared/{server.BYTulgUc.d.ts → server.DLt5njUb.d.ts} +9 -10
  31. package/dist/shared/{server.B3Tm0IXY.d.ts → server.DfyOFejj.d.ts} +27 -29
  32. package/dist/shared/{server.Bz_xNBjz.d.mts → server.DgrNIRDf.d.mts} +2 -2
  33. package/dist/shared/{server.BeJithK4.d.mts → server.Dm5DEJl5.d.mts} +27 -29
  34. package/dist/shared/server.DnuwaDJo.d.ts +10 -0
  35. package/package.json +8 -8
  36. package/dist/shared/server.DoP20NVH.mjs +0 -29
  37. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, mergeTags, isContractProcedure, getContractRouter } from '@orpc/contract';
2
2
  export { ValidationError, eventIterator, type } from '@orpc/contract';
3
- import { P as Procedure, d as addMiddleware, c as createProcedureClient, e as enhanceRouter, l as lazy, s as setHiddenRouterContract, i as isProcedure, f as isLazy, h as createAssertedLazyProcedure, g as getRouter } from './shared/server.BtxZnWJ9.mjs';
4
- export { L as LAZY_SYMBOL, q as call, w as createAccessibleLazyRouter, b as createContractedProcedure, j as createORPCErrorConstructorMap, r as getHiddenRouterContract, k as getLazyMeta, o as isStartWithMiddlewares, m as mergeCurrentContext, p as mergeMiddlewares, n as middlewareOutputFn, x as resolveContractProcedures, a as toHttpPath, t as traverseContractProcedures, u as unlazy, y as unlazyRouter, v as validateORPCError } from './shared/server.BtxZnWJ9.mjs';
3
+ import { P as Procedure, b as addMiddleware, c as createProcedureClient, e as enhanceRouter, l as lazy, s as setHiddenRouterContract, i as isProcedure, d as isLazy, f as createAssertedLazyProcedure, g as getRouter } from './shared/server.C37gDhSZ.mjs';
4
+ export { L as LAZY_SYMBOL, p as call, r as createAccessibleLazyRouter, a as createContractedProcedure, h as createORPCErrorConstructorMap, q as getHiddenRouterContract, j as getLazyMeta, n as isStartWithMiddlewares, m as mergeCurrentContext, o as mergeMiddlewares, k as middlewareOutputFn, w as resolveContractProcedures, t as traverseContractProcedures, u as unlazy, x as unlazyRouter, v as validateORPCError } from './shared/server.C37gDhSZ.mjs';
5
+ import { toORPCError } from '@orpc/client';
5
6
  export { ORPCError, isDefinedError, safe } from '@orpc/client';
6
7
  export { onError, onFinish, onStart, onSuccess } from '@orpc/shared';
7
8
  export { getEventMeta, withEventMeta } from '@orpc/standard-server';
@@ -44,6 +45,17 @@ function decorateMiddleware(middleware) {
44
45
  return decorated;
45
46
  }
46
47
 
48
+ function createActionableClient(client) {
49
+ const action = async (input) => {
50
+ try {
51
+ return [null, await client(input)];
52
+ } catch (error) {
53
+ return [toORPCError(error).toJSON(), void 0];
54
+ }
55
+ };
56
+ return action;
57
+ }
58
+
47
59
  class DecoratedProcedure extends Procedure {
48
60
  errors(errors) {
49
61
  return new DecoratedProcedure({
@@ -74,7 +86,8 @@ class DecoratedProcedure extends Procedure {
74
86
  * Make this procedure callable (works like a function while still being a procedure).
75
87
  */
76
88
  callable(...rest) {
77
- return new Proxy(createProcedureClient(this, ...rest), {
89
+ const client = createProcedureClient(this, ...rest);
90
+ return new Proxy(client, {
78
91
  get: (target, key) => {
79
92
  return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
80
93
  },
@@ -84,10 +97,18 @@ class DecoratedProcedure extends Procedure {
84
97
  });
85
98
  }
86
99
  /**
87
- * Make this procedure compatible with server action (the same as .callable, but the type is compatible with server action).
100
+ * Make this procedure compatible with server action.
88
101
  */
89
102
  actionable(...rest) {
90
- return this.callable(...rest);
103
+ const action = createActionableClient(createProcedureClient(this, ...rest));
104
+ return new Proxy(action, {
105
+ get: (target, key) => {
106
+ return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
107
+ },
108
+ has: (target, key) => {
109
+ return Reflect.has(this, key) || Reflect.has(target, key);
110
+ }
111
+ });
91
112
  }
92
113
  }
93
114
 
@@ -339,4 +360,4 @@ function createRouterClient(router, ...[options]) {
339
360
  return recursive;
340
361
  }
341
362
 
342
- export { Builder, DecoratedProcedure, Procedure, addMiddleware, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, fallbackConfig, getRouter, implement, implementerInternal, isLazy, isProcedure, lazy, os, setHiddenRouterContract };
363
+ export { Builder, DecoratedProcedure, Procedure, addMiddleware, createActionableClient, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, fallbackConfig, getRouter, implement, implementerInternal, isLazy, isProcedure, lazy, os, setHiddenRouterContract };
@@ -1,31 +1,68 @@
1
- import { b as StandardHandlerInterceptorOptions, H as HandlerPlugin, a as StandardHandlerOptions } from '../shared/server.BeJithK4.mjs';
2
- export { C as CompositePlugin } from '../shared/server.BeJithK4.mjs';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.BYTulgUc.mjs';
5
- import '@orpc/contract';
6
- import '@orpc/standard-server';
2
+ import { StandardRequest, StandardHeaders } from '@orpc/standard-server';
3
+ import { BatchResponseBodyItem } from '@orpc/standard-server/batch';
4
+ import { g as StandardHandlerInterceptorOptions, i as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.Dm5DEJl5.mjs';
5
+ import { C as Context } from '../shared/server.DLt5njUb.mjs';
7
6
  import '@orpc/client';
7
+ import '@orpc/contract';
8
+
9
+ interface BatchHandlerOptions<T extends Context> {
10
+ /**
11
+ * The max size of the batch allowed.
12
+ *
13
+ * @default 10
14
+ */
15
+ maxSize?: Value<number, [StandardHandlerInterceptorOptions<T>]>;
16
+ /**
17
+ * Map the request before processing it.
18
+ *
19
+ * @default merged back batch request headers into the request
20
+ */
21
+ mapRequestItem?(request: StandardRequest, batchOptions: StandardHandlerInterceptorOptions<T>): StandardRequest;
22
+ /**
23
+ * Success batch response status code.
24
+ *
25
+ * @default 207
26
+ */
27
+ successStatus?: Value<number, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
28
+ /**
29
+ * success batch response headers.
30
+ *
31
+ * @default {}
32
+ */
33
+ headers?: Value<StandardHeaders, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
34
+ }
35
+ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
36
+ private readonly maxSize;
37
+ private readonly mapRequestItem;
38
+ private readonly successStatus;
39
+ private readonly headers;
40
+ order: number;
41
+ constructor(options?: BatchHandlerOptions<T>);
42
+ init(options: StandardHandlerOptions<T>): void;
43
+ }
8
44
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
45
+ interface CORSOptions<T extends Context> {
46
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
12
48
  allowMethods?: readonly string[];
13
49
  allowHeaders?: readonly string[];
14
50
  maxAge?: number;
15
51
  credentials?: boolean;
16
52
  exposeHeaders?: readonly string[];
17
53
  }
18
- declare class CORSPlugin<TContext extends Context> implements HandlerPlugin<TContext> {
54
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
55
  private readonly options;
20
- constructor(options?: CORSOptions<TContext>);
21
- init(options: StandardHandlerOptions<TContext>): void;
56
+ order: number;
57
+ constructor(options?: CORSOptions<T>);
58
+ init(options: StandardHandlerOptions<T>): void;
22
59
  }
23
60
 
24
61
  interface ResponseHeadersPluginContext {
25
62
  resHeaders?: Headers;
26
63
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements HandlerPlugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
64
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
65
+ init(options: StandardHandlerOptions<T>): void;
29
66
  }
30
67
 
31
- export { type CORSOptions, CORSPlugin, HandlerPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
68
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
@@ -1,31 +1,68 @@
1
- import { b as StandardHandlerInterceptorOptions, H as HandlerPlugin, a as StandardHandlerOptions } from '../shared/server.B3Tm0IXY.js';
2
- export { C as CompositePlugin } from '../shared/server.B3Tm0IXY.js';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.BYTulgUc.js';
5
- import '@orpc/contract';
6
- import '@orpc/standard-server';
2
+ import { StandardRequest, StandardHeaders } from '@orpc/standard-server';
3
+ import { BatchResponseBodyItem } from '@orpc/standard-server/batch';
4
+ import { g as StandardHandlerInterceptorOptions, i as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.DfyOFejj.js';
5
+ import { C as Context } from '../shared/server.DLt5njUb.js';
7
6
  import '@orpc/client';
7
+ import '@orpc/contract';
8
+
9
+ interface BatchHandlerOptions<T extends Context> {
10
+ /**
11
+ * The max size of the batch allowed.
12
+ *
13
+ * @default 10
14
+ */
15
+ maxSize?: Value<number, [StandardHandlerInterceptorOptions<T>]>;
16
+ /**
17
+ * Map the request before processing it.
18
+ *
19
+ * @default merged back batch request headers into the request
20
+ */
21
+ mapRequestItem?(request: StandardRequest, batchOptions: StandardHandlerInterceptorOptions<T>): StandardRequest;
22
+ /**
23
+ * Success batch response status code.
24
+ *
25
+ * @default 207
26
+ */
27
+ successStatus?: Value<number, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
28
+ /**
29
+ * success batch response headers.
30
+ *
31
+ * @default {}
32
+ */
33
+ headers?: Value<StandardHeaders, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
34
+ }
35
+ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
36
+ private readonly maxSize;
37
+ private readonly mapRequestItem;
38
+ private readonly successStatus;
39
+ private readonly headers;
40
+ order: number;
41
+ constructor(options?: BatchHandlerOptions<T>);
42
+ init(options: StandardHandlerOptions<T>): void;
43
+ }
8
44
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
45
+ interface CORSOptions<T extends Context> {
46
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
12
48
  allowMethods?: readonly string[];
13
49
  allowHeaders?: readonly string[];
14
50
  maxAge?: number;
15
51
  credentials?: boolean;
16
52
  exposeHeaders?: readonly string[];
17
53
  }
18
- declare class CORSPlugin<TContext extends Context> implements HandlerPlugin<TContext> {
54
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
55
  private readonly options;
20
- constructor(options?: CORSOptions<TContext>);
21
- init(options: StandardHandlerOptions<TContext>): void;
56
+ order: number;
57
+ constructor(options?: CORSOptions<T>);
58
+ init(options: StandardHandlerOptions<T>): void;
22
59
  }
23
60
 
24
61
  interface ResponseHeadersPluginContext {
25
62
  resHeaders?: Headers;
26
63
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements HandlerPlugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
64
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
65
+ init(options: StandardHandlerOptions<T>): void;
29
66
  }
30
67
 
31
- export { type CORSOptions, CORSPlugin, HandlerPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
68
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
@@ -1,8 +1,98 @@
1
- export { C as CompositePlugin } from '../shared/server.Q6ZmnTgO.mjs';
2
1
  import { value } from '@orpc/shared';
2
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
3
+
4
+ class BatchHandlerPlugin {
5
+ maxSize;
6
+ mapRequestItem;
7
+ successStatus;
8
+ headers;
9
+ order = 5e6;
10
+ constructor(options = {}) {
11
+ this.maxSize = options.maxSize ?? 10;
12
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
13
+ ...request,
14
+ headers: {
15
+ ...batchRequest.headers,
16
+ ...request.headers
17
+ }
18
+ }));
19
+ this.successStatus = options.successStatus ?? 207;
20
+ this.headers = options.headers ?? {};
21
+ }
22
+ init(options) {
23
+ options.rootInterceptors ??= [];
24
+ options.rootInterceptors.unshift(async (options2) => {
25
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
26
+ return options2.next();
27
+ }
28
+ let isParsing = false;
29
+ try {
30
+ isParsing = true;
31
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
32
+ isParsing = false;
33
+ const maxSize = await value(this.maxSize, options2);
34
+ if (parsed.length > maxSize) {
35
+ return {
36
+ matched: true,
37
+ response: {
38
+ status: 413,
39
+ headers: {},
40
+ body: "Batch request size exceeds the maximum allowed size"
41
+ }
42
+ };
43
+ }
44
+ const responses = parsed.map(
45
+ (request, index) => {
46
+ const mapped = this.mapRequestItem(request, options2);
47
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
48
+ if (matched) {
49
+ return { ...response2, index };
50
+ }
51
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
52
+ }).catch(() => {
53
+ return { index, status: 500, headers: {}, body: "Internal server error" };
54
+ });
55
+ }
56
+ );
57
+ await Promise.race(responses);
58
+ const status = await value(this.successStatus, responses, options2);
59
+ const headers = await value(this.headers, responses, options2);
60
+ const response = toBatchResponse({
61
+ status,
62
+ headers,
63
+ body: async function* () {
64
+ const promises = [...responses];
65
+ while (true) {
66
+ const handling = promises.filter((p) => p !== void 0);
67
+ if (handling.length === 0) {
68
+ return;
69
+ }
70
+ const result = await Promise.race(handling);
71
+ promises[result.index] = void 0;
72
+ yield result;
73
+ }
74
+ }()
75
+ });
76
+ return {
77
+ matched: true,
78
+ response
79
+ };
80
+ } catch (cause) {
81
+ if (isParsing) {
82
+ return {
83
+ matched: true,
84
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
85
+ };
86
+ }
87
+ throw cause;
88
+ }
89
+ });
90
+ }
91
+ }
3
92
 
4
93
  class CORSPlugin {
5
94
  options;
95
+ order = 9e6;
6
96
  constructor(options = {}) {
7
97
  const defaults = {
8
98
  origin: (origin) => origin,
@@ -79,14 +169,19 @@ class ResponseHeadersPlugin {
79
169
  init(options) {
80
170
  options.rootInterceptors ??= [];
81
171
  options.rootInterceptors.push(async (interceptorOptions) => {
82
- const headers = new Headers();
83
- interceptorOptions.context.resHeaders = headers;
84
- const result = await interceptorOptions.next();
172
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
173
+ const result = await interceptorOptions.next({
174
+ ...interceptorOptions,
175
+ context: {
176
+ ...interceptorOptions.context,
177
+ resHeaders
178
+ }
179
+ });
85
180
  if (!result.matched) {
86
181
  return result;
87
182
  }
88
183
  const responseHeaders = result.response.headers;
89
- for (const [key, value] of headers) {
184
+ for (const [key, value] of resHeaders) {
90
185
  if (Array.isArray(responseHeaders[key])) {
91
186
  responseHeaders[key].push(value);
92
187
  } else if (responseHeaders[key] !== void 0) {
@@ -100,4 +195,4 @@ class ResponseHeadersPlugin {
100
195
  }
101
196
  }
102
197
 
103
- export { CORSPlugin, ResponseHeadersPlugin };
198
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin };
@@ -0,0 +1,9 @@
1
+ function resolveFriendlyStandardHandleOptions(options) {
2
+ return {
3
+ ...options,
4
+ context: options?.context ?? {}
5
+ // Context only optional if all fields are optional
6
+ };
7
+ }
8
+
9
+ export { resolveFriendlyStandardHandleOptions as r };
@@ -1,6 +1,6 @@
1
1
  import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
2
  import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
- import { value, intercept, toError } from '@orpc/shared';
3
+ import { value, intercept } from '@orpc/shared';
4
4
 
5
5
  const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
6
  function lazy(loader, meta = {}) {
@@ -127,7 +127,7 @@ function createProcedureClient(lazyableProcedure, ...[options]) {
127
127
  );
128
128
  } catch (e) {
129
129
  if (!(e instanceof ORPCError)) {
130
- throw toError(e);
130
+ throw e;
131
131
  }
132
132
  const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
133
  throw validated;
@@ -169,35 +169,29 @@ async function executeProcedureInternal(procedure, options) {
169
169
  const middlewares = procedure["~orpc"].middlewares;
170
170
  const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
171
  const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
172
- let currentIndex = 0;
173
- let currentContext = options.context;
174
- let currentInput = options.input;
175
- const next = async (...[nextOptions]) => {
176
- const index = currentIndex;
177
- const midContext = nextOptions?.context ?? {};
178
- currentIndex += 1;
179
- currentContext = mergeCurrentContext(currentContext, midContext);
172
+ const next = async (index, context, input) => {
173
+ let currentInput = input;
180
174
  if (index === inputValidationIndex) {
181
175
  currentInput = await validateInput(procedure, currentInput);
182
176
  }
183
177
  const mid = middlewares[index];
184
- const result = mid ? {
185
- context: midContext,
186
- output: (await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn)).output
187
- } : {
188
- context: midContext,
189
- output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput })
190
- };
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 });
191
189
  if (index === outputValidationIndex) {
192
- const validatedOutput = await validateOutput(procedure, result.output);
193
- return {
194
- context: result.context,
195
- output: validatedOutput
196
- };
190
+ return await validateOutput(procedure, output);
197
191
  }
198
- return result;
192
+ return output;
199
193
  };
200
- return (await next()).output;
194
+ return next(0, options.context, options.input);
201
195
  }
202
196
 
203
197
  const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
@@ -367,8 +361,4 @@ function call(procedure, input, ...rest) {
367
361
  return createProcedureClient(procedure, ...rest)(input);
368
362
  }
369
363
 
370
- function toHttpPath(path) {
371
- return `/${path.map(encodeURIComponent).join("/")}`;
372
- }
373
-
374
- 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, createORPCErrorConstructorMap as j, getLazyMeta as k, lazy as l, mergeCurrentContext as m, middlewareOutputFn as n, isStartWithMiddlewares as o, mergeMiddlewares as p, call as q, getHiddenRouterContract as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, validateORPCError as v, createAccessibleLazyRouter as w, resolveContractProcedures as x, unlazyRouter as y };
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,10 @@
1
+ import { C as Context } from './server.DLt5njUb.mjs';
2
+ import { S as StandardHandleOptions } from './server.Dm5DEJl5.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 };
@@ -1,51 +1,66 @@
1
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.BtxZnWJ9.mjs';
2
+ import { toArray, intercept, parseEmptyableJSON } from '@orpc/shared';
3
+ import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.C37gDhSZ.mjs';
4
+ import { toHttpPath } from '@orpc/client/standard';
5
+
6
+ class CompositeStandardHandlerPlugin {
7
+ plugins;
8
+ constructor(plugins = []) {
9
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
10
+ }
11
+ init(options) {
12
+ for (const plugin of this.plugins) {
13
+ plugin.init?.(options);
14
+ }
15
+ }
16
+ }
5
17
 
6
18
  class StandardHandler {
7
19
  constructor(router, matcher, codec, options) {
8
20
  this.matcher = matcher;
9
21
  this.codec = codec;
10
- this.options = options;
11
- this.plugin = new CompositePlugin(options.plugins);
12
- this.plugin.init(this.options);
22
+ const plugins = new CompositeStandardHandlerPlugin(options.plugins);
23
+ plugins.init(options);
24
+ this.interceptors = toArray(options.interceptors);
25
+ this.clientInterceptors = toArray(options.clientInterceptors);
26
+ this.rootInterceptors = toArray(options.rootInterceptors);
13
27
  this.matcher.init(router);
14
28
  }
15
- plugin;
16
- handle(request, ...[options]) {
29
+ interceptors;
30
+ clientInterceptors;
31
+ rootInterceptors;
32
+ async handle(request, options) {
33
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
34
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
35
+ return { matched: false, response: void 0 };
36
+ }
17
37
  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
- },
38
+ this.rootInterceptors,
39
+ { ...options, request, prefix },
25
40
  async (interceptorOptions) => {
26
41
  let isDecoding = false;
27
42
  try {
28
43
  return await intercept(
29
- this.options.interceptors ?? [],
44
+ this.interceptors,
30
45
  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);
46
+ async ({ request: request2, context, prefix: prefix2 }) => {
47
+ const method = request2.method;
48
+ const url = request2.url;
49
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
50
+ const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
36
51
  if (!match) {
37
52
  return { matched: false, response: void 0 };
38
53
  }
39
54
  const client = createProcedureClient(match.procedure, {
40
- context: interceptorOptions2.context,
55
+ context,
41
56
  path: match.path,
42
- interceptors: this.options.clientInterceptors
57
+ interceptors: this.clientInterceptors
43
58
  });
44
59
  isDecoding = true;
45
- const input = await this.codec.decode(request, match.params, match.procedure);
60
+ const input = await this.codec.decode(request2, match.params, match.procedure);
46
61
  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 });
62
+ const lastEventId = Array.isArray(request2.headers["last-event-id"]) ? request2.headers["last-event-id"].at(-1) : request2.headers["last-event-id"];
63
+ const output = await client(input, { signal: request2.signal, lastEventId });
49
64
  const response = this.codec.encode(output, match.procedure);
50
65
  return {
51
66
  matched: true,
@@ -54,7 +69,7 @@ class StandardHandler {
54
69
  }
55
70
  );
56
71
  } catch (e) {
57
- const error = isDecoding ? new ORPCError("BAD_REQUEST", {
72
+ const error = isDecoding && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
58
73
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
59
74
  cause: e
60
75
  }) : toORPCError(e);
@@ -155,4 +170,4 @@ class StandardRPCMatcher {
155
170
  }
156
171
  }
157
172
 
158
- export { StandardHandler as S, StandardRPCCodec as a, StandardRPCMatcher as b };
173
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardRPCCodec as a, StandardRPCMatcher as b };