@temporary-name/server 1.9.3-alpha.cf2fe368e72e6a6ab0ce041b812dbf8134f70b0b → 1.9.3-alpha.d0c8ba895f81e5ee5f2f893da0804bd96a5aa41c

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 (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +4 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +4 -6
  3. package/dist/adapters/aws-lambda/index.mjs +4 -4
  4. package/dist/adapters/fetch/index.d.mts +8 -86
  5. package/dist/adapters/fetch/index.d.ts +8 -86
  6. package/dist/adapters/fetch/index.mjs +16 -155
  7. package/dist/adapters/node/index.d.mts +8 -63
  8. package/dist/adapters/node/index.d.ts +8 -63
  9. package/dist/adapters/node/index.mjs +14 -120
  10. package/dist/adapters/standard/index.d.mts +20 -33
  11. package/dist/adapters/standard/index.d.ts +20 -33
  12. package/dist/adapters/standard/index.mjs +4 -4
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +113 -280
  15. package/dist/index.d.ts +113 -280
  16. package/dist/index.mjs +189 -393
  17. package/dist/openapi/index.d.mts +12 -28
  18. package/dist/openapi/index.d.ts +12 -28
  19. package/dist/openapi/index.mjs +66 -150
  20. package/dist/shared/server.BYV-qTJt.d.ts +41 -0
  21. package/dist/shared/server.C1RJffw4.mjs +30 -0
  22. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  23. package/dist/shared/server.CWb33y9B.d.mts +41 -0
  24. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  25. package/dist/shared/server.DXzEGRE2.mjs +403 -0
  26. package/dist/shared/server.DgzAlPjF.mjs +160 -0
  27. package/dist/shared/server.DimTvmOQ.d.mts +373 -0
  28. package/dist/shared/server.DimTvmOQ.d.ts +373 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +9 -27
  31. package/dist/plugins/index.d.mts +0 -160
  32. package/dist/plugins/index.d.ts +0 -160
  33. package/dist/plugins/index.mjs +0 -288
  34. package/dist/shared/server.B9i6p26R.d.ts +0 -57
  35. package/dist/shared/server.BEHw7Eyx.mjs +0 -247
  36. package/dist/shared/server.Bzrdopnd.d.mts +0 -192
  37. package/dist/shared/server.Bzrdopnd.d.ts +0 -192
  38. package/dist/shared/server.C-j2WKJz.d.mts +0 -57
  39. package/dist/shared/server.CYRDznXq.d.ts +0 -23
  40. package/dist/shared/server.Cp__uvkw.d.mts +0 -23
  41. package/dist/shared/server.CvI-wPHM.mjs +0 -293
  42. package/dist/shared/server.NLSomL7m.mjs +0 -202
package/dist/index.mjs CHANGED
@@ -1,134 +1,72 @@
1
- import { onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
2
- export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, safe, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
3
- import { isContractProcedure, mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, enhanceRoute, mergeTags, ContractProcedure, prefixRoute, getContractRouter } from '@temporary-name/contract';
4
- export { ValidationError, eventIterator, validateORPCError } from '@temporary-name/contract';
5
- import { SchemaClass, gatingContext } from '@temporary-name/zod';
6
- import { c as createProcedureClient, i as isLazy, g as getLazyMeta, l as lazy, u as unlazy } from './shared/server.NLSomL7m.mjs';
7
- export { L as LAZY_SYMBOL, a as createORPCErrorConstructorMap, m as mergeCurrentContext, b as middlewareOutputFn } from './shared/server.NLSomL7m.mjs';
1
+ import { assertNever, splitFirst, ORPCError, onError, resolveMaybeOptionalOptions, isTypescriptObject, isPropertyKey } from '@temporary-name/shared';
2
+ export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
3
+ import * as z from '@temporary-name/zod';
4
+ import { SchemaClass, object, core, gatingContext } from '@temporary-name/zod';
5
+ import { g as getCookie } from './shared/server.C1RJffw4.mjs';
6
+ import { P as Procedure, m as mergePrefix, a as mergeTags, e as enhanceRouter, C as Contract, p as parseEndpointDefinition, b as mergeRoute, c as prefixRoute, d as addMiddleware, l as lazyInternal, f as getLazyMeta, u as unlazy, i as isProcedure, h as isLazy, j as getRouter } from './shared/server.ChOv1yG3.mjs';
7
+ export { L as LAZY_SYMBOL, V as ValidationError, q as createAccessibleLazyRouter, w as endpointRegex, g as getDynamicParams, n as isStartWithMiddlewares, k as lazy, o as mergeMiddlewares, r as resolveContractProcedures, s as standardizeHTTPPath, t as traverseContractProcedures, v as unlazyRouter } from './shared/server.ChOv1yG3.mjs';
8
+ import { c as createProcedureClient } from './shared/server.DgzAlPjF.mjs';
9
+ export { m as mergeCurrentContext, a as middlewareOutputFn } from './shared/server.DgzAlPjF.mjs';
10
+ export { e as eventIterator, g as getEventIteratorSchemaDetails } from './shared/server.YUvuxHty.mjs';
8
11
  export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
12
+ import 'cookie';
9
13
 
10
- function isStartWithMiddlewares(middlewares, compare) {
11
- if (compare.length > middlewares.length) {
12
- return false;
13
- }
14
- for (let i = 0; i < middlewares.length; i++) {
15
- if (compare[i] === void 0) {
16
- return true;
17
- }
18
- if (middlewares[i] !== compare[i]) {
19
- return false;
20
- }
14
+ function validateTokenPrefix(prefix, token) {
15
+ if (prefix && !token.startsWith(prefix)) {
16
+ throw new ORPCError("UNAUTHORIZED", { message: `Invalid auth token. It must start with "${prefix}"` });
21
17
  }
22
- return true;
23
18
  }
24
- function mergeMiddlewares(first, second, options) {
25
- if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
26
- return second;
27
- }
28
- return [...first, ...second];
19
+ function validateTokenAuth(config, token, options) {
20
+ const { tokenPrefix, validate } = config;
21
+ validateTokenPrefix(tokenPrefix, token);
22
+ return validate(token, options);
29
23
  }
30
- function addMiddleware(middlewares, addition) {
31
- return [...middlewares, addition];
24
+ function authByQuery(config, options) {
25
+ const { name, tokenPrefix, validate } = config;
26
+ const query = options.request.url.searchParams;
27
+ const token = query.get(name);
28
+ if (!token) return void 0;
29
+ validateTokenPrefix(tokenPrefix, token);
30
+ return validate(token, options);
32
31
  }
33
-
34
- function decorateMiddleware(middleware) {
35
- const decorated = ((...args) => middleware(...args));
36
- decorated.mapInput = (mapInput) => {
37
- const mapped = decorateMiddleware(
38
- (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
39
- );
40
- return mapped;
41
- };
42
- decorated.concat = (concatMiddleware, mapInput) => {
43
- const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
44
- const concatted = decorateMiddleware((options, input, output, ...rest) => {
45
- const merged = middleware(
46
- {
47
- ...options,
48
- next: (...[nextOptions1]) => mapped(
49
- {
50
- ...options,
51
- context: { ...options.context, ...nextOptions1?.context },
52
- next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
53
- },
54
- input,
55
- output,
56
- ...rest
57
- )
58
- },
59
- input,
60
- output,
61
- ...rest
62
- );
63
- return merged;
64
- });
65
- return concatted;
66
- };
67
- return decorated;
32
+ function authByHeader(config, options) {
33
+ const authHeader = options.request.headers.get(config.name);
34
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
68
35
  }
69
-
70
- class Procedure {
71
- /**
72
- * This property holds the defined options.
73
- */
74
- "~orpc";
75
- constructor(def) {
76
- this["~orpc"] = def;
77
- }
36
+ function authByCookie(config, options) {
37
+ const cookie = getCookie(options.request.headers, config.name);
38
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
78
39
  }
79
- function isProcedure(item) {
80
- if (item instanceof Procedure) {
81
- return true;
82
- }
83
- return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
40
+ function authByBearer(config, options) {
41
+ const authHeader = options.request.headers.get("Authorization");
42
+ if (!authHeader) return void 0;
43
+ const [authType, bearer] = splitFirst(authHeader, " ");
44
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
45
+ }
46
+ function authByBasic(config, options) {
47
+ const authHeader = options.request.headers.get("Authorization");
48
+ if (!authHeader) return void 0;
49
+ const [authType, encoded] = splitFirst(authHeader, " ");
50
+ if (authType !== "Basic") return void 0;
51
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
52
+ const [username, password] = splitFirst(decoded, ":");
53
+ validateTokenPrefix(config.tokenPrefix, password);
54
+ return config.validate(username, password, options);
55
+ }
56
+ function authByType(config, options) {
57
+ const { type } = config;
58
+ 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);
59
+ }
60
+ function authDescription(config) {
61
+ const { type } = config;
62
+ 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);
63
+ }
64
+
65
+ function mergeMeta(meta1, meta2) {
66
+ return { ...meta1, ...meta2 };
84
67
  }
85
68
 
86
69
  class DecoratedProcedure extends Procedure {
87
- /**
88
- * Adds type-safe custom errors.
89
- * The provided errors are spared-merged with any existing errors.
90
- *
91
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
92
- */
93
- errors(errors) {
94
- return new DecoratedProcedure({
95
- ...this["~orpc"],
96
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
97
- });
98
- }
99
- /**
100
- * Sets or updates the metadata.
101
- * The provided metadata is spared-merged with any existing metadata.
102
- *
103
- * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
104
- */
105
- meta(meta) {
106
- return new DecoratedProcedure({
107
- ...this["~orpc"],
108
- meta: mergeMeta(this["~orpc"].meta, meta)
109
- });
110
- }
111
- /**
112
- * Sets or updates the route definition.
113
- * The provided route is spared-merged with any existing route.
114
- * This option is typically relevant when integrating with OpenAPI.
115
- *
116
- * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
117
- * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
118
- */
119
- route(route) {
120
- return new DecoratedProcedure({
121
- ...this["~orpc"],
122
- route: mergeRoute(this["~orpc"].route, route)
123
- });
124
- }
125
- use(middleware, mapInput) {
126
- const mapped = mapInput ? decorateMiddleware(middleware).mapInput(mapInput) : middleware;
127
- return new DecoratedProcedure({
128
- ...this["~orpc"],
129
- middlewares: addMiddleware(this["~orpc"].middlewares, mapped)
130
- });
131
- }
132
70
  /**
133
71
  * Make this procedure callable (works like a function while still being a procedure).
134
72
  *
@@ -147,170 +85,19 @@ class DecoratedProcedure extends Procedure {
147
85
  }
148
86
  }
149
87
 
150
- const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
151
- function setHiddenRouterContract(router, contract) {
152
- return new Proxy(router, {
153
- get(target, key) {
154
- if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
155
- return contract;
156
- }
157
- return Reflect.get(target, key);
158
- }
159
- });
160
- }
161
- function getHiddenRouterContract(router) {
162
- return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
163
- }
164
-
165
- function getRouter(router, path) {
166
- let current = router;
167
- for (let i = 0; i < path.length; i++) {
168
- const segment = path[i];
169
- if (!current) {
170
- return void 0;
171
- }
172
- if (isProcedure(current)) {
173
- return void 0;
174
- }
175
- if (!isLazy(current)) {
176
- current = current[segment];
177
- continue;
178
- }
179
- const lazied = current;
180
- const rest = path.slice(i);
181
- return lazy(async () => {
182
- const unwrapped = await unlazy(lazied);
183
- const next = getRouter(unwrapped.default, rest);
184
- return unlazy(next);
185
- }, getLazyMeta(lazied));
186
- }
187
- return current;
188
- }
189
- function createAccessibleLazyRouter(lazied) {
190
- const recursive = new Proxy(lazied, {
191
- get(target, key) {
192
- if (typeof key !== "string") {
193
- return Reflect.get(target, key);
194
- }
195
- const next = getRouter(lazied, [key]);
196
- return createAccessibleLazyRouter(next);
197
- }
198
- });
199
- return recursive;
200
- }
201
- function enhanceRouter(router, options) {
202
- if (isLazy(router)) {
203
- const laziedMeta = getLazyMeta(router);
204
- const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
205
- const enhanced2 = lazy(
206
- async () => {
207
- const { default: unlaziedRouter } = await unlazy(router);
208
- const enhanced3 = enhanceRouter(unlaziedRouter, options);
209
- return unlazy(enhanced3);
210
- },
211
- {
212
- ...laziedMeta,
213
- prefix: enhancedPrefix
214
- }
215
- );
216
- const accessible = createAccessibleLazyRouter(enhanced2);
217
- return accessible;
218
- }
219
- if (isProcedure(router)) {
220
- const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
221
- dedupeLeading: options.dedupeLeadingMiddlewares
222
- });
223
- const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
224
- const enhanced2 = new Procedure({
225
- ...router["~orpc"],
226
- route: enhanceRoute(router["~orpc"].route, options),
227
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
228
- middlewares: newMiddlewares,
229
- inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
230
- outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
231
- });
232
- return enhanced2;
233
- }
234
- const enhanced = {};
235
- for (const key in router) {
236
- enhanced[key] = enhanceRouter(router[key], options);
237
- }
238
- return enhanced;
239
- }
240
- function traverseContractProcedures(options, callback, lazyOptions = []) {
241
- let currentRouter = options.router;
242
- const hiddenContract = getHiddenRouterContract(options.router);
243
- if (hiddenContract !== void 0) {
244
- currentRouter = hiddenContract;
245
- }
246
- if (isLazy(currentRouter)) {
247
- lazyOptions.push({
248
- router: currentRouter,
249
- path: options.path
250
- });
251
- } else if (isContractProcedure(currentRouter)) {
252
- callback({
253
- contract: currentRouter,
254
- path: options.path
255
- });
256
- } else {
257
- for (const key in currentRouter) {
258
- traverseContractProcedures(
259
- {
260
- router: currentRouter[key],
261
- path: [...options.path, key]
262
- },
263
- callback,
264
- lazyOptions
265
- );
266
- }
267
- }
268
- return lazyOptions;
269
- }
270
- async function resolveContractProcedures(options, callback) {
271
- const pending = [options];
272
- for (const options2 of pending) {
273
- const lazyOptions = traverseContractProcedures(options2, callback);
274
- for (const options3 of lazyOptions) {
275
- const { default: router } = await unlazy(options3.router);
276
- pending.push({
277
- router,
278
- path: options3.path
279
- });
280
- }
281
- }
282
- }
283
- async function unlazyRouter(router) {
284
- if (isProcedure(router)) {
285
- return router;
286
- }
287
- const unlazied = {};
288
- for (const key in router) {
289
- const item = router[key];
290
- const { default: unlaziedRouter } = await unlazy(item);
291
- unlazied[key] = await unlazyRouter(unlaziedRouter);
292
- }
293
- return unlazied;
294
- }
88
+ const initialSchemas = {
89
+ pathSchema: z.strictObject({}),
90
+ querySchema: z.strictObject({}),
91
+ bodySchema: z.strictObject({}),
92
+ outputSchema: z.unknown()
93
+ };
295
94
 
296
- class ProcedureBuilder extends ContractProcedure {
95
+ class ProcedureBuilder extends Contract {
297
96
  z;
298
97
  constructor(def) {
299
98
  super(def);
300
99
  this.z = new SchemaClass();
301
100
  }
302
- /**
303
- * Adds type-safe custom errors to the contract.
304
- * The provided errors are spared-merged with any existing errors in the contract.
305
- *
306
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
307
- */
308
- errors(errors) {
309
- return new ProcedureBuilder({
310
- ...this["~orpc"],
311
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
312
- });
313
- }
314
101
  /**
315
102
  * Sets or updates the metadata for the contract.
316
103
  * The provided metadata is spared-merged with any existing metadata in the contract.
@@ -323,6 +110,19 @@ class ProcedureBuilder extends ContractProcedure {
323
110
  meta: mergeMeta(this["~orpc"].meta, meta)
324
111
  });
325
112
  }
113
+ endpoint(stringsOrEndpoint, ...values) {
114
+ const { method, path, pathSchema } = parseEndpointDefinition(stringsOrEndpoint, values);
115
+ const { prefix } = this["~orpc"];
116
+ const route = { method, path };
117
+ return new ProcedureBuilder({
118
+ ...this["~orpc"],
119
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route),
120
+ schemas: {
121
+ ...this["~orpc"].schemas,
122
+ pathSchema
123
+ }
124
+ });
125
+ }
326
126
  /**
327
127
  * Sets or updates the route definition for the contract.
328
128
  * The provided route is spared-merged with any existing route in the contract.
@@ -331,22 +131,30 @@ class ProcedureBuilder extends ContractProcedure {
331
131
  * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
332
132
  * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
333
133
  */
334
- route(route) {
134
+ endpointOpts(route) {
335
135
  const { prefix } = this["~orpc"];
336
136
  return new ProcedureBuilder({
337
137
  ...this["~orpc"],
338
138
  route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route)
339
139
  });
340
140
  }
341
- /**
342
- * Defines the input validation schema.
343
- *
344
- * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
345
- */
346
- input(schema) {
141
+ query(schema) {
347
142
  return new ProcedureBuilder({
348
143
  ...this["~orpc"],
349
- inputSchema: schema,
144
+ schemas: {
145
+ ...this["~orpc"].schemas,
146
+ querySchema: schema instanceof core.$ZodType ? schema : object(schema)
147
+ },
148
+ inputValidationIndex: this["~orpc"].middlewares.length
149
+ });
150
+ }
151
+ body(schema) {
152
+ return new ProcedureBuilder({
153
+ ...this["~orpc"],
154
+ schemas: {
155
+ ...this["~orpc"].schemas,
156
+ bodySchema: schema instanceof core.$ZodType ? schema : object(schema)
157
+ },
350
158
  inputValidationIndex: this["~orpc"].middlewares.length
351
159
  });
352
160
  }
@@ -358,7 +166,10 @@ class ProcedureBuilder extends ContractProcedure {
358
166
  output(schema) {
359
167
  return new ProcedureBuilder({
360
168
  ...this["~orpc"],
361
- outputSchema: schema,
169
+ schemas: {
170
+ ...this["~orpc"].schemas,
171
+ outputSchema: schema instanceof core.$ZodType ? schema : object(schema)
172
+ },
362
173
  outputValidationIndex: this["~orpc"].middlewares.length
363
174
  });
364
175
  }
@@ -375,6 +186,36 @@ class ProcedureBuilder extends ContractProcedure {
375
186
  middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
376
187
  });
377
188
  }
189
+ // `& {}` is so AuthType will be expanded in parameter info tooltips.
190
+ // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
191
+ // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
192
+ useAuth(type, ...rest) {
193
+ const config = { type, ...rest[0] };
194
+ const middleware = os.$context().middleware(async (options) => {
195
+ const { next, context } = options;
196
+ if (context.auth) return next();
197
+ const auth = await authByType(config, options);
198
+ if (auth === void 0) {
199
+ const { authConfigs } = options.procedure["~orpc"];
200
+ if (context.auth !== false && config === authConfigs.at(-1)) {
201
+ let authDescriptions = authConfigs.map(authDescription).join(", ");
202
+ if (authConfigs.length > 1) {
203
+ authDescriptions = `one of: ${authDescriptions}`;
204
+ }
205
+ throw new ORPCError("UNAUTHORIZED", {
206
+ message: `Authentication required. You must provide ${authDescriptions}`
207
+ });
208
+ }
209
+ return next();
210
+ }
211
+ return next({ context: { auth } });
212
+ });
213
+ return new this.constructor({
214
+ ...this["~orpc"],
215
+ authConfigs: [...this["~orpc"].authConfigs, config],
216
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
217
+ });
218
+ }
378
219
  useGating(gates, isGateEnabled) {
379
220
  return this.use(({ next, context }) => {
380
221
  return gatingContext.run(
@@ -389,6 +230,9 @@ class ProcedureBuilder extends ContractProcedure {
389
230
  * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
390
231
  */
391
232
  handler(handler) {
233
+ if (this["~orpc"].schemas.outputSchema === initialSchemas.outputSchema) {
234
+ throw new Error("You must call .output() before calling .handler()");
235
+ }
392
236
  return new DecoratedProcedure({
393
237
  ...this["~orpc"],
394
238
  handler
@@ -430,15 +274,42 @@ class BuilderWithMiddlewares extends ProcedureBuilder {
430
274
  router(router) {
431
275
  return enhanceRouter(router, this["~orpc"]);
432
276
  }
433
- /**
434
- * Create a lazy router
435
- * And applies all of the previously defined options to the specified router.
436
- *
437
- * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
438
- */
439
- lazyRoute(loader) {
440
- return enhanceRouter(lazy(loader), this["~orpc"]);
441
- }
277
+ }
278
+
279
+ function decorateMiddleware(middleware) {
280
+ const decorated = ((...args) => middleware(...args));
281
+ decorated.mapInput = (mapInput) => {
282
+ const mapped = decorateMiddleware(
283
+ (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
284
+ );
285
+ return mapped;
286
+ };
287
+ decorated.concat = (concatMiddleware, mapInput) => {
288
+ const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
289
+ const concatted = decorateMiddleware((options, input, output, ...rest) => {
290
+ const merged = middleware(
291
+ {
292
+ ...options,
293
+ next: (...[nextOptions1]) => mapped(
294
+ {
295
+ ...options,
296
+ context: { ...options.context, ...nextOptions1?.context },
297
+ next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
298
+ },
299
+ input,
300
+ output,
301
+ ...rest
302
+ )
303
+ },
304
+ input,
305
+ output,
306
+ ...rest
307
+ );
308
+ return merged;
309
+ });
310
+ return concatted;
311
+ };
312
+ return decorated;
442
313
  }
443
314
 
444
315
  class Builder extends BuilderWithMiddlewares {
@@ -463,7 +334,6 @@ function createApiBuilder(opts = {}) {
463
334
  return new Builder({
464
335
  route: {},
465
336
  meta: opts.meta ?? {},
466
- errorMap: {},
467
337
  inputValidationIndex: 0,
468
338
  outputValidationIndex: 0,
469
339
  middlewares: [
@@ -471,100 +341,17 @@ function createApiBuilder(opts = {}) {
471
341
  console.dir(error, { depth: null });
472
342
  })
473
343
  ],
344
+ schemas: initialSchemas,
474
345
  // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
475
346
  // the best solution). For now I've removed the interface to configure it externally.
476
- dedupeLeadingMiddlewares: true
347
+ dedupeLeadingMiddlewares: true,
348
+ authConfigs: []
477
349
  });
478
350
  }
479
351
  const os = createApiBuilder();
480
352
 
481
- function implementerInternal(contract, middlewares) {
482
- if (isContractProcedure(contract)) {
483
- const impl2 = new Builder({
484
- ...contract["~orpc"],
485
- middlewares,
486
- inputValidationIndex: middlewares.length,
487
- outputValidationIndex: middlewares.length,
488
- dedupeLeadingMiddlewares: true
489
- });
490
- return impl2;
491
- }
492
- const impl = new Proxy(contract, {
493
- get: (target, key) => {
494
- if (typeof key !== "string") {
495
- return Reflect.get(target, key);
496
- }
497
- let method;
498
- if (key === "middleware") {
499
- method = (mid) => decorateMiddleware(mid);
500
- } else if (key === "use") {
501
- method = (mid) => {
502
- return implementerInternal(contract, addMiddleware(middlewares, mid));
503
- };
504
- } else if (key === "router") {
505
- method = (router) => {
506
- const adapted = enhanceRouter(router, {
507
- 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
- prefix: void 0,
521
- tags: void 0,
522
- dedupeLeadingMiddlewares: true
523
- });
524
- return setHiddenRouterContract(adapted, contract);
525
- };
526
- }
527
- const next = getContractRouter(target, [key]);
528
- if (!next) {
529
- return method ?? next;
530
- }
531
- const nextImpl = implementerInternal(next, middlewares);
532
- if (method) {
533
- return new Proxy(method, {
534
- get(_, key2) {
535
- return Reflect.get(nextImpl, key2);
536
- }
537
- });
538
- }
539
- return nextImpl;
540
- }
541
- });
542
- return impl;
543
- }
544
- function implement(contract) {
545
- const implInternal = implementerInternal(contract, []);
546
- const impl = new Proxy(implInternal, {
547
- get: (target, key) => {
548
- let method;
549
- if (key === "$context") {
550
- method = () => impl;
551
- }
552
- const next = Reflect.get(target, key);
553
- if (!method || !next || typeof next !== "function" && typeof next !== "object") {
554
- return method || next;
555
- }
556
- return new Proxy(method, {
557
- get(_, key2) {
558
- return Reflect.get(next, key2);
559
- }
560
- });
561
- }
562
- });
563
- return impl;
564
- }
565
-
566
353
  function createAssertedLazyProcedure(lazied) {
567
- const lazyProcedure = lazy(async () => {
354
+ const lazyProcedure = lazyInternal(async () => {
568
355
  const { default: maybeProcedure } = await unlazy(lazied);
569
356
  if (!isProcedure(maybeProcedure)) {
570
357
  throw new Error(`
@@ -577,14 +364,6 @@ function createAssertedLazyProcedure(lazied) {
577
364
  }, getLazyMeta(lazied));
578
365
  return lazyProcedure;
579
366
  }
580
- function createContractedProcedure(procedure, contract) {
581
- return new Procedure({
582
- ...procedure["~orpc"],
583
- errorMap: contract["~orpc"].errorMap,
584
- route: contract["~orpc"].route,
585
- meta: contract["~orpc"].meta
586
- });
587
- }
588
367
  function call(procedure, input, ...rest) {
589
368
  const options = resolveMaybeOptionalOptions(rest);
590
369
  return createProcedureClient(procedure, options)(input, options);
@@ -615,4 +394,21 @@ function createRouterClient(router, ...rest) {
615
394
  return recursive;
616
395
  }
617
396
 
618
- export { Builder, BuilderWithMiddlewares, DecoratedProcedure, Procedure, ProcedureBuilder, 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 };
397
+ function isSchemaIssue(issue) {
398
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
399
+ return false;
400
+ }
401
+ if (issue.path !== void 0) {
402
+ if (!Array.isArray(issue.path)) {
403
+ return false;
404
+ }
405
+ if (!issue.path.every(
406
+ (segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key)
407
+ )) {
408
+ return false;
409
+ }
410
+ }
411
+ return true;
412
+ }
413
+
414
+ export { Builder, BuilderWithMiddlewares, Contract, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, initialSchemas, isLazy, isProcedure, isSchemaIssue, lazyInternal, mergeMeta, os, parseEndpointDefinition, unlazy };