@trpc/server 11.0.0-rc.361 → 11.0.0-rc.363

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 (178) hide show
  1. package/dist/@trpc/server/http.d.ts +7 -5
  2. package/dist/@trpc/server/http.d.ts.map +1 -1
  3. package/dist/@trpc/server/index.d.ts +1 -2
  4. package/dist/@trpc/server/index.d.ts.map +1 -1
  5. package/dist/adapters/aws-lambda/getPlanner.d.ts +13 -0
  6. package/dist/adapters/aws-lambda/getPlanner.d.ts.map +1 -0
  7. package/dist/adapters/aws-lambda/getPlanner.js +143 -0
  8. package/dist/adapters/aws-lambda/getPlanner.mjs +141 -0
  9. package/dist/adapters/aws-lambda/index.d.ts +12 -9
  10. package/dist/adapters/aws-lambda/index.d.ts.map +1 -1
  11. package/dist/adapters/aws-lambda/index.js +8 -77
  12. package/dist/adapters/aws-lambda/index.mjs +9 -72
  13. package/dist/adapters/express.js +1 -0
  14. package/dist/adapters/express.mjs +1 -0
  15. package/dist/adapters/fastify/fastifyRequestHandler.d.ts +19 -2
  16. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +1 -1
  17. package/dist/adapters/fastify/fastifyRequestHandler.js +22 -64
  18. package/dist/adapters/fastify/fastifyRequestHandler.mjs +22 -64
  19. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts +1 -1
  20. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +1 -1
  21. package/dist/adapters/fastify/fastifyTRPCPlugin.js +1 -0
  22. package/dist/adapters/fastify/fastifyTRPCPlugin.mjs +1 -0
  23. package/dist/adapters/fetch/fetchRequestHandler.d.ts +2 -2
  24. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  25. package/dist/adapters/fetch/fetchRequestHandler.js +29 -86
  26. package/dist/adapters/fetch/fetchRequestHandler.mjs +29 -86
  27. package/dist/adapters/fetch/types.d.ts +2 -2
  28. package/dist/adapters/fetch/types.d.ts.map +1 -1
  29. package/dist/adapters/next.js +1 -1
  30. package/dist/adapters/next.mjs +1 -1
  31. package/dist/adapters/node-http/incomingMessageToRequest.d.ts +18 -0
  32. package/dist/adapters/node-http/incomingMessageToRequest.d.ts.map +1 -0
  33. package/dist/adapters/node-http/incomingMessageToRequest.js +71 -0
  34. package/dist/adapters/node-http/incomingMessageToRequest.mjs +69 -0
  35. package/dist/adapters/node-http/index.d.ts +1 -0
  36. package/dist/adapters/node-http/index.d.ts.map +1 -1
  37. package/dist/adapters/node-http/index.js +2 -0
  38. package/dist/adapters/node-http/index.mjs +1 -0
  39. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +1 -1
  40. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  41. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +28 -71
  42. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +28 -71
  43. package/dist/adapters/node-http/types.d.ts +7 -8
  44. package/dist/adapters/node-http/types.d.ts.map +1 -1
  45. package/dist/adapters/ws.js +1 -1
  46. package/dist/adapters/ws.mjs +1 -1
  47. package/dist/bundle-analysis.json +174 -271
  48. package/dist/http.js +4 -2
  49. package/dist/http.mjs +2 -1
  50. package/dist/index.js +2 -4
  51. package/dist/index.mjs +1 -2
  52. package/dist/unstable-core-do-not-import/http/contentType.d.ts +8 -20
  53. package/dist/unstable-core-do-not-import/http/contentType.d.ts.map +1 -1
  54. package/dist/unstable-core-do-not-import/http/contentType.js +180 -0
  55. package/dist/unstable-core-do-not-import/http/contentType.mjs +178 -0
  56. package/dist/unstable-core-do-not-import/http/contentTypeParsers.d.ts +14 -0
  57. package/dist/unstable-core-do-not-import/http/contentTypeParsers.d.ts.map +1 -0
  58. package/dist/unstable-core-do-not-import/http/contentTypeParsers.js +14 -0
  59. package/dist/unstable-core-do-not-import/http/contentTypeParsers.mjs +12 -0
  60. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.d.ts +1 -1
  61. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.d.ts.map +1 -1
  62. package/dist/unstable-core-do-not-import/http/resolveResponse.d.ts +15 -0
  63. package/dist/unstable-core-do-not-import/http/resolveResponse.d.ts.map +1 -0
  64. package/dist/unstable-core-do-not-import/http/{resolveHTTPResponse.js → resolveResponse.js} +119 -134
  65. package/dist/unstable-core-do-not-import/http/{resolveHTTPResponse.mjs → resolveResponse.mjs} +119 -134
  66. package/dist/unstable-core-do-not-import/http/types.d.ts +25 -27
  67. package/dist/unstable-core-do-not-import/http/types.d.ts.map +1 -1
  68. package/dist/unstable-core-do-not-import/initTRPC.d.ts +1 -1
  69. package/dist/unstable-core-do-not-import/procedureBuilder.d.ts +1 -3
  70. package/dist/unstable-core-do-not-import/procedureBuilder.d.ts.map +1 -1
  71. package/dist/unstable-core-do-not-import/procedureBuilder.js +0 -2
  72. package/dist/unstable-core-do-not-import/procedureBuilder.mjs +1 -2
  73. package/dist/unstable-core-do-not-import/rootConfig.d.ts +0 -9
  74. package/dist/unstable-core-do-not-import/rootConfig.d.ts.map +1 -1
  75. package/dist/unstable-core-do-not-import/utils.d.ts +3 -0
  76. package/dist/unstable-core-do-not-import/utils.d.ts.map +1 -1
  77. package/dist/unstable-core-do-not-import/utils.js +2 -0
  78. package/dist/unstable-core-do-not-import/utils.mjs +2 -1
  79. package/dist/unstable-core-do-not-import.d.ts +9 -3
  80. package/dist/unstable-core-do-not-import.d.ts.map +1 -1
  81. package/dist/unstable-core-do-not-import.js +12 -8
  82. package/dist/unstable-core-do-not-import.mjs +7 -5
  83. package/package.json +3 -13
  84. package/src/@trpc/server/http.ts +7 -12
  85. package/src/@trpc/server/index.ts +0 -3
  86. package/src/adapters/aws-lambda/getPlanner.ts +191 -0
  87. package/src/adapters/aws-lambda/index.ts +43 -107
  88. package/src/adapters/express.ts +1 -1
  89. package/src/adapters/fastify/fastifyRequestHandler.ts +43 -90
  90. package/src/adapters/fastify/fastifyTRPCPlugin.ts +4 -3
  91. package/src/adapters/fetch/fetchRequestHandler.ts +35 -111
  92. package/src/adapters/fetch/types.ts +4 -2
  93. package/src/adapters/next.ts +1 -1
  94. package/src/adapters/node-http/incomingMessageToRequest.ts +94 -0
  95. package/src/adapters/node-http/index.ts +1 -0
  96. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +31 -97
  97. package/src/adapters/node-http/types.ts +27 -37
  98. package/src/adapters/standalone.ts +1 -1
  99. package/src/unstable-core-do-not-import/http/contentType.ts +214 -22
  100. package/src/unstable-core-do-not-import/http/contentTypeParsers.ts +29 -0
  101. package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +2 -2
  102. package/src/unstable-core-do-not-import/http/resolveResponse.ts +386 -0
  103. package/src/unstable-core-do-not-import/http/types.ts +25 -30
  104. package/src/unstable-core-do-not-import/procedureBuilder.ts +2 -4
  105. package/src/unstable-core-do-not-import/rootConfig.ts +0 -10
  106. package/src/unstable-core-do-not-import/utils.ts +4 -0
  107. package/src/unstable-core-do-not-import.ts +9 -3
  108. package/adapters/node-http/content-type/form-data/index.d.ts +0 -1
  109. package/adapters/node-http/content-type/form-data/index.js +0 -1
  110. package/adapters/node-http/content-type/json/index.d.ts +0 -1
  111. package/adapters/node-http/content-type/json/index.js +0 -1
  112. package/dist/adapters/aws-lambda/content-type/json/index.d.ts +0 -10
  113. package/dist/adapters/aws-lambda/content-type/json/index.d.ts.map +0 -1
  114. package/dist/adapters/aws-lambda/content-type/json/index.js +0 -62
  115. package/dist/adapters/aws-lambda/content-type/json/index.mjs +0 -60
  116. package/dist/adapters/aws-lambda/utils.d.ts +0 -31
  117. package/dist/adapters/aws-lambda/utils.d.ts.map +0 -1
  118. package/dist/adapters/aws-lambda/utils.js +0 -111
  119. package/dist/adapters/aws-lambda/utils.mjs +0 -103
  120. package/dist/adapters/content-handlers/concurrentCache.d.ts +0 -7
  121. package/dist/adapters/content-handlers/concurrentCache.d.ts.map +0 -1
  122. package/dist/adapters/content-handlers/concurrentCache.js +0 -17
  123. package/dist/adapters/content-handlers/concurrentCache.mjs +0 -15
  124. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts +0 -10
  125. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts.map +0 -1
  126. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.js +0 -33
  127. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.mjs +0 -31
  128. package/dist/adapters/fastify/content-type/json/index.d.ts +0 -8
  129. package/dist/adapters/fastify/content-type/json/index.d.ts.map +0 -1
  130. package/dist/adapters/fastify/content-type/json/index.js +0 -62
  131. package/dist/adapters/fastify/content-type/json/index.mjs +0 -60
  132. package/dist/adapters/fastify/types.d.ts +0 -11
  133. package/dist/adapters/fastify/types.d.ts.map +0 -1
  134. package/dist/adapters/fetch/content-type/json/index.d.ts +0 -9
  135. package/dist/adapters/fetch/content-type/json/index.d.ts.map +0 -1
  136. package/dist/adapters/fetch/content-type/json/index.js +0 -55
  137. package/dist/adapters/fetch/content-type/json/index.mjs +0 -53
  138. package/dist/adapters/node-http/content-type/form-data/index.d.ts +0 -5
  139. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +0 -1
  140. package/dist/adapters/node-http/content-type/form-data/index.js +0 -32
  141. package/dist/adapters/node-http/content-type/form-data/index.mjs +0 -30
  142. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts +0 -7
  143. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +0 -1
  144. package/dist/adapters/node-http/content-type/json/getPostBody.js +0 -45
  145. package/dist/adapters/node-http/content-type/json/getPostBody.mjs +0 -43
  146. package/dist/adapters/node-http/content-type/json/index.d.ts +0 -5
  147. package/dist/adapters/node-http/content-type/json/index.d.ts.map +0 -1
  148. package/dist/adapters/node-http/content-type/json/index.js +0 -68
  149. package/dist/adapters/node-http/content-type/json/index.mjs +0 -66
  150. package/dist/adapters/node-http/content-type/octet/index.d.ts +0 -5
  151. package/dist/adapters/node-http/content-type/octet/index.d.ts.map +0 -1
  152. package/dist/adapters/node-http/content-type/octet/index.js +0 -19
  153. package/dist/adapters/node-http/content-type/octet/index.mjs +0 -17
  154. package/dist/adapters/node-http/content-type/types.d.ts +0 -8
  155. package/dist/adapters/node-http/content-type/types.d.ts.map +0 -1
  156. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts +0 -16
  157. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts.map +0 -1
  158. package/dist/unstable-core-do-not-import/contentTypeParsers.js +0 -23
  159. package/dist/unstable-core-do-not-import/contentTypeParsers.mjs +0 -21
  160. package/dist/unstable-core-do-not-import/http/index.d.ts +0 -11
  161. package/dist/unstable-core-do-not-import/http/index.d.ts.map +0 -1
  162. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts +0 -51
  163. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts.map +0 -1
  164. package/src/adapters/aws-lambda/content-type/json/index.ts +0 -108
  165. package/src/adapters/aws-lambda/utils.ts +0 -170
  166. package/src/adapters/content-handlers/concurrentCache.ts +0 -16
  167. package/src/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.ts +0 -45
  168. package/src/adapters/fastify/content-type/json/index.ts +0 -106
  169. package/src/adapters/fastify/types.ts +0 -22
  170. package/src/adapters/fetch/content-type/json/index.ts +0 -90
  171. package/src/adapters/node-http/content-type/form-data/index.ts +0 -37
  172. package/src/adapters/node-http/content-type/json/getPostBody.ts +0 -49
  173. package/src/adapters/node-http/content-type/json/index.ts +0 -100
  174. package/src/adapters/node-http/content-type/octet/index.ts +0 -27
  175. package/src/adapters/node-http/content-type/types.ts +0 -19
  176. package/src/unstable-core-do-not-import/contentTypeParsers.ts +0 -37
  177. package/src/unstable-core-do-not-import/http/index.ts +0 -28
  178. package/src/unstable-core-do-not-import/http/resolveHTTPResponse.ts +0 -461
