@trpc/client 11.3.1 → 11.3.2-canary.2

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 (238) hide show
  1. package/dist/TRPCClientError-CGgRtttT.cjs +67 -0
  2. package/dist/TRPCClientError-COkhCKf3.mjs +56 -0
  3. package/dist/TRPCClientError-COkhCKf3.mjs.map +1 -0
  4. package/dist/chunk-DWy1uDak.cjs +39 -0
  5. package/dist/httpBatchLink-CIC9PZ_Z.cjs +267 -0
  6. package/dist/httpBatchLink-DIfnmmcu.mjs +238 -0
  7. package/dist/httpBatchLink-DIfnmmcu.mjs.map +1 -0
  8. package/dist/httpBatchLink.d-BN2Iw_cK.d.mts +33 -0
  9. package/dist/httpBatchLink.d-BN2Iw_cK.d.mts.map +1 -0
  10. package/dist/httpBatchLink.d-CLAuJKNV.d.cts +33 -0
  11. package/dist/httpBatchLink.d-CLAuJKNV.d.cts.map +1 -0
  12. package/dist/httpLink-9bpwQ15c.mjs +90 -0
  13. package/dist/httpLink-9bpwQ15c.mjs.map +1 -0
  14. package/dist/httpLink-BbVj_TgM.cjs +113 -0
  15. package/dist/httpLink.d-CTSOARfE.d.mts +23 -0
  16. package/dist/httpLink.d-CTSOARfE.d.mts.map +1 -0
  17. package/dist/httpLink.d-yMKfOlTU.d.cts +23 -0
  18. package/dist/httpLink.d-yMKfOlTU.d.cts.map +1 -0
  19. package/dist/httpUtils-3pbQzhUL.mjs +123 -0
  20. package/dist/httpUtils-3pbQzhUL.mjs.map +1 -0
  21. package/dist/httpUtils-Buf6jCgh.cjs +163 -0
  22. package/dist/httpUtils.d-C8wPxU79.d.mts +25 -0
  23. package/dist/httpUtils.d-C8wPxU79.d.mts.map +1 -0
  24. package/dist/httpUtils.d-DNRVGNHs.d.cts +25 -0
  25. package/dist/httpUtils.d-DNRVGNHs.d.cts.map +1 -0
  26. package/dist/index.cjs +731 -0
  27. package/dist/index.d.cts +197 -0
  28. package/dist/index.d.cts.map +1 -0
  29. package/dist/index.d.mts +197 -0
  30. package/dist/index.d.mts.map +1 -0
  31. package/dist/index.mjs +733 -16
  32. package/dist/index.mjs.map +1 -0
  33. package/dist/links/httpBatchLink.cjs +6 -0
  34. package/dist/links/httpBatchLink.d.cts +6 -0
  35. package/dist/links/httpBatchLink.d.mts +6 -0
  36. package/dist/links/httpBatchLink.mjs +5 -107
  37. package/dist/links/httpLink.cjs +6 -0
  38. package/dist/links/httpLink.d.cts +6 -0
  39. package/dist/links/httpLink.d.mts +6 -0
  40. package/dist/links/httpLink.mjs +5 -92
  41. package/dist/links/loggerLink.cjs +3 -0
  42. package/dist/links/loggerLink.d.cts +4 -0
  43. package/dist/links/loggerLink.d.mts +4 -0
  44. package/dist/links/loggerLink.mjs +2 -175
  45. package/dist/links/splitLink.cjs +3 -0
  46. package/dist/links/splitLink.d.cts +4 -0
  47. package/dist/links/splitLink.d.mts +4 -0
  48. package/dist/links/splitLink.mjs +2 -24
  49. package/dist/links/wsLink/wsLink.cjs +6 -0
  50. package/dist/links/wsLink/wsLink.d.cts +5 -0
  51. package/dist/links/wsLink/wsLink.d.mts +5 -0
  52. package/dist/links/wsLink/wsLink.mjs +4 -31
  53. package/dist/loggerLink-CsDfg5Bb.cjs +130 -0
  54. package/dist/loggerLink-PGBSQFcR.mjs +125 -0
  55. package/dist/loggerLink-PGBSQFcR.mjs.map +1 -0
  56. package/dist/loggerLink.d-CZjK1CXm.d.mts +54 -0
  57. package/dist/loggerLink.d-CZjK1CXm.d.mts.map +1 -0
  58. package/dist/loggerLink.d-DU855urG.d.cts +54 -0
  59. package/dist/loggerLink.d-DU855urG.d.cts.map +1 -0
  60. package/dist/splitLink-BMgxggng.cjs +58 -0
  61. package/dist/splitLink-BVblHq4n.mjs +47 -0
  62. package/dist/splitLink-BVblHq4n.mjs.map +1 -0
  63. package/dist/splitLink.d-BAqgq0NG.d.mts +20 -0
  64. package/dist/splitLink.d-BAqgq0NG.d.mts.map +1 -0
  65. package/dist/splitLink.d-GdevSkGW.d.cts +20 -0
  66. package/dist/splitLink.d-GdevSkGW.d.cts.map +1 -0
  67. package/dist/subscriptions.d-Ciljg_dH.d.cts +19 -0
  68. package/dist/subscriptions.d-Ciljg_dH.d.cts.map +1 -0
  69. package/dist/subscriptions.d-U92STdZl.d.mts +19 -0
  70. package/dist/subscriptions.d-U92STdZl.d.mts.map +1 -0
  71. package/dist/types.d-DXbqQLCC.d.mts +182 -0
  72. package/dist/types.d-DXbqQLCC.d.mts.map +1 -0
  73. package/dist/types.d-DqGYG6S_.d.cts +182 -0
  74. package/dist/types.d-DqGYG6S_.d.cts.map +1 -0
  75. package/dist/unstable-internals-CYBH4jbF.cjs +34 -0
  76. package/dist/unstable-internals-DU4WecoG.mjs +29 -0
  77. package/dist/unstable-internals-DU4WecoG.mjs.map +1 -0
  78. package/dist/unstable-internals.cjs +3 -0
  79. package/dist/unstable-internals.d-DyLd-B0J.d.mts +46 -0
  80. package/dist/unstable-internals.d-DyLd-B0J.d.mts.map +1 -0
  81. package/dist/unstable-internals.d-kWsZTlQq.d.cts +46 -0
  82. package/dist/unstable-internals.d-kWsZTlQq.d.cts.map +1 -0
  83. package/dist/unstable-internals.d.cts +3 -0
  84. package/dist/unstable-internals.d.mts +3 -0
  85. package/dist/unstable-internals.mjs +3 -1
  86. package/dist/wsLink-DbSHOzlB.mjs +698 -0
  87. package/dist/wsLink-DbSHOzlB.mjs.map +1 -0
  88. package/dist/wsLink-DhJ50EC5.cjs +715 -0
  89. package/dist/wsLink.d-BqO7ltN_.d.mts +194 -0
  90. package/dist/wsLink.d-BqO7ltN_.d.mts.map +1 -0
  91. package/dist/wsLink.d-DtZjg09g.d.cts +194 -0
  92. package/dist/wsLink.d-DtZjg09g.d.cts.map +1 -0
  93. package/links/httpBatchLink/package.json +1 -0
  94. package/links/httpLink/package.json +1 -0
  95. package/links/loggerLink/package.json +1 -0
  96. package/links/splitLink/package.json +1 -0
  97. package/links/wsLink/wsLink/package.json +1 -0
  98. package/package.json +67 -33
  99. package/unstable-internals/package.json +1 -0
  100. package/dist/TRPCClientError.d.ts +0 -30
  101. package/dist/TRPCClientError.d.ts.map +0 -1
  102. package/dist/TRPCClientError.js +0 -79
  103. package/dist/TRPCClientError.mjs +0 -76
  104. package/dist/createTRPCClient.d.ts +0 -69
  105. package/dist/createTRPCClient.d.ts.map +0 -1
  106. package/dist/createTRPCClient.js +0 -48
  107. package/dist/createTRPCClient.mjs +0 -43
  108. package/dist/createTRPCUntypedClient.d.ts +0 -7
  109. package/dist/createTRPCUntypedClient.d.ts.map +0 -1
  110. package/dist/createTRPCUntypedClient.js +0 -10
  111. package/dist/createTRPCUntypedClient.mjs +0 -7
  112. package/dist/getFetch.d.ts +0 -3
  113. package/dist/getFetch.d.ts.map +0 -1
  114. package/dist/getFetch.js +0 -17
  115. package/dist/getFetch.mjs +0 -15
  116. package/dist/index.d.ts +0 -16
  117. package/dist/index.d.ts.map +0 -1
  118. package/dist/index.js +0 -46
  119. package/dist/internals/TRPCUntypedClient.d.ts +0 -39
  120. package/dist/internals/TRPCUntypedClient.d.ts.map +0 -1
  121. package/dist/internals/TRPCUntypedClient.js +0 -115
  122. package/dist/internals/TRPCUntypedClient.mjs +0 -113
  123. package/dist/internals/dataLoader.d.ts +0 -13
  124. package/dist/internals/dataLoader.d.ts.map +0 -1
  125. package/dist/internals/dataLoader.js +0 -117
  126. package/dist/internals/dataLoader.mjs +0 -115
  127. package/dist/internals/inputWithTrackedEventId.d.ts +0 -2
  128. package/dist/internals/inputWithTrackedEventId.d.ts.map +0 -1
  129. package/dist/internals/inputWithTrackedEventId.js +0 -16
  130. package/dist/internals/inputWithTrackedEventId.mjs +0 -14
  131. package/dist/internals/signals.d.ts +0 -16
  132. package/dist/internals/signals.d.ts.map +0 -1
  133. package/dist/internals/signals.js +0 -61
  134. package/dist/internals/signals.mjs +0 -57
  135. package/dist/internals/transformer.d.ts +0 -42
  136. package/dist/internals/transformer.d.ts.map +0 -1
  137. package/dist/internals/transformer.js +0 -30
  138. package/dist/internals/transformer.mjs +0 -28
  139. package/dist/internals/types.d.ts +0 -82
  140. package/dist/internals/types.d.ts.map +0 -1
  141. package/dist/links/HTTPBatchLinkOptions.d.ts +0 -20
  142. package/dist/links/HTTPBatchLinkOptions.d.ts.map +0 -1
  143. package/dist/links/httpBatchLink.d.ts +0 -8
  144. package/dist/links/httpBatchLink.d.ts.map +0 -1
  145. package/dist/links/httpBatchLink.js +0 -110
  146. package/dist/links/httpBatchStreamLink.d.ts +0 -12
  147. package/dist/links/httpBatchStreamLink.d.ts.map +0 -1
  148. package/dist/links/httpBatchStreamLink.js +0 -150
  149. package/dist/links/httpBatchStreamLink.mjs +0 -147
  150. package/dist/links/httpLink.d.ts +0 -17
  151. package/dist/links/httpLink.d.ts.map +0 -1
  152. package/dist/links/httpLink.js +0 -95
  153. package/dist/links/httpSubscriptionLink.d.ts +0 -26
  154. package/dist/links/httpSubscriptionLink.d.ts.map +0 -1
  155. package/dist/links/httpSubscriptionLink.js +0 -177
  156. package/dist/links/httpSubscriptionLink.mjs +0 -174
  157. package/dist/links/internals/contentTypes.d.ts +0 -4
  158. package/dist/links/internals/contentTypes.d.ts.map +0 -1
  159. package/dist/links/internals/contentTypes.js +0 -16
  160. package/dist/links/internals/contentTypes.mjs +0 -12
  161. package/dist/links/internals/createChain.d.ts +0 -8
  162. package/dist/links/internals/createChain.d.ts.map +0 -1
  163. package/dist/links/internals/createChain.js +0 -26
  164. package/dist/links/internals/createChain.mjs +0 -24
  165. package/dist/links/internals/dedupeLink.d.ts +0 -7
  166. package/dist/links/internals/dedupeLink.d.ts.map +0 -1
  167. package/dist/links/internals/httpUtils.d.ts +0 -68
  168. package/dist/links/internals/httpUtils.d.ts.map +0 -1
  169. package/dist/links/internals/httpUtils.js +0 -141
  170. package/dist/links/internals/httpUtils.mjs +0 -133
  171. package/dist/links/internals/subscriptions.d.ts +0 -17
  172. package/dist/links/internals/subscriptions.d.ts.map +0 -1
  173. package/dist/links/internals/urlWithConnectionParams.d.ts +0 -23
  174. package/dist/links/internals/urlWithConnectionParams.d.ts.map +0 -1
  175. package/dist/links/internals/urlWithConnectionParams.js +0 -10
  176. package/dist/links/internals/urlWithConnectionParams.mjs +0 -8
  177. package/dist/links/localLink.d.ts +0 -15
  178. package/dist/links/localLink.d.ts.map +0 -1
  179. package/dist/links/localLink.js +0 -333
  180. package/dist/links/localLink.mjs +0 -331
  181. package/dist/links/loggerLink.d.ts +0 -52
  182. package/dist/links/loggerLink.d.ts.map +0 -1
  183. package/dist/links/loggerLink.js +0 -178
  184. package/dist/links/retryLink.d.ts +0 -33
  185. package/dist/links/retryLink.d.ts.map +0 -1
  186. package/dist/links/retryLink.js +0 -72
  187. package/dist/links/retryLink.mjs +0 -70
  188. package/dist/links/splitLink.d.ts +0 -14
  189. package/dist/links/splitLink.d.ts.map +0 -1
  190. package/dist/links/splitLink.js +0 -27
  191. package/dist/links/types.d.ts +0 -63
  192. package/dist/links/types.d.ts.map +0 -1
  193. package/dist/links/wsLink/createWsClient.d.ts +0 -6
  194. package/dist/links/wsLink/createWsClient.d.ts.map +0 -1
  195. package/dist/links/wsLink/createWsClient.js +0 -9
  196. package/dist/links/wsLink/createWsClient.mjs +0 -7
  197. package/dist/links/wsLink/wsClient/options.d.ts +0 -79
  198. package/dist/links/wsLink/wsClient/options.d.ts.map +0 -1
  199. package/dist/links/wsLink/wsClient/options.js +0 -22
  200. package/dist/links/wsLink/wsClient/options.mjs +0 -18
  201. package/dist/links/wsLink/wsClient/requestManager.d.ts +0 -106
  202. package/dist/links/wsLink/wsClient/requestManager.d.ts.map +0 -1
  203. package/dist/links/wsLink/wsClient/requestManager.js +0 -143
  204. package/dist/links/wsLink/wsClient/requestManager.mjs +0 -141
  205. package/dist/links/wsLink/wsClient/utils.d.ts +0 -38
  206. package/dist/links/wsLink/wsClient/utils.d.ts.map +0 -1
  207. package/dist/links/wsLink/wsClient/utils.js +0 -94
  208. package/dist/links/wsLink/wsClient/utils.mjs +0 -88
  209. package/dist/links/wsLink/wsClient/wsClient.d.ts +0 -84
  210. package/dist/links/wsLink/wsClient/wsClient.d.ts.map +0 -1
  211. package/dist/links/wsLink/wsClient/wsClient.js +0 -325
  212. package/dist/links/wsLink/wsClient/wsClient.mjs +0 -323
  213. package/dist/links/wsLink/wsClient/wsConnection.d.ts +0 -79
  214. package/dist/links/wsLink/wsClient/wsConnection.d.ts.map +0 -1
  215. package/dist/links/wsLink/wsClient/wsConnection.js +0 -188
  216. package/dist/links/wsLink/wsClient/wsConnection.mjs +0 -185
  217. package/dist/links/wsLink/wsLink.d.ts +0 -11
  218. package/dist/links/wsLink/wsLink.d.ts.map +0 -1
  219. package/dist/links/wsLink/wsLink.js +0 -35
  220. package/dist/links.d.ts +0 -12
  221. package/dist/links.d.ts.map +0 -1
  222. package/dist/unstable-internals.d.ts +0 -3
  223. package/dist/unstable-internals.d.ts.map +0 -1
  224. package/dist/unstable-internals.js +0 -7
  225. package/links/httpBatchLink/index.d.ts +0 -1
  226. package/links/httpBatchLink/index.js +0 -1
  227. package/links/httpLink/index.d.ts +0 -1
  228. package/links/httpLink/index.js +0 -1
  229. package/links/loggerLink/index.d.ts +0 -1
  230. package/links/loggerLink/index.js +0 -1
  231. package/links/splitLink/index.d.ts +0 -1
  232. package/links/splitLink/index.js +0 -1
  233. package/links/wsLink/index.d.ts +0 -1
  234. package/links/wsLink/index.js +0 -1
  235. package/links/wsLink/wsLink/index.d.ts +0 -1
  236. package/links/wsLink/wsLink/index.js +0 -1
  237. package/unstable-internals/index.d.ts +0 -1
  238. package/unstable-internals/index.js +0 -1
