@trpc/server 11.24.1-canary.7.8ff8793e9 → 11.25.0

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 (114) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/aws-lambda/index.cjs +1 -1
  3. package/dist/adapters/aws-lambda/index.d.cts +1 -1
  4. package/dist/adapters/aws-lambda/index.d.mts +1 -1
  5. package/dist/adapters/aws-lambda/index.mjs +1 -1
  6. package/dist/adapters/express.cjs +1 -1
  7. package/dist/adapters/express.d.cts +2 -2
  8. package/dist/adapters/express.d.mts +2 -2
  9. package/dist/adapters/express.mjs +1 -1
  10. package/dist/adapters/fastify/index.cjs +3 -3
  11. package/dist/adapters/fastify/index.d.cts +3 -3
  12. package/dist/adapters/fastify/index.d.mts +3 -3
  13. package/dist/adapters/fastify/index.mjs +3 -3
  14. package/dist/adapters/fetch/index.cjs +1 -1
  15. package/dist/adapters/fetch/index.d.cts +1 -1
  16. package/dist/adapters/fetch/index.d.mts +1 -1
  17. package/dist/adapters/fetch/index.mjs +1 -1
  18. package/dist/adapters/next-app-dir.d.cts +1 -1
  19. package/dist/adapters/next-app-dir.d.mts +1 -1
  20. package/dist/adapters/next.cjs +1 -1
  21. package/dist/adapters/next.d.cts +2 -2
  22. package/dist/adapters/next.d.mts +2 -2
  23. package/dist/adapters/next.mjs +1 -1
  24. package/dist/adapters/node-http/index.cjs +1 -1
  25. package/dist/adapters/node-http/index.d.cts +1 -1
  26. package/dist/adapters/node-http/index.d.mts +1 -1
  27. package/dist/adapters/node-http/index.mjs +1 -1
  28. package/dist/adapters/standalone.cjs +1 -1
  29. package/dist/adapters/standalone.d.cts +2 -2
  30. package/dist/adapters/standalone.d.mts +2 -2
  31. package/dist/adapters/standalone.mjs +1 -1
  32. package/dist/adapters/ws.cjs +1 -1
  33. package/dist/adapters/ws.d.cts +2 -2
  34. package/dist/adapters/ws.d.mts +2 -2
  35. package/dist/adapters/ws.mjs +1 -1
  36. package/dist/http.cjs +1 -1
  37. package/dist/http.d.cts +1 -1
  38. package/dist/http.d.mts +1 -1
  39. package/dist/http.mjs +1 -1
  40. package/dist/{index-Bdq70sid.d.cts → index-CFQnkrGZ.d.cts} +6 -3
  41. package/dist/{index-Bdq70sid.d.cts.map → index-CFQnkrGZ.d.cts.map} +1 -1
  42. package/dist/{index-Bdq70sid.d.mts → index-CFQnkrGZ.d.mts} +6 -3
  43. package/dist/{index-Bdq70sid.d.mts.map → index-CFQnkrGZ.d.mts.map} +1 -1
  44. package/dist/{index-C8o7kgHD.d.mts → index-DVmu6VtT.d.mts} +2 -2
  45. package/dist/{index-C8o7kgHD.d.mts.map → index-DVmu6VtT.d.mts.map} +1 -1
  46. package/dist/{index-mlF5Hred.d.cts → index-Dn1ucZS5.d.cts} +2 -2
  47. package/dist/{index-mlF5Hred.d.cts.map → index-Dn1ucZS5.d.cts.map} +1 -1
  48. package/dist/index.cjs +1 -1
  49. package/dist/index.d.cts +1 -1
  50. package/dist/index.d.mts +1 -1
  51. package/dist/index.mjs +1 -1
  52. package/dist/{initTRPC-BHFhyRlq.mjs → initTRPC-DPoVGUwX.mjs} +2 -2
  53. package/dist/{initTRPC-BHFhyRlq.mjs.map → initTRPC-DPoVGUwX.mjs.map} +1 -1
  54. package/dist/{initTRPC-Cqhzvadj.cjs → initTRPC-yeYwDikA.cjs} +1 -1
  55. package/dist/{node-http-CgxAZYco.mjs → node-http-Df_b1FfK.mjs} +33 -10
  56. package/dist/{node-http-CgxAZYco.mjs.map → node-http-Df_b1FfK.mjs.map} +1 -1
  57. package/dist/{node-http-zAXiTJ5z.cjs → node-http-vS2eeV-2.cjs} +31 -8
  58. package/dist/observable/index.cjs +2 -2
  59. package/dist/observable/index.d.cts +1 -1
  60. package/dist/observable/index.d.mts +1 -1
  61. package/dist/observable/index.mjs +2 -2
  62. package/dist/{observable-DvS5lN8Q.cjs → observable-1zKJIeLl.cjs} +27 -9
  63. package/dist/{observable-YaZmQKBm.mjs → observable-Cmd1MFy3.mjs} +17 -3
  64. package/dist/{observable-YaZmQKBm.mjs.map → observable-Cmd1MFy3.mjs.map} +1 -1
  65. package/dist/{observable-C__NrSHz.cjs → observable-CtU0hoef.cjs} +16 -2
  66. package/dist/{observable-Crotwz1G.mjs → observable-kpFFzvou.mjs} +28 -10
  67. package/dist/observable-kpFFzvou.mjs.map +1 -0
  68. package/dist/{resolveResponse-KsaMasi_.mjs → resolveResponse-C3K3zKPn.mjs} +2 -2
  69. package/dist/{resolveResponse-KsaMasi_.mjs.map → resolveResponse-C3K3zKPn.mjs.map} +1 -1
  70. package/dist/{resolveResponse-BiNVUUPp.cjs → resolveResponse-CoiQ9diV.cjs} +1 -1
  71. package/dist/rpc.d.cts +1 -1
  72. package/dist/rpc.d.mts +1 -1
  73. package/dist/shared.d.cts +1 -1
  74. package/dist/shared.d.mts +1 -1
  75. package/dist/{unstable-core-do-not-import-Dwco_7Rh.d.mts → unstable-core-do-not-import-CzDUc5m2.d.mts} +2 -2
  76. package/dist/{unstable-core-do-not-import-Dwco_7Rh.d.mts.map → unstable-core-do-not-import-CzDUc5m2.d.mts.map} +1 -1
  77. package/dist/{unstable-core-do-not-import-BSR46h1T.d.cts → unstable-core-do-not-import-Db2TnFh8.d.cts} +2 -2
  78. package/dist/{unstable-core-do-not-import-BSR46h1T.d.cts.map → unstable-core-do-not-import-Db2TnFh8.d.cts.map} +1 -1
  79. package/dist/unstable-core-do-not-import.cjs +2 -2
  80. package/dist/unstable-core-do-not-import.d.cts +1 -1
  81. package/dist/unstable-core-do-not-import.d.mts +1 -1
  82. package/dist/unstable-core-do-not-import.mjs +2 -2
  83. package/dist/{ws-DISNGMFd.mjs → ws-BqEmiHOX.mjs} +348 -195
  84. package/dist/ws-BqEmiHOX.mjs.map +1 -0
  85. package/dist/{ws-DFpyRwue.d.cts → ws-D-DF_k_T.d.cts} +3 -3
  86. package/dist/ws-D-DF_k_T.d.cts.map +1 -0
  87. package/dist/{ws-CO1rjQdN.d.mts → ws-lJRDMspc.d.mts} +3 -3
  88. package/dist/ws-lJRDMspc.d.mts.map +1 -0
  89. package/dist/{ws-BefV3QoE.cjs → ws-zjwsyre9.cjs} +346 -193
  90. package/package.json +9 -11
  91. package/skills/adapter-aws-lambda/SKILL.md +1 -1
  92. package/skills/adapter-express/SKILL.md +1 -1
  93. package/skills/adapter-fastify/SKILL.md +1 -1
  94. package/skills/adapter-fetch/SKILL.md +1 -1
  95. package/skills/adapter-standalone/SKILL.md +1 -1
  96. package/skills/auth/SKILL.md +1 -1
  97. package/skills/caching/SKILL.md +1 -1
  98. package/skills/error-handling/SKILL.md +1 -1
  99. package/skills/middlewares/SKILL.md +1 -1
  100. package/skills/non-json-content-types/SKILL.md +1 -1
  101. package/skills/server-setup/SKILL.md +1 -1
  102. package/skills/server-side-calls/SKILL.md +1 -1
  103. package/skills/service-oriented-architecture/SKILL.md +1 -1
  104. package/skills/subscriptions/SKILL.md +11 -3
  105. package/skills/trpc-router/SKILL.md +1 -1
  106. package/skills/validators/SKILL.md +1 -1
  107. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +37 -8
  108. package/src/adapters/ws.ts +333 -123
  109. package/src/observable/behaviorSubject.ts +20 -2
  110. package/src/observable/observable.ts +26 -11
  111. package/dist/observable-Crotwz1G.mjs.map +0 -1
  112. package/dist/ws-CO1rjQdN.d.mts.map +0 -1
  113. package/dist/ws-DFpyRwue.d.cts.map +0 -1
  114. package/dist/ws-DISNGMFd.mjs.map +0 -1
