@orpc/server 0.0.0-next.954e6e2 → 0.0.0-next.96f9dd3

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 +14 -1
  2. package/dist/adapters/fetch/index.d.mts +38 -11
  3. package/dist/adapters/fetch/index.d.ts +38 -11
  4. package/dist/adapters/fetch/index.mjs +6 -6
  5. package/dist/adapters/hono/index.d.mts +6 -4
  6. package/dist/adapters/hono/index.d.ts +6 -4
  7. package/dist/adapters/hono/index.mjs +6 -6
  8. package/dist/adapters/next/index.d.mts +6 -4
  9. package/dist/adapters/next/index.d.ts +6 -4
  10. package/dist/adapters/next/index.mjs +6 -6
  11. package/dist/adapters/node/index.d.mts +40 -22
  12. package/dist/adapters/node/index.d.ts +40 -22
  13. package/dist/adapters/node/index.mjs +77 -22
  14. package/dist/adapters/standard/index.d.mts +12 -15
  15. package/dist/adapters/standard/index.d.ts +12 -15
  16. package/dist/adapters/standard/index.mjs +2 -3
  17. package/dist/index.d.mts +160 -124
  18. package/dist/index.d.ts +160 -124
  19. package/dist/index.mjs +78 -48
  20. package/dist/plugins/index.d.mts +52 -17
  21. package/dist/plugins/index.d.ts +52 -17
  22. package/dist/plugins/index.mjs +100 -7
  23. package/dist/shared/server.BFt8M4Cr.d.ts +8 -0
  24. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  25. package/dist/shared/server.Bc6jnvPE.d.ts +10 -0
  26. package/dist/shared/server.BlxK0o8R.d.mts +66 -0
  27. package/dist/shared/{server.V6zT5iYQ.mjs → server.C37gDhSZ.mjs} +158 -173
  28. package/dist/shared/server.CCPFkKqC.mjs +98 -0
  29. package/dist/shared/server.CCgy73tk.d.mts +10 -0
  30. package/dist/shared/{server.BBGuTxHE.mjs → server.DJrRF9vD.mjs} +44 -45
  31. package/dist/shared/server.DLt5njUb.d.mts +143 -0
  32. package/dist/shared/server.DLt5njUb.d.ts +143 -0
  33. package/dist/shared/server.DuTpqr2w.d.ts +66 -0
  34. package/dist/shared/server.JgWzFqlo.d.mts +8 -0
  35. package/package.json +8 -8
  36. package/dist/shared/server.B-ewprcf.d.ts +0 -77
  37. package/dist/shared/server.CA-o8cUY.d.mts +0 -9
  38. package/dist/shared/server.Cn9ybJtE.d.mts +0 -152
  39. package/dist/shared/server.Cn9ybJtE.d.ts +0 -152
  40. package/dist/shared/server.DJrh0Ceu.d.mts +0 -77
  41. package/dist/shared/server.DPQt9YYq.d.ts +0 -9
  42. package/dist/shared/server.KwueCzFr.mjs +0 -26
  43. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
package/dist/index.mjs CHANGED
@@ -1,14 +1,16 @@
1
- import { mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, mergeTags, isContractProcedure } from '@orpc/contract';
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, f as adaptRouter, h as flatLazy, l as lazy, s as setRouterContract, i as isProcedure, j as isLazy, k as createLazyProcedureFormAnyLazy, g as getRouterChild } from './shared/server.V6zT5iYQ.mjs';
4
- export { L as LAZY_LOADER_SYMBOL, a as convertPathToHttpPath, q as createAccessibleLazyRouter, b as createContractedProcedure, n as deepSetLazyRouterPrefix, r as eachAllContractProcedure, e as eachContractProcedure, o as getLazyRouterPrefix, m as getRouterContract, p as middlewareOutputFn, u as unlazy } from './shared/server.V6zT5iYQ.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';
8
9
 
9
10
  const DEFAULT_CONFIG = {
10
11
  initialInputValidationIndex: 0,
11
- initialOutputValidationIndex: 0
12
+ initialOutputValidationIndex: 0,
13
+ dedupeLeadingMiddlewares: true
12
14
  };