@@ -0,0 +1,386 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
+ import { getErrorShape } from '../error/getErrorShape';
3
+ import { getTRPCErrorFromUnknown, TRPCError } from '../error/TRPCError';
4
+ import type { ProcedureType } from '../procedure';
5
+ import {
6
+ callProcedure,
7
+ type AnyRouter,
8
+ type inferRouterContext,
9
+ type inferRouterError,
10
+ } from '../router';
11
+ import type { TRPCResponse } from '../rpc';
12
+ import { transformTRPCResponse } from '../transformer';
13
+ import { getBatchStreamFormatter } from './batchStreamFormatter';
14
+ import { getRequestInfo } from './contentType';
15
+ import { getHTTPStatusCode } from './getHTTPStatusCode';
16
+ import type {
17
+ HTTPBaseHandlerOptions,
18
+ ResolveHTTPRequestOptionsContextFn,
19
+ TRPCRequestInfo,
20
+ } from './types';
21
+
22
+ const HTTP_METHOD_PROCEDURE_TYPE_MAP: Record<
23
+ string,
24
+ ProcedureType | undefined
25
+ > = {
26
+ GET: 'query',
27
+ POST: 'mutation',
28
+ };
29
+
30
+ interface ResolveHTTPRequestOptions<TRouter extends AnyRouter>
31
+ extends HTTPBaseHandlerOptions<TRouter, Request> {
32
+ createContext: ResolveHTTPRequestOptionsContextFn<TRouter>;
33
+ req: Request;
34
+ path: string;
35
+ /**
36
+ * If the request had an issue before reaching the handler
37
+ */
38
+ error: TRPCError | null;
39
+ }
40
+
41
+ function initResponse<TRouter extends AnyRouter, TRequest>(initOpts: {
42
+ ctx: inferRouterContext<TRouter> | undefined;
43
+ info: TRPCRequestInfo | undefined;
44
+ type: ProcedureType | 'unknown';
45
+ responseMeta?: HTTPBaseHandlerOptions<TRouter, TRequest>['responseMeta'];
46
+ untransformedJSON?:
47
+ | TRPCResponse<unknown, inferRouterError<TRouter>>
48
+ | TRPCResponse<unknown, inferRouterError<TRouter>>[]
49
+ | undefined;
50
+ errors: TRPCError[];
51
+ }) {
52
+ const {
53
+ ctx,
54
+ info,
55
+ type,
56
+ responseMeta,
57
+ untransformedJSON,
58
+ errors = [],
59
+ } = initOpts;
60
+
61
+ let status = untransformedJSON ? getHTTPStatusCode(untransformedJSON) : 200;
62
+
63
+ const headers = new Headers([['Content-Type', 'application/json']]);
64
+
65
+ const eagerGeneration = !untransformedJSON;
66
+ const data = eagerGeneration
67
+ ? []
68
+ : Array.isArray(untransformedJSON)
69
+ ? untransformedJSON
70
+ : [untransformedJSON];
71
+
72
+ const meta =
73
+ responseMeta?.({
74
+ ctx,
75
+ info,
76
+ paths: info?.calls.map((call) => call.path),
77
+ type,
78
+ data,
79
+ errors,
80
+ eagerGeneration,
81
+ }) ?? {};
82
+
83
+ if (meta.headers) {
84
+ if (meta.headers instanceof Headers) {
85
+ for (const [key, value] of meta.headers.entries()) {
86
+ headers.append(key, value);
87
+ }
88
+ } else {
89
+ /**
90
+ * @deprecated, delete in v12
91
+ */
92
+ for (const [key, value] of Object.entries(meta.headers)) {
93
+ if (Array.isArray(value)) {
94
+ for (const v of value) {
95
+ headers.append(key, v);
96
+ }
97
+ } else if (typeof value === 'string') {
98
+ headers.set(key, value);
99
+ }
100
+ }
101
+ }
102
+ }
103
+ if (meta.status) {
104
+ status = meta.status;
105
+ }
106
+
107
+ return {
108
+ status,
109
+ headers,
110
+ };
111
+ }
112
+
113
+ function caughtErrorToData<TRouter extends AnyRouter>(
114
+ cause: unknown,
115
+ errorOpts: {
116
+ opts: Pick<
117
+ ResolveHTTPRequestOptions<TRouter>,
118
+ 'onError' | 'req' | 'router'
119
+ >;
120
+ ctx: inferRouterContext<TRouter> | undefined;
121
+ type: ProcedureType | 'unknown';
122
+ path?: string;
123
+ input?: unknown;
124
+ },
125
+ ) {
126
+ const { router, req, onError } = errorOpts.opts;
127
+ const error = getTRPCErrorFromUnknown(cause);
128
+ onError?.({
129
+ error,
130
+ path: errorOpts.path,
131
+ input: errorOpts.input,
132
+ ctx: errorOpts.ctx,
133
+ type: errorOpts.type,
134
+ req,
135
+ });
136
+ const untransformedJSON = {
137
+ error: getErrorShape({
138
+ config: router._def._config,
139
+ error,
140
+ type: errorOpts.type,
141
+ path: errorOpts.path,
142
+ input: errorOpts.input,
143
+ ctx: errorOpts.ctx,
144
+ }),
145
+ };
146
+ const transformedJSON = transformTRPCResponse(
147
+ router._def._config,
148
+ untransformedJSON,
149
+ );
150
+ const body = JSON.stringify(transformedJSON);
151
+ return {
152
+ error,
153
+ untransformedJSON,
154
+ body,
155
+ };
156
+ }
157
+
158
+ export async function resolveResponse<TRouter extends AnyRouter>(
159
+ opts: ResolveHTTPRequestOptions<TRouter>,
160
+ ): Promise<Response> {
161
+ const { router, req } = opts;
162
+
163
+ const url = new URL(req.url);
164
+
165
+ if (req.method === 'HEAD') {
166
+ // can be used for lambda warmup
167
+ return new Response(null, {
168
+ status: 204,
169
+ });
170
+ }
171
+ const allowBatching = opts.allowBatching ?? opts.batching?.enabled ?? true;
172
+ const allowMethodOverride =
173
+ (opts.allowMethodOverride ?? false) && req.method === 'POST';
174
+
175
+ const type =
176
+ HTTP_METHOD_PROCEDURE_TYPE_MAP[req.method] ?? ('unknown' as const);
177
+ let ctx: inferRouterContext<TRouter> | undefined = undefined;
178
+ let info: TRPCRequestInfo | undefined = undefined;
179
+
180
+ const isStreamCall = req.headers.get('trpc-batch-mode') === 'stream';
181
+
182
+ try {
183
+ info = getRequestInfo({
184
+ req,
185
+ path: decodeURIComponent(opts.path),
186
+ config: router._def._config,
187
+ searchParams: url.searchParams,
188
+ });
189
+
190
+ // we create context early so that error handlers may access context information
191
+ ctx = await opts.createContext({
192
+ info,
193
+ });
194
+
195
+ if (opts.error) {
196
+ throw opts.error;
197
+ }
198
+ if (info.isBatchCall && !allowBatching) {
199
+ throw new TRPCError({
200
+ code: 'BAD_REQUEST',
201
+ message: `Batching is not enabled on the server`,
202
+ });
203
+ }
204
+ if (type === 'unknown') {
205
+ throw new TRPCError({
206
+ message: `Unexpected request method ${req.method}`,
207
+ code: 'METHOD_NOT_SUPPORTED',
208
+ });
209
+ }
210
+
211
+ const errors: TRPCError[] = [];
212
+
213
+ const promises: Promise<
214
+ TRPCResponse<unknown, inferRouterError<TRouter>>
215
+ >[] = info.calls.map(async (call) => {
216
+ try {
217
+ const data = await callProcedure({
218
+ procedures: opts.router._def.procedures,
219
+ path: call.path,
220
+ getRawInput: call.getRawInput,
221
+ ctx,
222
+ type,
223
+ allowMethodOverride,
224
+ });
225
+ return {
226
+ result: {
227
+ data,
228
+ },
229
+ };
230
+ } catch (cause) {
231
+ const error = getTRPCErrorFromUnknown(cause);
232
+ errors.push(error);
233
+ const input = call.result();
234
+
235
+ opts.onError?.({
236
+ error,
237
+ path: call.path,
238
+ input,
239
+ ctx,
240
+ type: type,
241
+ req: opts.req,
242
+ });
243
+
244
+ return {
245
+ error: getErrorShape({
246
+ config: opts.router._def._config,
247
+ error,
248
+ type,
249
+ path: call.path,
250
+ input,
251
+ ctx,
252
+ }),
253
+ };
254
+ }
255
+ });
256
+ if (!isStreamCall) {
257
+ /**
258
+ * Non-streaming response:
259
+ * - await all responses in parallel, blocking on the slowest one
260
+ * - create headers with known response body
261
+ * - return a complete HTTPResponse
262
+ */
263
+
264
+ const untransformedJSON = await Promise.all(promises);
265
+ const errors = untransformedJSON.flatMap((response) =>
266
+ 'error' in response ? [response.error] : [],
267
+ );
268
+
269
+ const headResponse = initResponse({
270
+ ctx,
271
+ info,
272
+ type,
273
+ responseMeta: opts.responseMeta,
274
+ untransformedJSON,
275
+ errors,
276
+ });
277
+
278
+ // return body stuff
279
+ const result = info.isBatchCall
280
+ ? untransformedJSON
281
+ : untransformedJSON[0]!;
282
+ const transformedJSON = transformTRPCResponse(
283
+ router._def._config,
284
+ result,
285
+ );
286
+ const body = JSON.stringify(transformedJSON);
287
+
288
+ return new Response(body, {
289
+ status: headResponse.status,
290
+ headers: headResponse.headers,
291
+ });
292
+ }
293
+
294
+ /**
295
+ * Streaming response:
296
+ * - block on none, call `onChunk` as soon as each response is ready
297
+ * - create headers with minimal data (cannot know the response body in advance)
298
+ * - return void
299
+ */
300
+ const headResponse = initResponse({
301
+ ctx,
302
+ info,
303
+ type,
304
+ responseMeta: opts.responseMeta,
305
+ errors: [],
306
+ });
307
+
308
+ const encoder = new TextEncoderStream();
309
+ const stream = encoder.readable;
310
+ const controller = encoder.writable.getWriter();
311
+ async function exec() {
312
+ const indexedPromises = new Map(
313
+ promises.map((promise, index) => [
314
+ index,
315
+ promise.then((r) => [index, r] as const),
316
+ ]),
317
+ );
318
+ const formatter = getBatchStreamFormatter();
319
+
320
+ while (indexedPromises.size > 0) {
321
+ const [index, untransformedJSON] = await Promise.race(
322
+ indexedPromises.values(),
323
+ );
324
+ indexedPromises.delete(index);
325
+
326
+ try {
327
+ const transformedJSON = transformTRPCResponse(
328
+ router._def._config,
329
+ untransformedJSON,
330
+ );
331
+ const body = JSON.stringify(transformedJSON);
332
+
333
+ await controller.write(formatter(index, body));
334
+ } catch (cause) {
335
+ const call = info!.calls[index]!;
336
+ const input = call.result();
337
+ const { body } = caughtErrorToData(cause, {
338
+ opts,
339
+ ctx,
340
+ type,
341
+ path: call.path,
342
+ input,
343
+ });
344
+
345
+ await controller.write(formatter(index, body));
346
+ }
347
+ }
348
+
349
+ await controller.write(formatter.end());
350
+ await controller.close();
351
+ }
352
+ exec().catch((err) => controller.abort(err));
353
+
354
+ return new Response(stream, {
355
+ headers: headResponse.headers,
356
+ status: headResponse.status,
357
+ });
358
+ } catch (cause) {
359
+ // we get here if
360
+ // - batching is called when it's not enabled
361
+ // - `createContext()` throws
362
+ // - `router._def._config.transformer.output.serialize()` throws
363
+ // - post body is too large
364
+ // - input deserialization fails
365
+ // - `errorFormatter` return value is malformed
366
+ const { error, untransformedJSON, body } = caughtErrorToData(cause, {
367
+ opts,
368
+ ctx,
369
+ type,
370
+ });
371
+
372
+ const headResponse = initResponse({
373
+ ctx,
374
+ info,
375
+ type,
376
+ responseMeta: opts.responseMeta,
377
+ untransformedJSON,
378
+ errors: [error],
379
+ });
380
+
381
+ return new Response(body, {
382
+ status: headResponse.status,
383
+ headers: headResponse.headers,
384
+ });
385
+ }
386
+ }
@@ -8,19 +8,14 @@ import type {
8
8
  import type { TRPCResponse } from '../rpc';
9
9
  import type { Dict } from '../types';
10
10
 
11
- export type HTTPHeaders = Dict<string[] | string>;
12
-
13
- export interface HTTPResponse {
14
- status: number;
15
- headers?: HTTPHeaders;
16
- body?: string;
17
- }
18
-
19
- export type ResponseChunk = [procedureIndex: number, responseBody: string];
11
+ /**
12
+ * @deprecated use `Headers` instead, this will be removed in v12
13
+ */
14
+ type HTTPHeaders = Dict<string[] | string>;
20
15
 
21
16
  export interface ResponseMeta {
22
17
  status?: number;
23
- headers?: HTTPHeaders;
18
+ headers?: Headers | HTTPHeaders;
24
19
  }
25
20
 
26
21
  /**
@@ -31,24 +26,18 @@ export type ResponseMetaFn<TRouter extends AnyRouter> = (opts: {
31
26
  ctx?: inferRouterContext<TRouter>;
32
27
  /**
33
28
  * The different tRPC paths requested
29
+ * @deprecated use `info` instead, this will be removed in v12
34
30
  **/
35
- paths?: string[];
31
+ paths: string[] | undefined;
32
+ info: TRPCRequestInfo | undefined;
36
33
  type: ProcedureType | 'unknown';
37
34
  errors: TRPCError[];
38
35
  /**
39
- * `true` if the `ResponseMeta` are being
40
- * generated without knowing the response data
41
- * (e.g. for streaming requests).
36
+ * `true` if the `ResponseMeta` is being generated without knowing the response data (e.g. for streamed requests).
42
37
  */
43
- eagerGeneration?: boolean;
38
+ eagerGeneration: boolean;
44
39
  }) => ResponseMeta;