@@ -2,9 +2,9 @@ const require_codes = require("./codes-Be-DrYMh.cjs");
2
2
  const require_getErrorShape = require("./getErrorShape-BAuHhNuh.cjs");
3
3
  const require_parseTRPCMessage = require("./parseTRPCMessage-BsPr5reh.cjs");
4
4
  const require_asyncGeneratorDelegate = require("./asyncGeneratorDelegate-CMdmcplC.cjs");
5
- const require_resolveResponse = require("./resolveResponse-BiNVUUPp.cjs");
6
- const require_observable = require("./observable-DvS5lN8Q.cjs");
7
- const require_node_http = require("./node-http-zAXiTJ5z.cjs");
5
+ const require_resolveResponse = require("./resolveResponse-CoiQ9diV.cjs");
6
+ const require_observable = require("./observable-1zKJIeLl.cjs");
7
+ const require_node_http = require("./node-http-vS2eeV-2.cjs");
8
8
  //#region src/adapters/wsEncoder.ts
9
9
  /**
10
10
  * The default encoder: JSON in text frames.
@@ -23,6 +23,58 @@ const jsonEncoder = {
23
23
  * @see https://github.com/trpc/trpc/pull/5279
24
24
  */
25
25
  const WEBSOCKET_OPEN = 1;