13
15
  function fallbackConfig(key, value) {
14
16
  if (value === void 0) {
@@ -18,7 +20,7 @@ function fallbackConfig(key, value) {
18
20
  }
19
21
 
20
22
  function decorateMiddleware(middleware) {
21
- const decorated = middleware;
23
+ const decorated = (...args) => middleware(...args);
22
24
  decorated.mapInput = (mapInput) => {
23
25
  const mapped = decorateMiddleware(
24
26
  (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
@@ -43,6 +45,17 @@ function decorateMiddleware(middleware) {
43
45
  return decorated;
44
46
  }
45
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
+
46
59
  class DecoratedProcedure extends Procedure {
47
60
  errors(errors) {
48
61
  return new DecoratedProcedure({
@@ -73,16 +86,29 @@ class DecoratedProcedure extends Procedure {
73
86
  * Make this procedure callable (works like a function while still being a procedure).
74
87
  */
75
88
  callable(...rest) {
76
- return Object.assign(createProcedureClient(this, ...rest), {
77
- "~type": "Procedure",
78
- "~orpc": this["~orpc"]
89
+ const client = createProcedureClient(this, ...rest);
90
+ return new Proxy(client, {
91
+ get: (target, key) => {
92
+ return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
93
+ },
94
+ has: (target, key) => {
95
+ return Reflect.has(this, key) || Reflect.has(target, key);
96
+ }
79
97
  });
80
98
  }
81
99
  /**
82
- * 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.
83
101
  */
84
102
  actionable(...rest) {
85
- 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
+ });
86
112
  }
87
113
  }
88
114
 
@@ -100,6 +126,7 @@ class Builder {
100
126
  return new Builder({
101
127
  ...this["~orpc"],
102
128
  config,
129
+ dedupeLeadingMiddlewares: fallbackConfig("dedupeLeadingMiddlewares", config.dedupeLeadingMiddlewares),
103
130
  inputValidationIndex: fallbackConfig("initialInputValidationIndex", config.initialInputValidationIndex) + inputValidationCount,
104
131
  outputValidationIndex: fallbackConfig("initialOutputValidationIndex", config.initialOutputValidationIndex) + outputValidationCount
105
132
  });
@@ -133,6 +160,12 @@ class Builder {
133
160
  route: initialRoute
134
161
  });
135
162
  }
163
+ $input(initialInputSchema) {
164
+ return new Builder({
165
+ ...this["~orpc"],
166
+ inputSchema: initialInputSchema
167
+ });
168
+ }
136
169
  middleware(middleware) {
137
170
  return decorateMiddleware(middleware);
138
171
  }
@@ -194,10 +227,10 @@ class Builder {
194
227
  });
195
228
  }
196
229
  router(router) {
197
- return adaptRouter(router, this["~orpc"]);
230
+ return enhanceRouter(router, this["~orpc"]);
198
231
  }
199
232
  lazy(loader) {
200
- return adaptRouter(flatLazy(lazy(loader)), this["~orpc"]);
233
+ return enhanceRouter(lazy(loader), this["~orpc"]);
201
234
  }
202
235
  }
203
236
  const os = new Builder({
@@ -205,17 +238,12 @@ const os = new Builder({
205
238
  route: {},
206
239
  meta: {},
207
240
  errorMap: {},
208
- inputSchema: void 0,
209
- outputSchema: void 0,
210
241
  inputValidationIndex: fallbackConfig("initialInputValidationIndex"),
211
242
  outputValidationIndex: fallbackConfig("initialOutputValidationIndex"),
212
- middlewares: []
243
+ middlewares: [],
244
+ dedupeLeadingMiddlewares: true
213
245
  });
214
246
 
215
- function mergeContext(context, other) {
216
- return { ...context, ...other };
217
- }
218
-
219
247
  function implementerInternal(contract, config, middlewares) {
220
248
  if (isContractProcedure(contract)) {
221
249
  const impl2 = new Builder({
@@ -223,12 +251,16 @@ function implementerInternal(contract, config, middlewares) {
223
251
  config,
224
252
  middlewares,
225
253
  inputValidationIndex: fallbackConfig("initialInputValidationIndex", config?.initialInputValidationIndex) + middlewares.length,
226
- outputValidationIndex: fallbackConfig("initialOutputValidationIndex", config?.initialOutputValidationIndex) + middlewares.length
254
+ outputValidationIndex: fallbackConfig("initialOutputValidationIndex", config?.initialOutputValidationIndex) + middlewares.length,
255
+ dedupeLeadingMiddlewares: fallbackConfig("dedupeLeadingMiddlewares", config.dedupeLeadingMiddlewares)
227
256
  });
228
257
  return impl2;
229
258
  }
230
259
  const impl = new Proxy(contract, {
231
260
  get: (target, key) => {
261
+ if (typeof key !== "string") {
262
+ return Reflect.get(target, key);
263
+ }
232
264
  let method;
233
265
  if (key === "middleware") {
234
266
  method = (mid) => decorateMiddleware(mid);
@@ -242,23 +274,29 @@ function implementerInternal(contract, config, middlewares) {
242
274
  };
243
275
  } else if (key === "router") {
244
276
  method = (router) => {
245
- const adapted = adaptRouter(router, {
277
+ const adapted = enhanceRouter(router, {
246
278
  middlewares,
247
- errorMap: {}
279
+ errorMap: {},
280
+ prefix: void 0,
281
+ tags: void 0,
282
+ dedupeLeadingMiddlewares: fallbackConfig("dedupeLeadingMiddlewares", config.dedupeLeadingMiddlewares)
248
283
  });
249
- return setRouterContract(adapted, contract);
284
+ return setHiddenRouterContract(adapted, contract);
250
285
  };
251
286
  } else if (key === "lazy") {
252
287
  method = (loader) => {
253
- const adapted = adaptRouter(flatLazy(lazy(loader)), {
288
+ const adapted = enhanceRouter(lazy(loader), {
254
289
  middlewares,
255
- errorMap: {}
290
+ errorMap: {},
291
+ prefix: void 0,
292
+ tags: void 0,
293
+ dedupeLeadingMiddlewares: fallbackConfig("dedupeLeadingMiddlewares", config.dedupeLeadingMiddlewares)
256
294
  });
257
- return setRouterContract(adapted, contract);
295
+ return setHiddenRouterContract(adapted, contract);
258
296
  };
259
297
  }
260
- const next = Reflect.get(target, key);
261
- if (!next || typeof next !== "function" && typeof next !== "object") {
298
+ const next = getContractRouter(target, [key]);
299
+ if (!next) {
262
300
  return method ?? next;
263
301
  }
264
302
  const nextImpl = implementerInternal(next, config, middlewares);
@@ -285,42 +323,34 @@ function implement(contract, config = {}) {
285
323
  method = (config2) => implement(contract, config2);
286
324
  }
287
325
  const next = Reflect.get(target, key);
288
- if (!next || typeof next !== "function" && typeof next !== "object") {
289
- return method ?? next;
290
- }
291
- if (method) {
292
- return new Proxy(method, {
293
- get(_, key2) {
294
- return Reflect.get(next, key2);
295
- }
296
- });
326
+ if (!method || !next || typeof next !== "function" && typeof next !== "object") {
327
+ return method || next;
297
328
  }
298
- return next;
329
+ return new Proxy(method, {
330
+ get(_, key2) {
331
+ return Reflect.get(next, key2);
332
+ }
333
+ });
299
334
  }
300
335
  });
301
336
  return impl;
302
337
  }
303
338
 
304
- function call(procedure, input, ...rest) {
305
- return createProcedureClient(procedure, ...rest)(input);
306
- }
307
-
308
- function createRouterClient(router, ...rest) {
339
+ function createRouterClient(router, ...[options]) {
309
340
  if (isProcedure(router)) {
310
- const caller = createProcedureClient(router, ...rest);
341
+ const caller = createProcedureClient(router, options);
311
342
  return caller;
312
343
  }
313
- const procedureCaller = isLazy(router) ? createProcedureClient(createLazyProcedureFormAnyLazy(router), ...rest) : {};
344
+ const procedureCaller = isLazy(router) ? createProcedureClient(createAssertedLazyProcedure(router), options) : {};
314
345
  const recursive = new Proxy(procedureCaller, {
315
346
  get(target, key) {
316
347
  if (typeof key !== "string") {
317
348
  return Reflect.get(target, key);
318
349
  }
319
- const next = getRouterChild(router, key);
350
+ const next = getRouter(router, [key]);
320
351
  if (!next) {
321
352
  return Reflect.get(target, key);
322
353
  }
323
- const [options] = rest;
324
354
  return createRouterClient(next, {
325
355
  ...options,
326
356
  path: [...options?.path ?? [], key]
@@ -330,4 +360,4 @@ function createRouterClient(router, ...rest) {
330
360
  return recursive;
331
361
  }
332
362
 
333
- export { Builder, DecoratedProcedure, Procedure, adaptRouter, call, createLazyProcedureFormAnyLazy, createProcedureClient, createRouterClient, decorateMiddleware, fallbackConfig, flatLazy, getRouterChild, implement, implementerInternal, isLazy, isProcedure, lazy, mergeContext, os, setRouterContract };
363
+ export { Builder, DecoratedProcedure, Procedure, addMiddleware, createActionableClient, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, fallbackConfig, getRouter, implement, implementerInternal, isLazy, isProcedure, lazy, os, setHiddenRouterContract };
@@ -1,31 +1,66 @@
1
- import { d as StandardHandlerInterceptorOptions, P as Plugin, a as StandardHandlerOptions } from '../shared/server.DJrh0Ceu.mjs';
2
- export { C as CompositePlugin } from '../shared/server.DJrh0Ceu.mjs';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.Cn9ybJtE.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 { h as StandardHandlerInterceptorOptions, g as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.BlxK0o8R.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
+ constructor(options?: BatchHandlerOptions<T>);
41
+ init(options: StandardHandlerOptions<T>): void;
42
+ }
8
43
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
12
- allowMethods?: string[];
13
- allowHeaders?: string[];
44
+ interface CORSOptions<T extends Context> {
45
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
46
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ allowMethods?: readonly string[];
48
+ allowHeaders?: readonly string[];
14
49
  maxAge?: number;
15
50
  credentials?: boolean;
16
- exposeHeaders?: string[];
51
+ exposeHeaders?: readonly string[];
17
52
  }
18
- declare class CORSPlugin<TContext extends Context> implements Plugin<TContext> {
53
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
54
  private readonly options;
20
- constructor(options?: Partial<CORSOptions<TContext>>);
21
- init(options: StandardHandlerOptions<TContext>): void;
55
+ constructor(options?: CORSOptions<T>);
56
+ init(options: StandardHandlerOptions<T>): void;
22
57
  }
23
58
 
24
59
  interface ResponseHeadersPluginContext {
25
60
  resHeaders?: Headers;
26
61
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements Plugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
62
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
63
+ init(options: StandardHandlerOptions<T>): void;
29
64
  }
30
65
 
31
- export { type CORSOptions, CORSPlugin, Plugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
66
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
@@ -1,31 +1,66 @@
1
- import { d as StandardHandlerInterceptorOptions, P as Plugin, a as StandardHandlerOptions } from '../shared/server.B-ewprcf.js';
2
- export { C as CompositePlugin } from '../shared/server.B-ewprcf.js';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.Cn9ybJtE.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 { h as StandardHandlerInterceptorOptions, g as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.DuTpqr2w.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
+ constructor(options?: BatchHandlerOptions<T>);
41
+ init(options: StandardHandlerOptions<T>): void;
42
+ }
8
43
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
12
- allowMethods?: string[];
13
- allowHeaders?: string[];
44
+ interface CORSOptions<T extends Context> {
45
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
46
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ allowMethods?: readonly string[];
48
+ allowHeaders?: readonly string[];
14
49
  maxAge?: number;
15
50
  credentials?: boolean;
16
- exposeHeaders?: string[];
51
+ exposeHeaders?: readonly string[];
17
52
  }
18
- declare class CORSPlugin<TContext extends Context> implements Plugin<TContext> {
53
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
54
  private readonly options;
20
- constructor(options?: Partial<CORSOptions<TContext>>);
21
- init(options: StandardHandlerOptions<TContext>): void;
55
+ constructor(options?: CORSOptions<T>);
56
+ init(options: StandardHandlerOptions<T>): void;
22
57
  }
23
58
 
24
59
  interface ResponseHeadersPluginContext {
25
60
  resHeaders?: Headers;
26
61
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements Plugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
62
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
63
+ init(options: StandardHandlerOptions<T>): void;
29
64
  }
30
65
 
31
- export { type CORSOptions, CORSPlugin, Plugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
66
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
@@ -1,9 +1,97 @@
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
+ constructor(options = {}) {
10
+ this.maxSize = options.maxSize ?? 10;
11
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
12
+ ...request,
13
+ headers: {
14
+ ...batchRequest.headers,
15
+ ...request.headers
16
+ }
17
+ }));
18
+ this.successStatus = options.successStatus ?? 207;
19
+ this.headers = options.headers ?? {};
20
+ }
21
+ init(options) {
22
+ options.rootInterceptors ??= [];
23
+ options.rootInterceptors.unshift(async (options2) => {
24
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
25
+ return options2.next();
26
+ }
27
+ let isParsing = false;
28
+ try {
29
+ isParsing = true;
30
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
31
+ isParsing = false;
32
+ const maxSize = await value(this.maxSize, options2);
33
+ if (parsed.length > maxSize) {
34
+ return {
35
+ matched: true,
36
+ response: {
37
+ status: 413,
38
+ headers: {},
39
+ body: "Batch request size exceeds the maximum allowed size"
40
+ }
41
+ };
42
+ }
43
+ const responses = parsed.map(
44
+ (request, index) => {
45
+ const mapped = this.mapRequestItem(request, options2);
46
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
47
+ if (matched) {
48
+ return { ...response2, index };
49
+ }
50
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
51
+ }).catch(() => {
52
+ return { index, status: 500, headers: {}, body: "Internal server error" };
53
+ });
54
+ }
55
+ );
56
+ await Promise.race(responses);
57
+ const status = await value(this.successStatus, responses, options2);
58
+ const headers = await value(this.headers, responses, options2);
59
+ const response = toBatchResponse({
60
+ status,
61
+ headers,
62
+ body: async function* () {
63
+ const promises = [...responses];
64
+ while (true) {
65
+ const handling = promises.filter((p) => p !== void 0);
66
+ if (handling.length === 0) {
67
+ return;
68
+ }
69
+ const result = await Promise.race(handling);
70
+ promises[result.index] = void 0;
71
+ yield result;
72
+ }
73
+ }()
74
+ });
75
+ return {
76
+ matched: true,
77
+ response
78
+ };
79
+ } catch (cause) {
80
+ if (isParsing) {
81
+ return {
82
+ matched: true,
83
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
84
+ };
85
+ }
86
+ throw cause;
87
+ }
88
+ });
89
+ }
90
+ }
3
91
 
4
92
  class CORSPlugin {
5
93
  options;
6
- constructor(options) {
94
+ constructor(options = {}) {
7
95
  const defaults = {
8
96
  origin: (origin) => origin,
9
97
  allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
@@ -79,14 +167,19 @@ class ResponseHeadersPlugin {
79
167
  init(options) {
80
168
  options.rootInterceptors ??= [];
81
169
  options.rootInterceptors.push(async (interceptorOptions) => {
82
- const headers = new Headers();
83
- interceptorOptions.context.resHeaders = headers;
84
- const result = await interceptorOptions.next();
170
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
171
+ const result = await interceptorOptions.next({
172
+ ...interceptorOptions,
173
+ context: {
174
+ ...interceptorOptions.context,
175
+ resHeaders
176
+ }
177
+ });
85
178
  if (!result.matched) {
86
179
  return result;
87
180
  }
88
181
  const responseHeaders = result.response.headers;
89
- for (const [key, value] of headers) {
182
+ for (const [key, value] of resHeaders) {
90
183
  if (Array.isArray(responseHeaders[key])) {
91
184
  responseHeaders[key].push(value);
92
185
  } else if (responseHeaders[key] !== void 0) {
@@ -100,4 +193,4 @@ class ResponseHeadersPlugin {
100
193
  }
101
194
  }
102
195
 
103
- export { CORSPlugin, ResponseHeadersPlugin };
196
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin };
@@ -0,0 +1,8 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { C as Context } from './server.DLt5njUb.js';
3
+ import { a as StandardHandlerOptions } from './server.DuTpqr2w.js';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ }
7
+
8
+ export type { StandardRPCHandlerOptions as S };
@@ -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 };
@@ -0,0 +1,10 @@
1
+ import { C as Context } from './server.DLt5njUb.js';
2
+ import { S as StandardHandleOptions } from './server.DuTpqr2w.js';
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,66 @@
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.mjs';
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 StandardHandleOptions<T extends Context> {
24
+ prefix?: HTTPPath;
25
+ context: T;
26
+ }
27
+ type StandardHandleResult = {
28
+ matched: true;
29
+ response: StandardResponse;
30
+ } | {
31
+ matched: false;
32
+ response: undefined;
33
+ };
34
+ interface StandardHandlerPlugin<TContext extends Context> {
35
+ init?(options: StandardHandlerOptions<TContext>): void;
36
+ }
37
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
38
+ request: StandardLazyRequest;
39
+ }
40
+ interface StandardHandlerOptions<TContext extends Context> {
41
+ plugins?: StandardHandlerPlugin<TContext>[];
42
+ /**
43
+ * Interceptors at the request level, helpful when you want catch errors
44
+ */
45
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
46
+ /**
47
+ * Interceptors at the root level, helpful when you want override the request/response
48
+ */
49
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
50
+ /**
51
+ *
52
+ * Interceptors for procedure client.
53
+ */
54
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
55
+ }
56
+ declare class StandardHandler<T extends Context> {
57
+ private readonly matcher;
58
+ private readonly codec;
59
+ private readonly interceptors;
60
+ private readonly clientInterceptors;
61
+ private readonly rootInterceptors;
62
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
63
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
64
+ }
65
+
66
+ export { type StandardHandleOptions as S, type StandardHandlerOptions as a, type StandardCodec as b, type StandardParams as c, type StandardMatcher as d, type StandardMatchResult as e, type StandardHandleResult as f, type StandardHandlerPlugin as g, type StandardHandlerInterceptorOptions as h, StandardHandler as i };