45
40
 
46
- export interface HTTPRequest {
47
- method: string;
48
- query: URLSearchParams;
49
- headers: HTTPHeaders;
50
- }
51
-
52
41
  /**
53
42
  * Base interface for anything using HTTP
54
43
  */
@@ -62,23 +51,29 @@ export interface HTTPBaseHandlerOptions<TRouter extends AnyRouter, TRequest>
62
51
  responseMeta?: ResponseMetaFn<TRouter>;
63
52
  }
64
53
 
65
- /** @internal */
66
- export type ProcedureCall = {
67
- type: ProcedureType;
54
+ interface TRPCRequestInfoProcedureCall {
68
55
  path: string;
69
- };
56
+ /**
57
+ * Read the raw input (deduped and memoized)
58
+ */
59
+ getRawInput: () => Promise<unknown>;
60
+ /**
61
+ * Get already parsed inputs - won't trigger reading the body or parsing the inputs
62
+ */
63
+ result: () => unknown;
64
+ }
70
65
 
71
66
  /**
72
67
  * Information about the incoming request
73
- * @internal
68
+ * @public
74
69
  */
75
- export type TRPCRequestInfo = {
70
+ export interface TRPCRequestInfo {
76
71
  isBatchCall: boolean;
77
- calls: ProcedureCall[];
78
- };
72
+ calls: TRPCRequestInfoProcedureCall[];
73
+ }
79
74
 
