@trpc/server 10.0.0-alpha.45 → 10.0.0-alpha.48

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 (146) hide show
  1. package/adapters/aws-lambda/index.js +1 -1
  2. package/adapters/fastify/index.js +1 -1
  3. package/adapters/fetch/index.js +1 -1
  4. package/adapters/node-http/index.js +1 -1
  5. package/dist/TRPCError-6f61762c.mjs +54 -0
  6. package/dist/TRPCError-9c7830b4.js +58 -0
  7. package/dist/adapters/aws-lambda/index.d.ts.map +1 -1
  8. package/dist/adapters/aws-lambda/index.js +119 -156
  9. package/dist/adapters/aws-lambda/index.mjs +119 -156
  10. package/dist/adapters/aws-lambda/utils.d.ts.map +1 -1
  11. package/dist/adapters/express.d.ts.map +1 -1
  12. package/dist/adapters/express.js +14 -14
  13. package/dist/adapters/express.mjs +14 -14
  14. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +1 -1
  15. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +1 -1
  16. package/dist/adapters/fastify/index.d.ts.map +1 -1
  17. package/dist/adapters/fastify/index.js +68 -89
  18. package/dist/adapters/fastify/index.mjs +68 -89
  19. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  20. package/dist/adapters/fetch/index.d.ts.map +1 -1
  21. package/dist/adapters/fetch/index.js +45 -57
  22. package/dist/adapters/fetch/index.mjs +45 -57
  23. package/dist/adapters/fetch/types.d.ts.map +1 -1
  24. package/dist/adapters/lambda/index.d.ts.map +1 -1
  25. package/dist/adapters/next.d.ts.map +1 -1
  26. package/dist/adapters/next.js +42 -46
  27. package/dist/adapters/next.mjs +42 -46
  28. package/dist/adapters/node-http/index.d.ts.map +1 -1
  29. package/dist/adapters/node-http/index.js +5 -5
  30. package/dist/adapters/node-http/index.mjs +5 -5
  31. package/dist/adapters/node-http/internals/getPostBody.d.ts.map +1 -1
  32. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  33. package/dist/adapters/node-http/types.d.ts.map +1 -1
  34. package/dist/adapters/standalone.d.ts.map +1 -1
  35. package/dist/adapters/standalone.js +30 -32
  36. package/dist/adapters/standalone.mjs +30 -32
  37. package/dist/adapters/ws.d.ts.map +1 -1
  38. package/dist/adapters/ws.js +272 -352
  39. package/dist/adapters/ws.mjs +272 -352
  40. package/dist/codes-1c24d919.js +47 -0
  41. package/dist/codes-aaa7d554.mjs +44 -0
  42. package/dist/core/index.d.ts.map +1 -1
  43. package/dist/core/initTRPC.d.ts.map +1 -1
  44. package/dist/core/internals/__generated__/mergeRoutersGeneric.d.ts.map +1 -1
  45. package/dist/core/internals/config.d.ts.map +1 -1
  46. package/dist/core/internals/getParseFn.d.ts.map +1 -1
  47. package/dist/core/internals/mergeRouters.d.ts.map +1 -1
  48. package/dist/core/internals/mergeWithoutOverrides.d.ts.map +1 -1
  49. package/dist/core/internals/omitPrototype.d.ts.map +1 -1
  50. package/dist/core/internals/prefixObjectKeys.d.ts.map +1 -1
  51. package/dist/core/internals/procedureBuilder.d.ts.map +1 -1
  52. package/dist/core/internals/utils.d.ts.map +1 -1
  53. package/dist/core/middleware.d.ts.map +1 -1
  54. package/dist/core/parser.d.ts.map +1 -1
  55. package/dist/core/procedure.d.ts.map +1 -1
  56. package/dist/core/router.d.ts.map +1 -1
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/deprecated/internals/callProcedure.d.ts.map +1 -1
  59. package/dist/deprecated/internals/middlewares.d.ts.map +1 -1
  60. package/dist/deprecated/internals/procedure.d.ts.map +1 -1
  61. package/dist/deprecated/interop.d.ts.map +1 -1
  62. package/dist/deprecated/router.d.ts.map +1 -1
  63. package/dist/error/TRPCError.d.ts.map +1 -1
  64. package/dist/error/formatter.d.ts.map +1 -1
  65. package/dist/error/utils.d.ts.map +1 -1
  66. package/dist/http/index.d.ts.map +1 -1
  67. package/dist/http/internals/getHTTPStatusCode.d.ts.map +1 -1
  68. package/dist/http/internals/types.d.ts.map +1 -1
  69. package/dist/http/resolveHTTPResponse.d.ts.map +1 -1
  70. package/dist/http/types.d.ts.map +1 -1
  71. package/dist/index-47817162.mjs +26 -0
  72. package/dist/index-9d687d33.js +28 -0
  73. package/dist/index.js +59 -95
  74. package/dist/index.mjs +60 -96
  75. package/dist/internals/invert.d.ts.map +1 -1
  76. package/dist/internals/transformTRPCResponse.d.ts.map +1 -1
  77. package/dist/internals/types.d.ts.map +1 -1
  78. package/dist/nodeHTTPRequestHandler-7c2a3037.js +82 -0
  79. package/dist/nodeHTTPRequestHandler-b37609f7.mjs +80 -0
  80. package/dist/observable/index.d.ts.map +1 -1
  81. package/dist/observable/index.js +125 -172
  82. package/dist/observable/index.mjs +125 -172
  83. package/dist/observable/internals/identity.d.ts.map +1 -1
  84. package/dist/observable/internals/observableToPromise.d.ts.map +1 -1
  85. package/dist/observable/internals/pipe.d.ts.map +1 -1
  86. package/dist/observable/observable.d.ts.map +1 -1
  87. package/dist/observable/operators/index.d.ts.map +1 -1
  88. package/dist/observable/operators/map.d.ts.map +1 -1
  89. package/dist/observable/operators/share.d.ts.map +1 -1
  90. package/dist/observable/operators/tap.d.ts.map +1 -1
  91. package/dist/observable/types.d.ts.map +1 -1
  92. package/dist/observable-b651bf11.js +84 -0
  93. package/dist/observable-e129ac9d.mjs +81 -0
  94. package/dist/resolveHTTPResponse-83703ee8.mjs +251 -0
  95. package/dist/resolveHTTPResponse-b486996d.js +255 -0
  96. package/dist/router-8372703e.js +886 -0
  97. package/dist/router-f21b6d06.mjs +876 -0
  98. package/dist/rpc/codes.d.ts.map +1 -1
  99. package/dist/rpc/envelopes.d.ts.map +1 -1
  100. package/dist/rpc/index.d.ts.map +1 -1
  101. package/dist/rpc/index.js +3 -7
  102. package/dist/rpc/index.mjs +1 -1
  103. package/dist/rpc/internals/invert.d.ts.map +1 -1
  104. package/dist/shared/createProxy/index.d.ts.map +1 -1
  105. package/dist/shared/index.d.ts.map +1 -1
  106. package/dist/shared/index.js +1 -1
  107. package/dist/shared/index.mjs +1 -1
  108. package/dist/subscription.js +24 -34
  109. package/dist/subscription.mjs +24 -34
  110. package/dist/transformTRPCResponse-11ac69cc.js +27 -0
  111. package/dist/transformTRPCResponse-c8138d5f.mjs +25 -0
  112. package/observable/index.js +1 -1
  113. package/package.json +12 -16
  114. package/rpc/index.js +1 -1
  115. package/shared/index.js +1 -1
  116. package/subscription/index.d.ts +1 -0
  117. package/subscription/index.js +1 -0
  118. package/dist/TRPCError-9050a68d.js +0 -69
  119. package/dist/TRPCError-97212592.mjs +0 -65
  120. package/dist/adapters/aws-lambda/index.ts.js +0 -1
  121. package/dist/adapters/express.ts.js +0 -1
  122. package/dist/adapters/fastify/index.ts.js +0 -1
  123. package/dist/adapters/fetch/index.ts.js +0 -1
  124. package/dist/adapters/next.ts.js +0 -1
  125. package/dist/adapters/node-http/index.ts.js +0 -1
  126. package/dist/adapters/standalone.ts.js +0 -1
  127. package/dist/adapters/ws.ts.js +0 -1
  128. package/dist/envelopes-2ae27c9f.js +0 -85
  129. package/dist/envelopes-b9f49d4d.mjs +0 -82
  130. package/dist/index-1a25ccbd.js +0 -33
  131. package/dist/index-a3bd54c7.mjs +0 -31
  132. package/dist/index.ts.js +0 -1
  133. package/dist/nodeHTTPRequestHandler-bee7aacc.js +0 -107
  134. package/dist/nodeHTTPRequestHandler-f1656eba.mjs +0 -105
  135. package/dist/observable/index.ts.js +0 -1
  136. package/dist/observable-341a0506.js +0 -109
  137. package/dist/observable-cfedfa30.mjs +0 -106
  138. package/dist/resolveHTTPResponse-455f1e51.mjs +0 -293
  139. package/dist/resolveHTTPResponse-5d90abc5.js +0 -297
  140. package/dist/router-4e50a6ac.js +0 -1104
  141. package/dist/router-a3db8f3a.mjs +0 -1094
  142. package/dist/rpc/index.ts.js +0 -1
  143. package/dist/shared/index.ts.js +0 -1
  144. package/dist/subscription.ts.js +0 -1
  145. package/dist/transformTRPCResponse-0c261655.js +0 -29
  146. package/dist/transformTRPCResponse-747b9a68.mjs +0 -27
