@temporary-name/server 1.9.3-alpha.0d2fa3247b6b23bbc2e3097a95f631b86740e4d8 → 1.9.3-alpha.0f2e1f4d66464608b85c66977bff51174cbb238f

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 (39) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +12 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +12 -7
  3. package/dist/adapters/aws-lambda/index.mjs +12 -4
  4. package/dist/adapters/fetch/index.d.mts +12 -7
  5. package/dist/adapters/fetch/index.d.ts +12 -7
  6. package/dist/adapters/fetch/index.mjs +12 -11
  7. package/dist/adapters/node/index.d.mts +12 -7
  8. package/dist/adapters/node/index.d.ts +12 -7
  9. package/dist/adapters/node/index.mjs +12 -11
  10. package/dist/adapters/standard/index.d.mts +27 -13
  11. package/dist/adapters/standard/index.d.ts +27 -13
  12. package/dist/adapters/standard/index.mjs +8 -100
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +82 -459
  15. package/dist/index.d.ts +82 -459
  16. package/dist/index.mjs +213 -366
  17. package/dist/openapi/index.d.mts +220 -0
  18. package/dist/openapi/index.d.ts +220 -0
  19. package/dist/openapi/index.mjs +709 -0
  20. package/dist/plugins/index.d.mts +5 -83
  21. package/dist/plugins/index.d.ts +5 -83
  22. package/dist/plugins/index.mjs +17 -189
  23. package/dist/shared/{server.Btxrgkj5.d.ts → server.25yUS-xw.d.mts} +7 -25
  24. package/dist/shared/server.BKwU5-Ea.d.mts +23 -0
  25. package/dist/shared/server.C1RJffw4.mjs +30 -0
  26. package/dist/shared/{server.Bo94xDTv.d.mts → server.Co-zpS8Y.d.ts} +7 -25
  27. package/dist/shared/server.DRYRuXpK.mjs +254 -0
  28. package/dist/shared/server.DV_PWBS2.d.ts +23 -0
  29. package/dist/shared/server.DWEp52Gx.mjs +379 -0
  30. package/dist/shared/server.JtIZ8YG7.mjs +237 -0
  31. package/dist/shared/server.VtI8pLxV.d.mts +242 -0
  32. package/dist/shared/server.VtI8pLxV.d.ts +242 -0
  33. package/package.json +18 -23
  34. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  35. package/dist/shared/server.C1YnHvvf.d.mts +0 -192
  36. package/dist/shared/server.C1YnHvvf.d.ts +0 -192
  37. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  38. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  39. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