26
+ function settle(promise) {
27
+ return promise.then((value) => ({
28
+ ok: true,
29
+ value
30
+ }), (error) => ({
31
+ ok: false,
32
+ error
33
+ }));
34
+ }
35
+ /**
36
+ * What `await using` rejects with when disposal fails after the scope threw:
37
+ * `error` is the disposal failure and `suppressed` the original error.
38
+ */
39
+ function isSuppressedError(cause) {
40
+ return require_codes.isObject(cause) && cause["name"] === "SuppressedError" && "error" in cause && "suppressed" in cause;
41
+ }
42
+ /**
43
+ * What the client gets when its error can't be formatted or encoded. It says
44
+ * nothing about the error, which is what `errorFormatter` would have hidden.
45
+ */
46
+ const fallbackErrorShape = {
47
+ code: require_codes.TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,
48
+ message: "Internal server error",
49
+ data: {
50
+ code: "INTERNAL_SERVER_ERROR",
51
+ httpStatus: 500
52
+ }
53
+ };
54
+ /**
55
+ * A procedure that gives up because its subscription was cancelled rejects
56
+ * with an `AbortError`, which is wrapped as an INTERNAL_SERVER_ERROR.
57
+ */
58
+ function isCancelledSetup(error, signal) {
59
+ return signal.aborted && error.code === "INTERNAL_SERVER_ERROR" && require_resolveResponse.isAbortError(error.cause);
60
+ }
61
+ /**
62
+ * `iterator.next()` for a subscription loop that races it against the
63
+ * subscription's `signal`, with a rejection turned into a `TRPCError`.
64
+ *
65
+ * Once the subscription is stopped, the loop doesn't wait for this call, so a
66
+ * rejection after the stop, such as a teardown that throws, goes to
67
+ * `onErrorAfterStop` and resolves `'abort'`. An `AbortError` is how a stopped
68
+ * subscription is expected to end, and isn't reported.
69
+ */
70
+ function nextUnlessStopped(iterator, signal, onErrorAfterStop) {
71
+ return iterator.next().catch((cause) => {
72
+ const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause);
73
+ if (!signal.aborted) return error;
74
+ if (!require_resolveResponse.isAbortError(error.cause)) onErrorAfterStop(error);
75
+ return "abort";
76
+ });
77
+ }
26
78
  /**
27
79
  * Returns a `ws` connection listener that serves a router. `applyWSSHandler`
28
80
  * uses it; call it to attach tRPC to your own WebSocket server.
@@ -36,6 +88,12 @@ function getWSConnectionHandler(opts) {
36
88
  var _opts$keepAlive;
37
89
  const clientSubscriptions = /* @__PURE__ */ new Map();
38
90
  const abortController = new AbortController();
