@trpc/server 11.0.0-alpha-tmp-export-from-main.221 → 11.0.0-alpha-tmp-export-from-main.222

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 (136) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +68 -0
  2. package/dist/adapters/aws-lambda/index.d.ts +54 -6
  3. package/dist/adapters/aws-lambda/index.js +110 -20
  4. package/dist/adapters/aws-lambda/index.mjs +94 -4
  5. package/dist/adapters/express.d.mts +19 -0
  6. package/dist/adapters/express.d.ts +9 -6
  7. package/dist/adapters/express.js +3 -3
  8. package/dist/adapters/express.mjs +1 -1
  9. package/dist/adapters/fastify/index.d.mts +33 -0
  10. package/dist/adapters/fastify/index.d.ts +33 -3
  11. package/dist/adapters/fastify/index.js +124 -5
  12. package/dist/adapters/fastify/index.mjs +125 -2
  13. package/dist/adapters/fetch/index.d.mts +51 -0
  14. package/dist/adapters/fetch/index.d.ts +51 -3
  15. package/dist/adapters/fetch/index.js +115 -4
  16. package/dist/adapters/fetch/index.mjs +116 -1
  17. package/dist/adapters/next.d.mts +21 -0
  18. package/dist/adapters/next.d.ts +11 -7
  19. package/dist/adapters/next.js +6 -6
  20. package/dist/adapters/next.mjs +2 -2
  21. package/dist/adapters/node-http/content-type/form-data/index.d.mts +219 -0
  22. package/dist/adapters/node-http/content-type/form-data/index.d.ts +201 -10
  23. package/dist/adapters/node-http/content-type/form-data/index.js +662 -23
  24. package/dist/adapters/node-http/content-type/form-data/index.mjs +646 -10
  25. package/dist/adapters/node-http/{types.d.ts → content-type/json/index.d.mts} +21 -15
  26. package/dist/adapters/node-http/content-type/json/index.d.ts +89 -2
  27. package/dist/adapters/node-http/content-type/json/index.js +48 -7
  28. package/dist/adapters/node-http/content-type/json/index.mjs +44 -3
  29. package/dist/adapters/node-http/index.d.mts +100 -0
  30. package/dist/adapters/node-http/index.d.ts +100 -3
  31. package/dist/adapters/node-http/index.js +106 -4
  32. package/dist/adapters/node-http/index.mjs +107 -1
  33. package/dist/adapters/standalone.d.mts +21 -0
  34. package/dist/adapters/standalone.d.ts +11 -9
  35. package/dist/adapters/standalone.js +9 -5
  36. package/dist/adapters/standalone.mjs +2 -2
  37. package/dist/adapters/ws.d.mts +36 -0
  38. package/dist/adapters/ws.d.ts +12 -13
  39. package/dist/adapters/ws.js +30 -28
  40. package/dist/adapters/ws.mjs +12 -10
  41. package/dist/http.d.mts +1 -0
  42. package/dist/http.d.ts +1 -7
  43. package/dist/http.js +7 -7
  44. package/dist/http.mjs +1 -1
  45. package/dist/index.d.mts +9 -0
  46. package/dist/index.d.ts +5 -65
  47. package/dist/index.js +809 -46
  48. package/dist/index.mjs +798 -1
  49. package/dist/observable.d.mts +1 -0
  50. package/dist/observable.d.ts +1 -3
  51. package/dist/observable.js +8 -8
  52. package/dist/observable.mjs +1 -1
  53. package/dist/rpc.d.mts +1 -0
  54. package/dist/rpc.d.ts +1 -3
  55. package/dist/rpc.js +5 -5
  56. package/dist/rpc.mjs +1 -1
  57. package/dist/shared.d.mts +1 -0
  58. package/dist/shared.d.ts +1 -26
  59. package/dist/shared.js +4 -4
  60. package/dist/shared.mjs +1 -1
  61. package/dist/unstableDontImportMe.d.mts +1 -0
  62. package/dist/unstableDontImportMe.d.ts +1 -10
  63. package/dist/unstableDontImportMe.js +1549 -142
  64. package/dist/unstableDontImportMe.mjs +1514 -1
  65. package/package.json +6 -4
  66. package/dist/@trpc-server/http.d.ts +0 -2
  67. package/dist/@trpc-server/http.d.ts.map +0 -1
  68. package/dist/adapters/aws-lambda/index.d.ts.map +0 -1
  69. package/dist/adapters/aws-lambda/utils.d.ts +0 -48
  70. package/dist/adapters/aws-lambda/utils.d.ts.map +0 -1
  71. package/dist/adapters/aws-lambda/utils.js +0 -100
  72. package/dist/adapters/aws-lambda/utils.mjs +0 -93
  73. package/dist/adapters/express.d.ts.map +0 -1
  74. package/dist/adapters/fastify/fastifyRequestHandler.d.ts +0 -13
  75. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +0 -1
  76. package/dist/adapters/fastify/fastifyRequestHandler.js +0 -81
  77. package/dist/adapters/fastify/fastifyRequestHandler.mjs +0 -79
  78. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts +0 -22
  79. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +0 -1
  80. package/dist/adapters/fastify/fastifyTRPCPlugin.js +0 -51
  81. package/dist/adapters/fastify/fastifyTRPCPlugin.mjs +0 -49
  82. package/dist/adapters/fastify/index.d.ts.map +0 -1
  83. package/dist/adapters/fetch/fetchRequestHandler.d.ts +0 -18
  84. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +0 -1
  85. package/dist/adapters/fetch/fetchRequestHandler.js +0 -118
  86. package/dist/adapters/fetch/fetchRequestHandler.mjs +0 -116
  87. package/dist/adapters/fetch/index.d.ts.map +0 -1
  88. package/dist/adapters/fetch/types.d.ts +0 -31
  89. package/dist/adapters/fetch/types.d.ts.map +0 -1
  90. package/dist/adapters/next.d.ts.map +0 -1
  91. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +0 -70
  92. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +0 -1
  93. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.js +0 -161
  94. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.mjs +0 -157
  95. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +0 -1
  96. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +0 -31
  97. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +0 -1
  98. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.js +0 -29
  99. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.mjs +0 -27
  100. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +0 -16
  101. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +0 -1
  102. package/dist/adapters/node-http/content-type/form-data/streamSlice.js +0 -46
  103. package/dist/adapters/node-http/content-type/form-data/streamSlice.mjs +0 -44
  104. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +0 -45
  105. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +0 -1
  106. package/dist/adapters/node-http/content-type/form-data/uploadHandler.js +0 -30
  107. package/dist/adapters/node-http/content-type/form-data/uploadHandler.mjs +0 -26
  108. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts +0 -7
  109. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +0 -1
  110. package/dist/adapters/node-http/content-type/json/getPostBody.js +0 -42
  111. package/dist/adapters/node-http/content-type/json/getPostBody.mjs +0 -40
  112. package/dist/adapters/node-http/content-type/json/index.d.ts.map +0 -1
  113. package/dist/adapters/node-http/index.d.ts.map +0 -1
  114. package/dist/adapters/node-http/internals/contentType.d.ts +0 -9
  115. package/dist/adapters/node-http/internals/contentType.d.ts.map +0 -1
  116. package/dist/adapters/node-http/internals/contentType.js +0 -8
  117. package/dist/adapters/node-http/internals/contentType.mjs +0 -6
  118. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +0 -14
  119. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +0 -1
  120. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +0 -109
  121. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +0 -107
  122. package/dist/adapters/node-http/types.d.ts.map +0 -1
  123. package/dist/adapters/standalone.d.ts.map +0 -1
  124. package/dist/adapters/ws.d.ts.map +0 -1
  125. package/dist/http.d.ts.map +0 -1
  126. package/dist/index.d.ts.map +0 -1
  127. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.js +0 -203
  128. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.mjs +0 -201
  129. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.js +0 -167
  130. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.mjs +0 -163
  131. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.js +0 -35
  132. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.mjs +0 -30
  133. package/dist/observable.d.ts.map +0 -1
  134. package/dist/rpc.d.ts.map +0 -1
  135. package/dist/shared.d.ts.map +0 -1
  136. package/dist/unstableDontImportMe.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1 +1,798 @@