@@ -0,0 +1,715 @@
1
+ const require_chunk = require('./chunk-DWy1uDak.cjs');
2
+ const require_TRPCClientError = require('./TRPCClientError-CGgRtttT.cjs');
3
+ const require_unstable_internals = require('./unstable-internals-CYBH4jbF.cjs');
4
+ const __trpc_server_observable = require_chunk.__toESM(require("@trpc/server/observable"));
5
+ const __trpc_server_unstable_core_do_not_import = require_chunk.__toESM(require("@trpc/server/unstable-core-do-not-import"));
6
+
7
+ //#region src/links/wsLink/wsClient/options.ts
8
+ const lazyDefaults = {
9
+ enabled: false,
10
+ closeMs: 0
11
+ };
12
+ const keepAliveDefaults = {
13
+ enabled: false,
14
+ pongTimeoutMs: 1e3,
15
+ intervalMs: 5e3
16
+ };
17
+ /**
18
+ * Calculates a delay for exponential backoff based on the retry attempt index.
19
+ * The delay starts at 0 for the first attempt and doubles for each subsequent attempt,
20
+ * capped at 30 seconds.
21
+ */
22
+ const exponentialBackoff = (attemptIndex) => {
23
+ return attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);
24
+ };
25
+
26
+ //#endregion
27
+ //#region src/links/internals/urlWithConnectionParams.ts
28
+ /**
29
+ * Get the result of a value or function that returns a value
30
+ * It also optionally accepts typesafe arguments for the function
31
+ */
32
+ const resultOf = (value, ...args) => {
33
+ return typeof value === "function" ? value(...args) : value;
34
+ };
35
+
36
+ //#endregion
37
+ //#region src/links/wsLink/wsClient/utils.ts
38
+ var TRPCWebSocketClosedError = class TRPCWebSocketClosedError extends Error {
39
+ constructor(opts) {
40
+ super(opts.message, { cause: opts.cause });
41
+ this.name = "TRPCWebSocketClosedError";
42
+ Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);
43
+ }
44
+ };
45
+ /**
46
+ * Utility class for managing a timeout that can be started, stopped, and reset.
47
+ * Useful for scenarios where the timeout duration is reset dynamically based on events.
48
+ */
49
+ var ResettableTimeout = class {
50
+ timeout;
51
+ constructor(onTimeout, timeoutMs) {
52
+ this.onTimeout = onTimeout;
53
+ this.timeoutMs = timeoutMs;
54
+ }
55
+ /**
56
+ * Resets the current timeout, restarting it with the same duration.
57
+ * Does nothing if no timeout is active.
58
+ */
59
+ reset() {
60
+ if (!this.timeout) return;
61
+ clearTimeout(this.timeout);
62
+ this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
63
+ }
64
+ start() {
65
+ clearTimeout(this.timeout);
66
+ this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
67
+ }
68
+ stop() {
69
+ clearTimeout(this.timeout);
70
+ this.timeout = void 0;
71
+ }
72
+ };
73
+ function withResolvers() {
74
+ let resolve;
75
+ let reject;
76
+ const promise = new Promise((res, rej) => {
77
+ resolve = res;
78
+ reject = rej;
79
+ });
80
+ return {
81
+ promise,
82
+ resolve,
83
+ reject
84
+ };
85
+ }
86
+ /**
87
+ * Resolves a WebSocket URL and optionally appends connection parameters.
88
+ *
89
+ * If connectionParams are provided, appends 'connectionParams=1' query parameter.
90
+ */
91
+ async function prepareUrl(urlOptions) {
92
+ const url = await resultOf(urlOptions.url);
93
+ if (!urlOptions.connectionParams) return url;
94
+ const prefix = url.includes("?") ? "&" : "?";
95
+ const connectionParams = `${prefix}connectionParams=1`;
96
+ return url + connectionParams;
97
+ }
98
+ async function buildConnectionMessage(connectionParams) {
99
+ const message = {
100
+ method: "connectionParams",
101
+ data: await resultOf(connectionParams)
102
+ };
103
+ return JSON.stringify(message);
104
+ }
105
+
106
+ //#endregion
107
+ //#region src/links/wsLink/wsClient/requestManager.ts
108
+ /**
109
+ * Manages WebSocket requests, tracking their lifecycle and providing utility methods
110
+ * for handling outgoing and pending requests.
111
+ *
112
+ * - **Outgoing requests**: Requests that are queued and waiting to be sent.
113
+ * - **Pending requests**: Requests that have been sent and are in flight awaiting a response.
114
+ * For subscriptions, multiple responses may be received until the subscription is closed.
115
+ */
116
+ var RequestManager = class {
117
+ /**
118
+ * Stores requests that are outgoing, meaning they are registered but not yet sent over the WebSocket.
119
+ */
120
+ outgoingRequests = new Array();
121
+ /**
122
+ * Stores requests that are pending (in flight), meaning they have been sent over the WebSocket
123
+ * and are awaiting responses. For subscriptions, this includes requests
124
+ * that may receive multiple responses.
125
+ */
126
+ pendingRequests = {};
127
+ /**
128
+ * Registers a new request by adding it to the outgoing queue and setting up
129
+ * callbacks for lifecycle events such as completion or error.
130
+ *
131
+ * @param message - The outgoing message to be sent.
132
+ * @param callbacks - Callback functions to observe the request's state.
133
+ * @returns A cleanup function to manually remove the request.
134
+ */
135
+ register(message, callbacks) {
136
+ const { promise: end, resolve } = withResolvers();
137
+ this.outgoingRequests.push({
138
+ id: String(message.id),
139
+ message,
140
+ end,
141
+ callbacks: {
142
+ next: callbacks.next,
143
+ complete: () => {
144
+ callbacks.complete();
145
+ resolve();
146
+ },
147
+ error: (e) => {
148
+ callbacks.error(e);
149
+ resolve();
150
+ }
151
+ }
152
+ });
153
+ return () => {
154
+ this.delete(message.id);
155
+ callbacks.complete();
156
+ resolve();
157
+ };
158
+ }
159
+ /**
160
+ * Deletes a request from both the outgoing and pending collections, if it exists.
161
+ */
162
+ delete(messageId) {
163
+ if (messageId === null) return;
164
+ this.outgoingRequests = this.outgoingRequests.filter(({ id }) => id !== String(messageId));
165
+ delete this.pendingRequests[String(messageId)];
166
+ }
167
+ /**
168
+ * Moves all outgoing requests to the pending state and clears the outgoing queue.
169
+ *
170
+ * The caller is expected to handle the actual sending of the requests
171
+ * (e.g., sending them over the network) after this method is called.
172
+ *
173
+ * @returns The list of requests that were transitioned to the pending state.
174
+ */
175
+ flush() {
176
+ const requests = this.outgoingRequests;
177
+ this.outgoingRequests = [];
178
+ for (const request of requests) this.pendingRequests[request.id] = request;
179
+ return requests;
180
+ }
181
+ /**
182
+ * Retrieves all currently pending requests, which are in flight awaiting responses
183
+ * or handling ongoing subscriptions.
184
+ */
185
+ getPendingRequests() {
186
+ return Object.values(this.pendingRequests);
187
+ }
188
+ /**
189
+ * Retrieves a specific pending request by its message ID.
190
+ */
191
+ getPendingRequest(messageId) {
192
+ if (messageId === null) return null;
193
+ return this.pendingRequests[String(messageId)];
194
+ }
195
+ /**
196
+ * Retrieves all outgoing requests, which are waiting to be sent.
197
+ */
198
+ getOutgoingRequests() {
199
+ return this.outgoingRequests;
200
+ }
201
+ /**
202
+ * Retrieves all requests, both outgoing and pending, with their respective states.
203
+ *
204
+ * @returns An array of all requests with their state ("outgoing" or "pending").
205
+ */
206
+ getRequests() {
207
+ return [...this.getOutgoingRequests().map((request) => ({
208
+ state: "outgoing",
209
+ message: request.message,
210
+ end: request.end,
211
+ callbacks: request.callbacks
212
+ })), ...this.getPendingRequests().map((request) => ({
213
+ state: "pending",
214
+ message: request.message,
215
+ end: request.end,
216
+ callbacks: request.callbacks
217
+ }))];
218
+ }
219
+ /**
220
+ * Checks if there are any pending requests, including ongoing subscriptions.
221
+ */
222
+ hasPendingRequests() {
223
+ return this.getPendingRequests().length > 0;
224
+ }
225
+ /**
226
+ * Checks if there are any pending subscriptions
227
+ */
228
+ hasPendingSubscriptions() {
229
+ return this.getPendingRequests().some((request) => request.message.method === "subscription");
230
+ }
231
+ /**
232
+ * Checks if there are any outgoing requests waiting to be sent.
233
+ */
234
+ hasOutgoingRequests() {
235
+ return this.outgoingRequests.length > 0;
236
+ }
237
+ };
238
+
239
+ //#endregion
240
+ //#region src/links/wsLink/wsClient/wsConnection.ts
241
+ /**
242
+ * Opens a WebSocket connection asynchronously and returns a promise
243
+ * that resolves when the connection is successfully established.
244
+ * The promise rejects if an error occurs during the connection attempt.
245
+ */
246
+ function asyncWsOpen(ws) {
247
+ const { promise, resolve, reject } = withResolvers();
248
+ ws.addEventListener("open", () => {
249
+ ws.removeEventListener("error", reject);
250
+ resolve();
251
+ });
252
+ ws.addEventListener("error", reject);
253
+ return promise;
254
+ }
255
+ /**
256
+ * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.
257
+ *
258
+ * - Sends "PING" messages at regular intervals defined by `intervalMs`.
259
+ * - If a "PONG" response is not received within the `pongTimeoutMs`, the WebSocket is closed.
260
+ * - The ping timer resets upon receiving any message to maintain activity.
261
+ * - Automatically starts the ping process when the WebSocket connection is opened.
262
+ * - Cleans up timers when the WebSocket is closed.
263
+ *
264
+ * @param ws - The WebSocket instance to manage.
265
+ * @param options - Configuration options for ping-pong intervals and timeouts.
266
+ */
267
+ function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {
268
+ let pingTimeout;
269
+ let pongTimeout;
270
+ function start() {
271
+ pingTimeout = setTimeout(() => {
272
+ ws.send("PING");
273
+ pongTimeout = setTimeout(() => {
274
+ ws.close();
275
+ }, pongTimeoutMs);
276
+ }, intervalMs);
277
+ }
278
+ function reset() {
279
+ clearTimeout(pingTimeout);
280
+ start();
281
+ }
282
+ function pong() {
283
+ clearTimeout(pongTimeout);
284
+ reset();
285
+ }
286
+ ws.addEventListener("open", start);
287
+ ws.addEventListener("message", ({ data }) => {
288
+ clearTimeout(pingTimeout);
289
+ start();
290
+ if (data === "PONG") pong();
291
+ });
292
+ ws.addEventListener("close", () => {
293
+ clearTimeout(pingTimeout);
294
+ clearTimeout(pongTimeout);
295
+ });
296
+ }
297
+ /**
298
+ * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,
299
+ * and observable state tracking.
300
+ */
301
+ var WsConnection = class WsConnection {
302
+ static connectCount = 0;
303
+ id = ++WsConnection.connectCount;
304
+ WebSocketPonyfill;
305
+ urlOptions;
306
+ keepAliveOpts;
307
+ wsObservable = (0, __trpc_server_observable.behaviorSubject)(null);
308
+ constructor(opts) {
309
+ this.WebSocketPonyfill = opts.WebSocketPonyfill ?? WebSocket;
310
+ if (!this.WebSocketPonyfill) throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
311
+ this.urlOptions = opts.urlOptions;
312
+ this.keepAliveOpts = opts.keepAlive;
313
+ }
314
+ get ws() {
315
+ return this.wsObservable.get();
316
+ }
317
+ set ws(ws) {
318
+ this.wsObservable.next(ws);
319
+ }
320
+ /**
321
+ * Checks if the WebSocket connection is open and ready to communicate.
322
+ */
323
+ isOpen() {
324
+ return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;
325
+ }
326
+ /**
327
+ * Checks if the WebSocket connection is closed or in the process of closing.
328
+ */
329
+ isClosed() {
330
+ return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);
331
+ }
332
+ /**
333
+ * Manages the WebSocket opening process, ensuring that only one open operation
334
+ * occurs at a time. Tracks the ongoing operation with `openPromise` to avoid
335
+ * redundant calls and ensure proper synchronization.
336
+ *
337
+ * Sets up the keep-alive mechanism and necessary event listeners for the connection.
338
+ *
339
+ * @returns A promise that resolves once the WebSocket connection is successfully opened.
340
+ */
341
+ openPromise = null;
342
+ async open() {
343
+ if (this.openPromise) return this.openPromise;
344
+ this.id = ++WsConnection.connectCount;
345
+ const wsPromise = prepareUrl(this.urlOptions).then((url) => new this.WebSocketPonyfill(url));
346
+ this.openPromise = wsPromise.then(async (ws) => {
347
+ this.ws = ws;
348
+ ws.addEventListener("message", function({ data }) {
349
+ if (data === "PING") this.send("PONG");
350
+ });
351
+ if (this.keepAliveOpts.enabled) setupPingInterval(ws, this.keepAliveOpts);
352
+ ws.addEventListener("close", () => {
353
+ if (this.ws === ws) this.ws = null;
354
+ });
355
+ await asyncWsOpen(ws);
356
+ if (this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(this.urlOptions.connectionParams));
357
+ });
358
+ try {
359
+ await this.openPromise;
360
+ } finally {
361
+ this.openPromise = null;
362
+ }
363
+ }
364
+ /**
365
+ * Closes the WebSocket connection gracefully.
366
+ * Waits for any ongoing open operation to complete before closing.
367
+ */
368
+ async close() {
369
+ try {
370
+ await this.openPromise;
371
+ } finally {
372
+ this.ws?.close();
373
+ }
374
+ }
375
+ };
376
+ /**
377
+ * Provides a backward-compatible representation of the connection state.
378
+ */
379
+ function backwardCompatibility(connection) {
380
+ if (connection.isOpen()) return {
381
+ id: connection.id,
382
+ state: "open",
383
+ ws: connection.ws
384
+ };
385
+ if (connection.isClosed()) return {
386
+ id: connection.id,
387
+ state: "closed",
388
+ ws: connection.ws
389
+ };
390
+ if (!connection.ws) return null;
391
+ return {
392
+ id: connection.id,
393
+ state: "connecting",
394
+ ws: connection.ws
395
+ };
396
+ }
397
+
398
+ //#endregion
399
+ //#region src/links/wsLink/wsClient/wsClient.ts
400
+ /**
401
+ * A WebSocket client for managing TRPC operations, supporting lazy initialization,
402
+ * reconnection, keep-alive, and request management.
403
+ */
404
+ var WsClient = class {
405
+ /**
406
+ * Observable tracking the current connection state, including errors.
407
+ */
408
+ connectionState;
409
+ allowReconnect = false;
410
+ requestManager = new RequestManager();
411
+ activeConnection;
412
+ reconnectRetryDelay;
413
+ inactivityTimeout;
414
+ callbacks;
415
+ lazyMode;
416
+ constructor(opts) {
417
+ this.callbacks = {
418
+ onOpen: opts.onOpen,
419
+ onClose: opts.onClose,
420
+ onError: opts.onError
421
+ };
422
+ const lazyOptions = {
423
+ ...lazyDefaults,
424
+ ...opts.lazy
425
+ };
426
+ this.inactivityTimeout = new ResettableTimeout(() => {
427
+ if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
428
+ this.inactivityTimeout.reset();
429
+ return;
430
+ }
431
+ this.close().catch(() => null);
432
+ }, lazyOptions.closeMs);
433
+ this.activeConnection = new WsConnection({
434
+ WebSocketPonyfill: opts.WebSocket,
435
+ urlOptions: opts,
436
+ keepAlive: {
437
+ ...keepAliveDefaults,
438
+ ...opts.keepAlive
439
+ }
440
+ });
441
+ this.activeConnection.wsObservable.subscribe({ next: (ws) => {
442
+ if (!ws) return;
443
+ this.setupWebSocketListeners(ws);
444
+ } });
445
+ this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;
446
+ this.lazyMode = lazyOptions.enabled;
447
+ this.connectionState = (0, __trpc_server_observable.behaviorSubject)({
448
+ type: "state",
449
+ state: lazyOptions.enabled ? "idle" : "connecting",
450
+ error: null
451
+ });
452
+ if (!this.lazyMode) this.open().catch(() => null);
453
+ }
454
+ /**
455
+ * Opens the WebSocket connection. Handles reconnection attempts and updates
456
+ * the connection state accordingly.
457
+ */
458
+ async open() {
459
+ this.allowReconnect = true;
460
+ if (this.connectionState.get().state !== "connecting") this.connectionState.next({
461
+ type: "state",
462
+ state: "connecting",
463
+ error: null
464
+ });
465
+ try {
466
+ await this.activeConnection.open();
467
+ } catch (error) {
468
+ this.reconnect(new TRPCWebSocketClosedError({
469
+ message: "Initialization error",
470
+ cause: error
471
+ }));
472
+ return this.reconnecting;
473
+ }
474
+ }
475
+ /**
476
+ * Closes the WebSocket connection and stops managing requests.
477
+ * Ensures all outgoing and pending requests are properly finalized.
478
+ */
479
+ async close() {
480
+ this.allowReconnect = false;
481
+ this.inactivityTimeout.stop();
482
+ const requestsToAwait = [];
483
+ for (const request of this.requestManager.getRequests()) if (request.message.method === "subscription") request.callbacks.complete();
484
+ else if (request.state === "outgoing") request.callbacks.error(require_TRPCClientError.TRPCClientError.from(new TRPCWebSocketClosedError({ message: "Closed before connection was established" })));
485
+ else requestsToAwait.push(request.end);
486
+ await Promise.all(requestsToAwait).catch(() => null);
487
+ await this.activeConnection.close().catch(() => null);
488
+ this.connectionState.next({
489
+ type: "state",
490
+ state: "idle",
491
+ error: null
492
+ });
493
+ }
494
+ /**
495
+ * Method to request the server.
496
+ * Handles data transformation, batching of requests, and subscription lifecycle.
497
+ *
498
+ * @param op - The operation details including id, type, path, input and signal
499
+ * @param transformer - Data transformer for serializing requests and deserializing responses
500
+ * @param lastEventId - Optional ID of the last received event for subscriptions
501
+ *
502
+ * @returns An observable that emits operation results and handles cleanup
503
+ */
504
+ request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
505
+ return (0, __trpc_server_observable.observable)((observer) => {
506
+ const abort = this.batchSend({
507
+ id,
508
+ method: type,
509
+ params: {
510
+ input: transformer.input.serialize(input),
511
+ path,
512
+ lastEventId
513
+ }
514
+ }, {
515
+ ...observer,
516
+ next(event) {
517
+ const transformed = (0, __trpc_server_unstable_core_do_not_import.transformResult)(event, transformer.output);
518
+ if (!transformed.ok) {
519
+ observer.error(require_TRPCClientError.TRPCClientError.from(transformed.error));
520
+ return;
521
+ }
522
+ observer.next({ result: transformed.result });
523
+ }
524
+ });
525
+ return () => {
526
+ abort();
527
+ if (type === "subscription" && this.activeConnection.isOpen()) this.send({
528
+ id,
529
+ method: "subscription.stop"
530
+ });
531
+ signal?.removeEventListener("abort", abort);
532
+ };
533
+ });
534
+ }
535
+ get connection() {
536
+ return backwardCompatibility(this.activeConnection);
537
+ }
538
+ /**
539
+ * Manages the reconnection process for the WebSocket using retry logic.
540
+ * Ensures that only one reconnection attempt is active at a time by tracking the current
541
+ * reconnection state in the `reconnecting` promise.
542
+ */
543
+ reconnecting = null;
544
+ reconnect(closedError) {
545
+ this.connectionState.next({
546
+ type: "state",
547
+ state: "connecting",
548
+ error: require_TRPCClientError.TRPCClientError.from(closedError)
549
+ });
550
+ if (this.reconnecting) return;
551
+ const tryReconnect = async (attemptIndex) => {
552
+ try {
553
+ await (0, __trpc_server_unstable_core_do_not_import.sleep)(this.reconnectRetryDelay(attemptIndex));
554
+ if (this.allowReconnect) {
555
+ await this.activeConnection.close();
556
+ await this.activeConnection.open();
557
+ if (this.requestManager.hasPendingRequests()) this.send(this.requestManager.getPendingRequests().map(({ message }) => message));
558
+ }
559
+ this.reconnecting = null;
560
+ } catch {
561
+ await tryReconnect(attemptIndex + 1);
562
+ }
563
+ };
564
+ this.reconnecting = tryReconnect(0);
565
+ }
566
+ setupWebSocketListeners(ws) {
567
+ const handleCloseOrError = (cause) => {
568
+ const reqs = this.requestManager.getPendingRequests();
569
+ for (const { message, callbacks } of reqs) {
570
+ if (message.method === "subscription") continue;
571
+ callbacks.error(require_TRPCClientError.TRPCClientError.from(cause ?? new TRPCWebSocketClosedError({
572
+ message: "WebSocket closed",
573
+ cause
574
+ })));
575
+ this.requestManager.delete(message.id);
576
+ }
577
+ };
578
+ ws.addEventListener("open", () => {
579
+ (0, __trpc_server_unstable_core_do_not_import.run)(async () => {
580
+ if (this.lazyMode) this.inactivityTimeout.start();
581
+ this.callbacks.onOpen?.();
582
+ this.connectionState.next({
583
+ type: "state",
584
+ state: "pending",
585
+ error: null
586
+ });
587
+ }).catch((error) => {
588
+ ws.close(3e3);
589
+ handleCloseOrError(error);
590
+ });
591
+ });
592
+ ws.addEventListener("message", ({ data }) => {
593
+ this.inactivityTimeout.reset();
594
+ if (typeof data !== "string" || ["PING", "PONG"].includes(data)) return;
595
+ const incomingMessage = JSON.parse(data);
596
+ if ("method" in incomingMessage) {
597
+ this.handleIncomingRequest(incomingMessage);
598
+ return;
599
+ }
600
+ this.handleResponseMessage(incomingMessage);
601
+ });
602
+ ws.addEventListener("close", (event) => {
603
+ handleCloseOrError(event);
604
+ this.callbacks.onClose?.(event);
605
+ if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) this.reconnect(new TRPCWebSocketClosedError({
606
+ message: "WebSocket closed",
607
+ cause: event
608
+ }));
609
+ });
610
+ ws.addEventListener("error", (event) => {
611
+ handleCloseOrError(event);
612
+ this.callbacks.onError?.(event);
613
+ this.reconnect(new TRPCWebSocketClosedError({
614
+ message: "WebSocket closed",
615
+ cause: event
616
+ }));
617
+ });
618
+ }
619
+ handleResponseMessage(message) {
620
+ const request = this.requestManager.getPendingRequest(message.id);
621
+ if (!request) return;
622
+ request.callbacks.next(message);
623
+ let completed = true;
624
+ if ("result" in message && request.message.method === "subscription") {
625
+ if (message.result.type === "data") request.message.params.lastEventId = message.result.id;
626
+ if (message.result.type !== "stopped") completed = false;
627
+ }
628
+ if (completed) {
629
+ request.callbacks.complete();
630
+ this.requestManager.delete(message.id);
631
+ }
632
+ }
633
+ handleIncomingRequest(message) {
634
+ if (message.method === "reconnect") this.reconnect(new TRPCWebSocketClosedError({ message: "Server requested reconnect" }));
635
+ }
636
+ /**
637
+ * Sends a message or batch of messages directly to the server.
638
+ */
639
+ send(messageOrMessages) {
640
+ if (!this.activeConnection.isOpen()) throw new Error("Active connection is not open");
641
+ const messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];
642
+ this.activeConnection.ws.send(JSON.stringify(messages.length === 1 ? messages[0] : messages));
643
+ }
644
+ /**
645
+ * Groups requests for batch sending.
646
+ *
647
+ * @returns A function to abort the batched request.
648
+ */
649
+ batchSend(message, callbacks) {
650
+ this.inactivityTimeout.reset();
651
+ (0, __trpc_server_unstable_core_do_not_import.run)(async () => {
652
+ if (!this.activeConnection.isOpen()) await this.open();
653
+ await (0, __trpc_server_unstable_core_do_not_import.sleep)(0);
654
+ if (!this.requestManager.hasOutgoingRequests()) return;
655
+ this.send(this.requestManager.flush().map(({ message: message$1 }) => message$1));
656
+ }).catch((err) => {
657
+ this.requestManager.delete(message.id);
658
+ callbacks.error(require_TRPCClientError.TRPCClientError.from(err));
659
+ });
660
+ return this.requestManager.register(message, callbacks);
661
+ }
662
+ };
663
+
664
+ //#endregion
665
+ //#region src/links/wsLink/createWsClient.ts
666
+ function createWSClient(opts) {
667
+ return new WsClient(opts);
668
+ }
669
+
670
+ //#endregion
671
+ //#region src/links/wsLink/wsLink.ts
672
+ function wsLink(opts) {
673
+ const { client } = opts;
674
+ const transformer = require_unstable_internals.getTransformer(opts.transformer);
675
+ return () => {
676
+ return ({ op }) => {
677
+ return (0, __trpc_server_observable.observable)((observer) => {
678
+ const connStateSubscription = op.type === "subscription" ? client.connectionState.subscribe({ next(result) {
679
+ observer.next({
680
+ result,
681
+ context: op.context
682
+ });
683
+ } }) : null;
684
+ const requestSubscription = client.request({
685
+ op,
686
+ transformer
687
+ }).subscribe(observer);
688
+ return () => {
689
+ requestSubscription.unsubscribe();
690
+ connStateSubscription?.unsubscribe();
691
+ };
692
+ });
693
+ };
694
+ };
695
+ }
696
+
697
+ //#endregion
698
+ Object.defineProperty(exports, 'createWSClient', {
699
+ enumerable: true,
700
+ get: function () {
701
+ return createWSClient;
702
+ }
703
+ });
704
+ Object.defineProperty(exports, 'resultOf', {
705
+ enumerable: true,
706
+ get: function () {
707
+ return resultOf;
708
+ }
709
+ });
710
+ Object.defineProperty(exports, 'wsLink', {
711
+ enumerable: true,
712
+ get: function () {
713
+ return wsLink;
714
+ }
715
+ });