80
75
  /**
81
- * Inner createContext function for `resolveHTTPResponse` used to forward `TRPCRequestInfo` to `createContext`
76
+ * Inner createContext function for `resolveResponse` used to forward `TRPCRequestInfo` to `createContext`
82
77
  * @internal
83
78
  */
84
79
  export type ResolveHTTPRequestOptionsContextFn<TRouter extends AnyRouter> =
@@ -30,6 +30,7 @@ import type {
30
30
  Simplify,
31
31
  TypeError,
32
32
  } from './types';
33
+ import type { UnsetMarker } from './utils';
33
34
  import { mergeWithoutOverrides } from './utils';
34
35
 
35
36
  type IntersectIfDefined<TType, TWith> = TType extends UnsetMarker
@@ -37,10 +38,7 @@ type IntersectIfDefined<TType, TWith> = TType extends UnsetMarker
37
38
  : TWith extends UnsetMarker
38
39
  ? TType
39
40
  : Simplify<TType & TWith>;
40
-
41
- /** @internal */
42
- export const unsetMarker = Symbol('unsetMarker');
43
- type UnsetMarker = typeof unsetMarker;
41
+ ``;
44
42
  type DefaultValue<TValue, TFallback> = TValue extends UnsetMarker
45
43
  ? TFallback