1
- export { TRPCError, callProcedure, callProcedure as callTRPCProcedure, createFlatProxy as createTRPCFlatProxy, experimental_standaloneMiddleware, experimental_standaloneMiddleware as experimental_trpcMiddleware, getErrorShape, getTRPCErrorFromUnknown, initTRPC, transformTRPCResponse } from '@trpc/core';
1
+ /**
2
+ * @internal
3
+ */ function invert(obj) {
4
+ const newObj = Object.create(null);
5
+ for(const key in obj){
6
+ const v = obj[key];
7
+ newObj[v] = key;
8
+ }
9
+ return newObj;
10
+ }
11
+ /**
12
+ * Ensures there are no duplicate keys when building a procedure.
13
+ * @internal
14
+ */ function mergeWithoutOverrides(obj1, ...objs) {
15
+ const newObj = Object.assign(Object.create(null), obj1);
16
+ for (const overrides of objs){
17
+ for(const key in overrides){
18
+ if (key in newObj && newObj[key] !== overrides[key]) {
19
+ throw new Error(`Duplicate key ${key}`);
20
+ }
21
+ newObj[key] = overrides[key];
22
+ }
23
+ }
24
+ return newObj;
25
+ }
26
+ /**
27
+ * Check that value is object
28
+ * @internal
29
+ */ function isObject(value) {
30
+ return !!value && !Array.isArray(value) && typeof value === 'object';
31
+ }
32
+ /**
33
+ * Create an object without inheriting anything from `Object.prototype`
34
+ * @internal
35
+ */ function omitPrototype(obj) {
36
+ return Object.assign(Object.create(null), obj);
37
+ }
38
+
39
+ // reference: https://www.jsonrpc.org/specification
40
+ /**
41
+ * JSON-RPC 2.0 Error codes
42
+ *
43
+ * `-32000` to `-32099` are reserved for implementation-defined server-errors.
44
+ * For tRPC we're copying the last digits of HTTP 4XX errors.
45
+ */ const TRPC_ERROR_CODES_BY_KEY = {
46
+ /**
47
+ * Invalid JSON was received by the server.
48
+ * An error occurred on the server while parsing the JSON text.
49
+ */ PARSE_ERROR: -32700,
50
+ /**
51
+ * The JSON sent is not a valid Request object.
52
+ */ BAD_REQUEST: -32600,
53
+ // Internal JSON-RPC error
54
+ INTERNAL_SERVER_ERROR: -32603,
55
+ NOT_IMPLEMENTED: -32603,
56
+ // Implementation specific errors
57
+ UNAUTHORIZED: -32001,
58
+ FORBIDDEN: -32003,
59
+ NOT_FOUND: -32004,
60
+ METHOD_NOT_SUPPORTED: -32005,
61
+ TIMEOUT: -32008,
62
+ CONFLICT: -32009,
63
+ PRECONDITION_FAILED: -32012,
64
+ PAYLOAD_TOO_LARGE: -32013,
65
+ UNPROCESSABLE_CONTENT: -32022,
66
+ TOO_MANY_REQUESTS: -32029,
67
+ CLIENT_CLOSED_REQUEST: -32099
68
+ };
69
+ invert(TRPC_ERROR_CODES_BY_KEY);
70
+
71
+ const JSONRPC2_TO_HTTP_CODE = {
72
+ PARSE_ERROR: 400,
73
+ BAD_REQUEST: 400,
74
+ UNAUTHORIZED: 401,
75
+ NOT_FOUND: 404,
76
+ FORBIDDEN: 403,
77
+ METHOD_NOT_SUPPORTED: 405,
78
+ TIMEOUT: 408,
79
+ CONFLICT: 409,
80
+ PRECONDITION_FAILED: 412,
81
+ PAYLOAD_TOO_LARGE: 413,
82
+ UNPROCESSABLE_CONTENT: 422,
83
+ TOO_MANY_REQUESTS: 429,
84
+ CLIENT_CLOSED_REQUEST: 499,
85
+ INTERNAL_SERVER_ERROR: 500,
86
+ NOT_IMPLEMENTED: 501
87
+ };
88
+ function getStatusCodeFromKey(code) {
89
+ return JSONRPC2_TO_HTTP_CODE[code] ?? 500;
90
+ }
91
+ function getHTTPStatusCodeFromError(error) {
92
+ return getStatusCodeFromKey(error.code);
93
+ }
94
+
95
+ /**
96
+ * @internal
97
+ */ function getErrorShape(opts) {
98
+ const { path, error, config } = opts;
99
+ const { code } = opts.error;
100
+ const shape = {
101
+ message: error.message,
102
+ code: TRPC_ERROR_CODES_BY_KEY[code],
103
+ data: {
104
+ code,
105
+ httpStatus: getHTTPStatusCodeFromError(error)
106
+ }
107
+ };
108
+ if (config.isDev && typeof opts.error.stack === 'string') {
109
+ shape.data.stack = opts.error.stack;
110
+ }
111
+ if (typeof path === 'string') {
112
+ shape.data.path = path;
113
+ }
114
+ return config.errorFormatter({
115
+ ...opts,
116
+ shape
117
+ });
118
+ }
119
+
120
+ class UnknownCauseError extends Error {
121
+ }
122
+ function getCauseFromUnknown(cause) {
123
+ if (cause instanceof Error) {
124
+ return cause;
125
+ }
126
+ const type = typeof cause;
127
+ if (type === 'undefined' || type === 'function' || cause === null) {
128
+ return undefined;
129
+ }
130
+ // Primitive types just get wrapped in an error
131
+ if (type !== 'object') {
132
+ return new Error(String(cause));
133
+ }
134
+ // If it's an object, we'll create a synthetic error
135
+ if (isObject(cause)) {
136
+ const err = new UnknownCauseError();
137
+ for(const key in cause){
138
+ err[key] = cause[key];
139
+ }
140
+ return err;
141
+ }
142
+ return undefined;
143
+ }
144
+ function getTRPCErrorFromUnknown(cause) {
145
+ if (cause instanceof TRPCError) {
146
+ return cause;
147
+ }
148
+ if (cause instanceof Error && cause.name === 'TRPCError') {
149
+ // https://github.com/trpc/trpc/pull/4848
150
+ return cause;
151
+ }
152
+ const trpcError = new TRPCError({
153
+ code: 'INTERNAL_SERVER_ERROR',
154
+ cause
155
+ });
156
+ // Inherit stack from error
157
+ if (cause instanceof Error && cause.stack) {
158
+ trpcError.stack = cause.stack;
159
+ }
160
+ return trpcError;
161
+ }
162
+ class TRPCError extends Error {
163
+ constructor(opts){
164
+ const cause = getCauseFromUnknown(opts.cause);
165
+ const message = opts.message ?? cause?.message ?? opts.code;
166
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
167
+ // @ts-ignore https://github.com/tc39/proposal-error-cause
168
+ super(message, {
169
+ cause
170
+ });
171
+ this.code = opts.code;
172
+ this.name = 'TRPCError';
173
+ if (!this.cause) {
174
+ // < ES2022 / < Node 16.9.0 compatability
175
+ this.cause = cause;
176
+ }
177
+ }
178
+ }
179
+
180
+ const noop = ()=>{
181
+ // noop
182
+ };
183
+ function createInnerProxy(callback, path) {
184
+ const proxy = new Proxy(noop, {
185
+ get (_obj, key) {
186
+ if (typeof key !== 'string' || key === 'then') {
187
+ // special case for if the proxy is accidentally treated
188
+ // like a PromiseLike (like in `Promise.resolve(proxy)`)
189
+ return undefined;
190
+ }
191
+ return createInnerProxy(callback, [
192
+ ...path,
193
+ key
194
+ ]);
195
+ },
196
+ apply (_1, _2, args) {
197
+ const isApply = path[path.length - 1] === 'apply';
198
+ return callback({
199
+ args: isApply ? args.length >= 2 ? args[1] : [] : args,
200
+ path: isApply ? path.slice(0, -1) : path
201
+ });
202
+ }
203
+ });
204
+ return proxy;
205
+ }
206
+ /**
207
+ * Creates a proxy that calls the callback with the path and arguments
208
+ *
209
+ * @internal
210
+ */ const createRecursiveProxy = (callback)=>createInnerProxy(callback, []);
211
+ /**
212
+ * Used in place of `new Proxy` where each handler will map 1 level deep to another value.
213
+ *
214
+ * @internal
215
+ */ const createFlatProxy = (callback)=>{
216
+ return new Proxy(noop, {
217
+ get (_obj, name) {
218
+ if (typeof name !== 'string' || name === 'then') {
219
+ // special case for if the proxy is accidentally treated
220
+ // like a PromiseLike (like in `Promise.resolve(proxy)`)
221
+ return undefined;
222
+ }
223
+ return callback(name);
224
+ }
225
+ });
226
+ };
227
+
228
+ const defaultFormatter = ({ shape })=>{
229
+ return shape;
230
+ };
231
+
232
+ /** @internal */ const middlewareMarker = 'middlewareMarker';
233
+ /**
234
+ * @internal
235
+ */ function createMiddlewareFactory() {
236
+ function createMiddlewareInner(middlewares) {
237
+ return {
238
+ _middlewares: middlewares,
239
+ unstable_pipe (middlewareBuilderOrFn) {
240
+ const pipedMiddleware = '_middlewares' in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
241
+ middlewareBuilderOrFn
242
+ ];
243
+ return createMiddlewareInner([
244
+ ...middlewares,
245
+ ...pipedMiddleware
246
+ ]);
247
+ }
248
+ };
249
+ }
250
+ function createMiddleware(fn) {
251
+ return createMiddlewareInner([
252
+ fn
253
+ ]);
254
+ }
255
+ return createMiddleware;
256
+ }
257
+ /**
258
+ * Create a standalone middleware
259
+ * @link https://trpc.io/docs/v11/server/middlewares#experimental-standalone-middlewares
260
+ */ const experimental_standaloneMiddleware = ()=>({
261
+ create: createMiddlewareFactory()
262
+ });
263
+ /**
264
+ * @internal
265
+ * Please note, `trpc-openapi` uses this function.
266
+ */ function createInputMiddleware(parse) {
267
+ const inputMiddleware = async function inputValidatorMiddleware(opts) {
268
+ let parsedInput;
269
+ const rawInput = await opts.getRawInput();
270
+ try {
271
+ parsedInput = await parse(rawInput);
272
+ } catch (cause) {
273
+ throw new TRPCError({
274
+ code: 'BAD_REQUEST',
275
+ cause
276
+ });
277
+ }
278
+ // Multiple input parsers
279
+ const combinedInput = isObject(opts.input) && isObject(parsedInput) ? {
280
+ ...opts.input,
281
+ ...parsedInput
282
+ } : parsedInput;
283
+ return opts.next({
284
+ input: combinedInput
285
+ });
286
+ };
287
+ inputMiddleware._type = 'input';
288
+ return inputMiddleware;
289
+ }
290
+ /**
291
+ * @internal
292
+ */ function createOutputMiddleware(parse) {
293
+ const outputMiddleware = async function outputValidatorMiddleware({ next }) {
294
+ const result = await next();
295
+ if (!result.ok) {
296
+ // pass through failures without validating
297
+ return result;
298
+ }
299
+ try {
300
+ const data = await parse(result.data);
301
+ return {
302
+ ...result,
303
+ data
304
+ };
305
+ } catch (cause) {
306
+ throw new TRPCError({
307
+ message: 'Output validation failed',
308
+ code: 'INTERNAL_SERVER_ERROR',
309
+ cause
310
+ });
311
+ }
312
+ };
313
+ outputMiddleware._type = 'output';
314
+ return outputMiddleware;
315
+ }
316
+
317
+ // zod / @decs/typeschema
318
+ function getParseFn(procedureParser) {
319
+ const parser = procedureParser;
320
+ if (typeof parser === 'function') {
321
+ // ParserCustomValidatorEsque
322
+ return parser;
323
+ }
324
+ if (typeof parser.parseAsync === 'function') {
325
+ // ParserZodEsque
326
+ return parser.parseAsync.bind(parser);
327
+ }
328
+ if (typeof parser.parse === 'function') {
329
+ // ParserZodEsque
330
+ // ParserValibotEsque (<= v0.12.X)
331
+ return parser.parse.bind(parser);
332
+ }
333
+ if (typeof parser.validateSync === 'function') {
334
+ // ParserYupEsque
335
+ return parser.validateSync.bind(parser);
336
+ }
337
+ if (typeof parser.create === 'function') {
338
+ // ParserSuperstructEsque
339
+ return parser.create.bind(parser);
340
+ }
341
+ if (typeof parser.assert === 'function') {
342
+ // ParserScaleEsque
343
+ return (value)=>{
344
+ parser.assert(value);
345
+ return value;
346
+ };
347
+ }
348
+ throw new Error('Could not find a validator fn');
349
+ }
350
+
351
+ function createNewBuilder(def1, def2) {
352
+ const { middlewares = [], inputs, meta, ...rest } = def2;
353
+ // TODO: maybe have a fn here to warn about calls
354
+ return createBuilder({
355
+ ...mergeWithoutOverrides(def1, rest),
356
+ inputs: [
357
+ ...def1.inputs,
358
+ ...inputs ?? []
359
+ ],
360
+ middlewares: [
361
+ ...def1.middlewares,
362
+ ...middlewares
363
+ ],
364
+ meta: def1.meta && meta ? {
365
+ ...def1.meta,
366
+ ...meta
367
+ } : meta ?? def1.meta
368
+ });
369
+ }
370
+ function createBuilder(initDef = {}) {
371
+ const _def = {
372
+ procedure: true,
373
+ inputs: [],
374
+ middlewares: [],
375
+ ...initDef
376
+ };
377
+ const builder = {
378
+ _def,
379
+ input (input) {
380
+ const parser = getParseFn(input);
381
+ return createNewBuilder(_def, {
382
+ inputs: [
383
+ input
384
+ ],
385
+ middlewares: [
386
+ createInputMiddleware(parser)
387
+ ]
388
+ });
389
+ },
390
+ output (output) {
391
+ const parser = getParseFn(output);
392
+ return createNewBuilder(_def, {
393
+ output,
394
+ middlewares: [
395
+ createOutputMiddleware(parser)
396
+ ]
397
+ });
398
+ },
399
+ meta (meta) {
400
+ return createNewBuilder(_def, {
401
+ meta
402
+ });
403
+ },
404
+ use (middlewareBuilderOrFn) {
405
+ // Distinguish between a middleware builder and a middleware function
406
+ const middlewares = '_middlewares' in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
407
+ middlewareBuilderOrFn
408
+ ];
409
+ return createNewBuilder(_def, {
410
+ middlewares: middlewares
411
+ });
412
+ },
413
+ query (resolver) {
414
+ return createResolver({
415
+ ..._def,
416
+ type: 'query'
417
+ }, resolver);
418
+ },
419
+ mutation (resolver) {
420
+ return createResolver({
421
+ ..._def,
422
+ type: 'mutation'
423
+ }, resolver);
424
+ },
425
+ subscription (resolver) {
426
+ return createResolver({
427
+ ..._def,
428
+ type: 'subscription'
429
+ }, resolver);
430
+ }
431
+ };
432
+ return builder;
433
+ }
434
+ function createResolver(_def, resolver) {
435
+ const finalBuilder = createNewBuilder(_def, {
436
+ resolver,
437
+ middlewares: [
438
+ async function resolveMiddleware(opts) {
439
+ const data = await resolver(opts);
440
+ return {
441
+ marker: middlewareMarker,
442
+ ok: true,
443
+ data,
444
+ ctx: opts.ctx
445
+ };
446
+ }
447
+ ]
448
+ });
449
+ return createProcedureCaller(finalBuilder._def);
450
+ }
451
+ const codeblock = `
452
+ This is a client-only function.
453
+ If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
454
+ `.trim();
455
+ function createProcedureCaller(_def) {
456
+ async function procedure(opts) {
457
+ // is direct server-side call
458
+ if (!opts || !('getRawInput' in opts)) {
459
+ throw new Error(codeblock);
460
+ }
461
+ // run the middlewares recursively with the resolver as the last one
462
+ async function callRecursive(callOpts = {
463
+ index: 0,
464
+ ctx: opts.ctx
465
+ }) {
466
+ try {
467
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
468
+ const middleware = _def.middlewares[callOpts.index];
469
+ const result = await middleware({
470
+ ctx: callOpts.ctx,
471
+ type: opts.type,
472
+ path: opts.path,
473
+ getRawInput: callOpts.getRawInput ?? opts.getRawInput,
474
+ meta: _def.meta,
475
+ input: callOpts.input,
476
+ next (_nextOpts) {
477
+ const nextOpts = _nextOpts;
478
+ return callRecursive({
479
+ index: callOpts.index + 1,
480
+ ctx: nextOpts && 'ctx' in nextOpts ? {
481
+ ...callOpts.ctx,
482
+ ...nextOpts.ctx
483
+ } : callOpts.ctx,
484
+ input: nextOpts && 'input' in nextOpts ? nextOpts.input : callOpts.input,
485
+ getRawInput: nextOpts && 'getRawInput' in nextOpts ? nextOpts.getRawInput : callOpts.getRawInput
486
+ });
487
+ }
488
+ });
489
+ return result;
490
+ } catch (cause) {
491
+ return {
492
+ ok: false,
493
+ error: getTRPCErrorFromUnknown(cause),
494
+ marker: middlewareMarker
495
+ };
496
+ }
497
+ }
498
+ // there's always at least one "next" since we wrap this.resolver in a middleware
499
+ const result = await callRecursive();
500
+ if (!result) {
501
+ throw new TRPCError({
502
+ code: 'INTERNAL_SERVER_ERROR',
503
+ message: 'No result from middlewares - did you forget to `return next()`?'
504
+ });
505
+ }
506
+ if (!result.ok) {
507
+ // re-throw original error
508
+ throw result.error;
509
+ }
510
+ return result.data;
511
+ }
512
+ procedure._def = _def;
513
+ // FIXME typecast shouldn't be needed - fixittt
514
+ return procedure;
515
+ }
516
+
517
+ /**
518
+ * The default check to see if we're in a server
519
+ */ const isServerDefault = typeof window === 'undefined' || 'Deno' in window || // eslint-disable-next-line @typescript-eslint/dot-notation
520
+ globalThis.process?.env?.['NODE_ENV'] === 'test' || !!globalThis.process?.env?.['JEST_WORKER_ID'] || !!globalThis.process?.env?.['VITEST_WORKER_ID'];
521
+
522
+ /**
523
+ * @internal
524
+ */ function getDataTransformer(transformer) {
525
+ if ('input' in transformer) {
526
+ return transformer;
527
+ }
528
+ return {
529
+ input: transformer,
530
+ output: transformer
531
+ };
532
+ }
533
+ /**
534
+ * @internal
535
+ */ const defaultTransformer = {
536
+ _default: true,
537
+ input: {
538
+ serialize: (obj)=>obj,
539
+ deserialize: (obj)=>obj
540
+ },
541
+ output: {
542
+ serialize: (obj)=>obj,
543
+ deserialize: (obj)=>obj
544
+ }
545
+ };
546
+ function transformTRPCResponseItem(config, item) {
547
+ if ('error' in item) {
548
+ return {
549
+ ...item,
550
+ error: config.transformer.output.serialize(item.error)
551
+ };
552
+ }
553
+ if ('data' in item.result) {
554
+ return {
555
+ ...item,
556
+ result: {
557
+ ...item.result,
558
+ data: config.transformer.output.serialize(item.result.data)
559
+ }
560
+ };
561
+ }
562
+ return item;
563
+ }
564
+ /**
565
+ * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers
566
+ **/ function transformTRPCResponse(config, itemOrItems) {
567
+ return Array.isArray(itemOrItems) ? itemOrItems.map((item)=>transformTRPCResponseItem(config, item)) : transformTRPCResponseItem(config, itemOrItems);
568
+ }
569
+
570
+ function isRouter(procedureOrRouter) {
571
+ return 'router' in procedureOrRouter._def;
572
+ }
573
+ const emptyRouter = {
574
+ _ctx: null,
575
+ _errorShape: null,
576
+ _meta: null,
577
+ queries: {},
578
+ mutations: {},
579
+ subscriptions: {},
580
+ errorFormatter: defaultFormatter,
581
+ transformer: defaultTransformer
582
+ };
583
+ /**
584
+ * Reserved words that can't be used as router or procedure names
585
+ */ const reservedWords = [
586
+ /**
587
+ * Then is a reserved word because otherwise we can't return a promise that returns a Proxy
588
+ * since JS will think that `.then` is something that exists
589
+ */ 'then'
590
+ ];
591
+ /**
592
+ * @internal
593
+ */ function createRouterFactory(config) {
594
+ return function createRouterInner(procedures) {
595
+ const reservedWordsUsed = new Set(Object.keys(procedures).filter((v)=>reservedWords.includes(v)));
596
+ if (reservedWordsUsed.size > 0) {
597
+ throw new Error('Reserved words used in `router({})` call: ' + Array.from(reservedWordsUsed).join(', '));
598
+ }
599
+ const routerProcedures = omitPrototype({});
600
+ function recursiveGetPaths(procedures, path = '') {
601
+ for (const [key, procedureOrRouter] of Object.entries(procedures ?? {})){
602
+ const newPath = `${path}${key}`;
603
+ if (isRouter(procedureOrRouter)) {
604
+ recursiveGetPaths(procedureOrRouter._def.procedures, `${newPath}.`);
605
+ continue;
606
+ }
607
+ if (routerProcedures[newPath]) {
608
+ throw new Error(`Duplicate key: ${newPath}`);
609
+ }
610
+ routerProcedures[newPath] = procedureOrRouter;
611
+ }
612
+ }
613
+ recursiveGetPaths(procedures);
614
+ const _def = {
615
+ _config: config,
616
+ router: true,
617
+ procedures: routerProcedures,
618
+ ...emptyRouter,
619
+ record: procedures
620
+ };
621
+ const router = {
622
+ ...procedures,
623
+ _def,
624
+ createCaller (ctx) {
625
+ const proxy = createRecursiveProxy(({ path, args })=>{
626
+ const fullPath = path.join('.');
627
+ const procedure = _def.procedures[fullPath];
628
+ return procedure({
629
+ path: fullPath,
630
+ getRawInput: async ()=>args[0],
631
+ ctx,
632
+ type: procedure._def.type
633
+ });
634
+ });
635
+ return proxy;
636
+ }
637
+ };
638
+ return router;
639
+ };
640
+ }
641
+ function isProcedure(procedureOrRouter) {
642
+ return !!procedureOrRouter._def.procedure;
643
+ }
644
+ /**
645
+ * @internal
646
+ */ function callProcedure(opts) {
647
+ const { type, path } = opts;
648
+ const proc = opts.procedures[path];
649
+ if (!proc || !isProcedure(proc) || proc._def.type !== type) {
650
+ throw new TRPCError({
651
+ code: 'NOT_FOUND',
652
+ message: `No "${type}"-procedure on path "${path}"`
653
+ });
654
+ }
655
+ return proc(opts);
656
+ }
657
+ function createCallerFactory() {
658
+ return function createCallerInner(router) {
659
+ const _def = router._def;
660
+ return function createCaller(maybeContext) {
661
+ const proxy = createRecursiveProxy(({ path, args })=>{
662
+ const fullPath = path.join('.');
663
+ const procedure = _def.procedures[fullPath];
664
+ const callProc = (ctx)=>procedure({
665
+ path: fullPath,
666
+ getRawInput: async ()=>args[0],
667
+ ctx,
668
+ type: procedure._def.type
669
+ });
670
+ if (typeof maybeContext === 'function') {
671
+ const context = maybeContext();
672
+ if (context instanceof Promise) {
673
+ return context.then(callProc);
674
+ }
675
+ return callProc(context);
676
+ }
677
+ return callProc(maybeContext);
678
+ });
679
+ return proxy;
680
+ };
681
+ };
682
+ }
683
+ function mergeRouters(...routerList) {
684
+ const record = mergeWithoutOverrides({}, ...routerList.map((r)=>r._def.record));
685
+ const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter)=>{
686
+ if (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {
687
+ if (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) {
688
+ throw new Error('You seem to have several error formatters');
689
+ }
690
+ return nextRouter._def._config.errorFormatter;
691
+ }
692
+ return currentErrorFormatter;
693
+ }, defaultFormatter);
694
+ const transformer = routerList.reduce((prev, current)=>{
695
+ if (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {
696
+ if (prev !== defaultTransformer && prev !== current._def._config.transformer) {
697
+ throw new Error('You seem to have several transformers');
698
+ }
699
+ return current._def._config.transformer;
700
+ }
701
+ return prev;
702
+ }, defaultTransformer);
703
+ const router = createRouterFactory({
704
+ errorFormatter,
705
+ transformer,
706
+ isDev: routerList.some((r)=>r._def._config.isDev),
707
+ allowOutsideOfServer: routerList.some((r)=>r._def._config.allowOutsideOfServer),
708
+ isServer: routerList.some((r)=>r._def._config.isServer),
709
+ $types: routerList[0]?._def._config.$types
710
+ })(record);
711
+ return router;
712
+ }
713
+
714
+ /**
715
+ * TODO: This can be improved:
716
+ * - We should be able to chain `.meta()`/`.context()` only once
717
+ * - Simplify typings
718
+ * - Doesn't need to be a class but it doesn't really hurt either
719
+ */ class TRPCBuilder {
720
+ /**
721
+ * Add a context shape as a generic to the root object
722
+ * @link https://trpc.io/docs/v11/server/context
723
+ */ context() {
724
+ return new TRPCBuilder();
725
+ }
726
+ /**
727
+ * Add a meta shape as a generic to the root object
728
+ * @link https://trpc.io/docs/v11/quickstart
729
+ */ meta() {
730
+ return new TRPCBuilder();
731
+ }
732
+ /**
733
+ * Create the root object
734
+ * @link https://trpc.io/docs/v11/server/routers#initialize-trpc
735
+ */ create(options) {
736
+ return createTRPCInner()(options);
737
+ }
738
+ }
739
+ /**
740
+ * Builder to initialize the tRPC root object - use this exactly once per backend
741
+ * @link https://trpc.io/docs/v11/quickstart
742
+ */ const initTRPC = new TRPCBuilder();
743
+ function createTRPCInner() {
744
+ return function initTRPCInner(runtime) {
745
+ const errorFormatter = runtime?.errorFormatter ?? defaultFormatter;
746
+ const transformer = getDataTransformer(runtime?.transformer ?? defaultTransformer);
747
+ const config = {
748
+ transformer,
749
+ isDev: runtime?.isDev ?? // eslint-disable-next-line @typescript-eslint/dot-notation
750
+ globalThis.process?.env?.['NODE_ENV'] !== 'production',
751
+ allowOutsideOfServer: runtime?.allowOutsideOfServer ?? false,
752
+ errorFormatter,
753
+ isServer: runtime?.isServer ?? isServerDefault,
754
+ /**
755
+ * @internal
756
+ */ $types: createFlatProxy((key)=>{
757
+ throw new Error(`Tried to access "$types.${key}" which is not available at runtime`);
758
+ })
759
+ };
760
+ {
761
+ // Server check
762
+ const isServer = runtime?.isServer ?? isServerDefault;
763
+ if (!isServer && runtime?.allowOutsideOfServer !== true) {
764
+ throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
765
+ }
766
+ }
767
+ return {
768
+ /**
769
+ * These are just types, they can't be used
770
+ * @internal
771
+ */ _config: config,
772
+ /**
773
+ * Builder object for creating procedures
774
+ * @link https://trpc.io/docs/v11/server/procedures
775
+ */ procedure: createBuilder({
776
+ meta: runtime?.defaultMeta
777
+ }),
778
+ /**
779
+ * Create reusable middlewares
780
+ * @link https://trpc.io/docs/v11/server/middlewares
781
+ */ middleware: createMiddlewareFactory(),
782
+ /**
783
+ * Create a router
784
+ * @link https://trpc.io/docs/v11/server/routers
785
+ */ router: createRouterFactory(config),
786
+ /**
787
+ * Merge Routers
788
+ * @link https://trpc.io/docs/v11/server/merging-routers
789
+ */ mergeRouters,
790
+ /**
791
+ * Create a server-side caller for a router
792
+ * @link https://trpc.io/docs/v11/server/server-side-calls
793
+ */ createCallerFactory: createCallerFactory()
794
+ };
795
+ };
796
+ }
797
+
798
+ export { TRPCError, callProcedure, callProcedure as callTRPCProcedure, createFlatProxy as createTRPCFlatProxy, experimental_standaloneMiddleware, experimental_standaloneMiddleware as experimental_trpcMiddleware, getErrorShape, getTRPCErrorFromUnknown, initTRPC, transformTRPCResponse };