@trpc/server 11.0.0-next-beta.241 → 11.0.0-next-beta.248

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 (44) hide show
  1. package/dist/@trpc/server/index.d.ts +1 -5
  2. package/dist/@trpc/server/index.d.ts.map +1 -1
  3. package/dist/adapters/node-http/content-type/form-data/index.js +2 -2
  4. package/dist/adapters/node-http/content-type/form-data/index.mjs +1 -1
  5. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  6. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +2 -0
  7. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +2 -0
  8. package/dist/adapters/node-http/types.d.ts +3 -3
  9. package/dist/adapters/node-http/types.d.ts.map +1 -1
  10. package/dist/bundle-analysis.json +71 -129
  11. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.d.ts.map +1 -1
  12. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.js +2 -2
  13. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.mjs +2 -2
  14. package/dist/unstable-core-do-not-import/index.d.ts +1 -1
  15. package/dist/unstable-core-do-not-import/index.d.ts.map +1 -1
  16. package/dist/unstable-core-do-not-import/initTRPC.d.ts +21 -8
  17. package/dist/unstable-core-do-not-import/initTRPC.d.ts.map +1 -1
  18. package/dist/unstable-core-do-not-import/router.d.ts +39 -47
  19. package/dist/unstable-core-do-not-import/router.d.ts.map +1 -1
  20. package/dist/unstable-core-do-not-import/router.js +39 -22
  21. package/dist/unstable-core-do-not-import/router.mjs +40 -23
  22. package/dist/unstable-core-do-not-import/rpc/codes.d.ts +1 -2
  23. package/dist/unstable-core-do-not-import/rpc/codes.d.ts.map +1 -1
  24. package/dist/unstable-core-do-not-import/rpc/envelopes.d.ts +1 -1
  25. package/dist/unstable-core-do-not-import/rpc/envelopes.d.ts.map +1 -1
  26. package/dist/unstable-core-do-not-import/transformer.d.ts +1 -1
  27. package/dist/unstable-core-do-not-import/types.d.ts +1 -0
  28. package/dist/unstable-core-do-not-import/types.d.ts.map +1 -1
  29. package/package.json +2 -2
  30. package/src/@trpc/server/index.ts +1 -5
  31. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +4 -2
  32. package/src/adapters/node-http/types.ts +3 -3
  33. package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +6 -3
  34. package/src/unstable-core-do-not-import/index.ts +0 -4
  35. package/src/unstable-core-do-not-import/router.ts +123 -118
  36. package/src/unstable-core-do-not-import/rpc/codes.ts +1 -1
  37. package/src/unstable-core-do-not-import/rpc/envelopes.ts +1 -3
  38. package/src/unstable-core-do-not-import/types.ts +1 -0
  39. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.js +0 -203
  40. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.mjs +0 -201
  41. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.js +0 -167
  42. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.mjs +0 -163
  43. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.js +0 -35
  44. package/dist/node_modules/.pnpm/@web3-storage_multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.mjs +0 -30
@@ -7,7 +7,7 @@
7
7
  * import type { HTTPBaseHandlerOptions } from '@trpc/server/http'
