@trpc/server 10.0.0-proxy-alpha.76 → 10.0.0-proxy-alpha.77

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 (56) hide show
  1. package/dist/{TRPCError-281ac25a.mjs → TRPCError-e99e7cbe.mjs} +1 -1
  2. package/dist/adapters/aws-lambda/index.js +2 -2
  3. package/dist/adapters/aws-lambda/index.mjs +3 -3
  4. package/dist/adapters/express.js +4 -3
  5. package/dist/adapters/express.mjs +5 -4
  6. package/dist/adapters/fastify/index.js +3 -2
  7. package/dist/adapters/fastify/index.mjs +4 -3
  8. package/dist/adapters/fetch/index.js +3 -2
  9. package/dist/adapters/fetch/index.mjs +4 -3
  10. package/dist/adapters/next.js +4 -3
  11. package/dist/adapters/next.mjs +5 -4
  12. package/dist/adapters/node-http/index.js +4 -3
  13. package/dist/adapters/node-http/index.mjs +5 -4
  14. package/dist/adapters/standalone.js +4 -3
  15. package/dist/adapters/standalone.mjs +5 -4
  16. package/dist/adapters/ws.mjs +1 -1
  17. package/dist/core/index.d.ts +1 -1
  18. package/dist/core/index.d.ts.map +1 -1
  19. package/dist/core/internals/__generated__/mergeRoutersGeneric.d.ts +0 -40
  20. package/dist/core/internals/__generated__/mergeRoutersGeneric.d.ts.map +1 -1
  21. package/dist/core/internals/procedureBuilder.d.ts.map +1 -1
  22. package/dist/core/procedure.d.ts +3 -0
  23. package/dist/core/procedure.d.ts.map +1 -1
  24. package/dist/core/router.d.ts +17 -32
  25. package/dist/core/router.d.ts.map +1 -1
  26. package/dist/core/types.d.ts +5 -5
  27. package/dist/core/types.d.ts.map +1 -1
  28. package/dist/deprecated/interop.d.ts +20 -43
  29. package/dist/deprecated/interop.d.ts.map +1 -1
  30. package/dist/http/resolveHTTPResponse.d.ts.map +1 -1
  31. package/dist/index.js +23 -23
  32. package/dist/index.mjs +5 -5
  33. package/dist/{nodeHTTPRequestHandler-c3dbb39e.js → nodeHTTPRequestHandler-7295e689.js} +1 -1
  34. package/dist/{nodeHTTPRequestHandler-c30139c8.mjs → nodeHTTPRequestHandler-e4a030ab.mjs} +2 -2
  35. package/dist/{router-6b03ff5f.mjs → resolveHTTPResponse-3955937e.mjs} +411 -601
  36. package/dist/{router-da6086c3.js → resolveHTTPResponse-9a70b9b2.js} +414 -601
  37. package/dist/router-4f222389.mjs +450 -0
  38. package/dist/router-fee6849a.js +452 -0
  39. package/dist/shared/index.d.ts +0 -1
  40. package/dist/shared/index.d.ts.map +1 -1
  41. package/dist/subscription.mjs +1 -1
  42. package/dist/types.d.ts +0 -10
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +2 -2
  45. package/src/core/index.ts +4 -0
  46. package/src/core/internals/__generated__/mergeRoutersGeneric.ts +0 -40
  47. package/src/core/internals/procedureBuilder.ts +9 -6
  48. package/src/core/procedure.ts +3 -1
  49. package/src/core/router.ts +22 -38
  50. package/src/core/types.ts +7 -18
  51. package/src/deprecated/interop.ts +30 -78
  52. package/src/http/resolveHTTPResponse.ts +8 -2
  53. package/src/shared/index.ts +0 -2
  54. package/src/types.ts +0 -12
  55. package/dist/resolveHTTPResponse-1b339cff.mjs +0 -260
  56. package/dist/resolveHTTPResponse-d7a8a210.js +0 -264