46
44
  : TValue;
@@ -97,13 +97,3 @@ export type CreateContextCallback<
97
97
  createContext: TFunction;
98
98
  }
99
99
  >;
100
-
101
- /**
102
- * @internal
103
- */
104
- export type WrapCreateContext<TFunction extends (...args: any[]) => any> = {
105
- /**
106
- * @link https://trpc.io/docs/v11/context
107
- **/
108
- createContext?: TFunction;
109
- };
@@ -1,3 +1,7 @@
1
+ /** @internal */
2
+ export const unsetMarker = Symbol('unsetMarker');
3
+ export type UnsetMarker = typeof unsetMarker;
4
+
1
5
  /**
2
6
  * Ensures there are no duplicate keys when building a procedure.
3
7
  * @internal
@@ -1,5 +1,5 @@
1
1
  /**
2
- * **DO NOT IMPORT FROM HERE FILE**
2
+ * **DO NOT IMPORT FROM THIS FILE**
3
3
  *
4
4
  * This file is here to:
5
5
  * - make TypeScript happy and prevent _"The inferred type of 'createContext' cannot be named without a reference to [...]"_.
@@ -12,10 +12,16 @@ export * from './unstable-core-do-not-import/clientish/inference';
12
12
  export * from './unstable-core-do-not-import/clientish/inferrable';
13
13
  export * from './unstable-core-do-not-import/clientish/serialize';
14
14
  export * from './unstable-core-do-not-import/createProxy';
15
+ export * from './unstable-core-do-not-import/error/TRPCError';
15
16
  export * from './unstable-core-do-not-import/error/formatter';
16
17
  export * from './unstable-core-do-not-import/error/getErrorShape';
17
- export * from './unstable-core-do-not-import/error/TRPCError';
18
- export * from './unstable-core-do-not-import/http';
18
+ export * from './unstable-core-do-not-import/http/batchStreamFormatter';
19
+ export * from './unstable-core-do-not-import/http/contentType';
20
+ export * from './unstable-core-do-not-import/http/contentTypeParsers';
21
+ export * from './unstable-core-do-not-import/http/getHTTPStatusCode';
22
+ export * from './unstable-core-do-not-import/http/resolveResponse';
23
+ export * from './unstable-core-do-not-import/http/toURL';
24
+ export * from './unstable-core-do-not-import/http/types';
19
25
  export * from './unstable-core-do-not-import/initTRPC';
20
26
  export * from './unstable-core-do-not-import/middleware';
21
27
  export * from './unstable-core-do-not-import/parser';
@@ -1 +0,0 @@
1
- export * from '../../../../dist/adapters/node-http/content-type/form-data';
@@ -1 +0,0 @@
1
- module.exports = require('../../../../dist/adapters/node-http/content-type/form-data');
@@ -1 +0,0 @@
1
- export * from '../../../../dist/adapters/node-http/content-type/json';
@@ -1 +0,0 @@
1
- module.exports = require('../../../../dist/adapters/node-http/content-type/json');
@@ -1,10 +0,0 @@
1
- import type { AnyRouter } from '../../../../@trpc/server';
2
- import type { BaseContentTypeHandler, HTTPRequest } from '../../../../@trpc/server/http';
3
- import { type APIGatewayEvent, type AWSLambdaOptions } from '../../utils';
4
- export interface LambdaHTTPContentTypeHandler<TRouter extends AnyRouter, TEvent extends APIGatewayEvent> extends BaseContentTypeHandler<AWSLambdaOptions<TRouter, TEvent> & {
5
- event: TEvent;
6
- req: HTTPRequest;
7
- }> {
8
- }
9
- export declare const getLambdaHTTPJSONContentTypeHandler: <TRouter extends AnyRouter, TEvent extends APIGatewayEvent>() => LambdaHTTPContentTypeHandler<TRouter, TEvent>;
10
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/adapters/aws-lambda/content-type/json/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,SAAS,EAEV,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACV,sBAAsB,EACtB,WAAW,EACZ,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,4BAA4B,CAC3C,OAAO,SAAS,SAAS,EACzB,MAAM,SAAS,eAAe,CAC9B,SAAQ,sBAAsB,CAC5B,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,WAAW,CAAC;CAClB,CACF;CAAG;AAEN,eAAO,MAAM,mCAAmC,EAAE,CAChD,OAAO,SAAS,SAAS,EACzB,MAAM,SAAS,eAAe,OACzB,4BAA4B,CAAC,OAAO,EAAE,MAAM,CA6ElD,CAAC"}
@@ -1,62 +0,0 @@
1
- 'use strict';
2
-
3
- var TRPCError = require('../../../../unstable-core-do-not-import/error/TRPCError.js');
4
- require('../../../../unstable-core-do-not-import/rootConfig.js');
5
- var concurrentCache = require('../../../content-handlers/concurrentCache.js');
6
- var utils = require('../../utils.js');
7
-
8
- // @trpc/server
9
- const getLambdaHTTPJSONContentTypeHandler = ()=>{
10
- const cache = concurrentCache.createConcurrentCache();
11
- return {
12
- name: 'lambda-json',
13
- isMatch: (headers)=>{
14
- return !!headers.get('content-type')?.startsWith('application/json');
15
- },
16
- getInputs: async (opts, info)=>{
17
- function getRawProcedureInputOrThrow() {
18
- const { event , req } = opts;
19
- try {
20
- if (req.query.has('input')) {
21
- const input = req.query.get('input');
22
- if (!input) {
23
- return undefined;
24
- }
25
- return JSON.parse(input);
26
- }
27
- const body = utils.lambdaEventToHTTPBody(opts.event);
28
- if (typeof body === 'string') {
29
- // A mutation with no inputs will have req.body === ''
30
- return body.length === 0 ? undefined : JSON.parse(body);
31
- }
32
- return event.body;
33
- } catch (cause) {
34
- throw new TRPCError.TRPCError({
35
- code: 'PARSE_ERROR',
36
- cause
37
- });
38
- }
39
- }
40
- const deserializeInputValue = (rawValue, transformer)=>{
41
- return typeof rawValue !== 'undefined' ? transformer.input.deserialize(rawValue) : rawValue;
42
- };
43
- const rawInput = await cache.concurrentSafeGet('rawInput', ()=>getRawProcedureInputOrThrow());
44
- if (rawInput === undefined) {
45
- return undefined;
46
- }
47
- const transformer = opts.router._def._config.transformer;
48
- if (!info.isBatchCall) {
49
- return cache.concurrentSafeGet('input', ()=>deserializeInputValue(rawInput, transformer));
50
- }
51
- /* istanbul ignore if */ if (rawInput == null || typeof rawInput !== 'object' || Array.isArray(rawInput)) {
52
- throw new TRPCError.TRPCError({
53
- code: 'BAD_REQUEST',
54
- message: '"input" needs to be an object when doing a batch call'
55
- });
56
- }
57
- return cache.concurrentSafeGet(String(info.batch), ()=>deserializeInputValue(rawInput[info.batch], transformer));
58
- }
59
- };
60
- };
61
-
62
- exports.getLambdaHTTPJSONContentTypeHandler = getLambdaHTTPJSONContentTypeHandler;