91
+ function registerSubscription(id, subscription) {
92
+ clientSubscriptions.set(id, subscription);
93
+ return require_resolveResponse.makeResource({}, () => {
94
+ clientSubscriptions.delete(id);
95
+ });
96
+ }
39
97
  if ((_opts$keepAlive = opts.keepAlive) === null || _opts$keepAlive === void 0 ? void 0 : _opts$keepAlive.enabled) {
40
98
  const { pingMs, pongWaitMs } = opts.keepAlive;
41
99
  handleKeepAlive(client, pingMs, pongWaitMs);
@@ -43,6 +101,90 @@ function getWSConnectionHandler(opts) {
43
101
  function respond(untransformedJSON) {
44
102
  client.send(encoder.encode(require_asyncGeneratorDelegate.transformTRPCResponse(router._def._config, untransformedJSON)));
45
103
  }
104
+ /**
105
+ * `onError` runs in listeners and in promises nothing awaits, where a
106
+ * throw or a rejection would crash the process, so either goes to
107
+ * `onFailure` instead.
108
+ */
109
+ function guardOnError(info, onFailure) {
110
+ try {
111
+ var _opts$onError;
112
+ const result = (_opts$onError = opts.onError) === null || _opts$onError === void 0 ? void 0 : _opts$onError.call(opts, info);
113
+ if (require_resolveResponse.isPromise(result)) result.catch(onFailure);
114
+ } catch (cause) {
115
+ onFailure(cause);
116
+ }
117
+ }
118
+ /** Reports an error to `onError`, ignoring an `onError` that fails. */
119
+ function callOnError(info) {
120
+ guardOnError(info, () => {});
121
+ }
122
+ /**
123
+ * Reports a failure of the adapter's own error handling, such as an
124
+ * `errorFormatter` that throws or a reply that can't be sent. It's logged
125
+ * when `onError` is missing or fails, so it's never dropped silently.
126
+ */
127
+ function reportInternalError(info) {
128
+ const log = () => {
129
+ console.error("[@trpc/server/adapters/ws]", info.error);
130
+ };
131
+ if (!opts.onError) {
132
+ log();
133
+ return;
134
+ }
135
+ guardOnError(info, log);
136
+ }
137
+ /**
138
+ * The error shape the client gets, or a minimal one when `errorFormatter`
139
+ * throws, so that the request is still answered.
140
+ */
141
+ function errorShape(call) {
142
+ try {
143
+ return require_getErrorShape.getErrorShape(require_getErrorShape._objectSpread2({
144
+ config: router._def._config,
145
+ ctx
146
+ }, call));
147
+ } catch (cause) {
148
+ reportInternalError(require_getErrorShape._objectSpread2(require_getErrorShape._objectSpread2({}, call), {}, {
149
+ error: require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause),
150
+ ctx,
151
+ req
152
+ }));
153
+ return fallbackErrorShape;
154
+ }
155
+ }
156
+ function reportConnectionError(cause) {
157
+ reportInternalError({
158
+ error: require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause),
159
+ path: void 0,
160
+ type: "unknown",
161
+ ctx,
162
+ req,
163
+ input: void 0
164
+ });
165
+ }
166
+ /**
167
+ * Sends a response that isn't tied to a request, reporting it if it
168
+ * can't be built or sent. One that can't be sent is replaced by the
169
+ * fallback error, so that a client still learns it was rejected.
170
+ */
171
+ function respondOrReport(response) {
172
+ let message = null;
173
+ try {
174
+ message = response();
175
+ respond(message);
176
+ } catch (cause) {
177
+ reportConnectionError(cause);
178
+ if (message === null) return;
179
+ try {
180
+ respond({
181
+ id: message.id,
182
+ jsonrpc: message.jsonrpc,
183
+ error: fallbackErrorShape
184
+ });
185
+ } catch (_unused) {}
186
+ }
187
+ }
46
188
  async function createCtxPromise(getConnectionParams) {
47
189
  try {
48
190
  return await require_codes.run(async () => {
@@ -65,9 +207,9 @@ function getWSConnectionHandler(opts) {
65
207
  };
66
208
  });
67
209
  } catch (cause) {
68
- var _opts$onError, _globalThis$setImmedi;
210
+ var _globalThis$setImmedi;
69
211
  const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause);
70
- (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
212
+ callOnError({
71
213
  error,
72
214
  path: void 0,
73
215
  type: "unknown",
@@ -75,17 +217,15 @@ function getWSConnectionHandler(opts) {
75
217
  req,
76
218
  input: void 0
77
219
  });
78
- respond({
220
+ respondOrReport(() => ({
79
221
  id: null,
80
- error: require_getErrorShape.getErrorShape({
81
- config: router._def._config,
222
+ error: errorShape({
82
223
  error,
83
224
  type: "unknown",
84
225
  path: void 0,
85
- input: void 0,
86
- ctx
226
+ input: void 0
87
227
  })
88
- });
228
+ }));
89
229
  ((_globalThis$setImmedi = globalThis.setImmediate) !== null && _globalThis$setImmedi !== void 0 ? _globalThis$setImmedi : globalThis.setTimeout)(() => {
90
230
  client.close();
91
231
  });
@@ -103,15 +243,14 @@ function getWSConnectionHandler(opts) {
103
243
  * - if connection params are expected, they will be created once received
104
244
  */
105
245
  let ctxPromise = require_node_http.createURL(req).searchParams.get("connectionParams") === "1" ? null : createCtxPromise(() => null);
106
- function handleRequest(msg, batchIndex) {
246
+ async function handleRequest(msg, batchIndex, ctxResult) {
107
247
  const { id, jsonrpc } = msg;
108
248
  if (id === null) {
109
- var _opts$onError2;
110
249
  const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(new require_asyncGeneratorDelegate.TRPCError({
111
250
  code: "PARSE_ERROR",
112
251
  message: "`id` is required"
113
252
  }));
114
- (_opts$onError2 = opts.onError) === null || _opts$onError2 === void 0 || _opts$onError2.call(opts, {
253
+ callOnError({
115
254
  error,
116
255
  path: void 0,
117
256
  type: "unknown",
@@ -122,13 +261,11 @@ function getWSConnectionHandler(opts) {
122
261
  respond({
123
262
  id,
124
263
  jsonrpc,
125
- error: require_getErrorShape.getErrorShape({
126
- config: router._def._config,
264
+ error: errorShape({
127
265
  error,
128
266
  type: "unknown",
129
267
  path: void 0,
130
- input: void 0,
131
- ctx
268
+ input: void 0
132
269
  })
133
270
  });
134
271
  return;
@@ -148,175 +285,196 @@ function getWSConnectionHandler(opts) {
148
285
  (_input = input) !== null && _input !== void 0 || (input = { lastEventId });
149
286
  }
150
287
  }
151
- require_codes.run(async () => {
152
- const res = await ctxPromise;
153
- if (!res.ok) throw res.error;
154
- const abortController = new AbortController();
155
- const result = await require_asyncGeneratorDelegate.callProcedure({
156
- router,
288
+ const abortController = new AbortController();
289
+ const abort = () => {
290
+ if (!abortController.signal.aborted) abortController.abort();
291
+ };
292
+ const reportError = (cause) => {
293
+ const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause);
294
+ callOnError({
295
+ error,
157
296
  path,
158
- getRawInput: async () => input,
159
- ctx,
160
297
  type,
161
- signal: abortController.signal,
162
- batchIndex
298
+ ctx,
299
+ req,
300
+ input
163
301
  });
164
- const isIterableResult = require_codes.isAsyncIterable(result) || require_observable.isObservable(result);
165
- if (type !== "subscription") {
166
- if (isIterableResult) throw new require_asyncGeneratorDelegate.TRPCError({
167
- code: "UNSUPPORTED_MEDIA_TYPE",
168
- message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`
302
+ return error;
303
+ };
304
+ const respondWithError = (cause) => {
305
+ const error = reportError(cause);
306
+ respond({
307
+ id,
308
+ jsonrpc,
309
+ error: errorShape({
310
+ error,
311
+ type,
312
+ path,
313
+ input
314
+ })
315
+ });
316
+ };
317
+ if (type === "subscription" && clientSubscriptions.has(id)) {
318
+ respondWithError(new require_asyncGeneratorDelegate.TRPCError({
319
+ message: `Duplicate id ${id}`,
320
+ code: "BAD_REQUEST"
321
+ }));
322
+ return;
323
+ }
324
+ const execute = async () => {
325
+ try {
326
+ var _usingCtx$1 = require_resolveResponse._usingCtx();
327
+ _usingCtx$1.u(type === "subscription" ? registerSubscription(id, abortController) : null);
328
+ const res = await ctxResult;
329
+ if (!res.ok) throw res.error;
330
+ if (abortController.signal.aborted) return;
331
+ const result = await require_asyncGeneratorDelegate.callProcedure({
332
+ router,
333
+ path,
334
+ getRawInput: async () => input,
335
+ ctx,
336
+ type,
337
+ signal: abortController.signal,
338
+ batchIndex
339
+ });
340
+ const isIterableResult = require_codes.isAsyncIterable(result) || require_observable.isObservable(result);
341
+ if (type !== "subscription") {
342
+ if (isIterableResult) throw new require_asyncGeneratorDelegate.TRPCError({
343
+ code: "UNSUPPORTED_MEDIA_TYPE",
344
+ message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`
345
+ });
346
+ respond({
347
+ id,
348
+ jsonrpc,
349
+ result: {
350
+ type: "data",
351
+ data: result
352
+ }
353
+ });
354
+ return;
355
+ }
356
+ if (!isIterableResult) throw new require_asyncGeneratorDelegate.TRPCError({
357
+ message: `Subscription ${path} did not return an observable or a AsyncGenerator`,
358
+ code: "INTERNAL_SERVER_ERROR"
169
359
  });
360
+ const iterable = require_observable.isObservable(result) ? require_observable.observableToAsyncIterable(result, abortController.signal) : result;
361
+ if (abortController.signal.aborted) {
362
+ try {
363
+ try {
364
+ var _usingCtx3 = require_resolveResponse._usingCtx();
365
+ _usingCtx3.a(require_resolveResponse.iteratorResource(iterable));
366
+ } catch (_) {
367
+ _usingCtx3.e = _;
368
+ } finally {
369
+ await _usingCtx3.d();
370
+ }
371
+ } catch (cause) {
372
+ reportError(cause);
373
+ }
374
+ return;
375
+ }
170
376
  respond({
171
377
  id,
172
378
  jsonrpc,
173
- result: {
174
- type: "data",
175
- data: result
176
- }
379
+ result: { type: "started" }
177
380
  });
178
- return;
179
- }
180
- if (!isIterableResult) throw new require_asyncGeneratorDelegate.TRPCError({
181
- message: `Subscription ${path} did not return an observable or a AsyncGenerator`,
182
- code: "INTERNAL_SERVER_ERROR"
183
- });
184
- /* istanbul ignore next -- @preserve */
185
- if (client.readyState !== WEBSOCKET_OPEN) return;
186
- /* istanbul ignore next -- @preserve */
187
- if (clientSubscriptions.has(id)) throw new require_asyncGeneratorDelegate.TRPCError({
188
- message: `Duplicate id ${id}`,
189
- code: "BAD_REQUEST"
190
- });
191
- const iterable = require_observable.isObservable(result) ? require_observable.observableToAsyncIterable(result, abortController.signal) : result;
192
- require_codes.run(async () => {
381
+ let ended = false;
193
382
  try {
194
- var _usingCtx$1 = require_resolveResponse._usingCtx();
195
- const iterator = _usingCtx$1.a(require_resolveResponse.iteratorResource(iterable));
196
- const abortPromise = new Promise((resolve) => {
197
- abortController.signal.onabort = () => resolve("abort");
198
- });
199
- let next;
200
- let result;
201
- while (true) {
202
- next = await require_resolveResponse.Unpromise.race([iterator.next().catch(require_asyncGeneratorDelegate.getTRPCErrorFromUnknown), abortPromise]);
203
- if (next === "abort") {
204
- var _iterator$return;
205
- await ((_iterator$return = iterator.return) === null || _iterator$return === void 0 ? void 0 : _iterator$return.call(iterator));
206
- break;
207
- }
208
- if (next instanceof Error) {
209
- var _opts$onError3;
210
- const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(next);
211
- (_opts$onError3 = opts.onError) === null || _opts$onError3 === void 0 || _opts$onError3.call(opts, {
383
+ try {
384
+ var _usingCtx4 = require_resolveResponse._usingCtx();
385
+ const iterator = _usingCtx4.a(require_resolveResponse.iteratorResource(iterable));
386
+ let completed = false;
387
+ _usingCtx4.u(require_resolveResponse.makeResource({}, () => {
388
+ if (!completed) abort();
389
+ }));
390
+ const abortPromise = new Promise((resolve) => {
391
+ abortController.signal.onabort = () => resolve("abort");
392
+ });
393
+ let next;
394
+ let result;
395
+ while (true) {
396
+ next = await require_resolveResponse.Unpromise.race([nextUnlessStopped(iterator, abortController.signal, (error) => callOnError({
212
397
  error,
213
398
  path,
214
399
  type,
215
400
  ctx,
216
401
  req,
217
402
  input
218
- });
403
+ })), abortPromise]);
404
+ if (next === "abort") break;
405
+ if (next instanceof Error) throw next;
406
+ if (next.done) {
407
+ completed = true;
408
+ break;
409
+ }
410
+ result = {
411
+ type: "data",
412
+ data: next.value
413
+ };
414
+ if (require_asyncGeneratorDelegate.isTrackedEnvelope(next.value)) {
415
+ const [id, data] = next.value;
416
+ result.id = id;
417
+ result.data = {
418
+ id,
419
+ data
420
+ };
421
+ }
219
422
  respond({
220
423
  id,
221
424
  jsonrpc,
222
- error: require_getErrorShape.getErrorShape({
223
- config: router._def._config,
224
- error,
225
- type,
226
- path,
227
- input,
228
- ctx
229
- })
425
+ result
230
426
  });
231
- break;
427
+ next = null;
428
+ result = null;
232
429
  }
233
- if (next.done) break;
234
- result = {
235
- type: "data",
236
- data: next.value
237
- };
238
- if (require_asyncGeneratorDelegate.isTrackedEnvelope(next.value)) {
239
- const [id, data] = next.value;
240
- result.id = id;
241
- result.data = {
242
- id,
243
- data
244
- };
245
- }
246
- respond({
247
- id,
248
- jsonrpc,
249
- result
250
- });
251
- next = null;
252
- result = null;
430
+ ended = true;
431
+ } catch (_) {
432
+ _usingCtx4.e = _;
433
+ } finally {
434
+ await _usingCtx4.d();
253
435
  }
254
- respond({
436
+ } catch (cause) {
437
+ abort();
438
+ if (ended) reportError(cause);
439
+ else if (isSuppressedError(cause)) {
440
+ respondWithError(cause.suppressed);
441
+ reportError(cause.error);
442
+ } else respondWithError(cause);
443
+ }
444
+ } catch (_) {
445
+ _usingCtx$1.e = _;
446
+ } finally {
447
+ _usingCtx$1.d();
448
+ }
449
+ };
450
+ const outcome = await settle(execute());
451
+ if (!outcome.ok) {
452
+ const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(outcome.error);
453
+ if (!isCancelledSetup(error, abortController.signal)) {
454
+ try {
455
+ respondWithError(error);
456
+ } catch (cause) {
457
+ reportInternalError({
458
+ error: require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause),
459
+ path,
460
+ type,
461
+ ctx,
462
+ req,
463
+ input
464
+ });
465
+ respondOrReport(() => ({
255
466
  id,
256
467
  jsonrpc,
257
- result: { type: "stopped" }
258
- });
259
- clientSubscriptions.delete(id);
260
- } catch (_) {
261
- _usingCtx$1.e = _;
262
- } finally {
263
- await _usingCtx$1.d();
468
+ error: fallbackErrorShape
469
+ }));
264
470
  }
265
- }).catch((cause) => {
266
- var _opts$onError4;
267
- clientSubscriptions.delete(id);
268
- const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause);
269
- (_opts$onError4 = opts.onError) === null || _opts$onError4 === void 0 || _opts$onError4.call(opts, {
270
- error,
271
- path,
272
- type,
273
- ctx,
274
- req,
275
- input
276
- });
277
- respond({
278
- id,
279
- jsonrpc,
280
- error: require_getErrorShape.getErrorShape({
281
- config: router._def._config,
282
- error,
283
- type,
284
- path,
285
- input,
286
- ctx
287
- })
288
- });
289
- abortController.abort();
290
- });
291
- clientSubscriptions.set(id, abortController);
292
- respond({
293
- id,
294
- jsonrpc,
295
- result: { type: "started" }
296
- });
297
- }).catch((cause) => {
298
- var _opts$onError5;
299
- const error = require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause);
300
- (_opts$onError5 = opts.onError) === null || _opts$onError5 === void 0 || _opts$onError5.call(opts, {
301
- error,
302
- path,
303
- type,
304
- ctx,
305
- req,
306
- input
307
- });
308
- respond({
309
- id,
310
- jsonrpc,
311
- error: require_getErrorShape.getErrorShape({
312
- config: router._def._config,
313
- error,
314
- type,
315
- path,
316
- input,
317
- ctx
318
- })
319
- });
471
+ return;
472
+ }
473
+ }
474
+ if (type === "subscription") respond({
475
+ id,
476
+ jsonrpc,
477
+ result: { type: "stopped" }
320
478
  });
321
479
  }
322
480
  client.on("message", (rawData, isBinary) => {
@@ -333,17 +491,15 @@ function getWSConnectionHandler(opts) {
333
491
  code: "UNPROCESSABLE_CONTENT",
334
492
  message: "Unexpected WebSocket message format"
335
493
  });
336
- respond({
494
+ respondOrReport(() => ({
337
495
  id: null,
338
- error: require_getErrorShape.getErrorShape({
339
- config: router._def._config,
496
+ error: errorShape({
340
497
  error,
341
498
  type: "unknown",
342
499
  path: void 0,
343
- input: void 0,
344
- ctx
500
+ input: void 0
345
501
  })
346
- });
502
+ }));
347
503
  return;
348
504
  }
349
505
  const data = isBinary ? rawData : rawData.toString("utf8");
@@ -364,17 +520,16 @@ function getWSConnectionHandler(opts) {
364
520
  });
365
521
  return;
366
522
  }
367
- require_codes.run(() => {
523
+ const parsedMsgs = require_codes.run(() => {
368
524
  try {
369
525
  const msgJSON = encoder.decode(data);
370
526
  const msgs = Array.isArray(msgJSON) ? msgJSON : [msgJSON];
371
527
  if (Array.isArray(msgJSON) && typeof opts.maxBatchSize === "number" && msgs.length > opts.maxBatchSize) {
372
- var _opts$onError6;
373
528
  const error = new require_asyncGeneratorDelegate.TRPCError({
374
529
  code: "BAD_REQUEST",
375
530
  message: `Batch call exceeds maximum size`
376
531
  });
377
- (_opts$onError6 = opts.onError) === null || _opts$onError6 === void 0 || _opts$onError6.call(opts, {
532
+ callOnError({
378
533
  error,
379
534
  path: void 0,
380
535
  type: "unknown",
@@ -382,27 +537,27 @@ function getWSConnectionHandler(opts) {
382
537
  req,
383
538
  input: void 0
384
539
  });
385
- const errorShape = require_getErrorShape.getErrorShape({
386
- config: router._def._config,
540
+ const shape = errorShape({
387
541
  error,
388
542
  type: "unknown",
389
543
  path: void 0,
390
- input: void 0,
391
- ctx
544
+ input: void 0
392
545
  });
393
546
  let responded = false;
394
547
  for (const raw of msgs) if (require_codes.isObject(raw) && raw["method"] !== "subscription.stop" && (typeof raw["id"] === "number" || typeof raw["id"] === "string")) {
395
- respond({
396
- id: raw["id"],
397
- jsonrpc: raw["jsonrpc"] === "2.0" ? "2.0" : void 0,
398
- error: errorShape
399
- });
548
+ const id = raw["id"];
549
+ const jsonrpc = raw["jsonrpc"] === "2.0" ? "2.0" : void 0;
550
+ respondOrReport(() => ({
551
+ id,
552
+ jsonrpc,
553
+ error: shape
554
+ }));
400
555
  responded = true;
401
556
  }
402
- if (!responded) respond({
557
+ if (!responded) respondOrReport(() => ({
403
558
  id: null,
404
- error: errorShape
405
- });
559
+ error: shape
560
+ }));
406
561
  return [];
407
562
  }
408
563
  return msgs.map((raw) => require_parseTRPCMessage.parseTRPCMessage(raw, transformer));
@@ -411,24 +566,22 @@ function getWSConnectionHandler(opts) {
411
566
  code: "PARSE_ERROR",
412
567
  cause
413
568
  });
414
- respond({
569
+ respondOrReport(() => ({
415
570
  id: null,
416
- error: require_getErrorShape.getErrorShape({
417
- config: router._def._config,
571
+ error: errorShape({
418
572
  error,
419
573
  type: "unknown",
420
574
  path: void 0,
421
- input: void 0,
422
- ctx
575
+ input: void 0
423
576
  })
424
- });
577
+ }));
425
578
  return [];
426
579
  }
427
- }).map((msg, index) => handleRequest(msg, index));
580
+ });
581
+ for (const [index, msg] of parsedMsgs.entries()) handleRequest(msg, index, ctxPromise).catch(reportConnectionError);
428
582
  });
429
583
  client.on("error", (cause) => {
430
- var _opts$onError7;
431
- (_opts$onError7 = opts.onError) === null || _opts$onError7 === void 0 || _opts$onError7.call(opts, {
584
+ callOnError({
432
585
  ctx,
433
586
  error: require_asyncGeneratorDelegate.getTRPCErrorFromUnknown(cause),
434
587
  input: void 0,