8
8
  * ```
9
9
  */
10
- import type { IncomingMessage, ServerResponse } from 'http';
10
+ import type * as http from 'http';
11
11
  // @trpc/server
12
12
  import type { AnyRouter, inferRouterContext } from '../../@trpc/server';
13
13
  // @trpc/server/http
@@ -23,11 +23,11 @@ interface ParsedQs {
23
23
  [key: string]: ParsedQs | ParsedQs[] | string[] | string | undefined;
24
24
  }
25
25
 
26
- export type NodeHTTPRequest = IncomingMessage & {
26
+ export type NodeHTTPRequest = http.IncomingMessage & {
27
27
  query?: ParsedQs;
28
28
  body?: unknown;
29
29
  };
30
- export type NodeHTTPResponse = ServerResponse & {
30
+ export type NodeHTTPResponse = http.ServerResponse & {
31
31
  /**
32
32
  * Force the partially-compressed response to be flushed to the client.
33
33
  *
@@ -1,3 +1,4 @@
1
+ import type { DefaultErrorData } from '../error/formatter';
1
2
  import type { TRPCError } from '../error/TRPCError';
2
3
  import type { TRPC_ERROR_CODES_BY_KEY, TRPCResponse } from '../rpc';
3
4
  import { TRPC_ERROR_CODES_BY_NUMBER } from '../rpc';
@@ -32,9 +33,11 @@ export function getHTTPStatusCode(json: TRPCResponse | TRPCResponse[]) {
32
33
  const httpStatuses = new Set(
33
34
  arr.map((res) => {
34
35
  if ('error' in res) {
35
- const data = res.error.data;
36
- if (typeof data['httpStatus'] === 'number') {
37
- return data['httpStatus'];
36
+ const data = res.error.data as
37
+ | Record<string, unknown>
38
+ | DefaultErrorData;
39
+ if (typeof data.httpStatus === 'number') {
40
+ return data.httpStatus;
38
41
  }
39
42
  const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];
40
43
  return getStatusCodeFromKey(code);
@@ -52,10 +52,6 @@ export type { ProcedureBuilder } from './procedureBuilder';
52
52
  export * from './rootConfig';
53
53
  export type {
54
54
  AnyRouter,
55
- AnyRouterDef,
56
- CreateRouterInner,
57
- ProcedureRecord,
58
- ProcedureRouterRecord,
59
55
  Router,
60
56
  RouterCaller,
61
57
  createRouterFactory,
@@ -9,29 +9,13 @@ import type {
9
9
  import type { ProcedureCallOptions } from './procedureBuilder';
10
10
  import type { AnyRootTypes, RootConfig } from './rootConfig';
11
11
  import { defaultTransformer } from './transformer';
12
- import type { MaybePromise } from './types';
12
+ import type { MaybePromise, ValueOf } from './types';
13
13
  import { mergeWithoutOverrides, omitPrototype } from './utils';
14
14
 
15
- /** @internal **/
16
- export type ProcedureRecord = Record<string, AnyProcedure>;
17
-
18
- export interface ProcedureRouterRecord {
19
- [key: string]: AnyProcedure | AnyRouter;
20
- }
21
-
22
- export interface RouterDef<
23
- TRoot extends AnyRootTypes,
24
- TRecord extends ProcedureRouterRecord,
25
- > {
26
- _config: RootConfig<TRoot>;
27
- router: true;
28
- procedure?: never;
29
- procedures: TRecord;
30
- record: TRecord;
15
+ export interface RouterRecord {
16
+ [key: string]: AnyProcedure | RouterRecord;
31
17
  }
32
18
 
33
- export type AnyRouterDef = RouterDef<any, any>;
34
-
35
19
  type DecorateProcedure<TProcedure extends AnyProcedure> = (
36
20
  input: inferProcedureInput<TProcedure>,
37
21
  ) => Promise<TProcedure['_def']['_output_out']>;
@@ -39,85 +23,96 @@ type DecorateProcedure<TProcedure extends AnyProcedure> = (
39
23
  /**
40
24
  * @internal
41
25
  */
42
- type DecoratedProcedureRecord<TProcedures extends ProcedureRouterRecord> = {
43
- [TKey in keyof TProcedures]: TProcedures[TKey] extends AnyRouter
44
- ? DecoratedProcedureRecord<TProcedures[TKey]['_def']['record']>
45
- : TProcedures[TKey] extends AnyProcedure
46
- ? DecorateProcedure<TProcedures[TKey]>
26
+ export type DecorateRouterRecord<TRecord extends RouterRecord> = {
27
+ [TKey in keyof TRecord]: TRecord[TKey] extends AnyProcedure
28
+ ? DecorateProcedure<TRecord[TKey]>
29
+ : TRecord[TKey] extends RouterRecord
30
+ ? DecorateRouterRecord<TRecord[TKey]>
47
31
  : never;
48
32
  };
49
33
 
50
34
  /**
51
35
  * @internal
52
36
  */
53
- export type RouterCaller<TDef extends AnyRouterDef> = (
37
+ export type RouterCaller<
38
+ TRoot extends AnyRootTypes,
39
+ TRecord extends RouterRecord,
40
+ > = (
54
41
  /**
55
42
  * @note
56
43
  * If passing a function, we recommend it's a cached function
57
44
  * e.g. wrapped in `React.cache` to avoid unnecessary computations
58
45
  */
59
- ctx:
60
- | TDef['_config']['$types']['ctx']
61
- | (() => MaybePromise<TDef['_config']['$types']['ctx']>),
62
- ) => DecoratedProcedureRecord<TDef['record']>;
46
+ ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),
47
+ ) => DecorateRouterRecord<TRecord>;
63
48
 
64
- export interface Router<TDef extends AnyRouterDef> {
65
- _def: TDef;
49
+ export interface Router<
50
+ TRoot extends AnyRootTypes,
51
+ TRecord extends RouterRecord,
52
+ > {
53
+ _def: {
54
+ _config: RootConfig<TRoot>;
55
+ router: true;
56
+ procedure?: never;
57
+ procedures: TRecord;
58
+ record: TRecord;
59
+ };
66
60
  /**
67
61
  * @deprecated use `t.createCallerFactory(router)` instead
68
62
  * @link https://trpc.io/docs/v11/server/server-side-calls
69
63
  */
70
- createCaller: RouterCaller<TDef>;
64
+ createCaller: RouterCaller<TRoot, TRecord>;
71
65
  }
72
66
 
73
- export type AnyRouter = Router<AnyRouterDef>;
67
+ export type BuiltRouter<
68
+ TRoot extends AnyRootTypes,
69
+ TDef extends RouterRecord,
70
+ > = Router<TRoot, TDef> & TDef;
71
+
72
+ export type AnyRouter = Router<any, any>;
74
73
 
75
- type inferRouterDef<TRouter extends AnyRouter> = TRouter extends Router<
76
- infer TParams
77
- >
78
- ? TParams extends AnyRouterDef
79
- ? TParams
80
- : never
81
- : never;
82
- type inferRouterConfig<TRouter extends AnyRouter> =
83
- inferRouterDef<TRouter>['_config'];
74
+ export type inferRouterRootTypes<TRouter extends AnyRouter> =
75
+ TRouter['_def']['_config']['$types'];
84
76
 
85
77
  export type inferRouterContext<TRouter extends AnyRouter> =
86
- inferRouterConfig<TRouter>['$types']['ctx'];
78
+ inferRouterRootTypes<TRouter>['ctx'];
87
79
  export type inferRouterError<TRouter extends AnyRouter> =
88
- inferRouterConfig<TRouter>['$types']['errorShape'];
80
+ inferRouterRootTypes<TRouter>['errorShape'];
89
81
  export type inferRouterMeta<TRouter extends AnyRouter> =
90
- inferRouterConfig<TRouter>['$types']['meta'];
82
+ inferRouterRootTypes<TRouter>['meta'];
91
83
 
92
- type GetInferenceHelpers<
84
+ export type GetInferenceHelpers<
93
85
  TType extends 'input' | 'output',
94
- TRouter extends AnyRouter,
86
+ TRoot extends AnyRootTypes,
87
+ TRecord extends RouterRecord,
95
88
  > = {
96
- [TKey in keyof TRouter['_def']['record']]: TRouter['_def']['record'][TKey] extends infer TRouterOrProcedure
97
- ? TRouterOrProcedure extends AnyRouter
98
- ? GetInferenceHelpers<TType, TRouterOrProcedure>
99
- : TRouterOrProcedure extends AnyProcedure
89
+ [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value
90
+ ? $Value extends RouterRecord
91
+ ? GetInferenceHelpers<TType, TRoot, $Value>
92
+ : $Value extends AnyProcedure
100
93
  ? TType extends 'input'
101
- ? inferProcedureInput<TRouterOrProcedure>
102
- : inferTransformedProcedureOutput<TRouter, TRouterOrProcedure>
94
+ ? inferProcedureInput<$Value>
95
+ : inferTransformedProcedureOutput<TRoot, $Value>
103
96
  : never
104
97
  : never;
105
98
  };
106
99
 
107
100
  export type inferRouterInputs<TRouter extends AnyRouter> = GetInferenceHelpers<
108
101
  'input',
109
- TRouter
102
+ TRouter['_def']['_config']['$types'],
103
+ TRouter['_def']['record']
110
104
  >;
111
105
 
112
106
  export type inferRouterOutputs<TRouter extends AnyRouter> = GetInferenceHelpers<
113
107
  'output',
114
- TRouter
108
+ TRouter['_def']['_config']['$types'],
109
+ TRouter['_def']['record']
115
110
  >;
116
111
 
117
112
  function isRouter(
118
- procedureOrRouter: AnyProcedure | AnyRouter,
113
+ procedureOrRouter: ValueOf<CreateRouterOptions>,
119
114
  ): procedureOrRouter is AnyRouter {
120
- return 'router' in procedureOrRouter._def;
115
+ return procedureOrRouter._def && 'router' in procedureOrRouter._def;
121
116
  }
122
117
 
123
118
  const emptyRouter = {
@@ -142,17 +137,23 @@ const reservedWords = [
142
137
  'then',
143
138
  ];
144
139
 
145
- /**
146
- * @internal
147
- */
148
- export type CreateRouterInner<
149
- TRoot extends AnyRootTypes,
150
- TProcRouterRecord extends ProcedureRouterRecord,
151
- > = Router<RouterDef<TRoot, TProcRouterRecord>> &
152
- /**
153
- * This adds ability to call procedures directly but is primarily used for quick access in type inference
154
- */
155
- TProcRouterRecord;
140
+ export type CreateRouterOptions = {
141
+ [key: string]: AnyProcedure | AnyRouter | CreateRouterOptions;
142
+ };
143
+
144
+ export type DecorateCreateRouterOptions<
145
+ TRouterOptions extends CreateRouterOptions,
146
+ > = {
147
+ [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value
148
+ ? $Value extends AnyProcedure
149
+ ? $Value
150
+ : $Value extends Router<any, infer TRecord>
151
+ ? TRecord
152
+ : $Value extends CreateRouterOptions
153
+ ? DecorateCreateRouterOptions<$Value>
154
+ : never
155
+ : never;
156
+ };
156
157
 
157
158
  /**
158
159
  * @internal
@@ -160,13 +161,15 @@ export type CreateRouterInner<
160
161
  export function createRouterFactory<TRoot extends AnyRootTypes>(
161
162
  config: RootConfig<TRoot>,
162
163
  ) {
163
- return function createRouterInner<
164
- TProcRouterRecord extends ProcedureRouterRecord,
165
- >(
166
- procedures: TProcRouterRecord,
167
- ): CreateRouterInner<TRoot, TProcRouterRecord> {
164
+ function createRouterInner<TInput extends RouterRecord>(
165
+ input: TInput,
166
+ ): BuiltRouter<TRoot, TInput>;
167
+ function createRouterInner<TInput extends CreateRouterOptions>(
168
+ input: TInput,
169
+ ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;
170
+ function createRouterInner(input: RouterRecord | CreateRouterOptions) {
168
171
  const reservedWordsUsed = new Set(
169
- Object.keys(procedures).filter((v) => reservedWords.includes(v)),
172
+ Object.keys(input).filter((v) => reservedWords.includes(v)),
170
173
  );
171
174
  if (reservedWordsUsed.size > 0) {
172
175
  throw new Error(
@@ -175,37 +178,47 @@ export function createRouterFactory<TRoot extends AnyRootTypes>(
175
178
  );
176
179
  }
177
180
 
178
- const routerProcedures: ProcedureRecord = omitPrototype({});
179
- function recursiveGetPaths(procedures: ProcedureRouterRecord, path = '') {
180
- for (const [key, procedureOrRouter] of Object.entries(procedures ?? {})) {
181
- const newPath = `${path}${key}`;
181
+ const procedures: Record<string, AnyProcedure> = omitPrototype({});
182
182
 
183
- if (isRouter(procedureOrRouter)) {
184
- recursiveGetPaths(procedureOrRouter._def.procedures, `${newPath}.`);
183
+ function step(from: CreateRouterOptions, path: string[] = []) {
184
+ const aggregate: RouterRecord = omitPrototype({});
185
+ for (const [key, item] of Object.entries(from ?? {})) {
186
+ if (isRouter(item)) {
187
+ aggregate[key] = step(item._def.record, [...path, key]);
185
188
  continue;
186
189
  }
190
+ if (!isProcedure(item)) {
191
+ // RouterRecord
192
+ aggregate[key] = step(item, [...path, key]);
193
+ continue;
194
+ }
195
+
196
+ const newPath = [...path, key].join('.');
187
197
 
188
- if (routerProcedures[newPath]) {
198
+ if (procedures[newPath]) {
189
199
  throw new Error(`Duplicate key: ${newPath}`);
190
200
  }
191
201
 
192
- routerProcedures[newPath] = procedureOrRouter;
202
+ procedures[newPath] = item;
203
+ aggregate[key] = item;
193
204
  }
205
+
206
+ return aggregate;
194
207
  }
195
- recursiveGetPaths(procedures);
208
+ const record = step(input);
196
209
 
197
- const _def: AnyRouterDef = {
210
+ const _def: AnyRouter['_def'] = {
198
211
  _config: config,
199
212
  router: true,
200
- procedures: routerProcedures,
213
+ procedures,
201
214
  ...emptyRouter,
202
- record: procedures,
215
+ record,
203
216
  };
204
217
 
205
- const router: AnyRouter = {
206
- ...procedures,
218
+ return {
219
+ ...record,
207
220
  _def,
208
- createCaller(ctx) {
221
+ createCaller(ctx: TRoot['ctx']) {
209
222
  const proxy = createRecursiveProxy(({ path, args }) => {
210
223
  const fullPath = path.join('.');
211
224
  const procedure = _def.procedures[fullPath] as AnyProcedure;
@@ -218,24 +231,24 @@ export function createRouterFactory<TRoot extends AnyRootTypes>(
218
231
  });
219
232
  });
220
233
 
221
- return proxy as ReturnType<RouterCaller<any>>;
234
+ return proxy as ReturnType<RouterCaller<any, any>>;
222
235
  },
223
236
  };
237
+ }
224
238
 
225
- return router as any;
226
- };
239
+ return createRouterInner;
227
240
  }
228
241
 
229
242
  function isProcedure(
230
- procedureOrRouter: AnyProcedure | AnyRouter,
243
+ procedureOrRouter: ValueOf<CreateRouterOptions>,
231
244
  ): procedureOrRouter is AnyProcedure {
232
- return !!procedureOrRouter._def.procedure;
245
+ return typeof procedureOrRouter === 'function';
233
246
  }
234
247
  /**
235
248
  * @internal
236
249
  */
237
250
  export function callProcedure(
238
- opts: ProcedureCallOptions & { procedures: ProcedureRouterRecord },
251
+ opts: ProcedureCallOptions & { procedures: RouterRecord },
239
252
  ) {
240
253
  const { type, path } = opts;
241
254
  const proc = opts.procedures[path];
@@ -250,15 +263,16 @@ export function callProcedure(
250
263
  }
251
264
 
252
265
  export function createCallerFactory<TRoot extends AnyRootTypes>() {
253
- return function createCallerInner<
254
- TRouter extends Router<RouterDef<TRoot, any>>,
255
- >(router: TRouter): RouterCaller<TRouter['_def']> {
266
+ return function createCallerInner<TRecord extends RouterRecord>(
267
+ router: Router<TRoot, TRecord>,
268
+ ): RouterCaller<TRoot, TRecord> {
256
269
  const _def = router._def;
257
270
  type Context = TRoot['ctx'];
258
271
 
259
272
  return function createCaller(maybeContext) {
260
273
  const proxy = createRecursiveProxy(({ path, args }) => {
261
274
  const fullPath = path.join('.');
275
+
262
276
  const procedure = _def.procedures[fullPath] as AnyProcedure;
263
277
 
264
278
  const callProc = (ctx: Context) =>
@@ -280,7 +294,7 @@ export function createCallerFactory<TRoot extends AnyRootTypes>() {
280
294
  return callProc(maybeContext);
281
295
  });
282
296
 
283
- return proxy as ReturnType<RouterCaller<any>>;
297
+ return proxy as ReturnType<RouterCaller<any, any>>;
284
298
  };
285
299
  };
286
300
  }
@@ -288,25 +302,15 @@ export function createCallerFactory<TRoot extends AnyRootTypes>() {
288
302
  /** @internal */
289
303
  type MergeRouters<
290
304
  TRouters extends AnyRouter[],
291
- TRouterDef extends AnyRouterDef = RouterDef<
292
- TRouters[0]['_def']['_config']['$types'],
293
- // eslint-disable-next-line @typescript-eslint/ban-types
294
- {}
295
- >,
305
+ TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],
306
+ // eslint-disable-next-line @typescript-eslint/ban-types
307
+ TRecord extends RouterRecord = {},
296
308
  > = TRouters extends [
297
309
  infer Head extends AnyRouter,
298
310
  ...infer Tail extends AnyRouter[],
299
311
  ]
300
- ? MergeRouters<
301
- Tail,
302
- {
303
- _config: TRouterDef['_config'];
304
- router: true;
305
- procedures: Head['_def']['procedures'] & TRouterDef['procedures'];
306
- record: Head['_def']['record'] & TRouterDef['record'];
307
- }
308
- >
309
- : Router<TRouterDef> & TRouterDef['record'];
312
+ ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>
313
+ : BuiltRouter<TRoot, TRecord>;
310
314
 
311
315
  export function mergeRouters<TRouters extends AnyRouter[]>(
312
316
  ...routerList: [...TRouters]
@@ -353,12 +357,13 @@ export function mergeRouters<TRouters extends AnyRouter[]>(
353
357
  const router = createRouterFactory({
354
358
  errorFormatter,
355
359
  transformer,
356
- isDev: routerList.some((r) => r._def._config.isDev),
357
- allowOutsideOfServer: routerList.some(
360
+ isDev: routerList.every((r) => r._def._config.isDev),
361
+ allowOutsideOfServer: routerList.every(
358
362
  (r) => r._def._config.allowOutsideOfServer,
359
363
  ),
360
- isServer: routerList.some((r) => r._def._config.isServer),
364
+ isServer: routerList.every((r) => r._def._config.isServer),
361
365
  $types: routerList[0]?._def._config.$types,
362
366
  })(record);
363
- return router as any;
367
+
368
+ return router as MergeRouters<TRouters>;
364
369
  }
@@ -1,3 +1,4 @@
1
+ import type { ValueOf } from '../types';
1
2
  import { invert } from '../utils';
2
3
 
3
4
  // reference: https://www.jsonrpc.org/specification
@@ -39,6 +40,5 @@ export const TRPC_ERROR_CODES_BY_KEY = {
39
40
 
40
41
  export const TRPC_ERROR_CODES_BY_NUMBER = invert(TRPC_ERROR_CODES_BY_KEY);
41
42
 
42
- type ValueOf<TObj> = TObj[keyof TObj];
43
43
  export type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;
44
44
  export type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;
@@ -5,9 +5,7 @@ import type { TRPC_ERROR_CODE_NUMBER } from './codes';
5
5
  /**
6
6
  * Error response
7
7
  */
8
- export interface TRPCErrorShape<
9
- TData extends Record<string, unknown> = Record<string, unknown>,
10
- > {
8
+ export interface TRPCErrorShape<TData extends object = object> {
11
9
  code: TRPC_ERROR_CODE_NUMBER;
12
10
  message: string;
13
11
  data: TData;
@@ -154,3 +154,4 @@ export const ERROR_SYMBOL = Symbol('TypeError');
154
154
  export type TypeError<TMessage extends string> = TMessage & {
155
155
  _: typeof ERROR_SYMBOL;
156
156
  };
157
+ export type ValueOf<TObj> = TObj[keyof TObj];
@@ -1,203 +0,0 @@
1
- 'use strict';
2
-
3
- var search = require('./search.js');
4
- var utils = require('./utils.js');
5
-
6
- const mergeArrays2 = Function.prototype.apply.bind(utils.mergeArrays, undefined);
7
- const dash = utils.stringToArray('--');
8
- const CRLF = utils.stringToArray('\r\n');
9
- function parseContentDisposition(header) {
10
- const parts = header.split(';').map(part => part.trim());
11
- if (parts.shift() !== 'form-data') {
12
- throw new Error('malformed content-disposition header: missing "form-data" in `' + JSON.stringify(parts) + '`');
13
- }
14
- const out = {};
15
- for (const part of parts) {
16
- const kv = part.split('=', 2);
17
- if (kv.length !== 2) {
18
- throw new Error('malformed content-disposition header: key-value pair not found - ' + part + ' in `' + header + '`');
19
- }
20
- const [name, value] = kv;
21
- if (value[0] === '"' && value[value.length - 1] === '"') {
22
- out[name] = value.slice(1, -1).replace(/\\"/g, '"');
23
- } else if (value[0] !== '"' && value[value.length - 1] !== '"') {
24
- out[name] = value;
25
- } else if (value[0] === '"' && value[value.length - 1] !== '"' || value[0] !== '"' && value[value.length - 1] === '"') {
26
- throw new Error('malformed content-disposition header: mismatched quotations in `' + header + '`');
27
- }
28
- }
29
- if (!out.name) {
30
- throw new Error('malformed content-disposition header: missing field name in `' + header + '`');
31
- }
32
- return out;
33
- }
34
- function parsePartHeaders(lines) {
35
- const entries = [];
36
- let disposition = false;
37
- let line;
38
- while (typeof (line = lines.shift()) !== 'undefined') {
39
- const colon = line.indexOf(':');
40
- if (colon === -1) {
41
- throw new Error('malformed multipart-form header: missing colon');
42
- }
43
- const header = line.slice(0, colon).trim().toLowerCase();
44
- const value = line.slice(colon + 1).trim();
45
- switch (header) {
46
- case 'content-disposition':
47
- disposition = true;
48
- entries.push(...Object.entries(parseContentDisposition(value)));
49
- break;
50
- case 'content-type':
51
- entries.push([
52
- 'contentType',
53
- value
54
- ]);
55
- }
56
- }
57
- if (!disposition) {
58
- throw new Error('malformed multipart-form header: missing content-disposition');
59
- }
60
- return Object.fromEntries(entries);
61
- }
62
- async function readHeaderLines(it, needle) {
63
- let firstChunk = true;
64
- let lastTokenWasMatch = false;
65
- const headerLines = [[]];
66
- const crlfSearch = new search.StreamSearch(CRLF);
67
- for (;;) {
68
- const result = await it.next();
69
- if (result.done) {
70
- throw new Error('malformed multipart-form data: unexpected end of stream');
71
- }
72
- if (firstChunk && result.value !== search.MATCH && utils.arraysEqual(result.value.slice(0, 2), dash)) {
73
- return [
74
- undefined,
75
- new Uint8Array()
76
- ];
77
- }
78
- let chunk;
79
- if (result.value !== search.MATCH) {
80
- chunk = result.value;
81
- } else if (!lastTokenWasMatch) {
82
- chunk = needle;
83
- } else {
84
- throw new Error('malformed multipart-form data: unexpected boundary');
85
- }
86
- if (!chunk.length) {
87
- continue;
88
- }
89
- if (firstChunk) {
90
- firstChunk = false;
91
- }
92
- const tokens = crlfSearch.feed(chunk);
93
- for (const [i, token] of tokens.entries()) {
94
- const isMatch = token === search.MATCH;
95
- if (!isMatch && !token.length) {
96
- continue;
97
- }
98
- if (lastTokenWasMatch && isMatch) {
99
- tokens.push(crlfSearch.end());
100
- return [
101
- headerLines.filter(chunks => chunks.length).map(mergeArrays2).map(utils.arrayToString),
102
- utils.mergeArrays(...tokens.slice(i + 1).map(token => token === search.MATCH ? CRLF : token))
103
- ];
104
- }
105
- if (lastTokenWasMatch = isMatch) {
106
- headerLines.push([]);
107
- } else {
108
- headerLines[headerLines.length - 1].push(token);
109
- }
110
- }
111
- }
112
- }
113
- async function* streamMultipart(body, boundary) {
114
- const needle = utils.mergeArrays(dash, utils.stringToArray(boundary));
115
- const it = new search.ReadableStreamSearch(needle, body)[Symbol.asyncIterator]();
116
- for (;;) {
117
- const result = await it.next();
118
- if (result.done) {
119
- return;
120
- }
121
- if (result.value === search.MATCH) {
122
- break;
123
- }
124
- }
125
- const crlfSearch = new search.StreamSearch(CRLF);
126
- for (;;) {
127
- const [headerLines, tail] = await readHeaderLines(it, needle);
128
- if (!headerLines) {
129
- return;
130
- }
131
- async function nextToken() {
132
- const result = await it.next();
133
- if (result.done) {
134
- throw new Error('malformed multipart-form data: unexpected end of stream');
135
- }
136
- return result;
137
- }
138
- let trailingCRLF = false;
139
- function feedChunk(chunk) {
140
- const chunks = [];
141
- for (const token of crlfSearch.feed(chunk)) {
142
- if (trailingCRLF) {
143
- chunks.push(CRLF);
144
- }
145
- if (!(trailingCRLF = token === search.MATCH)) {
146
- chunks.push(token);
147
- }
148
- }
149
- return utils.mergeArrays(...chunks);
150
- }
151
- let done = false;
152
- async function nextChunk() {
153
- const result = await nextToken();
154
- let chunk;
155
- if (result.value !== search.MATCH) {
156
- chunk = result.value;
157
- } else if (!trailingCRLF) {
158
- chunk = CRLF;
159
- } else {
160
- done = true;
161
- return { value: crlfSearch.end() };
162
- }
163
- return { value: feedChunk(chunk) };
164
- }
165
- const bufferedChunks = [{ value: feedChunk(tail) }];
166
- yield {
167
- ...parsePartHeaders(headerLines),
168
- data: {
169
- [Symbol.asyncIterator]() {
170
- return this;
171
- },
172
- async next() {
173
- for (;;) {
174
- const result = bufferedChunks.shift();
175
- if (!result) {
176
- break;
177
- }
178
- if (result.value.length > 0) {
179
- return result;
180
- }
181
- }
182
- for (;;) {
183
- if (done) {
184
- return {
185
- done,
186
- value: undefined
187
- };
188
- }
189
- const result = await nextChunk();
190
- if (result.value.length > 0) {
191
- return result;
192
- }
193
- }
194
- }
195
- }
196
- };
197
- while (!done) {
198
- bufferedChunks.push(await nextChunk());
199
- }
200
- }
201
- }
202
-
203
- exports.streamMultipart = streamMultipart;