package/dist/index.mjs CHANGED
@@ -1,335 +1,163 @@
1
- import { isContractProcedure, mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, enhanceRoute, mergeTags, getContractRouter } from '@temporary-name/contract';
2
- export { ValidationError, eventIterator, type, validateORPCError } from '@temporary-name/contract';
3
- import { onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
4
- export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, safe, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
5
- import { g as gatingContext } from './shared/server.D6K9uoPI.mjs';
6
- import { c as createProcedureClient, i as isLazy, g as getLazyMeta, l as lazy, u as unlazy } from './shared/server.BEQrAa3A.mjs';
7
- export { L as LAZY_SYMBOL, a as createORPCErrorConstructorMap, m as mergeCurrentContext, b as middlewareOutputFn } from './shared/server.BEQrAa3A.mjs';
1
+ import { mergePrefix, mergeTags, ContractProcedure, mergeMeta, parseEndpointDefinition, mergeRoute, prefixRoute, initialSchemas, isContractProcedure, getContractRouter } from '@temporary-name/contract';
2
+ export { ValidationError, eventIterator } from '@temporary-name/contract';
3
+ import { assertNever, splitFirst, ORPCError, onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
4
+ export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
5
+ import { SchemaClass, object, core, gatingContext } from '@temporary-name/zod';
6
+ import { g as getCookie } from './shared/server.C1RJffw4.mjs';
7
+ import { P as Procedure, c as createProcedureClient, e as enhanceRouter, a as addMiddleware, s as setHiddenRouterContract, l as lazyInternal, g as getLazyMeta, u as unlazy, i as isProcedure, b as isLazy, d as getRouter } from './shared/server.DWEp52Gx.mjs';
8
+ export { L as LAZY_SYMBOL, o as createAccessibleLazyRouter, n as getHiddenRouterContract, j as isStartWithMiddlewares, f as lazy, m as mergeCurrentContext, k as mergeMiddlewares, h as middlewareOutputFn, r as resolveContractProcedures, t as traverseContractProcedures, p as unlazyRouter } from './shared/server.DWEp52Gx.mjs';
8
9
  export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
9
- import 'node:async_hooks';
10
- import 'zod';
11
- import 'zod/v4/core';
10
+ import 'cookie';
12
11
 
13
- function decorateMiddleware(middleware) {
14
- const decorated = ((...args) => middleware(...args));
15
- decorated.mapInput = (mapInput) => {
16
- const mapped = decorateMiddleware(
17
- (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
18
- );
19
- return mapped;
20
- };
21
- decorated.concat = (concatMiddleware, mapInput) => {
22
- const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
23
- const concatted = decorateMiddleware((options, input, output, ...rest) => {
24
- const merged = middleware(
25
- {
26
- ...options,
27
- next: (...[nextOptions1]) => mapped(
28
- {
29
- ...options,
30
- context: { ...options.context, ...nextOptions1?.context },
31
- next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
32
- },
33
- input,
34
- output,
35
- ...rest
36
- )
37
- },
38
- input,
39
- output,
40
- ...rest
41
- );
42
- return merged;
43
- });
44
- return concatted;
45
- };
46
- return decorated;
47
- }
48
-
49
- function isStartWithMiddlewares(middlewares, compare) {
50
- if (compare.length > middlewares.length) {
51
- return false;
52
- }
53
- for (let i = 0; i < middlewares.length; i++) {
54
- if (compare[i] === void 0) {
55
- return true;
56
- }
57
- if (middlewares[i] !== compare[i]) {
58
- return false;
59
- }
12
+ function validateTokenPrefix(prefix, token) {
13
+ if (prefix && !token.startsWith(prefix)) {
14
+ throw new ORPCError("UNAUTHORIZED", { message: `Invalid auth token. It must start with "${prefix}"` });
60
15
  }
61
- return true;
62
16
  }
63
- function mergeMiddlewares(first, second, options) {
64
- if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
65
- return second;
66
- }
67
- return [...first, ...second];
17
+ function validateTokenAuth(config, token, options) {
18
+ const { tokenPrefix, validate } = config;
19
+ validateTokenPrefix(tokenPrefix, token);
20
+ return validate(token, options);
68
21
  }
69
- function addMiddleware(middlewares, addition) {
70
- return [...middlewares, addition];
22
+ function authByQuery(config, options) {
23
+ const { name, tokenPrefix, validate } = config;
24
+ const query = options.request.url.searchParams;
25
+ const token = query.get(name);
26
+ if (!token) return void 0;
27
+ validateTokenPrefix(tokenPrefix, token);
28
+ return validate(token, options);
71
29
  }
72
-
73
- class Procedure {
74
- /**
75
- * This property holds the defined options.
76
- */
77
- "~orpc";
78
- constructor(def) {
79
- this["~orpc"] = def;
80
- }
30
+ function authByHeader(config, options) {
31
+ const authHeader = options.request.headers.get(config.name);
32
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
81
33
  }
82
- function isProcedure(item) {
83
- if (item instanceof Procedure) {
84
- return true;
85
- }
86
- return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
34
+ function authByCookie(config, options) {
35
+ const cookie = getCookie(options.request.headers, config.name);
36
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
37
+ }
38
+ function authByBearer(config, options) {
39
+ const authHeader = options.request.headers.get("Authorization");
40
+ if (!authHeader) return void 0;
41
+ const [authType, bearer] = splitFirst(authHeader, " ");
42
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
43
+ }
44
+ function authByBasic(config, options) {
45
+ const authHeader = options.request.headers.get("Authorization");
46
+ if (!authHeader) return void 0;
47
+ const [authType, encoded] = splitFirst(authHeader, " ");
48
+ if (authType !== "Basic") return void 0;
49
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
50
+ const [username, password] = splitFirst(decoded, ":");
51
+ validateTokenPrefix(config.tokenPrefix, password);
52
+ return config.validate(username, password, options);
53
+ }
54
+ function authByType(config, options) {
55
+ const { type } = config;
56
+ return type === "header" ? authByHeader(config, options) : type === "query" ? authByQuery(config, options) : type === "cookie" ? authByCookie(config, options) : type === "bearer" ? authByBearer(config, options) : type === "basic" ? authByBasic(config, options) : type === "none" ? false : assertNever(type);
57
+ }
58
+ function authDescription(config) {
59
+ const { type } = config;
60
+ return type === "basic" ? "a Basic Authentication header" : type === "bearer" ? "a Bearer Authentication header" : type === "header" ? `a header named "${config.name}"` : type === "query" ? `a query parameter named "${config.name}"` : type === "cookie" ? `a cookie named "${config.name}"` : type === "none" ? "no authentication" : assertNever(type);
87
61
  }
88
62
 
89
63
  class DecoratedProcedure extends Procedure {
90
64
  /**
91
- * Adds type-safe custom errors.
92
- * The provided errors are spared-merged with any existing errors.
65
+ * Make this procedure callable (works like a function while still being a procedure).
93
66
  *
94
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
67
+ * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
95
68
  */
96
- errors(errors) {
97
- return new DecoratedProcedure({
98
- ...this["~orpc"],
99
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
69
+ callable(...rest) {
70
+ const client = createProcedureClient(this, ...rest);
71
+ return new Proxy(client, {
72
+ get: (target, key) => {
73
+ return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
74
+ },
75
+ has: (target, key) => {
76
+ return Reflect.has(this, key) || Reflect.has(target, key);
77
+ }
100
78
  });
101
79
  }
80
+ }
81
+
82
+ class ProcedureBuilder extends ContractProcedure {
83
+ z;
84
+ constructor(def) {
85
+ super(def);
86
+ this.z = new SchemaClass();
87
+ }
102
88
  /**
103
- * Sets or updates the metadata.
104
- * The provided metadata is spared-merged with any existing metadata.
89
+ * Sets or updates the metadata for the contract.
90
+ * The provided metadata is spared-merged with any existing metadata in the contract.
105
91
  *
106
92
  * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
107
93
  */
108
94
  meta(meta) {
109
- return new DecoratedProcedure({
95
+ return new ProcedureBuilder({
110
96
  ...this["~orpc"],
111
97
  meta: mergeMeta(this["~orpc"].meta, meta)
112
98
  });
113
99
  }
100
+ endpoint(stringsOrEndpoint, ...values) {
101
+ const { method, path, pathSchema } = parseEndpointDefinition(stringsOrEndpoint, values);
102
+ const { prefix } = this["~orpc"];
103
+ const route = { method, path };
104
+ return new ProcedureBuilder({
105
+ ...this["~orpc"],
106
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route),
107
+ schemas: {
108
+ ...this["~orpc"].schemas,
109
+ pathSchema
110
+ }
111
+ });
112
+ }
114
113
  /**
115
- * Sets or updates the route definition.
116
- * The provided route is spared-merged with any existing route.
114
+ * Sets or updates the route definition for the contract.
115
+ * The provided route is spared-merged with any existing route in the contract.
117
116
  * This option is typically relevant when integrating with OpenAPI.
118
117
  *
119
118
  * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
120
119
  * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
121
120
  */
122
- route(route) {
123
- return new DecoratedProcedure({
121
+ endpointOpts(route) {
122
+ const { prefix } = this["~orpc"];
123
+ return new ProcedureBuilder({
124
124
  ...this["~orpc"],
125
- route: mergeRoute(this["~orpc"].route, route)
125
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route)
126
126
  });
127
127
  }
128
- use(middleware, mapInput) {
129
- const mapped = mapInput ? decorateMiddleware(middleware).mapInput(mapInput) : middleware;
130
- return new DecoratedProcedure({
128
+ query(schema) {
129
+ return new ProcedureBuilder({
131
130
  ...this["~orpc"],
132
- middlewares: addMiddleware(this["~orpc"].middlewares, mapped)
133
- });
134
- }
135
- /**
136
- * Make this procedure callable (works like a function while still being a procedure).
137
- *
138
- * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
139
- */
140
- callable(...rest) {
141
- const client = createProcedureClient(this, ...rest);
142
- return new Proxy(client, {
143
- get: (target, key) => {
144
- return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
131
+ schemas: {
132
+ ...this["~orpc"].schemas,
133
+ querySchema: schema instanceof core.$ZodType ? schema : object(schema)
145
134
  },
146
- has: (target, key) => {
147
- return Reflect.has(this, key) || Reflect.has(target, key);
148
- }
135
+ inputValidationIndex: this["~orpc"].middlewares.length
149
136
  });
150
137
  }
151
- }
152
-
153
- const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
154
- function setHiddenRouterContract(router, contract) {
155
- return new Proxy(router, {
156
- get(target, key) {
157
- if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
158
- return contract;
159
- }
160
- return Reflect.get(target, key);
161
- }
162
- });
163
- }
164
- function getHiddenRouterContract(router) {
165
- return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
166
- }
167
-
168
- function getRouter(router, path) {
169
- let current = router;
170
- for (let i = 0; i < path.length; i++) {
171
- const segment = path[i];
172
- if (!current) {
173
- return void 0;
174
- }
175
- if (isProcedure(current)) {
176
- return void 0;
177
- }
178
- if (!isLazy(current)) {
179
- current = current[segment];
180
- continue;
181
- }
182
- const lazied = current;
183
- const rest = path.slice(i);
184
- return lazy(async () => {
185
- const unwrapped = await unlazy(lazied);
186
- const next = getRouter(unwrapped.default, rest);
187
- return unlazy(next);
188
- }, getLazyMeta(lazied));
189
- }
190
- return current;
191
- }
192
- function createAccessibleLazyRouter(lazied) {
193
- const recursive = new Proxy(lazied, {
194
- get(target, key) {
195
- if (typeof key !== "string") {
196
- return Reflect.get(target, key);
197
- }
198
- const next = getRouter(lazied, [key]);
199
- return createAccessibleLazyRouter(next);
200
- }
201
- });
202
- return recursive;
203
- }
204
- function enhanceRouter(router, options) {
205
- if (isLazy(router)) {
206
- const laziedMeta = getLazyMeta(router);
207
- const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
208
- const enhanced2 = lazy(
209
- async () => {
210
- const { default: unlaziedRouter } = await unlazy(router);
211
- const enhanced3 = enhanceRouter(unlaziedRouter, options);
212
- return unlazy(enhanced3);
138
+ body(schema) {
139
+ return new ProcedureBuilder({
140
+ ...this["~orpc"],
141
+ schemas: {
142
+ ...this["~orpc"].schemas,
143
+ bodySchema: schema instanceof core.$ZodType ? schema : object(schema)
213
144
  },
214
- {
215
- ...laziedMeta,
216
- prefix: enhancedPrefix
217
- }
218
- );
219
- const accessible = createAccessibleLazyRouter(enhanced2);
220
- return accessible;
221
- }
222
- if (isProcedure(router)) {
223
- const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
224
- dedupeLeading: options.dedupeLeadingMiddlewares
225
- });
226
- const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
227
- const enhanced2 = new Procedure({
228
- ...router["~orpc"],
229
- route: enhanceRoute(router["~orpc"].route, options),
230
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
231
- middlewares: newMiddlewares,
232
- inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
233
- outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
234
- });
235
- return enhanced2;
236
- }
237
- const enhanced = {};
238
- for (const key in router) {
239
- enhanced[key] = enhanceRouter(router[key], options);
240
- }
241
- return enhanced;
242
- }
243
- function traverseContractProcedures(options, callback, lazyOptions = []) {
244
- let currentRouter = options.router;
245
- const hiddenContract = getHiddenRouterContract(options.router);
246
- if (hiddenContract !== void 0) {
247
- currentRouter = hiddenContract;
248
- }
249
- if (isLazy(currentRouter)) {
250
- lazyOptions.push({
251
- router: currentRouter,
252
- path: options.path
253
- });
254
- } else if (isContractProcedure(currentRouter)) {
255
- callback({
256
- contract: currentRouter,
257
- path: options.path
145
+ inputValidationIndex: this["~orpc"].middlewares.length
258
146
  });
259
- } else {
260
- for (const key in currentRouter) {
261
- traverseContractProcedures(
262
- {
263
- router: currentRouter[key],
264
- path: [...options.path, key]
265
- },
266
- callback,
267
- lazyOptions
268
- );
269
- }
270
- }
271
- return lazyOptions;
272
- }
273
- async function resolveContractProcedures(options, callback) {
274
- const pending = [options];
275
- for (const options2 of pending) {
276
- const lazyOptions = traverseContractProcedures(options2, callback);
277
- for (const options3 of lazyOptions) {
278
- const { default: router } = await unlazy(options3.router);
279
- pending.push({
280
- router,
281
- path: options3.path
282
- });
283
- }
284
- }
285
- }
286
- async function unlazyRouter(router) {
287
- if (isProcedure(router)) {
288
- return router;
289
- }
290
- const unlazied = {};
291
- for (const key in router) {
292
- const item = router[key];
293
- const { default: unlaziedRouter } = await unlazy(item);
294
- unlazied[key] = await unlazyRouter(unlaziedRouter);
295
- }
296
- return unlazied;
297
- }
298
-
299
- class Builder {
300
- /**
301
- * This property holds the defined options.
302
- */
303
- "~orpc";
304
- constructor(def) {
305
- this["~orpc"] = def;
306
- }
307
- /**
308
- * Set or override the initial context.
309
- *
310
- * @see {@link https://orpc.unnoq.com/docs/context Context Docs}
311
- */
312
- $context() {
313
- return this;
314
147
  }
315
148
  /**
316
- * Creates a middleware.
317
- *
318
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
319
- */
320
- middleware(middleware) {
321
- return decorateMiddleware(middleware);
322
- }
323
- /**
324
- * Adds type-safe custom errors.
325
- * The provided errors are spared-merged with any existing errors.
149
+ * Defines the output validation schema.
326
150
  *
327
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
151
+ * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Output Validation Docs}
328
152
  */
329
- errors(errors) {
330
- return new Builder({
153
+ output(schema) {
154
+ return new ProcedureBuilder({
331
155
  ...this["~orpc"],
332
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
156
+ schemas: {
157
+ ...this["~orpc"].schemas,
158
+ outputSchema: schema instanceof core.$ZodType ? schema : object(schema)
159
+ },
160
+ outputValidationIndex: this["~orpc"].middlewares.length
333
161
  });
334
162
  }
335
163
  /**
@@ -340,11 +168,41 @@ class Builder {
340
168
  * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
341
169
  */
342
170
  use(middleware) {
343
- return new Builder({
171
+ return new this.constructor({
344
172
  ...this["~orpc"],
345
173
  middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
346
174
  });
347
175
  }
176
+ // `& {}` is so AuthType will be expanded in parameter info tooltips.
177
+ // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
178
+ // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
179
+ useAuth(type, ...rest) {
180
+ const config = { type, ...rest[0] };
181
+ const middleware = os.$context().middleware(async (options) => {
182
+ const { next, context } = options;
183
+ if (context.auth) return next();
184
+ const auth = await authByType(config, options);
185
+ if (auth === void 0) {
186
+ const { authConfigs } = options.procedure["~orpc"];
187
+ if (context.auth !== false && config === authConfigs.at(-1)) {
188
+ let authDescriptions = authConfigs.map(authDescription).join(", ");
189
+ if (authConfigs.length > 1) {
190
+ authDescriptions = `one of: ${authDescriptions}`;
191
+ }
192
+ throw new ORPCError("UNAUTHORIZED", {
193
+ message: `Authentication required. You must provide ${authDescriptions}`
194
+ });
195
+ }
196
+ return next();
197
+ }
198
+ return next({ context: { auth } });
199
+ });
200
+ return new this.constructor({
201
+ ...this["~orpc"],
202
+ authConfigs: [...this["~orpc"].authConfigs, config],
203
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
204
+ });
205
+ }
348
206
  useGating(gates, isGateEnabled) {
349
207
  return this.use(({ next, context }) => {
350
208
  return gatingContext.run(
@@ -353,67 +211,22 @@ class Builder {
353
211
  );
354
212
  });
355
213
  }
356
- /**
357
- * Sets or updates the metadata.
358
- * The provided metadata is spared-merged with any existing metadata.
359
- *
360
- * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
361
- */
362
- meta(meta) {
363
- return new Builder({
364
- ...this["~orpc"],
365
- meta: mergeMeta(this["~orpc"].meta, meta)
366
- });
367
- }
368
- /**
369
- * Sets or updates the route definition.
370
- * The provided route is spared-merged with any existing route.
371
- * This option is typically relevant when integrating with OpenAPI.
372
- *
373
- * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
374
- * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
375
- */
376
- route(route) {
377
- return new Builder({
378
- ...this["~orpc"],
379
- route: mergeRoute(this["~orpc"].route, route)
380
- });
381
- }
382
- /**
383
- * Defines the input validation schema.
384
- *
385
- * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
386
- */
387
- input(schema) {
388
- return new Builder({
389
- ...this["~orpc"],
390
- inputSchema: schema,
391
- inputValidationIndex: this["~orpc"].middlewares.length
392
- });
393
- }
394
- /**
395
- * Defines the output validation schema.
396
- *
397
- * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Output Validation Docs}
398
- */
399
- output(schema) {
400
- return new Builder({
401
- ...this["~orpc"],
402
- outputSchema: schema,
403
- outputValidationIndex: this["~orpc"].middlewares.length
404
- });
405
- }
406
214
  /**
407
215
  * Defines the handler of the procedure.
408
216
  *
409
217
  * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
410
218
  */
411
219
  handler(handler) {
220
+ if (this["~orpc"].schemas.outputSchema === initialSchemas.outputSchema) {
221
+ throw new Error("You must call .output() before calling .handler()");
222
+ }
412
223
  return new DecoratedProcedure({
413
224
  ...this["~orpc"],
414
225
  handler
415
226
  });
416
227
  }
228
+ }
229
+ class BuilderWithMiddlewares extends ProcedureBuilder {
417
230
  /**
418
231
  * Prefixes all procedures in the router.
419
232
  * The provided prefix is post-appended to any existing router prefix.
@@ -423,7 +236,7 @@ class Builder {
423
236
  * @see {@link https://orpc.unnoq.com/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}
424
237
  */
425
238
  prefix(prefix) {
426
- return new Builder({
239
+ return new this.constructor({
427
240
  ...this["~orpc"],
428
241
  prefix: mergePrefix(this["~orpc"].prefix, prefix)
429
242
  });
@@ -435,7 +248,7 @@ class Builder {
435
248
  * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}
436
249
  */
437
250
  tag(...tags) {
438
- return new Builder({
251
+ return new this.constructor({
439
252
  ...this["~orpc"],
440
253
  tags: mergeTags(this["~orpc"].tags, tags)
441
254
  });
@@ -448,33 +261,79 @@ class Builder {
448
261
  router(router) {
449
262
  return enhanceRouter(router, this["~orpc"]);
450
263
  }
264
+ }
265
+
266
+ function decorateMiddleware(middleware) {
267
+ const decorated = ((...args) => middleware(...args));
268
+ decorated.mapInput = (mapInput) => {
269
+ const mapped = decorateMiddleware(
270
+ (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
271
+ );
272
+ return mapped;
273
+ };
274
+ decorated.concat = (concatMiddleware, mapInput) => {
275
+ const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
276
+ const concatted = decorateMiddleware((options, input, output, ...rest) => {
277
+ const merged = middleware(
278
+ {
279
+ ...options,
280
+ next: (...[nextOptions1]) => mapped(
281
+ {
282
+ ...options,
283
+ context: { ...options.context, ...nextOptions1?.context },
284
+ next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
285
+ },
286
+ input,
287
+ output,
288
+ ...rest
289
+ )
290
+ },
291
+ input,
292
+ output,
293
+ ...rest
294
+ );
295
+ return merged;
296
+ });
297
+ return concatted;
298
+ };
299
+ return decorated;
300
+ }
301
+
302
+ class Builder extends BuilderWithMiddlewares {
451
303
  /**
452
- * Create a lazy router
453
- * And applies all of the previously defined options to the specified router.
304
+ * Set or override the initial context.
454
305
  *
455
- * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
306
+ * @see {@link https://orpc.unnoq.com/docs/context Context Docs}
456
307
  */
457
- lazyRoute(loader) {
458
- return enhanceRouter(lazy(loader), this["~orpc"]);
308
+ $context() {
309
+ return this;
310
+ }
311
+ /**
312
+ * Creates a middleware.
313
+ *
314
+ * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
315
+ */
316
+ middleware(middleware) {
317
+ return decorateMiddleware(middleware);
459
318
  }
460
319
  }
461
320
  function createApiBuilder(opts = {}) {
462
- const base = new Builder({
321
+ return new Builder({
463
322
  route: {},
464
323
  meta: opts.meta ?? {},
465
- errorMap: {},
466
324
  inputValidationIndex: 0,
467
325
  outputValidationIndex: 0,
468
326
  middlewares: [
469
- onError((error, options) => {
327
+ onError((error, _options) => {
470
328
  console.dir(error, { depth: null });
471
329
  })
472
330
  ],
331
+ schemas: initialSchemas,
473
332
  // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
474
333
  // the best solution). For now I've removed the interface to configure it externally.
475
- dedupeLeadingMiddlewares: true
334
+ dedupeLeadingMiddlewares: true,
335
+ authConfigs: []
476
336
  });
477
- return base;
478
337
  }
479
338
  const os = createApiBuilder();
480
339
 
@@ -483,6 +342,7 @@ function implementerInternal(contract, middlewares) {
483
342
  const impl2 = new Builder({
484
343
  ...contract["~orpc"],
485
344
  middlewares,
345
+ authConfigs: [],
486
346
  inputValidationIndex: middlewares.length,
487
347
  outputValidationIndex: middlewares.length,
488
348
  dedupeLeadingMiddlewares: true
@@ -505,18 +365,6 @@ function implementerInternal(contract, middlewares) {
505
365
  method = (router) => {
506
366
  const adapted = enhanceRouter(router, {
507
367
  middlewares,
508
- errorMap: {},
509
- prefix: void 0,
510
- tags: void 0,
511
- dedupeLeadingMiddlewares: true
512
- });
513
- return setHiddenRouterContract(adapted, contract);
514
- };
515
- } else if (key === "lazyRoute") {
516
- method = (loader) => {
517
- const adapted = enhanceRouter(lazy(loader), {
518
- middlewares,
519
- errorMap: {},
520
368
  prefix: void 0,
521
369
  tags: void 0,
522
370
  dedupeLeadingMiddlewares: true
@@ -564,7 +412,7 @@ function implement(contract) {
564
412
  }
565
413
 
566
414
  function createAssertedLazyProcedure(lazied) {
567
- const lazyProcedure = lazy(async () => {
415
+ const lazyProcedure = lazyInternal(async () => {
568
416
  const { default: maybeProcedure } = await unlazy(lazied);
569
417
  if (!isProcedure(maybeProcedure)) {
570
418
  throw new Error(`
@@ -580,7 +428,6 @@ function createAssertedLazyProcedure(lazied) {
580
428
  function createContractedProcedure(procedure, contract) {
581
429
  return new Procedure({
582
430
  ...procedure["~orpc"],
583
- errorMap: contract["~orpc"].errorMap,
584
431
  route: contract["~orpc"].route,
585
432
  meta: contract["~orpc"].meta
586
433
  });
@@ -615,4 +462,4 @@ function createRouterClient(router, ...rest) {
615
462
  return recursive;
616
463
  }
617
464
 
618
- export { Builder, DecoratedProcedure, Procedure, addMiddleware, call, createAccessibleLazyRouter, createApiBuilder, createAssertedLazyProcedure, createContractedProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getHiddenRouterContract, getLazyMeta, getRouter, implement, implementerInternal, isLazy, isProcedure, isStartWithMiddlewares, lazy, mergeMiddlewares, os, resolveContractProcedures, setHiddenRouterContract, traverseContractProcedures, unlazy, unlazyRouter };
465
+ export { Builder, BuilderWithMiddlewares, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createContractedProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, implement, implementerInternal, isLazy, isProcedure, lazyInternal, os, setHiddenRouterContract, unlazy };