@trpc/server 11.4.1 → 11.4.2-canary.1

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 (105) hide show
  1. package/dist/adapters/aws-lambda/index.cjs +49 -42
  2. package/dist/adapters/aws-lambda/index.mjs +47 -40
  3. package/dist/adapters/aws-lambda/index.mjs.map +1 -1
  4. package/dist/adapters/express.cjs +14 -15
  5. package/dist/adapters/express.mjs +14 -15
  6. package/dist/adapters/express.mjs.map +1 -1
  7. package/dist/adapters/fastify/index.cjs +27 -28
  8. package/dist/adapters/fastify/index.mjs +27 -28
  9. package/dist/adapters/fastify/index.mjs.map +1 -1
  10. package/dist/adapters/fetch/index.cjs +18 -19
  11. package/dist/adapters/fetch/index.mjs +18 -19
  12. package/dist/adapters/fetch/index.mjs.map +1 -1
  13. package/dist/adapters/next-app-dir.cjs +57 -53
  14. package/dist/adapters/next-app-dir.mjs +15 -11
  15. package/dist/adapters/next-app-dir.mjs.map +1 -1
  16. package/dist/adapters/next.cjs +14 -15
  17. package/dist/adapters/next.mjs +14 -15
  18. package/dist/adapters/next.mjs.map +1 -1
  19. package/dist/adapters/node-http/index.cjs +8 -8
  20. package/dist/adapters/node-http/index.mjs +8 -8
  21. package/dist/adapters/standalone.cjs +17 -17
  22. package/dist/adapters/standalone.mjs +16 -16
  23. package/dist/adapters/standalone.mjs.map +1 -1
  24. package/dist/adapters/ws.cjs +10 -10
  25. package/dist/adapters/ws.mjs +10 -10
  26. package/dist/getErrorShape-DKiEF6Zc.cjs +339 -0
  27. package/dist/getErrorShape-Uhlrl4Bk.mjs +263 -0
  28. package/dist/getErrorShape-Uhlrl4Bk.mjs.map +1 -0
  29. package/dist/http.cjs +5 -5
  30. package/dist/http.mjs +5 -5
  31. package/dist/index.cjs +4 -4
  32. package/dist/index.mjs +4 -4
  33. package/dist/{initTRPC-DjEpHmY2.cjs → initTRPC-IT4M4lu3.cjs} +83 -64
  34. package/dist/{initTRPC-COaJMShh.mjs → initTRPC-IT_6ZYJd.mjs} +84 -65
  35. package/dist/initTRPC-IT_6ZYJd.mjs.map +1 -0
  36. package/dist/{node-http-BUQnHuGI.mjs → node-http-Du8akt-R.mjs} +26 -23
  37. package/dist/{node-http-BUQnHuGI.mjs.map → node-http-Du8akt-R.mjs.map} +1 -1
  38. package/dist/{node-http-BPR68yI4.cjs → node-http-kIQEhZUH.cjs} +25 -22
  39. package/dist/observable/index.cjs +2 -2
  40. package/dist/observable/index.mjs +2 -2
  41. package/dist/{observable-BwdrSFZU.cjs → observable-B1Nk6r1H.cjs} +7 -4
  42. package/dist/{observable-C6qq2Ydk.cjs → observable-BVzLuBs6.cjs} +19 -7
  43. package/dist/{observable-CFXA_tyK.mjs → observable-CUiPknO-.mjs} +20 -8
  44. package/dist/{observable-CFXA_tyK.mjs.map → observable-CUiPknO-.mjs.map} +1 -1
  45. package/dist/{observable-B1orLHHI.mjs → observable-UMO3vUa_.mjs} +8 -5
  46. package/dist/{observable-B1orLHHI.mjs.map → observable-UMO3vUa_.mjs.map} +1 -1
  47. package/dist/{parseTRPCMessage-CNyYMSRB.mjs → parseTRPCMessage-ByIHyFRz.mjs} +2 -2
  48. package/dist/{parseTRPCMessage-CNyYMSRB.mjs.map → parseTRPCMessage-ByIHyFRz.mjs.map} +1 -1
  49. package/dist/{parseTRPCMessage-ByQWigsq.cjs → parseTRPCMessage-snNQop7N.cjs} +1 -1
  50. package/dist/{resolveResponse-B2CuaT_1.cjs → resolveResponse-CVGbakBm.cjs} +664 -405
  51. package/dist/{resolveResponse-DPbYgJDD.mjs → resolveResponse-CzlbRpCI.mjs} +660 -389
  52. package/dist/resolveResponse-CzlbRpCI.mjs.map +1 -0
  53. package/dist/rpc.cjs +2 -2
  54. package/dist/rpc.mjs +2 -2
  55. package/dist/shared.cjs +2 -2
  56. package/dist/shared.mjs +2 -2
  57. package/dist/{tracked-Dl9sBZxY.cjs → tracked-HoF8L_mq.cjs} +30 -42
  58. package/dist/{tracked-GEWPoL0C.mjs → tracked-gU3ttYjg.mjs} +31 -43
  59. package/dist/{tracked-GEWPoL0C.mjs.map → tracked-gU3ttYjg.mjs.map} +1 -1
  60. package/dist/unstable-core-do-not-import.cjs +7 -7
  61. package/dist/unstable-core-do-not-import.mjs +7 -7
  62. package/dist/{utils-BHZJcBRv.mjs → utils-DdbbrDku.mjs} +1 -1
  63. package/dist/{utils-BHZJcBRv.mjs.map → utils-DdbbrDku.mjs.map} +1 -1
  64. package/dist/{ws-C2nEUNk_.cjs → ws-BhrWsMpl.cjs} +37 -26
  65. package/dist/{ws-eIVIMTrw.mjs → ws-Bn5rkP_I.mjs} +37 -26
  66. package/dist/{ws-eIVIMTrw.mjs.map → ws-Bn5rkP_I.mjs.map} +1 -1
  67. package/package.json +2 -2
  68. package/adapters/aws-lambda/index.d.ts +0 -1
  69. package/adapters/aws-lambda/index.js +0 -1
  70. package/adapters/express/index.d.ts +0 -1
  71. package/adapters/express/index.js +0 -1
  72. package/adapters/fastify/index.d.ts +0 -1
  73. package/adapters/fastify/index.js +0 -1
  74. package/adapters/fetch/index.d.ts +0 -1
  75. package/adapters/fetch/index.js +0 -1
  76. package/adapters/next/index.d.ts +0 -1
  77. package/adapters/next/index.js +0 -1
  78. package/adapters/next-app-dir/index.d.ts +0 -1
  79. package/adapters/next-app-dir/index.js +0 -1
  80. package/adapters/node-http/content-type/form-data/index.d.ts +0 -1
  81. package/adapters/node-http/content-type/form-data/index.js +0 -1
  82. package/adapters/node-http/content-type/json/index.d.ts +0 -1
  83. package/adapters/node-http/content-type/json/index.js +0 -1
  84. package/adapters/node-http/index.d.ts +0 -1
  85. package/adapters/node-http/index.js +0 -1
  86. package/adapters/standalone/index.d.ts +0 -1
  87. package/adapters/standalone/index.js +0 -1
  88. package/adapters/ws/index.d.ts +0 -1
  89. package/adapters/ws/index.js +0 -1
  90. package/dist/getErrorShape-CsikfkAc.cjs +0 -201
  91. package/dist/getErrorShape-DyYil4aT.mjs +0 -149
  92. package/dist/getErrorShape-DyYil4aT.mjs.map +0 -1
  93. package/dist/initTRPC-COaJMShh.mjs.map +0 -1
  94. package/dist/resolveResponse-DPbYgJDD.mjs.map +0 -1
  95. package/http/index.d.ts +0 -1
  96. package/http/index.js +0 -1
  97. package/observable/index.d.ts +0 -1
  98. package/observable/index.js +0 -1
  99. package/rpc/index.d.ts +0 -1
  100. package/rpc/index.js +0 -1
  101. package/shared/index.d.ts +0 -1
  102. package/shared/index.js +0 -1
  103. package/unstable-core-do-not-import/index.d.ts +0 -1
  104. package/unstable-core-do-not-import/index.js +0 -1
  105. /package/dist/{utils-DVO6HZiR.cjs → utils-BhNVZA-c.cjs} +0 -0
@@ -1,5 +1,5 @@
1
- import { createRecursiveProxy } from "./getErrorShape-DyYil4aT.mjs";
2
- import { isFunction, isObject, mergeWithoutOverrides, omitPrototype } from "./utils-BHZJcBRv.mjs";
1
+ import { __toESM, createRecursiveProxy, require_defineProperty, require_objectSpread2 } from "./getErrorShape-Uhlrl4Bk.mjs";
2
+ import { isFunction, isObject, mergeWithoutOverrides, omitPrototype } from "./utils-DdbbrDku.mjs";
3
3
 
4
4
  //#region src/unstable-core-do-not-import/error/formatter.ts
5
5
  const defaultFormatter = ({ shape }) => {
@@ -8,6 +8,7 @@ const defaultFormatter = ({ shape }) => {
8
8
 
9
9
  //#endregion
10
10
  //#region src/unstable-core-do-not-import/error/TRPCError.ts
11
+ var import_defineProperty = __toESM(require_defineProperty(), 1);
11
12
  var UnknownCauseError = class extends Error {};
12
13
  function getCauseFromUnknown(cause) {
13
14
  if (cause instanceof Error) return cause;
@@ -28,20 +29,22 @@ function getTRPCErrorFromUnknown(cause) {
28
29
  return trpcError;
29
30
  }
30
31
  var TRPCError = class extends Error {
31
- cause;
32
- code;
33
32
  constructor(opts) {
33
+ var _ref, _opts$message, _this$cause;
34
34
  const cause = getCauseFromUnknown(opts.cause);
35
- const message = opts.message ?? cause?.message ?? opts.code;
35
+ const message = (_ref = (_opts$message = opts.message) !== null && _opts$message !== void 0 ? _opts$message : cause === null || cause === void 0 ? void 0 : cause.message) !== null && _ref !== void 0 ? _ref : opts.code;
36
36
  super(message, { cause });
37
+ (0, import_defineProperty.default)(this, "cause", void 0);
38
+ (0, import_defineProperty.default)(this, "code", void 0);
37
39
  this.code = opts.code;
38
40
  this.name = "TRPCError";
39
- this.cause ??= cause;
41
+ (_this$cause = this.cause) !== null && _this$cause !== void 0 || (this.cause = cause);
40
42
  }
41
43
  };
42
44
 
43
45
  //#endregion
44
46
  //#region src/unstable-core-do-not-import/transformer.ts
47
+ var import_objectSpread2$1 = __toESM(require_objectSpread2(), 1);
45
48
  /**
46
49
  * @internal
47
50
  */
@@ -66,17 +69,8 @@ const defaultTransformer = {
66
69
  }
67
70
  };
68
71
  function transformTRPCResponseItem(config, item) {
69
- if ("error" in item) return {
70
- ...item,
71
- error: config.transformer.output.serialize(item.error)
72
- };
73
- if ("data" in item.result) return {
74
- ...item,
75
- result: {
76
- ...item.result,
77
- data: config.transformer.output.serialize(item.result.data)
78
- }
79
- };
72
+ if ("error" in item) return (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, item), {}, { error: config.transformer.output.serialize(item.error) });
73
+ if ("data" in item.result) return (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, item), {}, { result: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, item.result), {}, { data: config.transformer.output.serialize(item.result.data) }) });
80
74
  return item;
81
75
  }