@@ -0,0 +1,876 @@
1
+ import { a as assertNotBrowser, g as getHTTPStatusCodeFromError } from './resolveHTTPResponse-83703ee8.mjs';
2
+ import { T as TRPCError, a as getCauseFromUnknown, g as getErrorFromUnknown } from './TRPCError-6f61762c.mjs';
3
+ import { T as TRPC_ERROR_CODES_BY_KEY } from './codes-aaa7d554.mjs';
4
+ import { c as createProxy } from './index-47817162.mjs';
5
+
6
+ assertNotBrowser();
7
+
8
+ /* eslint-disable @typescript-eslint/no-explicit-any */ /**
9
+ * @public
10
+ */ /**
11
+ * @internal
12
+ */ function getDataTransformer$1(transformer) {
13
+ if ('input' in transformer) {
14
+ return transformer;
15
+ }
16
+ return {
17
+ input: transformer,
18
+ output: transformer
19
+ };
20
+ }
21
+ /**
22
+ * @internal
23
+ */ const defaultTransformer = {
24
+ _default: true,
25
+ input: {
26
+ serialize: (obj)=>obj,
27
+ deserialize: (obj)=>obj
28
+ },
29
+ output: {
30
+ serialize: (obj)=>obj,
31
+ deserialize: (obj)=>obj
32
+ }
33
+ };
34
+
35
+ const defaultFormatter = ({ shape })=>{
36
+ return shape;
37
+ };
38
+
39
+ /**
40
+ * @deprecated
41
+ */ const middlewareMarker$1 = 'middlewareMarker';
42
+
43
+ assertNotBrowser();
44
+ function getParseFn$1(procedureParser) {
45
+ const parser = procedureParser;
46
+ if (typeof parser === 'function') {
47
+ // ProcedureParserCustomValidatorEsque
48
+ return parser;
49
+ }
50
+ if (typeof parser.parseAsync === 'function') {
51
+ // ProcedureParserZodEsque
52
+ return parser.parseAsync.bind(parser);
53
+ }
54
+ if (typeof parser.parse === 'function') {
55
+ // ProcedureParserZodEsque
56
+ return parser.parse.bind(parser);
57
+ }
58
+ if (typeof parser.validateSync === 'function') {
59
+ // ProcedureParserYupEsque
60
+ return parser.validateSync.bind(parser);
61
+ }
62
+ if (typeof parser.create === 'function') {
63
+ // ProcedureParserSuperstructEsque
64
+ return parser.create.bind(parser);
65
+ }
66
+ throw new Error('Could not find a validator fn');
67
+ }
68
+ /**
69
+ * @internal
70
+ * @deprecated
71
+ */ class Procedure {
72
+ _def() {
73
+ return {
74
+ middlewares: this.middlewares,
75
+ resolver: this.resolver,
76
+ inputParser: this.inputParser,
77
+ outputParser: this.outputParser,
78
+ meta: this.meta
79
+ };
80
+ }
81
+ async parseInput(rawInput) {
82
+ try {
83
+ return await this.parseInputFn(rawInput);
84
+ } catch (cause) {
85
+ throw new TRPCError({
86
+ code: 'BAD_REQUEST',
87
+ cause: getCauseFromUnknown(cause)
88
+ });
89
+ }
90
+ }
91
+ async parseOutput(rawOutput) {
92
+ try {
93
+ return await this.parseOutputFn(rawOutput);
94
+ } catch (cause) {
95
+ throw new TRPCError({
96
+ code: 'INTERNAL_SERVER_ERROR',
97
+ cause: getCauseFromUnknown(cause),
98
+ message: 'Output validation failed'
99
+ });
100
+ }
101
+ }
102
+ /**
103
+ * Trigger middlewares in order, parse raw input, call resolver & parse raw output
104
+ * @internal
105
+ */ async call(opts) {
106
+ // wrap the actual resolver and treat as the last "middleware"
107
+ const middlewaresWithResolver = this.middlewares.concat([
108
+ async ({ ctx })=>{
109
+ const input = await this.parseInput(opts.rawInput);
110
+ const rawOutput = await this.resolver({
111
+ ...opts,
112
+ ctx,
113
+ input
114
+ });
115
+ const data = await this.parseOutput(rawOutput);
116
+ return {
117
+ marker: middlewareMarker$1,
118
+ ok: true,
119
+ data,
120
+ ctx
121
+ };
122
+ },
123
+ ]);
124
+ // run the middlewares recursively with the resolver as the last one
125
+ const callRecursive = async (callOpts = {
126
+ index: 0,
127
+ ctx: opts.ctx
128
+ })=>{
129
+ try {
130
+ const result = await middlewaresWithResolver[callOpts.index]({
131
+ ctx: callOpts.ctx,
132
+ type: opts.type,
133
+ path: opts.path,
134
+ rawInput: opts.rawInput,
135
+ meta: this.meta,
136
+ next: async (nextOpts)=>{
137
+ return await callRecursive({
138
+ index: callOpts.index + 1,
139
+ ctx: nextOpts ? nextOpts.ctx : callOpts.ctx
140
+ });
141
+ }
142
+ });
143
+ return result;
144
+ } catch (cause) {
145
+ return {
146
+ ctx: callOpts.ctx,
147
+ ok: false,
148
+ error: getErrorFromUnknown(cause),
149
+ marker: middlewareMarker$1
150
+ };
151
+ }
152
+ };
153
+ // there's always at least one "next" since we wrap this.resolver in a middleware
154
+ const result = await callRecursive();
155
+ if (!result) {
156
+ throw new TRPCError({
157
+ code: 'INTERNAL_SERVER_ERROR',
158
+ message: 'No result from middlewares - did you forget to `return next()`?'
159
+ });
160
+ }
161
+ if (!result.ok) {
162
+ // re-throw original error
163
+ throw result.error;
164
+ }
165
+ return result.data;
166
+ }
167
+ /**
168
+ * Create new procedure with passed middlewares
169
+ * @param middlewares
170
+ */ inheritMiddlewares(middlewares) {
171
+ const Constructor = this.constructor;
172
+ const instance = new Constructor({
173
+ middlewares: [
174
+ ...middlewares,
175
+ ...this.middlewares
176
+ ],
177
+ resolver: this.resolver,
178
+ inputParser: this.inputParser,
179
+ outputParser: this.outputParser,
180
+ meta: this.meta
181
+ });
182
+ return instance;
183
+ }
184
+ constructor(opts){
185
+ this.middlewares = opts.middlewares;
186
+ this.resolver = opts.resolver;
187
+ this.inputParser = opts.inputParser;
188
+ this.parseInputFn = getParseFn$1(this.inputParser);
189
+ this.outputParser = opts.outputParser;
190
+ this.parseOutputFn = getParseFn$1(this.outputParser);
191
+ this.meta = opts.meta;
192
+ }
193
+ }
194
+ function createProcedure(opts) {
195
+ const inputParser = 'input' in opts ? opts.input : (input)=>{
196
+ if (input != null) {
197
+ throw new TRPCError({
198
+ code: 'BAD_REQUEST',
199
+ message: 'No input expected'
200
+ });
201
+ }
202
+ return undefined;
203
+ };
204
+ const outputParser = 'output' in opts && opts.output ? opts.output : (output)=>output;
205
+ return new Procedure({
206
+ inputParser: inputParser,
207
+ resolver: opts.resolve,
208
+ middlewares: [],
209
+ outputParser: outputParser,
210
+ meta: opts.meta
211
+ });
212
+ }
213
+
214
+ function getParseFn(procedureParser) {
215
+ const parser = procedureParser;
216
+ if (typeof parser === 'function') {
217
+ // ProcedureParserCustomValidatorEsque
218
+ return parser;
219
+ }
220
+ if (typeof parser.parseAsync === 'function') {
221
+ // ProcedureParserZodEsque
222
+ return parser.parseAsync.bind(parser);
223
+ }
224
+ if (typeof parser.parse === 'function') {
225
+ // ProcedureParserZodEsque
226
+ return parser.parse.bind(parser);
227
+ }
228
+ if (typeof parser.validateSync === 'function') {
229
+ // ProcedureParserYupEsque
230
+ return parser.validateSync.bind(parser);
231
+ }
232
+ if (typeof parser.create === 'function') {
233
+ // ProcedureParserSuperstructEsque
234
+ return parser.create.bind(parser);
235
+ }
236
+ throw new Error('Could not find a validator fn');
237
+ }
238
+ /**
239
+ * @deprecated only for backwards compat
240
+ * @internal
241
+ */ function getParseFnOrPassThrough(procedureParser) {
242
+ if (!procedureParser) {
243
+ return (v)=>v;
244
+ }
245
+ return getParseFn(procedureParser);
246
+ }
247
+
248
+ /**
249
+ * Ensures there are no duplicate keys when building a procedure.
250
+ */ function mergeWithoutOverrides(obj1, ...objs) {
251
+ const newObj = Object.assign(Object.create(null), obj1);
252
+ for (const overrides of objs){
253
+ for(const key in overrides){
254
+ if (key in newObj && newObj[key] !== overrides[key]) {
255
+ throw new Error(`Duplicate key ${key}`);
256
+ }
257
+ newObj[key] = overrides[key];
258
+ }
259
+ }
260
+ return newObj;
261
+ }
262
+
263
+ /**
264
+ * @internal
265
+ */ const middlewareMarker = 'middlewareMarker';
266
+
267
+ function createNewBuilder(def1, def2) {
268
+ const { middlewares =[] , ...rest } = def2;
269
+ // TODO: maybe have a fn here to warn about calls
270
+ return createBuilder({
271
+ ...mergeWithoutOverrides(def1, rest),
272
+ middlewares: [
273
+ ...def1.middlewares,
274
+ ...middlewares
275
+ ]
276
+ });
277
+ }
278
+ function createBuilder(initDef) {
279
+ const _def = initDef || {
280
+ middlewares: []
281
+ };
282
+ return {
283
+ _def,
284
+ input (input) {
285
+ const parser = getParseFn(input);
286
+ return createNewBuilder(_def, {
287
+ input,
288
+ middlewares: [
289
+ createInputMiddleware(parser)
290
+ ]
291
+ });
292
+ },
293
+ output (output) {
294
+ const parseOutput = getParseFn(output);
295
+ return createNewBuilder(_def, {
296
+ output,
297
+ middlewares: [
298
+ createOutputMiddleware(parseOutput)
299
+ ]
300
+ });
301
+ },
302
+ meta (meta) {
303
+ return createNewBuilder(_def, {
304
+ meta: meta
305
+ });
306
+ },
307
+ unstable_concat (builder) {
308
+ return createNewBuilder(_def, builder._def);
309
+ },
310
+ use (middleware) {
311
+ return createNewBuilder(_def, {
312
+ middlewares: [
313
+ middleware
314
+ ]
315
+ });
316
+ },
317
+ query (resolver) {
318
+ return createResolver({
319
+ ..._def,
320
+ query: true
321
+ }, resolver);
322
+ },
323
+ mutation (resolver) {
324
+ return createResolver({
325
+ ..._def,
326
+ mutation: true
327
+ }, resolver);
328
+ },
329
+ subscription (resolver) {
330
+ return createResolver({
331
+ ..._def,
332
+ subscription: true
333
+ }, resolver);
334
+ }
335
+ };
336
+ }
337
+ function createInputMiddleware(parse) {
338
+ return async function inputMiddleware({ next , rawInput }) {
339
+ let input;
340
+ try {
341
+ input = await parse(rawInput);
342
+ } catch (cause) {
343
+ throw new TRPCError({
344
+ code: 'BAD_REQUEST',
345
+ cause: getCauseFromUnknown(cause)
346
+ });
347
+ }
348
+ // TODO fix this typing?
349
+ return next({
350
+ input
351
+ });
352
+ };
353
+ }
354
+ function createOutputMiddleware(parse) {
355
+ return async function outputMiddleware({ next }) {
356
+ const result = await next();
357
+ if (!result.ok) {
358
+ // pass through failures without validating
359
+ return result;
360
+ }
361
+ try {
362
+ const data = await parse(result.data);
363
+ return {
364
+ ...result,
365
+ data
366
+ };
367
+ } catch (cause) {
368
+ throw new TRPCError({
369
+ message: 'Output validation failed',
370
+ code: 'INTERNAL_SERVER_ERROR',
371
+ cause: getCauseFromUnknown(cause)
372
+ });
373
+ }
374
+ };
375
+ }
376
+ function createResolver(_def, resolver) {
377
+ const finalBuilder = createNewBuilder(_def, {
378
+ resolver,
379
+ middlewares: [
380
+ async function resolveMiddleware(opts) {
381
+ const data = await resolver(opts);
382
+ return {
383
+ marker: middlewareMarker,
384
+ ok: true,
385
+ data,
386
+ ctx: opts.ctx
387
+ };
388
+ },
389
+ ]
390
+ });
391
+ return createProcedureCaller(finalBuilder._def);
392
+ }
393
+ const codeblock = `
394
+ If you want to call this function on the server, you do the following:
395
+ This is a client-only function.
396
+
397
+ const caller = appRouter.createCaller({
398
+ /* ... your context */
399
+ });
400
+
401
+ const result = await caller.call('myProcedure', input);
402
+ `.trim();
403
+ function createProcedureCaller(_def) {
404
+ const procedure = async function resolve(opts) {
405
+ // is direct server-side call
406
+ if (!opts || !('rawInput' in opts)) {
407
+ throw new Error(codeblock);
408
+ }
409
+ // run the middlewares recursively with the resolver as the last one
410
+ const callRecursive = async (callOpts = {
411
+ index: 0,
412
+ ctx: opts.ctx
413
+ })=>{
414
+ try {
415
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
416
+ const middleware = _def.middlewares[callOpts.index];
417
+ const result = await middleware({
418
+ ctx: callOpts.ctx,
419
+ type: opts.type,
420
+ path: opts.path,
421
+ rawInput: opts.rawInput,
422
+ meta: _def.meta,
423
+ input: callOpts.input,
424
+ next: async (nextOpts)=>{
425
+ return await callRecursive({
426
+ index: callOpts.index + 1,
427
+ ctx: nextOpts && 'ctx' in nextOpts ? {
428
+ ...callOpts.ctx,
429
+ ...nextOpts.ctx
430
+ } : callOpts.ctx,
431
+ input: nextOpts && 'input' in nextOpts ? nextOpts.input : callOpts.input
432
+ });
433
+ }
434
+ });
435
+ return result;
436
+ } catch (cause) {
437
+ return {
438
+ ok: false,
439
+ error: getErrorFromUnknown(cause),
440
+ marker: middlewareMarker
441
+ };
442
+ }
443
+ };
444
+ // there's always at least one "next" since we wrap this.resolver in a middleware
445
+ const result = await callRecursive();
446
+ if (!result) {
447
+ throw new TRPCError({
448
+ code: 'INTERNAL_SERVER_ERROR',
449
+ message: 'No result from middlewares - did you forget to `return next()`?'
450
+ });
451
+ }
452
+ if (!result.ok) {
453
+ // re-throw original error
454
+ throw result.error;
455
+ }
456
+ return result.data;
457
+ };
458
+ procedure._def = _def;
459
+ procedure.meta = _def.meta;
460
+ return procedure;
461
+ }
462
+
463
+ /**
464
+ * Create an object without inheriting anything from `Object.prototype`
465
+ * @internal
466
+ */ function omitPrototype(obj1) {
467
+ return Object.assign(Object.create(null), obj1);
468
+ }
469
+
470
+ const procedureTypes = [
471
+ 'query',
472
+ 'mutation',
473
+ 'subscription'
474
+ ];
475
+
476
+ function isRouter(procedureOrRouter) {
477
+ return 'router' in procedureOrRouter._def;
478
+ }
479
+ const emptyRouter = {
480
+ _ctx: null,
481
+ _errorShape: null,
482
+ _meta: null,
483
+ queries: {},
484
+ mutations: {},
485
+ subscriptions: {},
486
+ errorFormatter: defaultFormatter,
487
+ transformer: defaultTransformer
488
+ };
489
+ /**
490
+ *
491
+ * @internal
492
+ */ function createRouterFactory(defaults) {
493
+ return function createRouterInner(opts) {
494
+ const routerProcedures = omitPrototype({});
495
+ function recursiveGetPaths(procedures, path = '') {
496
+ for (const [key, procedureOrRouter] of Object.entries(procedures ?? {})){
497
+ const newPath = `${path}${key}`;
498
+ if (isRouter(procedureOrRouter)) {
499
+ recursiveGetPaths(procedureOrRouter._def.procedures, `${newPath}.`);
500
+ continue;
501
+ }
502
+ routerProcedures[newPath] = procedureOrRouter;
503
+ }
504
+ }
505
+ recursiveGetPaths(opts);
506
+ const result = mergeWithoutOverrides({
507
+ transformer: defaults?.transformer ?? defaultTransformer,
508
+ errorFormatter: defaults?.errorFormatter ?? defaultFormatter
509
+ }, {
510
+ procedures: routerProcedures
511
+ });
512
+ const _def = {
513
+ router: true,
514
+ legacy: {},
515
+ procedures: {},
516
+ ...emptyRouter,
517
+ ...result,
518
+ record: opts,
519
+ queries: Object.entries(result.procedures || {}).filter((pair)=>pair[1]._def.query).reduce((acc, [key, val])=>({
520
+ ...acc,
521
+ [key]: val
522
+ }), {}),
523
+ mutations: Object.entries(result.procedures || {}).filter((pair)=>pair[1]._def.mutation).reduce((acc, [key, val])=>({
524
+ ...acc,
525
+ [key]: val
526
+ }), {}),
527
+ subscriptions: Object.entries(result.procedures || {}).filter((pair)=>pair[1]._def.subscription).reduce((acc, [key, val])=>({
528
+ ...acc,
529
+ [key]: val
530
+ }), {}),
531
+ routers: Object.entries(result.procedures || {}).filter((pair)=>pair[1]._def._router).reduce((acc, [key, val])=>({
532
+ ...acc,
533
+ [key]: val
534
+ }), {})
535
+ };
536
+ const router = {
537
+ ...opts,
538
+ _def,
539
+ transformer: _def.transformer,
540
+ errorFormatter: _def.errorFormatter,
541
+ createCaller (ctx) {
542
+ const proxy = createProxy(({ path , args })=>{
543
+ // interop mode
544
+ if (path.length === 1 && procedureTypes.includes(path[0])) {
545
+ return callProcedure({
546
+ procedures: _def.procedures,
547
+ path: args[0],
548
+ rawInput: args[1],
549
+ ctx,
550
+ type: path[0]
551
+ });
552
+ }
553
+ const fullPath = path.join('.');
554
+ const procedure = _def.procedures[fullPath];
555
+ let type = 'query';
556
+ if (procedure._def.mutation) {
557
+ type = 'mutation';
558
+ } else if (procedure._def.subscription) {
559
+ type = 'subscription';
560
+ }
561
+ return procedure({
562
+ path: fullPath,
563
+ rawInput: args[0],
564
+ ctx,
565
+ type
566
+ });
567
+ });
568
+ return proxy;
569
+ },
570
+ getErrorShape (opts) {
571
+ const { path , error } = opts;
572
+ const { code } = opts.error;
573
+ const shape = {
574
+ message: error.message,
575
+ code: TRPC_ERROR_CODES_BY_KEY[code],
576
+ data: {
577
+ code,
578
+ httpStatus: getHTTPStatusCodeFromError(error)
579
+ }
580
+ };
581
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
582
+ shape.data.stack = opts.error.stack;
583
+ }
584
+ if (typeof path === 'string') {
585
+ shape.data.path = path;
586
+ }
587
+ return this._def.errorFormatter({
588
+ ...opts,
589
+ shape
590
+ });
591
+ }
592
+ };
593
+ return router;
594
+ };
595
+ }
596
+ /**
597
+ * @internal
598
+ */ function callProcedure(opts) {
599
+ const { type , path } = opts;
600
+ if (!(path in opts.procedures) || !opts.procedures[path]?._def[type]) {
601
+ throw new TRPCError({
602
+ code: 'NOT_FOUND',
603
+ message: `No "${type}"-procedure on path "${path}"`
604
+ });
605
+ }
606
+ const procedure = opts.procedures[path];
607
+ return procedure(opts);
608
+ }
609
+
610
+ function migrateProcedure(oldProc, type) {
611
+ const def = oldProc._def();
612
+ const inputParser = getParseFnOrPassThrough(def.inputParser);
613
+ const outputParser = getParseFnOrPassThrough(def.outputParser);
614
+ const inputMiddleware = createInputMiddleware(inputParser);
615
+ const builder = createBuilder({
616
+ input: def.inputParser,
617
+ middlewares: [
618
+ ...def.middlewares,
619
+ inputMiddleware,
620
+ createOutputMiddleware(outputParser),
621
+ ],
622
+ meta: def.meta,
623
+ output: def.outputParser,
624
+ mutation: type === 'mutation',
625
+ query: type === 'query',
626
+ subscription: type === 'subscription'
627
+ });
628
+ const proc = builder[type]((opts)=>def.resolver(opts));
629
+ return proc;
630
+ }
631
+ function migrateRouter(oldRouter) {
632
+ const errorFormatter = oldRouter._def.errorFormatter;
633
+ const transformer = oldRouter._def.transformer;
634
+ const queries = {};
635
+ const mutations = {};
636
+ const subscriptions = {};
637
+ for (const [name, procedure] of Object.entries(oldRouter._def.queries)){
638
+ queries[name] = migrateProcedure(procedure, 'query');
639
+ }
640
+ for (const [name1, procedure1] of Object.entries(oldRouter._def.mutations)){
641
+ mutations[name1] = migrateProcedure(procedure1, 'mutation');
642
+ }
643
+ for (const [name2, procedure2] of Object.entries(oldRouter._def.subscriptions)){
644
+ subscriptions[name2] = migrateProcedure(procedure2, 'subscription');
645
+ }
646
+ const procedures = mergeWithoutOverrides(queries, mutations, subscriptions);
647
+ const newRouter = createRouterFactory({
648
+ transformer,
649
+ errorFormatter
650
+ })(procedures);
651
+ return newRouter;
652
+ }
653
+
654
+ assertNotBrowser();
655
+ function getDataTransformer(transformer) {
656
+ if ('input' in transformer) {
657
+ return transformer;
658
+ }
659
+ return {
660
+ input: transformer,
661
+ output: transformer
662
+ };
663
+ }
664
+ const PROCEDURE_DEFINITION_MAP = {
665
+ query: 'queries',
666
+ mutation: 'mutations',
667
+ subscription: 'subscriptions'
668
+ };
669
+ function safeObject(...args) {
670
+ return Object.assign(Object.create(null), ...args);
671
+ }
672
+ /**
673
+ * @internal The type signature of this class may change without warning.
674
+ * @deprecated
675
+ */ class Router {
676
+ static prefixProcedures(procedures, prefix) {
677
+ const eps = safeObject();
678
+ for (const [key, procedure] of Object.entries(procedures)){
679
+ eps[prefix + key] = procedure;
680
+ }
681
+ return eps;
682
+ }
683
+ query(path, procedure) {
684
+ const router = new Router({
685
+ queries: safeObject({
686
+ [path]: createProcedure(procedure)
687
+ })
688
+ });
689
+ return this.merge(router);
690
+ }
691
+ mutation(path, procedure) {
692
+ const router = new Router({
693
+ mutations: safeObject({
694
+ [path]: createProcedure(procedure)
695
+ })
696
+ });
697
+ return this.merge(router);
698
+ }
699
+ subscription(path, procedure) {
700
+ const router = new Router({
701
+ subscriptions: safeObject({
702
+ [path]: createProcedure(procedure)
703
+ })
704
+ });
705
+ return this.merge(router);
706
+ }
707
+ merge(prefixOrRouter, maybeRouter) {
708
+ let prefix = '';
709
+ let childRouter;
710
+ if (typeof prefixOrRouter === 'string' && maybeRouter instanceof Router) {
711
+ prefix = prefixOrRouter;
712
+ childRouter = maybeRouter;
713
+ } else if (prefixOrRouter instanceof Router) {
714
+ childRouter = prefixOrRouter;
715
+ } else {
716
+ throw new Error('Invalid args');
717
+ }
718
+ const duplicateQueries = Object.keys(childRouter._def.queries).filter((key)=>!!this._def['queries'][prefix + key]);
719
+ const duplicateMutations = Object.keys(childRouter._def.mutations).filter((key)=>!!this._def['mutations'][prefix + key]);
720
+ const duplicateSubscriptions = Object.keys(childRouter._def.subscriptions).filter((key)=>!!this._def['subscriptions'][prefix + key]);
721
+ const duplicates = [
722
+ ...duplicateQueries,
723
+ ...duplicateMutations,
724
+ ...duplicateSubscriptions,
725
+ ];
726
+ if (duplicates.length) {
727
+ throw new Error(`Duplicate endpoint(s): ${duplicates.join(', ')}`);
728
+ }
729
+ const mergeProcedures = (defs)=>{
730
+ const newDefs = safeObject();
731
+ for (const [key, procedure] of Object.entries(defs)){
732
+ const newProcedure = procedure.inheritMiddlewares(this._def.middlewares);
733
+ newDefs[key] = newProcedure;
734
+ }
735
+ return Router.prefixProcedures(newDefs, prefix);
736
+ };
737
+ return new Router({
738
+ ...this._def,
739
+ queries: safeObject(this._def.queries, mergeProcedures(childRouter._def.queries)),
740
+ mutations: safeObject(this._def.mutations, mergeProcedures(childRouter._def.mutations)),
741
+ subscriptions: safeObject(this._def.subscriptions, mergeProcedures(childRouter._def.subscriptions))
742
+ });
743
+ }
744
+ /**
745
+ * Invoke procedure. Only for internal use within library.
746
+ */ async call(opts) {
747
+ const { type , path } = opts;
748
+ const defTarget = PROCEDURE_DEFINITION_MAP[type];
749
+ const defs = this._def[defTarget];
750
+ const procedure = defs[path];
751
+ if (!procedure) {
752
+ throw new TRPCError({
753
+ code: 'NOT_FOUND',
754
+ message: `No "${type}"-procedure on path "${path}"`
755
+ });
756
+ }
757
+ return procedure.call(opts);
758
+ }
759
+ createCaller(ctx) {
760
+ return {
761
+ query: (path, ...args)=>{
762
+ return this.call({
763
+ type: 'query',
764
+ ctx,
765
+ path,
766
+ rawInput: args[0]
767
+ });
768
+ },
769
+ mutation: (path, ...args)=>{
770
+ return this.call({
771
+ type: 'mutation',
772
+ ctx,
773
+ path,
774
+ rawInput: args[0]
775
+ });
776
+ },
777
+ subscription: (path, ...args)=>{
778
+ return this.call({
779
+ type: 'subscription',
780
+ ctx,
781
+ path,
782
+ rawInput: args[0]
783
+ });
784
+ }
785
+ };
786
+ }
787
+ /**
788
+ * Function to be called before any procedure is invoked
789
+ * @link https://trpc.io/docs/middlewares
790
+ */ middleware(middleware) {
791
+ return new Router({
792
+ ...this._def,
793
+ middlewares: [
794
+ ...this._def.middlewares,
795
+ middleware
796
+ ]
797
+ });
798
+ }
799
+ /**
800
+ * Format errors
801
+ * @link https://trpc.io/docs/error-formatting
802
+ */ formatError(errorFormatter) {
803
+ if (this._def.errorFormatter !== defaultFormatter) {
804
+ throw new Error('You seem to have double `formatError()`-calls in your router tree');
805
+ }
806
+ return new Router({
807
+ ...this._def,
808
+ errorFormatter: errorFormatter
809
+ });
810
+ }
811
+ getErrorShape(opts) {
812
+ const { path , error } = opts;
813
+ const { code } = opts.error;
814
+ const shape = {
815
+ message: error.message,
816
+ code: TRPC_ERROR_CODES_BY_KEY[code],
817
+ data: {
818
+ code,
819
+ httpStatus: getHTTPStatusCodeFromError(error)
820
+ }
821
+ };
822
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
823
+ shape.data.stack = opts.error.stack;
824
+ }
825
+ if (typeof path === 'string') {
826
+ shape.data.path = path;
827
+ }
828
+ return this._def.errorFormatter({
829
+ ...opts,
830
+ shape
831
+ });
832
+ }
833
+ /**
834
+ * Add data transformer to serialize/deserialize input args + output
835
+ * @link https://trpc.io/docs/data-transformers
836
+ */ transformer(_transformer) {
837
+ const transformer = getDataTransformer(_transformer);
838
+ if (this._def.transformer !== defaultTransformer) {
839
+ throw new Error('You seem to have double `transformer()`-calls in your router tree');
840
+ }
841
+ return new Router({
842
+ ...this._def,
843
+ transformer
844
+ });
845
+ }
846
+ /**
847
+ * Flattens the generics of TQueries/TMutations/TSubscriptions.
848
+ * ⚠️ Experimental - might disappear. ⚠️
849
+ *
850
+ * @alpha
851
+ */ flat() {
852
+ return this;
853
+ }
854
+ /**
855
+ * Interop mode for v9.x -> v10.x
856
+ */ interop() {
857
+ return migrateRouter(this);
858
+ }
859
+ constructor(def){
860
+ this._def = {
861
+ queries: def?.queries ?? safeObject(),
862
+ mutations: def?.mutations ?? safeObject(),
863
+ subscriptions: def?.subscriptions ?? safeObject(),
864
+ middlewares: def?.middlewares ?? [],
865
+ errorFormatter: def?.errorFormatter ?? defaultFormatter,
866
+ transformer: def?.transformer ?? defaultTransformer
867
+ };
868
+ }
869
+ }
870
+ /**
871
+ * @deprecated
872
+ */ function router() {
873
+ return new Router();
874
+ }
875
+
876
+ export { defaultTransformer as a, createBuilder as b, createRouterFactory as c, defaultFormatter as d, callProcedure as e, getDataTransformer$1 as g, mergeWithoutOverrides as m, procedureTypes as p, router as r };