@@ -0,0 +1,450 @@
1
+ import { f as assertNotBrowser, m as mergeWithoutOverrides, c as createRouterFactory, k as getParseFnOrPassThrough, i as createInputMiddleware, b as createBuilder, j as createOutputMiddleware, d as defaultFormatter, l as getHTTPStatusCodeFromError, a as defaultTransformer } from './resolveHTTPResponse-3955937e.mjs';
2
+ import { T as TRPC_ERROR_CODES_BY_KEY } from './codes-aaa7d554.mjs';
3
+ import { T as TRPCError, g as getCauseFromUnknown, a as getTRPCErrorFromUnknown } from './TRPCError-e99e7cbe.mjs';
4
+
5
+ assertNotBrowser();
6
+
7
+ /**
8
+ * @deprecated
9
+ */ const middlewareMarker = 'middlewareMarker';
10
+
11
+ assertNotBrowser();
12
+ function getParseFn(procedureParser) {
13
+ const parser = procedureParser;
14
+ if (typeof parser === 'function') {
15
+ // ProcedureParserCustomValidatorEsque
16
+ return parser;
17
+ }
18
+ if (typeof parser.parseAsync === 'function') {
19
+ // ProcedureParserZodEsque
20
+ return parser.parseAsync.bind(parser);
21
+ }
22
+ if (typeof parser.parse === 'function') {
23
+ // ProcedureParserZodEsque
24
+ return parser.parse.bind(parser);
25
+ }
26
+ if (typeof parser.validateSync === 'function') {
27
+ // ProcedureParserYupEsque
28
+ return parser.validateSync.bind(parser);
29
+ }
30
+ if (typeof parser.create === 'function') {
31
+ // ProcedureParserSuperstructEsque
32
+ return parser.create.bind(parser);
33
+ }
34
+ throw new Error('Could not find a validator fn');
35
+ }
36
+ /**
37
+ * @internal
38
+ * @deprecated
39
+ */ class Procedure {
40
+ _def() {
41
+ return {
42
+ middlewares: this.middlewares,
43
+ resolver: this.resolver,
44
+ inputParser: this.inputParser,
45
+ outputParser: this.outputParser,
46
+ meta: this.meta
47
+ };
48
+ }
49
+ async parseInput(rawInput) {
50
+ try {
51
+ return await this.parseInputFn(rawInput);
52
+ } catch (cause) {
53
+ throw new TRPCError({
54
+ code: 'BAD_REQUEST',
55
+ cause: getCauseFromUnknown(cause)
56
+ });
57
+ }
58
+ }
59
+ async parseOutput(rawOutput) {
60
+ try {
61
+ return await this.parseOutputFn(rawOutput);
62
+ } catch (cause) {
63
+ throw new TRPCError({
64
+ code: 'INTERNAL_SERVER_ERROR',
65
+ cause: getCauseFromUnknown(cause),
66
+ message: 'Output validation failed'
67
+ });
68
+ }
69
+ }
70
+ /**
71
+ * Trigger middlewares in order, parse raw input, call resolver & parse raw output
72
+ * @internal
73
+ */ async call(opts) {
74
+ // wrap the actual resolver and treat as the last "middleware"
75
+ const middlewaresWithResolver = this.middlewares.concat([
76
+ async ({ ctx })=>{
77
+ const input = await this.parseInput(opts.rawInput);
78
+ const rawOutput = await this.resolver({
79
+ ...opts,
80
+ ctx,
81
+ input
82
+ });
83
+ const data = await this.parseOutput(rawOutput);
84
+ return {
85
+ marker: middlewareMarker,
86
+ ok: true,
87
+ data,
88
+ ctx
89
+ };
90
+ },
91
+ ]);
92
+ // run the middlewares recursively with the resolver as the last one
93
+ const callRecursive = async (callOpts = {
94
+ index: 0,
95
+ ctx: opts.ctx
96
+ })=>{
97
+ try {
98
+ const result = await middlewaresWithResolver[callOpts.index]({
99
+ ctx: callOpts.ctx,
100
+ type: opts.type,
101
+ path: opts.path,
102
+ rawInput: opts.rawInput,
103
+ meta: this.meta,
104
+ next: async (nextOpts)=>{
105
+ return await callRecursive({
106
+ index: callOpts.index + 1,
107
+ ctx: nextOpts ? nextOpts.ctx : callOpts.ctx
108
+ });
109
+ }
110
+ });
111
+ return result;
112
+ } catch (cause) {
113
+ return {
114
+ ctx: callOpts.ctx,
115
+ ok: false,
116
+ error: getTRPCErrorFromUnknown(cause),
117
+ marker: middlewareMarker
118
+ };
119
+ }
120
+ };
121
+ // there's always at least one "next" since we wrap this.resolver in a middleware
122
+ const result = await callRecursive();
123
+ if (!result) {
124
+ throw new TRPCError({
125
+ code: 'INTERNAL_SERVER_ERROR',
126
+ message: 'No result from middlewares - did you forget to `return next()`?'
127
+ });
128
+ }
129
+ if (!result.ok) {
130
+ // re-throw original error
131
+ throw result.error;
132
+ }
133
+ return result.data;
134
+ }
135
+ /**
136
+ * Create new procedure with passed middlewares
137
+ * @param middlewares
138
+ */ inheritMiddlewares(middlewares) {
139
+ const Constructor = this.constructor;
140
+ const instance = new Constructor({
141
+ middlewares: [
142
+ ...middlewares,
143
+ ...this.middlewares
144
+ ],
145
+ resolver: this.resolver,
146
+ inputParser: this.inputParser,
147
+ outputParser: this.outputParser,
148
+ meta: this.meta
149
+ });
150
+ return instance;
151
+ }
152
+ constructor(opts){
153
+ this.middlewares = opts.middlewares;
154
+ this.resolver = opts.resolver;
155
+ this.inputParser = opts.inputParser;
156
+ this.parseInputFn = getParseFn(this.inputParser);
157
+ this.outputParser = opts.outputParser;
158
+ this.parseOutputFn = getParseFn(this.outputParser);
159
+ this.meta = opts.meta;
160
+ }
161
+ }
162
+ function createProcedure(opts) {
163
+ const inputParser = 'input' in opts ? opts.input : (input)=>{
164
+ if (input != null) {
165
+ throw new TRPCError({
166
+ code: 'BAD_REQUEST',
167
+ message: 'No input expected'
168
+ });
169
+ }
170
+ return undefined;
171
+ };
172
+ const outputParser = 'output' in opts && opts.output ? opts.output : (output)=>output;
173
+ return new Procedure({
174
+ inputParser: inputParser,
175
+ resolver: opts.resolve,
176
+ middlewares: [],
177
+ outputParser: outputParser,
178
+ meta: opts.meta
179
+ });
180
+ }
181
+
182
+ function migrateProcedure(oldProc, type) {
183
+ const def = oldProc._def();
184
+ const inputParser = getParseFnOrPassThrough(def.inputParser);
185
+ const outputParser = getParseFnOrPassThrough(def.outputParser);
186
+ const inputMiddleware = createInputMiddleware(inputParser);
187
+ const builder = createBuilder({
188
+ inputs: [
189
+ def.inputParser
190
+ ],
191
+ middlewares: [
192
+ ...def.middlewares,
193
+ inputMiddleware,
194
+ createOutputMiddleware(outputParser),
195
+ ],
196
+ meta: def.meta,
197
+ output: def.outputParser,
198
+ mutation: type === 'mutation',
199
+ query: type === 'query',
200
+ subscription: type === 'subscription'
201
+ });
202
+ const proc = builder[type]((opts)=>def.resolver(opts));
203
+ return proc;
204
+ }
205
+ function migrateRouter(oldRouter) {
206
+ const errorFormatter = oldRouter._def.errorFormatter;
207
+ const transformer = oldRouter._def.transformer;
208
+ const queries = {};
209
+ const mutations = {};
210
+ const subscriptions = {};
211
+ for (const [name, procedure] of Object.entries(oldRouter._def.queries)){
212
+ queries[name] = migrateProcedure(procedure, 'query');
213
+ }
214
+ for (const [name1, procedure1] of Object.entries(oldRouter._def.mutations)){
215
+ mutations[name1] = migrateProcedure(procedure1, 'mutation');
216
+ }
217
+ for (const [name2, procedure2] of Object.entries(oldRouter._def.subscriptions)){
218
+ subscriptions[name2] = migrateProcedure(procedure2, 'subscription');
219
+ }
220
+ const procedures = mergeWithoutOverrides(queries, mutations, subscriptions);
221
+ const newRouter = createRouterFactory({
222
+ transformer,
223
+ errorFormatter
224
+ })(procedures);
225
+ return newRouter;
226
+ }
227
+
228
+ assertNotBrowser();
229
+ function getDataTransformer(transformer) {
230
+ if ('input' in transformer) {
231
+ return transformer;
232
+ }
233
+ return {
234
+ input: transformer,
235
+ output: transformer
236
+ };
237
+ }
238
+ const PROCEDURE_DEFINITION_MAP = {
239
+ query: 'queries',
240
+ mutation: 'mutations',
241
+ subscription: 'subscriptions'
242
+ };
243
+ function safeObject(...args) {
244
+ return Object.assign(Object.create(null), ...args);
245
+ }
246
+ /**
247
+ * @internal The type signature of this class may change without warning.
248
+ * @deprecated
249
+ */ class Router {
250
+ static prefixProcedures(procedures, prefix) {
251
+ const eps = safeObject();
252
+ for (const [key, procedure] of Object.entries(procedures)){
253
+ eps[prefix + key] = procedure;
254
+ }
255
+ return eps;
256
+ }
257
+ query(path, procedure) {
258
+ const router = new Router({
259
+ queries: safeObject({
260
+ [path]: createProcedure(procedure)
261
+ })
262
+ });
263
+ return this.merge(router);
264
+ }
265
+ mutation(path, procedure) {
266
+ const router = new Router({
267
+ mutations: safeObject({
268
+ [path]: createProcedure(procedure)
269
+ })
270
+ });
271
+ return this.merge(router);
272
+ }
273
+ subscription(path, procedure) {
274
+ const router = new Router({
275
+ subscriptions: safeObject({
276
+ [path]: createProcedure(procedure)
277
+ })
278
+ });
279
+ return this.merge(router);
280
+ }
281
+ merge(prefixOrRouter, maybeRouter) {
282
+ let prefix = '';
283
+ let childRouter;
284
+ if (typeof prefixOrRouter === 'string' && maybeRouter instanceof Router) {
285
+ prefix = prefixOrRouter;
286
+ childRouter = maybeRouter;
287
+ } else if (prefixOrRouter instanceof Router) {
288
+ childRouter = prefixOrRouter;
289
+ } else {
290
+ throw new Error('Invalid args');
291
+ }
292
+ const duplicateQueries = Object.keys(childRouter._def.queries).filter((key)=>!!this._def['queries'][prefix + key]);
293
+ const duplicateMutations = Object.keys(childRouter._def.mutations).filter((key)=>!!this._def['mutations'][prefix + key]);
294
+ const duplicateSubscriptions = Object.keys(childRouter._def.subscriptions).filter((key)=>!!this._def['subscriptions'][prefix + key]);
295
+ const duplicates = [
296
+ ...duplicateQueries,
297
+ ...duplicateMutations,
298
+ ...duplicateSubscriptions,
299
+ ];
300
+ if (duplicates.length) {
301
+ throw new Error(`Duplicate endpoint(s): ${duplicates.join(', ')}`);
302
+ }
303
+ const mergeProcedures = (defs)=>{
304
+ const newDefs = safeObject();
305
+ for (const [key, procedure] of Object.entries(defs)){
306
+ const newProcedure = procedure.inheritMiddlewares(this._def.middlewares);
307
+ newDefs[key] = newProcedure;
308
+ }
309
+ return Router.prefixProcedures(newDefs, prefix);
310
+ };
311
+ return new Router({
312
+ ...this._def,
313
+ queries: safeObject(this._def.queries, mergeProcedures(childRouter._def.queries)),
314
+ mutations: safeObject(this._def.mutations, mergeProcedures(childRouter._def.mutations)),
315
+ subscriptions: safeObject(this._def.subscriptions, mergeProcedures(childRouter._def.subscriptions))
316
+ });
317
+ }
318
+ /**
319
+ * Invoke procedure. Only for internal use within library.
320
+ */ async call(opts) {
321
+ const { type , path } = opts;
322
+ const defTarget = PROCEDURE_DEFINITION_MAP[type];
323
+ const defs = this._def[defTarget];
324
+ const procedure = defs[path];
325
+ if (!procedure) {
326
+ throw new TRPCError({
327
+ code: 'NOT_FOUND',
328
+ message: `No "${type}"-procedure on path "${path}"`
329
+ });
330
+ }
331
+ return procedure.call(opts);
332
+ }
333
+ createCaller(ctx) {
334
+ return {
335
+ query: (path, ...args)=>{
336
+ return this.call({
337
+ type: 'query',
338
+ ctx,
339
+ path,
340
+ rawInput: args[0]
341
+ });
342
+ },
343
+ mutation: (path, ...args)=>{
344
+ return this.call({
345
+ type: 'mutation',
346
+ ctx,
347
+ path,
348
+ rawInput: args[0]
349
+ });
350
+ },
351
+ subscription: (path, ...args)=>{
352
+ return this.call({
353
+ type: 'subscription',
354
+ ctx,
355
+ path,
356
+ rawInput: args[0]
357
+ });
358
+ }
359
+ };
360
+ }
361
+ /**
362
+ * Function to be called before any procedure is invoked
363
+ * @link https://trpc.io/docs/middlewares
364
+ */ middleware(middleware) {
365
+ return new Router({
366
+ ...this._def,
367
+ middlewares: [
368
+ ...this._def.middlewares,
369
+ middleware
370
+ ]
371
+ });
372
+ }
373
+ /**
374
+ * Format errors
375
+ * @link https://trpc.io/docs/error-formatting
376
+ */ formatError(errorFormatter) {
377
+ if (this._def.errorFormatter !== defaultFormatter) {
378
+ throw new Error('You seem to have double `formatError()`-calls in your router tree');
379
+ }
380
+ return new Router({
381
+ ...this._def,
382
+ errorFormatter: errorFormatter
383
+ });
384
+ }
385
+ getErrorShape(opts) {
386
+ const { path , error } = opts;
387
+ const { code } = opts.error;
388
+ const shape = {
389
+ message: error.message,
390
+ code: TRPC_ERROR_CODES_BY_KEY[code],
391
+ data: {
392
+ code,
393
+ httpStatus: getHTTPStatusCodeFromError(error)
394
+ }
395
+ };
396
+ if (process.env.NODE_ENV !== 'production' && typeof opts.error.stack === 'string') {
397
+ shape.data.stack = opts.error.stack;
398
+ }
399
+ if (typeof path === 'string') {
400
+ shape.data.path = path;
401
+ }
402
+ return this._def.errorFormatter({
403
+ ...opts,
404
+ shape
405
+ });
406
+ }
407
+ /**
408
+ * Add data transformer to serialize/deserialize input args + output
409
+ * @link https://trpc.io/docs/data-transformers
410
+ */ transformer(_transformer) {
411
+ const transformer = getDataTransformer(_transformer);
412
+ if (this._def.transformer !== defaultTransformer) {
413
+ throw new Error('You seem to have double `transformer()`-calls in your router tree');
414
+ }
415
+ return new Router({
416
+ ...this._def,
417
+ transformer
418
+ });
419
+ }
420
+ /**
421
+ * Flattens the generics of TQueries/TMutations/TSubscriptions.
422
+ * ⚠️ Experimental - might disappear. ⚠️
423
+ *
424
+ * @alpha
425
+ */ flat() {
426
+ return this;
427
+ }
428
+ /**
429
+ * Interop mode for v9.x -> v10.x
430
+ */ interop() {
431
+ return migrateRouter(this);
432
+ }
433
+ constructor(def){
434
+ this._def = {
435
+ queries: def?.queries ?? safeObject(),
436
+ mutations: def?.mutations ?? safeObject(),
437
+ subscriptions: def?.subscriptions ?? safeObject(),
438
+ middlewares: def?.middlewares ?? [],
439
+ errorFormatter: def?.errorFormatter ?? defaultFormatter,
440
+ transformer: def?.transformer ?? defaultTransformer
441
+ };
442
+ }
443
+ }
444
+ /**
445
+ * @deprecated
446
+ */ function router() {
447
+ return new Router();
448
+ }
449
+
450
+ export { router as r };