82
76
  /**
@@ -91,19 +85,13 @@ function transformResultInner(response, transformer) {
91
85
  const error = transformer.deserialize(response.error);
92
86
  return {
93
87
  ok: false,
94
- error: {
95
- ...response,
96
- error
97
- }
88
+ error: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response), {}, { error })
98
89
  };
99
90
  }
100
- const result = {
101
- ...response.result,
102
- ...(!response.result.type || response.result.type === "data") && {
103
- type: "data",
104
- data: transformer.deserialize(response.result.data)
105
- }
106
- };
91
+ const result = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response.result), (!response.result.type || response.result.type === "data") && {
92
+ type: "data",
93
+ data: transformer.deserialize(response.result.data)
94
+ });
107
95
  return {
108
96
  ok: true,
109
97
  result
@@ -122,7 +110,7 @@ function transformResult(response, transformer) {
122
110
  let result;
123
111
  try {
124
112
  result = transformResultInner(response, transformer);
125
- } catch {
113
+ } catch (_unused) {
126
114
  throw new TransformResultError();
127
115
  }
128
116
  if (!result.ok && (!isObject(result.error.error) || typeof result.error.error["code"] !== "number")) throw new TransformResultError();
@@ -132,6 +120,7 @@ function transformResult(response, transformer) {
132
120
 
133
121
  //#endregion
134
122
  //#region src/unstable-core-do-not-import/router.ts
123
+ var import_objectSpread2 = __toESM(require_objectSpread2(), 1);
135
124
  const lazySymbol = Symbol("lazy");
136
125
  function once(fn) {
137
126
  const uncalled = Symbol();
@@ -212,7 +201,7 @@ function createRouterFactory(config) {
212
201
  }
213
202
  function step(from, path = []) {
214
203
  const aggregate = omitPrototype({});
215
- for (const [key, item] of Object.entries(from ?? {})) {
204
+ for (const [key, item] of Object.entries(from !== null && from !== void 0 ? from : {})) {
216
205
  if (isLazy(item)) {
217
206
  lazy$1[[...path, key].join(".")] = createLazyLoader({
218
207
  path,
@@ -238,19 +227,16 @@ function createRouterFactory(config) {
238
227
  return aggregate;
239
228
  }
240
229
  const record = step(input);
241
- const _def = {
230
+ const _def = (0, import_objectSpread2.default)((0, import_objectSpread2.default)({
242
231
  _config: config,
243
232
  router: true,
244
233
  procedures,
245
- lazy: lazy$1,
246
- ...emptyRouter,
247
- record
248
- };
249
- const router = {
250
- ...record,
234
+ lazy: lazy$1
235
+ }, emptyRouter), {}, { record });
236
+ const router = (0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, record), {}, {
251
237
  _def,
252
238
  createCaller: createCallerFactory()({ _def })
253
- };
239
+ });
254
240
  return router;
255
241
  }
256
242
  return createRouterInner;
@@ -310,15 +296,16 @@ function createCallerFactory() {
310
296
  getRawInput: async () => args[0],
311
297
  ctx,
312
298
  type: procedure._def.type,
313
- signal: opts?.signal
299
+ signal: opts === null || opts === void 0 ? void 0 : opts.signal
314
300
  });
315
301
  } catch (cause) {
316
- opts?.onError?.({
302
+ var _opts$onError, _procedure$_def$type;
303
+ opts === null || opts === void 0 || (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
317
304
  ctx,
318
305
  error: getTRPCErrorFromUnknown(cause),
319
306
  input: args[0],
320
307
  path: fullPath,
321
- type: procedure?._def.type ?? "unknown"
308
+ type: (_procedure$_def$type = procedure === null || procedure === void 0 ? void 0 : procedure._def.type) !== null && _procedure$_def$type !== void 0 ? _procedure$_def$type : "unknown"
322
309
  });
323
310
  throw cause;
324
311
  }
@@ -327,6 +314,7 @@ function createCallerFactory() {
327
314
  };
328
315
  }
329
316
  function mergeRouters(...routerList) {
317
+ var _routerList$;
330
318
  const record = mergeWithoutOverrides({}, ...routerList.map((r) => r._def.record));
331
319
  const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter) => {
332
320
  if (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {
@@ -348,7 +336,7 @@ function mergeRouters(...routerList) {
348
336
  isDev: routerList.every((r) => r._def._config.isDev),
349
337
  allowOutsideOfServer: routerList.every((r) => r._def._config.allowOutsideOfServer),
350
338
  isServer: routerList.every((r) => r._def._config.isServer),
351
- $types: routerList[0]?._def._config.$types
339
+ $types: (_routerList$ = routerList[0]) === null || _routerList$ === void 0 ? void 0 : _routerList$._def._config.$types
352
340
  })(record);
353
341
  return router;
354
342
  }
@@ -380,4 +368,4 @@ function tracked(id, data) {
380
368
 
381
369
  //#endregion
382
370
  export { TRPCError, callProcedure, createCallerFactory, createRouterFactory, defaultFormatter, defaultTransformer, getCauseFromUnknown, getDataTransformer, getProcedureAtPath, getTRPCErrorFromUnknown, isTrackedEnvelope, lazy, mergeRouters, sse, tracked, transformResult, transformTRPCResponse };
383
- //# sourceMappingURL=tracked-GEWPoL0C.mjs.map
371
+ //# sourceMappingURL=tracked-gU3ttYjg.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tracked-GEWPoL0C.mjs","names":["defaultFormatter: ErrorFormatter<any, any>","cause: unknown","opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }","transformer: DataTransformerOptions","defaultTransformer: CombinedDataTransformer","config: RootConfig<AnyRootTypes>","item: TResponseItem","itemOrItems: TResponse","response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>","transformer: DataTransformer","result: ReturnType<typeof transformResultInner>","fn: () => T","result: T | typeof uncalled","importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >","input: unknown","value: unknown","config: RootConfig<TRoot>","input: TInput","procedures: Record<string, AnyProcedure>","lazy: Record<string, LazyLoader<AnyRouter>>","opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }","router","lazy","from: CreateRouterOptions","path: readonly string[]","aggregate: RouterRecord","_def: AnyRouter['_def']","router: BuiltRouter<TRoot, {}>","procedureOrRouter: ValueOf<CreateRouterOptions>","router: Pick<Router<any, any>, '_def'>","path: string","key","opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n }","router: Pick<Router<TRoot, TRecord>, '_def'>","ctx: Context | undefined","event: { id: string; data: TData }","value: unknown","id: string","data: TData"],"sources":["../src/unstable-core-do-not-import/error/formatter.ts","../src/unstable-core-do-not-import/error/TRPCError.ts","../src/unstable-core-do-not-import/transformer.ts","../src/unstable-core-do-not-import/router.ts","../src/unstable-core-do-not-import/stream/tracked.ts"],"sourcesContent":["import type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (opts: {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext | undefined;\n shape: DefaultErrorShape;\n}) => TShape;\n\n/**\n * @internal\n */\nexport type DefaultErrorData = {\n code: TRPC_ERROR_CODE_KEY;\n httpStatus: number;\n /**\n * Path to the procedure that threw the error\n */\n path?: string;\n /**\n * Stack trace of the error (only in development)\n */\n stack?: string;\n};\n\n/**\n * @internal\n */\nexport interface DefaultErrorShape extends TRPCErrorShape<DefaultErrorData> {\n message: string;\n code: TRPC_ERROR_CODE_NUMBER;\n}\n\nexport const defaultFormatter: ErrorFormatter<any, any> = ({ shape }) => {\n return shape;\n};\n","import type { TRPC_ERROR_CODE_KEY } from '../rpc/codes';\nimport { isObject } from '../utils';\n\nclass UnknownCauseError extends Error {\n [key: string]: unknown;\n}\nexport function getCauseFromUnknown(cause: unknown): Error | undefined {\n if (cause instanceof Error) {\n return cause;\n }\n\n const type = typeof cause;\n if (type === 'undefined' || type === 'function' || cause === null) {\n return undefined;\n }\n\n // Primitive types just get wrapped in an error\n if (type !== 'object') {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return new Error(String(cause));\n }\n\n // If it's an object, we'll create a synthetic error\n if (isObject(cause)) {\n return Object.assign(new UnknownCauseError(), cause);\n }\n\n return undefined;\n}\n\nexport function getTRPCErrorFromUnknown(cause: unknown): TRPCError {\n if (cause instanceof TRPCError) {\n return cause;\n }\n if (cause instanceof Error && cause.name === 'TRPCError') {\n // https://github.com/trpc/trpc/pull/4848\n return cause as TRPCError;\n }\n\n const trpcError = new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n\n // Inherit stack from error\n if (cause instanceof Error && cause.stack) {\n trpcError.stack = cause.stack;\n }\n\n return trpcError;\n}\n\nexport class TRPCError extends Error {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause?: Error;\n public readonly code;\n\n constructor(opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }) {\n const cause = getCauseFromUnknown(opts.cause);\n const message = opts.message ?? cause?.message ?? opts.code;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.code = opts.code;\n this.name = 'TRPCError';\n this.cause ??= cause;\n }\n}\n","import type { AnyRootTypes, RootConfig } from './rootConfig';\nimport type { AnyRouter, inferRouterError } from './router';\nimport type {\n TRPCResponse,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from './rpc';\nimport { isObject } from './utils';\n\n/**\n * @public\n */\nexport interface DataTransformer {\n serialize: (object: any) => any;\n deserialize: (object: any) => any;\n}\n\ninterface InputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the client** before sending the data to the server.\n */\n serialize: (object: any) => any;\n /**\n * This function runs **on the server** to transform the data before it is passed to the resolver\n */\n deserialize: (object: any) => any;\n}\n\ninterface OutputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the server** before sending the data to the client.\n */\n serialize: (object: any) => any;\n /**\n * This function runs **only on the client** to transform the data sent from the server.\n */\n deserialize: (object: any) => any;\n}\n\n/**\n * @public\n */\nexport interface CombinedDataTransformer {\n /**\n * Specify how the data sent from the client to the server should be transformed.\n */\n input: InputDataTransformer;\n /**\n * Specify how the data sent from the server to the client should be transformed.\n */\n output: OutputDataTransformer;\n}\n\n/**\n * @public\n */\nexport type CombinedDataTransformerClient = {\n input: Pick<CombinedDataTransformer['input'], 'serialize'>;\n output: Pick<CombinedDataTransformer['output'], 'deserialize'>;\n};\n\n/**\n * @public\n */\nexport type DataTransformerOptions = CombinedDataTransformer | DataTransformer;\n\n/**\n * @internal\n */\nexport function getDataTransformer(\n transformer: DataTransformerOptions,\n): CombinedDataTransformer {\n if ('input' in transformer) {\n return transformer;\n }\n return { input: transformer, output: transformer };\n}\n\n/**\n * @internal\n */\nexport const defaultTransformer: CombinedDataTransformer = {\n input: { serialize: (obj) => obj, deserialize: (obj) => obj },\n output: { serialize: (obj) => obj, deserialize: (obj) => obj },\n};\n\nfunction transformTRPCResponseItem<\n TResponseItem extends TRPCResponse | TRPCResponseMessage,\n>(config: RootConfig<AnyRootTypes>, item: TResponseItem): TResponseItem {\n if ('error' in item) {\n return {\n ...item,\n error: config.transformer.output.serialize(item.error),\n };\n }\n\n if ('data' in item.result) {\n return {\n ...item,\n result: {\n ...item.result,\n data: config.transformer.output.serialize(item.result.data),\n },\n };\n }\n\n return item;\n}\n\n/**\n * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers\n **/\nexport function transformTRPCResponse<\n TResponse extends\n | TRPCResponse\n | TRPCResponse[]\n | TRPCResponseMessage\n | TRPCResponseMessage[],\n>(config: RootConfig<AnyRootTypes>, itemOrItems: TResponse) {\n return Array.isArray(itemOrItems)\n ? itemOrItems.map((item) => transformTRPCResponseItem(config, item))\n : transformTRPCResponseItem(config, itemOrItems);\n}\n\n// FIXME:\n// - the generics here are probably unnecessary\n// - the RPC-spec could probably be simplified to combine HTTP + WS\n/** @internal */\nfunction transformResultInner<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n) {\n if ('error' in response) {\n const error = transformer.deserialize(\n response.error,\n ) as inferRouterError<TRouter>;\n return {\n ok: false,\n error: {\n ...response,\n error,\n },\n } as const;\n }\n\n const result = {\n ...response.result,\n ...((!response.result.type || response.result.type === 'data') && {\n type: 'data',\n data: transformer.deserialize(response.result.data),\n }),\n } as TRPCResultMessage<TOutput>['result'];\n return { ok: true, result } as const;\n}\n\nclass TransformResultError extends Error {\n constructor() {\n super('Unable to transform response from server');\n }\n}\n\n/**\n * Transforms and validates that the result is a valid TRPCResponse\n * @internal\n */\nexport function transformResult<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n): ReturnType<typeof transformResultInner> {\n let result: ReturnType<typeof transformResultInner>;\n try {\n // Use the data transformers on the JSON-response\n result = transformResultInner(response, transformer);\n } catch {\n throw new TransformResultError();\n }\n\n // check that output of the transformers is a valid TRPCResponse\n if (\n !result.ok &&\n (!isObject(result.error.error) ||\n typeof result.error.error['code'] !== 'number')\n ) {\n throw new TransformResultError();\n }\n if (result.ok && !isObject(result.result)) {\n throw new TransformResultError();\n }\n return result;\n}\n","import type { Observable } from '../observable';\nimport { createRecursiveProxy } from './createProxy';\nimport { defaultFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyProcedure,\n ErrorHandlerOptions,\n inferProcedureInput,\n inferProcedureOutput,\n LegacyObservableSubscriptionProcedure,\n} from './procedure';\nimport type { ProcedureCallOptions } from './procedureBuilder';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { defaultTransformer } from './transformer';\nimport type { MaybePromise, ValueOf } from './types';\nimport {\n isFunction,\n isObject,\n mergeWithoutOverrides,\n omitPrototype,\n} from './utils';\n\nexport interface RouterRecord {\n [key: string]: AnyProcedure | RouterRecord;\n}\n\ntype DecorateProcedure<TProcedure extends AnyProcedure> = (\n input: inferProcedureInput<TProcedure>,\n) => Promise<\n TProcedure['_def']['type'] extends 'subscription'\n ? TProcedure extends LegacyObservableSubscriptionProcedure<any>\n ? Observable<inferProcedureOutput<TProcedure>, TRPCError>\n : inferProcedureOutput<TProcedure>\n : inferProcedureOutput<TProcedure>\n>;\n\n/**\n * @internal\n */\nexport type DecorateRouterRecord<TRecord extends RouterRecord> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<$Value>\n : $Value extends RouterRecord\n ? DecorateRouterRecord<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\n\nexport type RouterCallerErrorHandler<TContext> = (\n opts: ErrorHandlerOptions<TContext>,\n) => void;\n\n/**\n * @internal\n */\nexport type RouterCaller<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = (\n /**\n * @note\n * If passing a function, we recommend it's a cached function\n * e.g. wrapped in `React.cache` to avoid unnecessary computations\n */\n ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),\n options?: {\n onError?: RouterCallerErrorHandler<TRoot['ctx']>;\n signal?: AbortSignal;\n },\n) => DecorateRouterRecord<TRecord>;\n\nconst lazySymbol = Symbol('lazy');\nexport type Lazy<TAny> = (() => Promise<TAny>) & { [lazySymbol]: true };\n\ntype LazyLoader<TAny> = {\n load: () => Promise<void>;\n ref: Lazy<TAny>;\n};\n\nfunction once<T>(fn: () => T): () => T {\n const uncalled = Symbol();\n let result: T | typeof uncalled = uncalled;\n return (): T => {\n if (result === uncalled) {\n result = fn();\n }\n return result;\n };\n}\n\n/**\n * Lazy load a router\n * @see https://trpc.io/docs/server/merging-routers#lazy-load\n */\nexport function lazy<TRouter extends AnyRouter>(\n importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >,\n): Lazy<NoInfer<TRouter>> {\n async function resolve(): Promise<TRouter> {\n const mod = await importRouter();\n\n // if the module is a router, return it\n if (isRouter(mod)) {\n return mod;\n }\n\n const routers = Object.values(mod);\n\n if (routers.length !== 1 || !isRouter(routers[0])) {\n throw new Error(\n \"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\",\n );\n }\n\n return routers[0];\n }\n resolve[lazySymbol] = true as const;\n\n return resolve;\n}\n\nfunction isLazy<TAny>(input: unknown): input is Lazy<TAny> {\n return typeof input === 'function' && lazySymbol in input;\n}\n\n/**\n * @internal\n */\nexport interface RouterDef<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _config: RootConfig<TRoot>;\n router: true;\n procedure?: never;\n procedures: TRecord;\n record: TRecord;\n lazy: Record<string, LazyLoader<AnyRouter>>;\n}\n\nexport interface Router<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _def: RouterDef<TRoot, TRecord>;\n /**\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCaller: RouterCaller<TRoot, TRecord>;\n}\n\nexport type BuiltRouter<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = Router<TRoot, TRecord> & TRecord;\n\nexport interface RouterBuilder<TRoot extends AnyRootTypes> {\n <TIn extends CreateRouterOptions>(\n _: TIn,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TIn>>;\n}\n\nexport type AnyRouter = Router<any, any>;\n\nexport type inferRouterRootTypes<TRouter extends AnyRouter> =\n TRouter['_def']['_config']['$types'];\n\nexport type inferRouterContext<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['ctx'];\nexport type inferRouterError<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['errorShape'];\nexport type inferRouterMeta<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['meta'];\n\nfunction isRouter(value: unknown): value is AnyRouter {\n return (\n isObject(value) && isObject(value['_def']) && 'router' in value['_def']\n );\n}\n\nconst emptyRouter = {\n _ctx: null as any,\n _errorShape: null as any,\n _meta: null as any,\n queries: {},\n mutations: {},\n subscriptions: {},\n errorFormatter: defaultFormatter,\n transformer: defaultTransformer,\n};\n\n/**\n * Reserved words that can't be used as router or procedure names\n */\nconst reservedWords = [\n /**\n * Then is a reserved word because otherwise we can't return a promise that returns a Proxy\n * since JS will think that `.then` is something that exists\n */\n 'then',\n /**\n * `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`\n */\n 'call',\n 'apply',\n];\n\n/** @internal */\nexport type CreateRouterOptions = {\n [key: string]:\n | AnyProcedure\n | AnyRouter\n | CreateRouterOptions\n | Lazy<AnyRouter>;\n};\n\n/** @internal */\nexport type DecorateCreateRouterOptions<\n TRouterOptions extends CreateRouterOptions,\n> = {\n [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value\n ? $Value extends AnyProcedure\n ? $Value\n : $Value extends Router<any, infer TRecord>\n ? TRecord\n : $Value extends Lazy<Router<any, infer TRecord>>\n ? TRecord\n : $Value extends CreateRouterOptions\n ? DecorateCreateRouterOptions<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\nexport function createRouterFactory<TRoot extends AnyRootTypes>(\n config: RootConfig<TRoot>,\n) {\n function createRouterInner<TInput extends CreateRouterOptions>(\n input: TInput,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>> {\n const reservedWordsUsed = new Set(\n Object.keys(input).filter((v) => reservedWords.includes(v)),\n );\n if (reservedWordsUsed.size > 0) {\n throw new Error(\n 'Reserved words used in `router({})` call: ' +\n Array.from(reservedWordsUsed).join(', '),\n );\n }\n\n const procedures: Record<string, AnyProcedure> = omitPrototype({});\n const lazy: Record<string, LazyLoader<AnyRouter>> = omitPrototype({});\n\n function createLazyLoader(opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }): LazyLoader<AnyRouter> {\n return {\n ref: opts.ref,\n load: once(async () => {\n const router = await opts.ref();\n const lazyPath = [...opts.path, opts.key];\n const lazyKey = lazyPath.join('.');\n\n opts.aggregate[opts.key] = step(router._def.record, lazyPath);\n\n delete lazy[lazyKey];\n\n // add lazy loaders for nested routers\n for (const [nestedKey, nestedItem] of Object.entries(\n router._def.lazy,\n )) {\n const nestedRouterKey = [...lazyPath, nestedKey].join('.');\n\n // console.log('adding lazy', nestedRouterKey);\n lazy[nestedRouterKey] = createLazyLoader({\n ref: nestedItem.ref,\n path: lazyPath,\n key: nestedKey,\n aggregate: opts.aggregate[opts.key] as RouterRecord,\n });\n }\n }),\n };\n }\n\n function step(from: CreateRouterOptions, path: readonly string[] = []) {\n const aggregate: RouterRecord = omitPrototype({});\n for (const [key, item] of Object.entries(from ?? {})) {\n if (isLazy(item)) {\n lazy[[...path, key].join('.')] = createLazyLoader({\n path,\n ref: item,\n key,\n aggregate,\n });\n continue;\n }\n if (isRouter(item)) {\n aggregate[key] = step(item._def.record, [...path, key]);\n continue;\n }\n if (!isProcedure(item)) {\n // RouterRecord\n aggregate[key] = step(item, [...path, key]);\n continue;\n }\n\n const newPath = [...path, key].join('.');\n\n if (procedures[newPath]) {\n throw new Error(`Duplicate key: ${newPath}`);\n }\n\n procedures[newPath] = item;\n aggregate[key] = item;\n }\n\n return aggregate;\n }\n const record = step(input);\n\n const _def: AnyRouter['_def'] = {\n _config: config,\n router: true,\n procedures,\n lazy,\n ...emptyRouter,\n record,\n };\n\n const router: BuiltRouter<TRoot, {}> = {\n ...(record as {}),\n _def,\n createCaller: createCallerFactory<TRoot>()({\n _def,\n }),\n };\n return router as BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;\n }\n\n return createRouterInner;\n}\n\nfunction isProcedure(\n procedureOrRouter: ValueOf<CreateRouterOptions>,\n): procedureOrRouter is AnyProcedure {\n return typeof procedureOrRouter === 'function';\n}\n\n/**\n * @internal\n */\nexport async function getProcedureAtPath(\n router: Pick<Router<any, any>, '_def'>,\n path: string,\n): Promise<AnyProcedure | null> {\n const { _def } = router;\n let procedure = _def.procedures[path];\n\n while (!procedure) {\n const key = Object.keys(_def.lazy).find((key) => path.startsWith(key));\n // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);\n\n if (!key) {\n return null;\n }\n // console.log('loading', key, '.......');\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lazyRouter = _def.lazy[key]!;\n await lazyRouter.load();\n\n procedure = _def.procedures[path];\n }\n\n return procedure;\n}\n\n/**\n * @internal\n */\nexport async function callProcedure(\n opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n },\n) {\n const { type, path } = opts;\n const proc = await getProcedureAtPath(opts.router, path);\n if (\n !proc ||\n !isProcedure(proc) ||\n (proc._def.type !== type && !opts.allowMethodOverride)\n ) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No \"${type}\"-procedure on path \"${path}\"`,\n });\n }\n\n /* istanbul ignore if -- @preserve */\n if (\n proc._def.type !== type &&\n opts.allowMethodOverride &&\n proc._def.type === 'subscription'\n ) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Method override is not supported for subscriptions`,\n });\n }\n\n return proc(opts);\n}\n\nexport interface RouterCallerFactory<TRoot extends AnyRootTypes> {\n <TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord>;\n}\n\nexport function createCallerFactory<\n TRoot extends AnyRootTypes,\n>(): RouterCallerFactory<TRoot> {\n return function createCallerInner<TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord> {\n const { _def } = router;\n type Context = TRoot['ctx'];\n\n return function createCaller(ctxOrCallback, opts) {\n return createRecursiveProxy<ReturnType<RouterCaller<any, any>>>(\n async ({ path, args }) => {\n const fullPath = path.join('.');\n\n if (path.length === 1 && path[0] === '_def') {\n return _def;\n }\n\n const procedure = await getProcedureAtPath(router, fullPath);\n\n let ctx: Context | undefined = undefined;\n try {\n if (!procedure) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${path}\"`,\n });\n }\n ctx = isFunction(ctxOrCallback)\n ? await Promise.resolve(ctxOrCallback())\n : ctxOrCallback;\n\n return await procedure({\n path: fullPath,\n getRawInput: async () => args[0],\n ctx,\n type: procedure._def.type,\n signal: opts?.signal,\n });\n } catch (cause) {\n opts?.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: args[0],\n path: fullPath,\n type: procedure?._def.type ?? 'unknown',\n });\n throw cause;\n }\n },\n );\n };\n };\n}\n\n/** @internal */\nexport type MergeRouters<\n TRouters extends AnyRouter[],\n TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],\n TRecord extends RouterRecord = {},\n> = TRouters extends [\n infer Head extends AnyRouter,\n ...infer Tail extends AnyRouter[],\n]\n ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>\n : BuiltRouter<TRoot, TRecord>;\n\nexport function mergeRouters<TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n): MergeRouters<TRouters> {\n const record = mergeWithoutOverrides(\n {},\n ...routerList.map((r) => r._def.record),\n );\n const errorFormatter = routerList.reduce(\n (currentErrorFormatter, nextRouter) => {\n if (\n nextRouter._def._config.errorFormatter &&\n nextRouter._def._config.errorFormatter !== defaultFormatter\n ) {\n if (\n currentErrorFormatter !== defaultFormatter &&\n currentErrorFormatter !== nextRouter._def._config.errorFormatter\n ) {\n throw new Error('You seem to have several error formatters');\n }\n return nextRouter._def._config.errorFormatter;\n }\n return currentErrorFormatter;\n },\n defaultFormatter,\n );\n\n const transformer = routerList.reduce((prev, current) => {\n if (\n current._def._config.transformer &&\n current._def._config.transformer !== defaultTransformer\n ) {\n if (\n prev !== defaultTransformer &&\n prev !== current._def._config.transformer\n ) {\n throw new Error('You seem to have several transformers');\n }\n return current._def._config.transformer;\n }\n return prev;\n }, defaultTransformer);\n\n const router = createRouterFactory({\n errorFormatter,\n transformer,\n isDev: routerList.every((r) => r._def._config.isDev),\n allowOutsideOfServer: routerList.every(\n (r) => r._def._config.allowOutsideOfServer,\n ),\n isServer: routerList.every((r) => r._def._config.isServer),\n $types: routerList[0]?._def._config.$types,\n })(record);\n\n return router as MergeRouters<TRouters>;\n}\n","const trackedSymbol = Symbol();\n\ntype TrackedId = string & {\n __brand: 'TrackedId';\n};\nexport type TrackedEnvelope<TData> = [TrackedId, TData, typeof trackedSymbol];\n\ntype TrackedData<TData> = {\n /**\n * The id of the message to keep track of in case the connection gets lost\n */\n id: string;\n /**\n * The data field of the message - this can be anything\n */\n data: TData;\n};\n/**\n * Produce a typed server-sent event message\n * @deprecated use `tracked(id, data)` instead\n */\nexport function sse<TData>(event: { id: string; data: TData }) {\n return tracked(event.id, event.data);\n}\n\nexport function isTrackedEnvelope<TData>(\n value: unknown,\n): value is TrackedEnvelope<TData> {\n return Array.isArray(value) && value[2] === trackedSymbol;\n}\n\n/**\n * Automatically track an event so that it can be resumed from a given id if the connection is lost\n */\nexport function tracked<TData>(\n id: string,\n data: TData,\n): TrackedEnvelope<TData> {\n if (id === '') {\n // This limitation could be removed by using different SSE event names / channels for tracked event and non-tracked event\n throw new Error(\n '`id` must not be an empty string as empty string is the same as not setting the id at all',\n );\n }\n return [id as TrackedId, data, trackedSymbol];\n}\n\nexport type inferTrackedOutput<TData> =\n TData extends TrackedEnvelope<infer $Data> ? TrackedData<$Data> : TData;\n"],"mappings":";;;;AA4CA,MAAaA,mBAA6C,CAAC,EAAE,OAAO,KAAK;AACvE,QAAO;AACR;;;;AC3CD,IAAM,oBAAN,cAAgC,MAAM,CAErC;AACD,SAAgB,oBAAoBC,OAAmC;AACrE,KAAI,iBAAiB,MACnB,QAAO;CAGT,MAAM,cAAc;AACpB,KAAI,SAAS,eAAe,SAAS,cAAc,UAAU,KAC3D;AAIF,KAAI,SAAS,SAEX,QAAO,IAAI,MAAM,OAAO,MAAM;AAIhC,KAAI,SAAS,MAAM,CACjB,QAAO,OAAO,OAAO,IAAI,qBAAqB,MAAM;AAGtD;AACD;AAED,SAAgB,wBAAwBA,OAA2B;AACjE,KAAI,iBAAiB,UACnB,QAAO;AAET,KAAI,iBAAiB,SAAS,MAAM,SAAS,YAE3C,QAAO;CAGT,MAAM,YAAY,IAAI,UAAU;EAC9B,MAAM;EACN;CACD;AAGD,KAAI,iBAAiB,SAAS,MAAM,MAClC,WAAU,QAAQ,MAAM;AAG1B,QAAO;AACR;AAED,IAAa,YAAb,cAA+B,MAAM;CAGnC,AAAyB;CACzB,AAAgB;CAEhB,YAAYC,MAIT;EACD,MAAM,QAAQ,oBAAoB,KAAK,MA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AI,MAAM;AAElB,UAAO,WAAW,KAAK,QAAQ;EAChC;AACD,SAAO;CACR,GACD,iBACD;CAED,MAAM,cAAc,WAAW,OAAO,CAAC,MAAM,YAAY;AACvD,MACE,QAAQ,KAAK,QAAQ,eACrB,QAAQ,KAAK,QAAQ,gBAAgB,oBACrC;AACA,OACE,SAAS,sBACT,SAAS,QAAQ,KAAK,QAAQ,YAE9B,OAAM,IAAI,MAAM;AAElB,UAAO,QAAQ,KAAK,QAAQ;EAC7B;AACD,SAAO;CACR,GAAE,mBAAmB;CAEtB,MAAM,SAAS,oBAAoB;EACjC;EACA;EACA,OAAO,WAAW,MAAM,CAAC,MAAM,EAAE,KAAK,QAAQ,MAAM;EACpD,sBAAsB,WAAW,MAC/B,CAAC,MAAM,EAAE,KAAK,QAAQ,qBACvB;EACD,UAAU,WAAW,MAAM,CAAC,MAAM,EAAE,KAAK,QAAQ,SAAS;EAC1D,QAAQ,WAAW,IAAI,KAAK,QAAQ;CACrC,EAAC,CAAC,OAAO;AAEV,QAAO;AACR;;;;AC3iBD,MAAM,gBAAgB,QAAQ;;;;;AAqB9B,SAAgB,IAAWC,OAAoC;AAC7D,QAAO,QAAQ,MAAM,IAAI,MAAM,KAAK;AACrC;AAED,SAAgB,kBACdC,OACiC;AACjC,QAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,OAAO;AAC7C;;;;AAKD,SAAgB,QACdC,IACAC,MACwB;AACxB,KAAI,OAAO,GAET,OAAM,IAAI,MACR;AAGJ,QAAO;EAAC;EAAiB;EAAM;CAAc;AAC9C"}
1
+ {"version":3,"file":"tracked-gU3ttYjg.mjs","names":["defaultFormatter: ErrorFormatter<any, any>","cause: unknown","opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }","transformer: DataTransformerOptions","defaultTransformer: CombinedDataTransformer","config: RootConfig<AnyRootTypes>","item: TResponseItem","itemOrItems: TResponse","response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>","transformer: DataTransformer","result: ReturnType<typeof transformResultInner>","fn: () => T","result: T | typeof uncalled","importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >","input: unknown","value: unknown","config: RootConfig<TRoot>","input: TInput","procedures: Record<string, AnyProcedure>","lazy: Record<string, LazyLoader<AnyRouter>>","opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }","router","lazy","from: CreateRouterOptions","path: readonly string[]","aggregate: RouterRecord","_def: AnyRouter['_def']","router: BuiltRouter<TRoot, {}>","procedureOrRouter: ValueOf<CreateRouterOptions>","router: Pick<Router<any, any>, '_def'>","path: string","key","opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n }","router: Pick<Router<TRoot, TRecord>, '_def'>","ctx: Context | undefined","event: { id: string; data: TData }","value: unknown","id: string","data: TData"],"sources":["../src/unstable-core-do-not-import/error/formatter.ts","../src/unstable-core-do-not-import/error/TRPCError.ts","../src/unstable-core-do-not-import/transformer.ts","../src/unstable-core-do-not-import/router.ts","../src/unstable-core-do-not-import/stream/tracked.ts"],"sourcesContent":["import type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (opts: {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext | undefined;\n shape: DefaultErrorShape;\n}) => TShape;\n\n/**\n * @internal\n */\nexport type DefaultErrorData = {\n code: TRPC_ERROR_CODE_KEY;\n httpStatus: number;\n /**\n * Path to the procedure that threw the error\n */\n path?: string;\n /**\n * Stack trace of the error (only in development)\n */\n stack?: string;\n};\n\n/**\n * @internal\n */\nexport interface DefaultErrorShape extends TRPCErrorShape<DefaultErrorData> {\n message: string;\n code: TRPC_ERROR_CODE_NUMBER;\n}\n\nexport const defaultFormatter: ErrorFormatter<any, any> = ({ shape }) => {\n return shape;\n};\n","import type { TRPC_ERROR_CODE_KEY } from '../rpc/codes';\nimport { isObject } from '../utils';\n\nclass UnknownCauseError extends Error {\n [key: string]: unknown;\n}\nexport function getCauseFromUnknown(cause: unknown): Error | undefined {\n if (cause instanceof Error) {\n return cause;\n }\n\n const type = typeof cause;\n if (type === 'undefined' || type === 'function' || cause === null) {\n return undefined;\n }\n\n // Primitive types just get wrapped in an error\n if (type !== 'object') {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return new Error(String(cause));\n }\n\n // If it's an object, we'll create a synthetic error\n if (isObject(cause)) {\n return Object.assign(new UnknownCauseError(), cause);\n }\n\n return undefined;\n}\n\nexport function getTRPCErrorFromUnknown(cause: unknown): TRPCError {\n if (cause instanceof TRPCError) {\n return cause;\n }\n if (cause instanceof Error && cause.name === 'TRPCError') {\n // https://github.com/trpc/trpc/pull/4848\n return cause as TRPCError;\n }\n\n const trpcError = new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n\n // Inherit stack from error\n if (cause instanceof Error && cause.stack) {\n trpcError.stack = cause.stack;\n }\n\n return trpcError;\n}\n\nexport class TRPCError extends Error {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause?: Error;\n public readonly code;\n\n constructor(opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }) {\n const cause = getCauseFromUnknown(opts.cause);\n const message = opts.message ?? cause?.message ?? opts.code;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.code = opts.code;\n this.name = 'TRPCError';\n this.cause ??= cause;\n }\n}\n","import type { AnyRootTypes, RootConfig } from './rootConfig';\nimport type { AnyRouter, inferRouterError } from './router';\nimport type {\n TRPCResponse,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from './rpc';\nimport { isObject } from './utils';\n\n/**\n * @public\n */\nexport interface DataTransformer {\n serialize: (object: any) => any;\n deserialize: (object: any) => any;\n}\n\ninterface InputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the client** before sending the data to the server.\n */\n serialize: (object: any) => any;\n /**\n * This function runs **on the server** to transform the data before it is passed to the resolver\n */\n deserialize: (object: any) => any;\n}\n\ninterface OutputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the server** before sending the data to the client.\n */\n serialize: (object: any) => any;\n /**\n * This function runs **only on the client** to transform the data sent from the server.\n */\n deserialize: (object: any) => any;\n}\n\n/**\n * @public\n */\nexport interface CombinedDataTransformer {\n /**\n * Specify how the data sent from the client to the server should be transformed.\n */\n input: InputDataTransformer;\n /**\n * Specify how the data sent from the server to the client should be transformed.\n */\n output: OutputDataTransformer;\n}\n\n/**\n * @public\n */\nexport type CombinedDataTransformerClient = {\n input: Pick<CombinedDataTransformer['input'], 'serialize'>;\n output: Pick<CombinedDataTransformer['output'], 'deserialize'>;\n};\n\n/**\n * @public\n */\nexport type DataTransformerOptions = CombinedDataTransformer | DataTransformer;\n\n/**\n * @internal\n */\nexport function getDataTransformer(\n transformer: DataTransformerOptions,\n): CombinedDataTransformer {\n if ('input' in transformer) {\n return transformer;\n }\n return { input: transformer, output: transformer };\n}\n\n/**\n * @internal\n */\nexport const defaultTransformer: CombinedDataTransformer = {\n input: { serialize: (obj) => obj, deserialize: (obj) => obj },\n output: { serialize: (obj) => obj, deserialize: (obj) => obj },\n};\n\nfunction transformTRPCResponseItem<\n TResponseItem extends TRPCResponse | TRPCResponseMessage,\n>(config: RootConfig<AnyRootTypes>, item: TResponseItem): TResponseItem {\n if ('error' in item) {\n return {\n ...item,\n error: config.transformer.output.serialize(item.error),\n };\n }\n\n if ('data' in item.result) {\n return {\n ...item,\n result: {\n ...item.result,\n data: config.transformer.output.serialize(item.result.data),\n },\n };\n }\n\n return item;\n}\n\n/**\n * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers\n **/\nexport function transformTRPCResponse<\n TResponse extends\n | TRPCResponse\n | TRPCResponse[]\n | TRPCResponseMessage\n | TRPCResponseMessage[],\n>(config: RootConfig<AnyRootTypes>, itemOrItems: TResponse) {\n return Array.isArray(itemOrItems)\n ? itemOrItems.map((item) => transformTRPCResponseItem(config, item))\n : transformTRPCResponseItem(config, itemOrItems);\n}\n\n// FIXME:\n// - the generics here are probably unnecessary\n// - the RPC-spec could probably be simplified to combine HTTP + WS\n/** @internal */\nfunction transformResultInner<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n) {\n if ('error' in response) {\n const error = transformer.deserialize(\n response.error,\n ) as inferRouterError<TRouter>;\n return {\n ok: false,\n error: {\n ...response,\n error,\n },\n } as const;\n }\n\n const result = {\n ...response.result,\n ...((!response.result.type || response.result.type === 'data') && {\n type: 'data',\n data: transformer.deserialize(response.result.data),\n }),\n } as TRPCResultMessage<TOutput>['result'];\n return { ok: true, result } as const;\n}\n\nclass TransformResultError extends Error {\n constructor() {\n super('Unable to transform response from server');\n }\n}\n\n/**\n * Transforms and validates that the result is a valid TRPCResponse\n * @internal\n */\nexport function transformResult<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n): ReturnType<typeof transformResultInner> {\n let result: ReturnType<typeof transformResultInner>;\n try {\n // Use the data transformers on the JSON-response\n result = transformResultInner(response, transformer);\n } catch {\n throw new TransformResultError();\n }\n\n // check that output of the transformers is a valid TRPCResponse\n if (\n !result.ok &&\n (!isObject(result.error.error) ||\n typeof result.error.error['code'] !== 'number')\n ) {\n throw new TransformResultError();\n }\n if (result.ok && !isObject(result.result)) {\n throw new TransformResultError();\n }\n return result;\n}\n","import type { Observable } from '../observable';\nimport { createRecursiveProxy } from './createProxy';\nimport { defaultFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyProcedure,\n ErrorHandlerOptions,\n inferProcedureInput,\n inferProcedureOutput,\n LegacyObservableSubscriptionProcedure,\n} from './procedure';\nimport type { ProcedureCallOptions } from './procedureBuilder';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { defaultTransformer } from './transformer';\nimport type { MaybePromise, ValueOf } from './types';\nimport {\n isFunction,\n isObject,\n mergeWithoutOverrides,\n omitPrototype,\n} from './utils';\n\nexport interface RouterRecord {\n [key: string]: AnyProcedure | RouterRecord;\n}\n\ntype DecorateProcedure<TProcedure extends AnyProcedure> = (\n input: inferProcedureInput<TProcedure>,\n) => Promise<\n TProcedure['_def']['type'] extends 'subscription'\n ? TProcedure extends LegacyObservableSubscriptionProcedure<any>\n ? Observable<inferProcedureOutput<TProcedure>, TRPCError>\n : inferProcedureOutput<TProcedure>\n : inferProcedureOutput<TProcedure>\n>;\n\n/**\n * @internal\n */\nexport type DecorateRouterRecord<TRecord extends RouterRecord> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<$Value>\n : $Value extends RouterRecord\n ? DecorateRouterRecord<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\n\nexport type RouterCallerErrorHandler<TContext> = (\n opts: ErrorHandlerOptions<TContext>,\n) => void;\n\n/**\n * @internal\n */\nexport type RouterCaller<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = (\n /**\n * @note\n * If passing a function, we recommend it's a cached function\n * e.g. wrapped in `React.cache` to avoid unnecessary computations\n */\n ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),\n options?: {\n onError?: RouterCallerErrorHandler<TRoot['ctx']>;\n signal?: AbortSignal;\n },\n) => DecorateRouterRecord<TRecord>;\n\nconst lazySymbol = Symbol('lazy');\nexport type Lazy<TAny> = (() => Promise<TAny>) & { [lazySymbol]: true };\n\ntype LazyLoader<TAny> = {\n load: () => Promise<void>;\n ref: Lazy<TAny>;\n};\n\nfunction once<T>(fn: () => T): () => T {\n const uncalled = Symbol();\n let result: T | typeof uncalled = uncalled;\n return (): T => {\n if (result === uncalled) {\n result = fn();\n }\n return result;\n };\n}\n\n/**\n * Lazy load a router\n * @see https://trpc.io/docs/server/merging-routers#lazy-load\n */\nexport function lazy<TRouter extends AnyRouter>(\n importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >,\n): Lazy<NoInfer<TRouter>> {\n async function resolve(): Promise<TRouter> {\n const mod = await importRouter();\n\n // if the module is a router, return it\n if (isRouter(mod)) {\n return mod;\n }\n\n const routers = Object.values(mod);\n\n if (routers.length !== 1 || !isRouter(routers[0])) {\n throw new Error(\n \"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\",\n );\n }\n\n return routers[0];\n }\n resolve[lazySymbol] = true as const;\n\n return resolve;\n}\n\nfunction isLazy<TAny>(input: unknown): input is Lazy<TAny> {\n return typeof input === 'function' && lazySymbol in input;\n}\n\n/**\n * @internal\n */\nexport interface RouterDef<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _config: RootConfig<TRoot>;\n router: true;\n procedure?: never;\n procedures: TRecord;\n record: TRecord;\n lazy: Record<string, LazyLoader<AnyRouter>>;\n}\n\nexport interface Router<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _def: RouterDef<TRoot, TRecord>;\n /**\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCaller: RouterCaller<TRoot, TRecord>;\n}\n\nexport type BuiltRouter<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = Router<TRoot, TRecord> & TRecord;\n\nexport interface RouterBuilder<TRoot extends AnyRootTypes> {\n <TIn extends CreateRouterOptions>(\n _: TIn,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TIn>>;\n}\n\nexport type AnyRouter = Router<any, any>;\n\nexport type inferRouterRootTypes<TRouter extends AnyRouter> =\n TRouter['_def']['_config']['$types'];\n\nexport type inferRouterContext<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['ctx'];\nexport type inferRouterError<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['errorShape'];\nexport type inferRouterMeta<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['meta'];\n\nfunction isRouter(value: unknown): value is AnyRouter {\n return (\n isObject(value) && isObject(value['_def']) && 'router' in value['_def']\n );\n}\n\nconst emptyRouter = {\n _ctx: null as any,\n _errorShape: null as any,\n _meta: null as any,\n queries: {},\n mutations: {},\n subscriptions: {},\n errorFormatter: defaultFormatter,\n transformer: defaultTransformer,\n};\n\n/**\n * Reserved words that can't be used as router or procedure names\n */\nconst reservedWords = [\n /**\n * Then is a reserved word because otherwise we can't return a promise that returns a Proxy\n * since JS will think that `.then` is something that exists\n */\n 'then',\n /**\n * `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`\n */\n 'call',\n 'apply',\n];\n\n/** @internal */\nexport type CreateRouterOptions = {\n [key: string]:\n | AnyProcedure\n | AnyRouter\n | CreateRouterOptions\n | Lazy<AnyRouter>;\n};\n\n/** @internal */\nexport type DecorateCreateRouterOptions<\n TRouterOptions extends CreateRouterOptions,\n> = {\n [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value\n ? $Value extends AnyProcedure\n ? $Value\n : $Value extends Router<any, infer TRecord>\n ? TRecord\n : $Value extends Lazy<Router<any, infer TRecord>>\n ? TRecord\n : $Value extends CreateRouterOptions\n ? DecorateCreateRouterOptions<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\nexport function createRouterFactory<TRoot extends AnyRootTypes>(\n config: RootConfig<TRoot>,\n) {\n function createRouterInner<TInput extends CreateRouterOptions>(\n input: TInput,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>> {\n const reservedWordsUsed = new Set(\n Object.keys(input).filter((v) => reservedWords.includes(v)),\n );\n if (reservedWordsUsed.size > 0) {\n throw new Error(\n 'Reserved words used in `router({})` call: ' +\n Array.from(reservedWordsUsed).join(', '),\n );\n }\n\n const procedures: Record<string, AnyProcedure> = omitPrototype({});\n const lazy: Record<string, LazyLoader<AnyRouter>> = omitPrototype({});\n\n function createLazyLoader(opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }): LazyLoader<AnyRouter> {\n return {\n ref: opts.ref,\n load: once(async () => {\n const router = await opts.ref();\n const lazyPath = [...opts.path, opts.key];\n const lazyKey = lazyPath.join('.');\n\n opts.aggregate[opts.key] = step(router._def.record, lazyPath);\n\n delete lazy[lazyKey];\n\n // add lazy loaders for nested routers\n for (const [nestedKey, nestedItem] of Object.entries(\n router._def.lazy,\n )) {\n const nestedRouterKey = [...lazyPath, nestedKey].join('.');\n\n // console.log('adding lazy', nestedRouterKey);\n lazy[nestedRouterKey] = createLazyLoader({\n ref: nestedItem.ref,\n path: lazyPath,\n key: nestedKey,\n aggregate: opts.aggregate[opts.key] as RouterRecord,\n });\n }\n }),\n };\n }\n\n function step(from: CreateRouterOptions, path: readonly string[] = []) {\n const aggregate: RouterRecord = omitPrototype({});\n for (const [key, item] of Object.entries(from ?? {})) {\n if (isLazy(item)) {\n lazy[[...path, key].join('.')] = createLazyLoader({\n path,\n ref: item,\n key,\n aggregate,\n });\n continue;\n }\n if (isRouter(item)) {\n aggregate[key] = step(item._def.record, [...path, key]);\n continue;\n }\n if (!isProcedure(item)) {\n // RouterRecord\n aggregate[key] = step(item, [...path, key]);\n continue;\n }\n\n const newPath = [...path, key].join('.');\n\n if (procedures[newPath]) {\n throw new Error(`Duplicate key: ${newPath}`);\n }\n\n procedures[newPath] = item;\n aggregate[key] = item;\n }\n\n return aggregate;\n }\n const record = step(input);\n\n const _def: AnyRouter['_def'] = {\n _config: config,\n router: true,\n procedures,\n lazy,\n ...emptyRouter,\n record,\n };\n\n const router: BuiltRouter<TRoot, {}> = {\n ...(record as {}),\n _def,\n createCaller: createCallerFactory<TRoot>()({\n _def,\n }),\n };\n return router as BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;\n }\n\n return createRouterInner;\n}\n\nfunction isProcedure(\n procedureOrRouter: ValueOf<CreateRouterOptions>,\n): procedureOrRouter is AnyProcedure {\n return typeof procedureOrRouter === 'function';\n}\n\n/**\n * @internal\n */\nexport async function getProcedureAtPath(\n router: Pick<Router<any, any>, '_def'>,\n path: string,\n): Promise<AnyProcedure | null> {\n const { _def } = router;\n let procedure = _def.procedures[path];\n\n while (!procedure) {\n const key = Object.keys(_def.lazy).find((key) => path.startsWith(key));\n // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);\n\n if (!key) {\n return null;\n }\n // console.log('loading', key, '.......');\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lazyRouter = _def.lazy[key]!;\n await lazyRouter.load();\n\n procedure = _def.procedures[path];\n }\n\n return procedure;\n}\n\n/**\n * @internal\n */\nexport async function callProcedure(\n opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n },\n) {\n const { type, path } = opts;\n const proc = await getProcedureAtPath(opts.router, path);\n if (\n !proc ||\n !isProcedure(proc) ||\n (proc._def.type !== type && !opts.allowMethodOverride)\n ) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No \"${type}\"-procedure on path \"${path}\"`,\n });\n }\n\n /* istanbul ignore if -- @preserve */\n if (\n proc._def.type !== type &&\n opts.allowMethodOverride &&\n proc._def.type === 'subscription'\n ) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Method override is not supported for subscriptions`,\n });\n }\n\n return proc(opts);\n}\n\nexport interface RouterCallerFactory<TRoot extends AnyRootTypes> {\n <TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord>;\n}\n\nexport function createCallerFactory<\n TRoot extends AnyRootTypes,\n>(): RouterCallerFactory<TRoot> {\n return function createCallerInner<TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord> {\n const { _def } = router;\n type Context = TRoot['ctx'];\n\n return function createCaller(ctxOrCallback, opts) {\n return createRecursiveProxy<ReturnType<RouterCaller<any, any>>>(\n async ({ path, args }) => {\n const fullPath = path.join('.');\n\n if (path.length === 1 && path[0] === '_def') {\n return _def;\n }\n\n const procedure = await getProcedureAtPath(router, fullPath);\n\n let ctx: Context | undefined = undefined;\n try {\n if (!procedure) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${path}\"`,\n });\n }\n ctx = isFunction(ctxOrCallback)\n ? await Promise.resolve(ctxOrCallback())\n : ctxOrCallback;\n\n return await procedure({\n path: fullPath,\n getRawInput: async () => args[0],\n ctx,\n type: procedure._def.type,\n signal: opts?.signal,\n });\n } catch (cause) {\n opts?.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: args[0],\n path: fullPath,\n type: procedure?._def.type ?? 'unknown',\n });\n throw cause;\n }\n },\n );\n };\n };\n}\n\n/** @internal */\nexport type MergeRouters<\n TRouters extends AnyRouter[],\n TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],\n TRecord extends RouterRecord = {},\n> = TRouters extends [\n infer Head extends AnyRouter,\n ...infer Tail extends AnyRouter[],\n]\n ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>\n : BuiltRouter<TRoot, TRecord>;\n\nexport function mergeRouters<TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n): MergeRouters<TRouters> {\n const record = mergeWithoutOverrides(\n {},\n ...routerList.map((r) => r._def.record),\n );\n const errorFormatter = routerList.reduce(\n (currentErrorFormatter, nextRouter) => {\n if (\n nextRouter._def._config.errorFormatter &&\n nextRouter._def._config.errorFormatter !== defaultFormatter\n ) {\n if (\n currentErrorFormatter !== defaultFormatter &&\n currentErrorFormatter !== nextRouter._def._config.errorFormatter\n ) {\n throw new Error('You seem to have several error formatters');\n }\n return nextRouter._def._config.errorFormatter;\n }\n return currentErrorFormatter;\n },\n defaultFormatter,\n );\n\n const transformer = routerList.reduce((prev, current) => {\n if (\n current._def._config.transformer &&\n current._def._config.transformer !== defaultTransformer\n ) {\n if (\n prev !== defaultTransformer &&\n prev !== current._def._config.transformer\n ) {\n throw new Error('You seem to have several transformers');\n }\n return current._def._config.transformer;\n }\n return prev;\n }, defaultTransformer);\n\n const router = createRouterFactory({\n errorFormatter,\n transformer,\n isDev: routerList.every((r) => r._def._config.isDev),\n allowOutsideOfServer: routerList.every(\n (r) => r._def._config.allowOutsideOfServer,\n ),\n isServer: routerList.every((r) => r._def._config.isServer),\n $types: routerList[0]?._def._config.$types,\n })(record);\n\n return router as MergeRouters<TRouters>;\n}\n","const trackedSymbol = Symbol();\n\ntype TrackedId = string & {\n __brand: 'TrackedId';\n};\nexport type TrackedEnvelope<TData> = [TrackedId, TData, typeof trackedSymbol];\n\ntype TrackedData<TData> = {\n /**\n * The id of the message to keep track of in case the connection gets lost\n */\n id: string;\n /**\n * The data field of the message - this can be anything\n */\n data: TData;\n};\n/**\n * Produce a typed server-sent event message\n * @deprecated use `tracked(id, data)` instead\n */\nexport function sse<TData>(event: { id: string; data: TData }) {\n return tracked(event.id, event.data);\n}\n\nexport function isTrackedEnvelope<TData>(\n value: unknown,\n): value is TrackedEnvelope<TData> {\n return Array.isArray(value) && value[2] === trackedSymbol;\n}\n\n/**\n * Automatically track an event so that it can be resumed from a given id if the connection is lost\n */\nexport function tracked<TData>(\n id: string,\n data: TData,\n): TrackedEnvelope<TData> {\n if (id === '') {\n // This limitation could be removed by using different SSE event names / channels for tracked event and non-tracked event\n throw new Error(\n '`id` must not be an empty string as empty string is the same as not setting the id at all',\n );\n }\n return [id as TrackedId, data, trackedSymbol];\n}\n\nexport type inferTrackedOutput<TData> =\n TData extends TrackedEnvelope<infer $Data> ? TrackedData<$Data> : TData;\n"],"mappings":";;;;AA4CA,MAAaA,mBAA6C,CAAC,EAAE,OAAO,KAAK;AACvE,QAAO;AACR;;;;;AC3CD,IAAM,oBAAN,cAAgC,MAAM,CAErC;AACD,SAAgB,oBAAoBC,OAAmC;AACrE,KAAI,iBAAiB,MACnB,QAAO;CAGT,MAAM,cAAc;AACpB,KAAI,SAAS,eAAe,SAAS,cAAc,UAAU,KAC3D;AAIF,KAAI,SAAS,SAEX,QAAO,IAAI,MAAM,OAAO,MAAM;AAIhC,KAAI,SAAS,MAAM,CACjB,QAAO,OAAO,OAAO,IAAI,qBAAqB,MAAM;AAGtD;AACD;AAED,SAAgB,wBAAwBA,OAA2B;AACjE,KAAI,iBAAiB,UACnB,QAAO;AAET,KAAI,iBAAiB,SAAS,MAAM,SAAS,YAE3C,QAAO;CAGT,MAAM,YAAY,IAAI,UAAU;EAC9B,MAAM;EACN;CACD;AAGD,KAAI,iBAAiB,SAAS,MAAM,MAClC,WAAU,QAAQ,MAAM;AAG1B,QAAO;AACR;AAED,IAAa,YAAb,cAA+B,MAAM;CAMnC,YAAYC,MAIT;;EACD,MAAM,QAAQ,oBAAoB,KAAK,MAAM;EAC7C,MAAM,mCAAU,KAAK,8GAAW,MAAO,8CAAW,KAAK;AAIvD,QAAM,SAAS,EAAE,MAAO,EAAC;qCAO3B,MApByB;qCAoBxB,MAnBe;AAcd,OAAK,OAAO,KAAK;AACjB,OAAK,OAAO;AACZ,sBAAK,8CAGL,KAHK,QAAU;CAChB;AACF;;;;;;;;ACLD,SAAgB,mBACdC,aACyB;AACzB,KAAI,WAAW,YACb,QAAO;AAET,QAAO;EAAE,OAAO;EAAa,QAAQ;CAAa;AACnD;;;;AAKD,MAAaC,qBAA8C;CACzD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CAAC,MAAM,EAAE,KAAK,QAAQ,MAAM;EACpD,sBAAsB,WAAW,MAC/B,CAAC,MAAM,EAAE,KAAK,QAAQ,qBACvB;EACD,UAAU,WAAW,MAAM,CAAC,MAAM,EAAE,KAAK,QAAQ,SAAS;EAC1D,wBAAQ,WAAW,gEAAI,KAAK,QAAQ;CACrC,EAAC,CAAC,OAAO;AAEV,QAAO;AACR;;;;AC3iBD,MAAM,gBAAgB,QAAQ;;;;;AAqB9B,SAAgB,IAAWC,OAAoC;AAC7D,QAAO,QAAQ,MAAM,IAAI,MAAM,KAAK;AACrC;AAED,SAAgB,kBACdC,OACiC;AACjC,QAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,OAAO;AAC7C;;;;AAKD,SAAgB,QACdC,IACAC,MACwB;AACxB,KAAI,OAAO,GAET,OAAM,IAAI,MACR;AAGJ,QAAO;EAAC;EAAiB;EAAM;CAAc;AAC9C"}
@@ -1,12 +1,12 @@
1
- const require_resolveResponse = require('./resolveResponse-B2CuaT_1.cjs');
2
- const require_getErrorShape = require('./getErrorShape-CsikfkAc.cjs');
3
- const require_tracked = require('./tracked-Dl9sBZxY.cjs');
4
- const require_utils = require('./utils-DVO6HZiR.cjs');
5
- const require_parseTRPCMessage = require('./parseTRPCMessage-ByQWigsq.cjs');
1
+ const require_getErrorShape = require('./getErrorShape-DKiEF6Zc.cjs');
2
+ const require_tracked = require('./tracked-HoF8L_mq.cjs');
3
+ const require_utils = require('./utils-BhNVZA-c.cjs');
4
+ const require_parseTRPCMessage = require('./parseTRPCMessage-snNQop7N.cjs');
5
+ const require_resolveResponse = require('./resolveResponse-CVGbakBm.cjs');
6
6
  const require_contentTypeParsers = require('./contentTypeParsers-iAFF_pJG.cjs');
7
7
  const require_unstable_core_do_not_import = require('./unstable-core-do-not-import-DFQys1IC.cjs');
8
- require('./observable-BwdrSFZU.cjs');
9
- const require_initTRPC = require('./initTRPC-DjEpHmY2.cjs');
8
+ require('./observable-B1Nk6r1H.cjs');
9
+ const require_initTRPC = require('./initTRPC-IT4M4lu3.cjs');
10
10
 
11
11
  exports.HTTP_CODE_TO_JSONRPC2 = require_getErrorShape.HTTP_CODE_TO_JSONRPC2;
12
12
  exports.JSONRPC2_TO_HTTP_CODE = require_getErrorShape.JSONRPC2_TO_HTTP_CODE;
@@ -1,11 +1,11 @@
1
- import { Unpromise, createDeferred, getRequestInfo, isAbortError, isPromise, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, makeAsyncResource, makeResource, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, resolveResponse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, withMaxDuration } from "./resolveResponse-DPbYgJDD.mjs";
2
- import { HTTP_CODE_TO_JSONRPC2, JSONRPC2_TO_HTTP_CODE, createFlatProxy, createRecursiveProxy, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getStatusCodeFromKey, getStatusKeyFromCode } from "./getErrorShape-DyYil4aT.mjs";
3
- import { TRPCError, callProcedure, createCallerFactory, createRouterFactory, defaultFormatter, defaultTransformer, getCauseFromUnknown, getDataTransformer, getProcedureAtPath, getTRPCErrorFromUnknown, isTrackedEnvelope, lazy, mergeRouters, sse, tracked, transformResult, transformTRPCResponse } from "./tracked-GEWPoL0C.mjs";
4
- import { TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, abortSignalsAnyPonyfill, assert, identity, isAsyncIterable, isFunction, isObject, mergeWithoutOverrides, noop, omitPrototype, retryableRpcCodes, run, sleep } from "./utils-BHZJcBRv.mjs";
5
- import { parseTRPCMessage, procedureTypes } from "./parseTRPCMessage-CNyYMSRB.mjs";
1
+ import { HTTP_CODE_TO_JSONRPC2, JSONRPC2_TO_HTTP_CODE, createFlatProxy, createRecursiveProxy, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getStatusCodeFromKey, getStatusKeyFromCode } from "./getErrorShape-Uhlrl4Bk.mjs";
2
+ import { TRPCError, callProcedure, createCallerFactory, createRouterFactory, defaultFormatter, defaultTransformer, getCauseFromUnknown, getDataTransformer, getProcedureAtPath, getTRPCErrorFromUnknown, isTrackedEnvelope, lazy, mergeRouters, sse, tracked, transformResult, transformTRPCResponse } from "./tracked-gU3ttYjg.mjs";
3
+ import { TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, abortSignalsAnyPonyfill, assert, identity, isAsyncIterable, isFunction, isObject, mergeWithoutOverrides, noop, omitPrototype, retryableRpcCodes, run, sleep } from "./utils-DdbbrDku.mjs";
4
+ import { parseTRPCMessage, procedureTypes } from "./parseTRPCMessage-ByIHyFRz.mjs";
5
+ import { Unpromise, createDeferred, getRequestInfo, isAbortError, isPromise, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, makeAsyncResource, makeResource, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, resolveResponse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, withMaxDuration } from "./resolveResponse-CzlbRpCI.mjs";
6
6
  import { octetInputParser } from "./contentTypeParsers-SN4WL9ze.mjs";
7
7
  import { formDataToObject } from "./unstable-core-do-not-import-D89CaGtL.mjs";
8
- import "./observable-B1orLHHI.mjs";
9
- import { StandardSchemaV1Error, createBuilder, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, experimental_standaloneMiddleware, getParseFn, initTRPC, isServerDefault, middlewareMarker } from "./initTRPC-COaJMShh.mjs";
8
+ import "./observable-UMO3vUa_.mjs";
9
+ import { StandardSchemaV1Error, createBuilder, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, experimental_standaloneMiddleware, getParseFn, initTRPC, isServerDefault, middlewareMarker } from "./initTRPC-IT_6ZYJd.mjs";
10
10
 
11
11
  export { HTTP_CODE_TO_JSONRPC2, JSONRPC2_TO_HTTP_CODE, StandardSchemaV1Error, TRPCError, TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, Unpromise, abortSignalsAnyPonyfill, assert, callProcedure, createBuilder, createCallerFactory, createDeferred, createFlatProxy, createInputMiddleware, createMiddlewareFactory, createOutputMiddleware, createRecursiveProxy, createRouterFactory, defaultFormatter, defaultTransformer, experimental_standaloneMiddleware, formDataToObject, getCauseFromUnknown, getDataTransformer, getErrorShape, getHTTPStatusCode, getHTTPStatusCodeFromError, getParseFn, getProcedureAtPath, getRequestInfo, getStatusCodeFromKey, getStatusKeyFromCode, getTRPCErrorFromUnknown, identity, initTRPC, isAbortError, isAsyncIterable, isFunction, isObject, isPromise, isServerDefault, isTrackedEnvelope, iteratorResource, jsonlStreamConsumer, jsonlStreamProducer, lazy, makeAsyncResource, makeResource, mergeRouters, mergeWithoutOverrides, middlewareMarker, noop, octetInputParser, omitPrototype, parseConnectionParamsFromString, parseConnectionParamsFromUnknown, parseTRPCMessage, procedureTypes, resolveResponse, retryableRpcCodes, run, sleep, sse, sseHeaders, sseStreamConsumer, sseStreamProducer, takeWithGrace, throwAbortError, tracked, transformResult, transformTRPCResponse, withMaxDuration };
@@ -134,4 +134,4 @@ function abortSignalsAnyPonyfill(signals) {
134
134
 
135
135
  //#endregion
136
136
  export { TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER, abortSignalsAnyPonyfill, assert, identity, isAsyncIterable, isFunction, isObject, mergeWithoutOverrides, noop, omitPrototype, retryableRpcCodes, run, sleep };
137
- //# sourceMappingURL=utils-BHZJcBRv.mjs.map
137
+ //# sourceMappingURL=utils-DdbbrDku.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils-BHZJcBRv.mjs","names":["TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n>","retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[]","obj1: TType","newObj: TType","value: unknown","fn: unknown","obj: TObj","fn: () => TValue","it: T","condition: boolean","signals: AbortSignal[]"],"sources":["../src/unstable-core-do-not-import/rpc/codes.ts","../src/unstable-core-do-not-import/utils.ts"],"sourcesContent":["import type { InvertKeyValue, ValueOf } from '../types';\n\n// reference: https://www.jsonrpc.org/specification\n\n/**\n * JSON-RPC 2.0 Error codes\n *\n * `-32000` to `-32099` are reserved for implementation-defined server-errors.\n * For tRPC we're copying the last digits of HTTP 4XX errors.\n */\nexport const TRPC_ERROR_CODES_BY_KEY = {\n /**\n * Invalid JSON was received by the server.\n * An error occurred on the server while parsing the JSON text.\n */\n PARSE_ERROR: -32700,\n /**\n * The JSON sent is not a valid Request object.\n */\n BAD_REQUEST: -32600, // 400\n\n // Internal JSON-RPC error\n INTERNAL_SERVER_ERROR: -32603, // 500\n NOT_IMPLEMENTED: -32603, // 501\n BAD_GATEWAY: -32603, // 502\n SERVICE_UNAVAILABLE: -32603, // 503\n GATEWAY_TIMEOUT: -32603, // 504\n\n // Implementation specific errors\n UNAUTHORIZED: -32001, // 401\n PAYMENT_REQUIRED: -32002, // 402\n FORBIDDEN: -32003, // 403\n NOT_FOUND: -32004, // 404\n METHOD_NOT_SUPPORTED: -32005, // 405\n TIMEOUT: -32008, // 408\n CONFLICT: -32009, // 409\n PRECONDITION_FAILED: -32012, // 412\n PAYLOAD_TOO_LARGE: -32013, // 413\n UNSUPPORTED_MEDIA_TYPE: -32015, // 415\n UNPROCESSABLE_CONTENT: -32022, // 422\n TOO_MANY_REQUESTS: -32029, // 429\n CLIENT_CLOSED_REQUEST: -32099, // 499\n} as const;\n\n// pure\nexport const TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n> = {\n [-32700]: 'PARSE_ERROR',\n [-32600]: 'BAD_REQUEST',\n [-32603]: 'INTERNAL_SERVER_ERROR',\n [-32001]: 'UNAUTHORIZED',\n [-32002]: 'PAYMENT_REQUIRED',\n [-32003]: 'FORBIDDEN',\n [-32004]: 'NOT_FOUND',\n [-32005]: 'METHOD_NOT_SUPPORTED',\n [-32008]: 'TIMEOUT',\n [-32009]: 'CONFLICT',\n [-32012]: 'PRECONDITION_FAILED',\n [-32013]: 'PAYLOAD_TOO_LARGE',\n [-32015]: 'UNSUPPORTED_MEDIA_TYPE',\n [-32022]: 'UNPROCESSABLE_CONTENT',\n [-32029]: 'TOO_MANY_REQUESTS',\n [-32099]: 'CLIENT_CLOSED_REQUEST',\n};\n\nexport type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;\nexport type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;\n\n/**\n * tRPC error codes that are considered retryable\n * With out of the box SSE, the client will reconnect when these errors are encountered\n */\nexport const retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[] = [\n TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n];\n","/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(Object.create(null), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function omitPrototype<TObj extends Record<string, unknown>>(\n obj: TObj,\n): TObj {\n return Object.assign(Object.create(null), obj);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop(): void {}\n\nexport function identity<T>(it: T): T {\n return it;\n}\n\n/**\n * Generic runtime assertion function. Throws, if the condition is not `true`.\n *\n * Can be used as a slightly less dangerous variant of type assertions. Code\n * mistakes would be revealed at runtime then (hopefully during testing).\n */\nexport function assert(\n condition: boolean,\n msg = 'no additional info',\n): asserts condition {\n if (!condition) {\n throw new Error(`AssertionError: ${msg}`);\n }\n}\n\nexport function sleep(ms = 0): Promise<void> {\n return new Promise<void>((res) => setTimeout(res, ms));\n}\n\n/**\n * Ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function abortSignalsAnyPonyfill(signals: AbortSignal[]): AbortSignal {\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any(signals);\n }\n\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n trigger();\n break;\n }\n signal.addEventListener('abort', trigger, { once: true });\n }\n\n return ac.signal;\n\n function trigger() {\n ac.abort();\n for (const signal of signals) {\n signal.removeEventListener('abort', trigger);\n }\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAa,0BAA0B;CAKrC,aAAa;CAIb,aAAa;CAGb,uBAAuB;CACvB,iBAAiB;CACjB,aAAa;CACb,qBAAqB;CACrB,iBAAiB;CAGjB,cAAc;CACd,kBAAkB;CAClB,WAAW;CACX,WAAW;CACX,sBAAsB;CACtB,SAAS;CACT,UAAU;CACV,qBAAqB;CACrB,mBAAmB;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GAAkB;AAC3C,QAAO,IAAI,QAAc,CAAC,QAAQ,WAAW,KAAK,GAAG;AACtD;;;;;AAMD,SAAgB,wBAAwBC,SAAqC;AAC3E,YAAW,YAAY,QAAQ,WAC7B,QAAO,YAAY,IAAI,QAAQ;CAGjC,MAAM,KAAK,IAAI;AAEf,MAAK,MAAM,UAAU,SAAS;AAC5B,MAAI,OAAO,SAAS;AAClB,YAAS;AACT;EACD;AACD,SAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAM,EAAC;CAC1D;AAED,QAAO,GAAG;CAEV,SAAS,UAAU;AACjB,KAAG,OAAO;AACV,OAAK,MAAM,UAAU,QACnB,QAAO,oBAAoB,SAAS,QAAQ;CAE/C;AACF"}
1
+ {"version":3,"file":"utils-DdbbrDku.mjs","names":["TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n>","retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[]","obj1: TType","newObj: TType","value: unknown","fn: unknown","obj: TObj","fn: () => TValue","it: T","condition: boolean","signals: AbortSignal[]"],"sources":["../src/unstable-core-do-not-import/rpc/codes.ts","../src/unstable-core-do-not-import/utils.ts"],"sourcesContent":["import type { InvertKeyValue, ValueOf } from '../types';\n\n// reference: https://www.jsonrpc.org/specification\n\n/**\n * JSON-RPC 2.0 Error codes\n *\n * `-32000` to `-32099` are reserved for implementation-defined server-errors.\n * For tRPC we're copying the last digits of HTTP 4XX errors.\n */\nexport const TRPC_ERROR_CODES_BY_KEY = {\n /**\n * Invalid JSON was received by the server.\n * An error occurred on the server while parsing the JSON text.\n */\n PARSE_ERROR: -32700,\n /**\n * The JSON sent is not a valid Request object.\n */\n BAD_REQUEST: -32600, // 400\n\n // Internal JSON-RPC error\n INTERNAL_SERVER_ERROR: -32603, // 500\n NOT_IMPLEMENTED: -32603, // 501\n BAD_GATEWAY: -32603, // 502\n SERVICE_UNAVAILABLE: -32603, // 503\n GATEWAY_TIMEOUT: -32603, // 504\n\n // Implementation specific errors\n UNAUTHORIZED: -32001, // 401\n PAYMENT_REQUIRED: -32002, // 402\n FORBIDDEN: -32003, // 403\n NOT_FOUND: -32004, // 404\n METHOD_NOT_SUPPORTED: -32005, // 405\n TIMEOUT: -32008, // 408\n CONFLICT: -32009, // 409\n PRECONDITION_FAILED: -32012, // 412\n PAYLOAD_TOO_LARGE: -32013, // 413\n UNSUPPORTED_MEDIA_TYPE: -32015, // 415\n UNPROCESSABLE_CONTENT: -32022, // 422\n TOO_MANY_REQUESTS: -32029, // 429\n CLIENT_CLOSED_REQUEST: -32099, // 499\n} as const;\n\n// pure\nexport const TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n> = {\n [-32700]: 'PARSE_ERROR',\n [-32600]: 'BAD_REQUEST',\n [-32603]: 'INTERNAL_SERVER_ERROR',\n [-32001]: 'UNAUTHORIZED',\n [-32002]: 'PAYMENT_REQUIRED',\n [-32003]: 'FORBIDDEN',\n [-32004]: 'NOT_FOUND',\n [-32005]: 'METHOD_NOT_SUPPORTED',\n [-32008]: 'TIMEOUT',\n [-32009]: 'CONFLICT',\n [-32012]: 'PRECONDITION_FAILED',\n [-32013]: 'PAYLOAD_TOO_LARGE',\n [-32015]: 'UNSUPPORTED_MEDIA_TYPE',\n [-32022]: 'UNPROCESSABLE_CONTENT',\n [-32029]: 'TOO_MANY_REQUESTS',\n [-32099]: 'CLIENT_CLOSED_REQUEST',\n};\n\nexport type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;\nexport type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;\n\n/**\n * tRPC error codes that are considered retryable\n * With out of the box SSE, the client will reconnect when these errors are encountered\n */\nexport const retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[] = [\n TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n];\n","/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(Object.create(null), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function omitPrototype<TObj extends Record<string, unknown>>(\n obj: TObj,\n): TObj {\n return Object.assign(Object.create(null), obj);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop(): void {}\n\nexport function identity<T>(it: T): T {\n return it;\n}\n\n/**\n * Generic runtime assertion function. Throws, if the condition is not `true`.\n *\n * Can be used as a slightly less dangerous variant of type assertions. Code\n * mistakes would be revealed at runtime then (hopefully during testing).\n */\nexport function assert(\n condition: boolean,\n msg = 'no additional info',\n): asserts condition {\n if (!condition) {\n throw new Error(`AssertionError: ${msg}`);\n }\n}\n\nexport function sleep(ms = 0): Promise<void> {\n return new Promise<void>((res) => setTimeout(res, ms));\n}\n\n/**\n * Ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function abortSignalsAnyPonyfill(signals: AbortSignal[]): AbortSignal {\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any(signals);\n }\n\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n trigger();\n break;\n }\n signal.addEventListener('abort', trigger, { once: true });\n }\n\n return ac.signal;\n\n function trigger() {\n ac.abort();\n for (const signal of signals) {\n signal.removeEventListener('abort', trigger);\n }\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAa,0BAA0B;CAKrC,aAAa;CAIb,aAAa;CAGb,uBAAuB;CACvB,iBAAiB;CACjB,aAAa;CACb,qBAAqB;CACrB,iBAAiB;CAGjB,cAAc;CACd,kBAAkB;CAClB,WAAW;CACX,WAAW;CACX,sBAAsB;CACtB,SAAS;CACT,UAAU;CACV,qBAAqB;CACrB,mBAAmB;CACnB,wBAAwB;CACxB,uBAAuB;CACvB,mBAAmB;CACnB,uBAAuB;AACxB;AAGD,MAAaA,6BAET;EACD,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;AACX;;;;;AASD,MAAaC,oBAA8C;CACzD,wBAAwB;CACxB,wBAAwB;CACxB,wBAAwB;CACxB,wBAAwB;AACzB;;;;;;;;ACrED,SAAgB,sBACdC,MACA,GAAG,MACI;CACP,MAAMC,SAAgB,OAAO,OAAO,OAAO,OAAO,KAAK,EAAE,KAAK;AAE9D,MAAK,MAAM,aAAa,KACtB,MA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./resolveResponse-B2CuaT_1.cjs');
2
- const require_getErrorShape = require('./getErrorShape-CsikfkAc.cjs');
3
- const require_tracked = require('./tracked-Dl9sBZxY.cjs');
4
- const require_utils = require('./utils-DVO6HZiR.cjs');
5
- const require_parseTRPCMessage = require('./parseTRPCMessage-ByQWigsq.cjs');
6
- const require_observable = require('./observable-BwdrSFZU.cjs');
7
- const require_node_http = require('./node-http-BPR68yI4.cjs');
1
+ const require_getErrorShape = require('./getErrorShape-DKiEF6Zc.cjs');
2
+ const require_tracked = require('./tracked-HoF8L_mq.cjs');
3
+ const require_utils = require('./utils-BhNVZA-c.cjs');
4
+ const require_parseTRPCMessage = require('./parseTRPCMessage-snNQop7N.cjs');
5
+ const require_resolveResponse = require('./resolveResponse-CVGbakBm.cjs');
6
+ const require_observable = require('./observable-B1Nk6r1H.cjs');
7
+ const require_node_http = require('./node-http-kIQEhZUH.cjs');
8
8
 
9
9
  //#region src/adapters/ws.ts
10
- var import_usingCtx = require_resolveResponse.__toESM(require_resolveResponse.require_usingCtx(), 1);
10
+ var import_objectSpread2 = require_getErrorShape.__toESM(require_getErrorShape.require_objectSpread2(), 1);
11
+ var import_usingCtx = require_getErrorShape.__toESM(require_resolveResponse.require_usingCtx(), 1);
11
12
  /**
12
13
  * Importing ws causes a build error
13
14
  * @see https://github.com/trpc/trpc/pull/5279
@@ -17,9 +18,10 @@ function getWSConnectionHandler(opts) {
17
18
  const { createContext, router } = opts;
18
19
  const { transformer } = router._def._config;
19
20
  return (client, req) => {
21
+ var _opts$keepAlive;
20
22
  const clientSubscriptions = /* @__PURE__ */ new Map();
21
23
  const abortController = new AbortController();
22
- if (opts.keepAlive?.enabled) {
24
+ if ((_opts$keepAlive = opts.keepAlive) === null || _opts$keepAlive === void 0 ? void 0 : _opts$keepAlive.enabled) {
23
25
  const { pingMs, pongWaitMs } = opts.keepAlive;
24
26
  handleKeepAlive(client, pingMs, pongWaitMs);
25
27
  }
@@ -29,7 +31,7 @@ function getWSConnectionHandler(opts) {
29
31
  async function createCtxPromise(getConnectionParams) {
30
32
  try {
31
33
  return await require_utils.run(async () => {
32
- ctx = await createContext?.({
34
+ ctx = await (createContext === null || createContext === void 0 ? void 0 : createContext({
33
35
  req,
34
36
  res: client,
35
37
  info: {
@@ -41,15 +43,16 @@ function getWSConnectionHandler(opts) {
41
43
  signal: abortController.signal,
42
44
  url: null
43
45
  }
44
- });
46
+ }));
45
47
  return {
46
48
  ok: true,
47
49
  value: ctx
48
50
  };
49
51
  });
50
52
  } catch (cause) {
53
+ var _opts$onError, _globalThis$setImmedi;
51
54
  const error = require_tracked.getTRPCErrorFromUnknown(cause);
52
- opts.onError?.({
55
+ (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
53
56
  error,
54
57
  path: void 0,
55
58
  type: "unknown",
@@ -68,7 +71,7 @@ function getWSConnectionHandler(opts) {
68
71
  ctx
69
72
  })
70
73
  });
71
- (globalThis.setImmediate ?? globalThis.setTimeout)(() => {
74
+ ((_globalThis$setImmedi = globalThis.setImmediate) !== null && _globalThis$setImmedi !== void 0 ? _globalThis$setImmedi : globalThis.setTimeout)(() => {
72
75
  client.close();
73
76
  });
74
77
  return {
@@ -88,11 +91,12 @@ function getWSConnectionHandler(opts) {
88
91
  function handleRequest(msg) {
89
92
  const { id, jsonrpc } = msg;
90
93
  if (id === null) {
94
+ var _opts$onError2;
91
95
  const error = require_tracked.getTRPCErrorFromUnknown(new require_tracked.TRPCError({
92
96
  code: "PARSE_ERROR",
93
97
  message: "`id` is required"
94
98
  }));
95
- opts.onError?.({
99
+ (_opts$onError2 = opts.onError) === null || _opts$onError2 === void 0 || _opts$onError2.call(opts, {
96
100
  error,
97
101
  path: void 0,
98
102
  type: "unknown",
@@ -115,17 +119,18 @@ function getWSConnectionHandler(opts) {
115
119
  return;
116
120
  }
117
121
  if (msg.method === "subscription.stop") {
118
- clientSubscriptions.get(id)?.abort();
122
+ var _clientSubscriptions$;
123
+ (_clientSubscriptions$ = clientSubscriptions.get(id)) === null || _clientSubscriptions$ === void 0 || _clientSubscriptions$.abort();
119
124
  return;
120
125
  }
121
126
  const { path, lastEventId } = msg.params;
122
127
  let { input } = msg.params;
123
128
  const type = msg.method;
124
- if (lastEventId !== void 0) if (require_utils.isObject(input)) input = {
125
- ...input,
126
- lastEventId
127
- };
128
- else input ??= { lastEventId };
129
+ if (lastEventId !== void 0) if (require_utils.isObject(input)) input = (0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, input), {}, { lastEventId });
130
+ else {
131
+ var _input;
132
+ (_input = input) !== null && _input !== void 0 || (input = { lastEventId });
133
+ }
129
134
  require_utils.run(async () => {
130
135
  const res = await ctxPromise;
131
136
  if (!res.ok) throw res.error;
@@ -178,12 +183,14 @@ function getWSConnectionHandler(opts) {
178
183
  while (true) {
179
184
  next = await require_resolveResponse.Unpromise.race([iterator.next().catch(require_tracked.getTRPCErrorFromUnknown), abortPromise]);
180
185
  if (next === "abort") {
181
- await iterator.return?.();
186
+ var _iterator$return;
187
+ await ((_iterator$return = iterator.return) === null || _iterator$return === void 0 ? void 0 : _iterator$return.call(iterator));
182
188
  break;
183
189
  }
184
190
  if (next instanceof Error) {
191
+ var _opts$onError3;
185
192
  const error = require_tracked.getTRPCErrorFromUnknown(next);
186
- opts.onError?.({
193
+ (_opts$onError3 = opts.onError) === null || _opts$onError3 === void 0 || _opts$onError3.call(opts, {
187
194
  error,
188
195
  path,
189
196
  type,
@@ -238,8 +245,9 @@ function getWSConnectionHandler(opts) {
238
245
  await _usingCtx.d();
239
246
  }
240
247
  }).catch((cause) => {
248
+ var _opts$onError4;
241
249
  const error = require_tracked.getTRPCErrorFromUnknown(cause);
242
- opts.onError?.({
250
+ (_opts$onError4 = opts.onError) === null || _opts$onError4 === void 0 || _opts$onError4.call(opts, {
243
251
  error,
244
252
  path,
245
253
  type,
@@ -268,8 +276,9 @@ function getWSConnectionHandler(opts) {
268
276
  result: { type: "started" }
269
277
  });
270
278
  }).catch((cause) => {
279
+ var _opts$onError5;
271
280
  const error = require_tracked.getTRPCErrorFromUnknown(cause);
272
- opts.onError?.({
281
+ (_opts$onError5 = opts.onError) === null || _opts$onError5 === void 0 || _opts$onError5.call(opts, {
273
282
  error,
274
283
  path,
275
284
  type,
@@ -343,7 +352,8 @@ function getWSConnectionHandler(opts) {
343
352
  parsedMsgs.map(handleRequest);
344
353
  });
345
354
  client.on("error", (cause) => {
346
- opts.onError?.({
355
+ var _opts$onError6;
356
+ (_opts$onError6 = opts.onError) === null || _opts$onError6 === void 0 || _opts$onError6.call(opts, {
347
357
  ctx,
348
358
  error: require_tracked.getTRPCErrorFromUnknown(cause),
349
359
  input: void 0,
@@ -391,7 +401,8 @@ function handleKeepAlive(client, pingMs = 3e4, pongWaitMs = 5e3) {
391
401
  function applyWSSHandler(opts) {
392
402
  const onConnection = getWSConnectionHandler(opts);
393
403
  opts.wss.on("connection", (client, req) => {
394
- if (opts.prefix && !req.url?.startsWith(opts.prefix)) return;
404
+ var _req$url;
405
+ if (opts.prefix && !((_req$url = req.url) === null || _req$url === void 0 ? void 0 : _req$url.startsWith(opts.prefix))) return;
395
406
  onConnection(client, req);
396
407
  });
397
408
  return { broadcastReconnectNotification: () => {