@trpc/client 11.3.1-canary.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 (237) 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/bundle-analysis.json +0 -451
  105. package/dist/createTRPCClient.d.ts +0 -69
  106. package/dist/createTRPCClient.d.ts.map +0 -1
  107. package/dist/createTRPCClient.js +0 -48
  108. package/dist/createTRPCClient.mjs +0 -43
  109. package/dist/createTRPCUntypedClient.d.ts +0 -7
  110. package/dist/createTRPCUntypedClient.d.ts.map +0 -1
  111. package/dist/createTRPCUntypedClient.js +0 -10
  112. package/dist/createTRPCUntypedClient.mjs +0 -7
  113. package/dist/getFetch.d.ts +0 -3
  114. package/dist/getFetch.d.ts.map +0 -1
  115. package/dist/getFetch.js +0 -17
  116. package/dist/getFetch.mjs +0 -15
  117. package/dist/index.d.ts +0 -16
  118. package/dist/index.d.ts.map +0 -1
  119. package/dist/index.js +0 -46
  120. package/dist/internals/TRPCUntypedClient.d.ts +0 -39
  121. package/dist/internals/TRPCUntypedClient.d.ts.map +0 -1
  122. package/dist/internals/TRPCUntypedClient.js +0 -115
  123. package/dist/internals/TRPCUntypedClient.mjs +0 -113
  124. package/dist/internals/dataLoader.d.ts +0 -13
  125. package/dist/internals/dataLoader.d.ts.map +0 -1
  126. package/dist/internals/dataLoader.js +0 -117
  127. package/dist/internals/dataLoader.mjs +0 -115
  128. package/dist/internals/inputWithTrackedEventId.d.ts +0 -2
  129. package/dist/internals/inputWithTrackedEventId.d.ts.map +0 -1
  130. package/dist/internals/inputWithTrackedEventId.js +0 -16
  131. package/dist/internals/inputWithTrackedEventId.mjs +0 -14
  132. package/dist/internals/signals.d.ts +0 -16
  133. package/dist/internals/signals.d.ts.map +0 -1
  134. package/dist/internals/signals.js +0 -61
  135. package/dist/internals/signals.mjs +0 -57
  136. package/dist/internals/transformer.d.ts +0 -42
  137. package/dist/internals/transformer.d.ts.map +0 -1
  138. package/dist/internals/transformer.js +0 -30
  139. package/dist/internals/transformer.mjs +0 -28
  140. package/dist/internals/types.d.ts +0 -82
  141. package/dist/internals/types.d.ts.map +0 -1
  142. package/dist/links/HTTPBatchLinkOptions.d.ts +0 -20
  143. package/dist/links/HTTPBatchLinkOptions.d.ts.map +0 -1
  144. package/dist/links/httpBatchLink.d.ts +0 -8
  145. package/dist/links/httpBatchLink.d.ts.map +0 -1
  146. package/dist/links/httpBatchLink.js +0 -110
  147. package/dist/links/httpBatchStreamLink.d.ts +0 -12
  148. package/dist/links/httpBatchStreamLink.d.ts.map +0 -1
  149. package/dist/links/httpBatchStreamLink.js +0 -150
  150. package/dist/links/httpBatchStreamLink.mjs +0 -147
  151. package/dist/links/httpLink.d.ts +0 -17
  152. package/dist/links/httpLink.d.ts.map +0 -1
  153. package/dist/links/httpLink.js +0 -95
  154. package/dist/links/httpSubscriptionLink.d.ts +0 -26
  155. package/dist/links/httpSubscriptionLink.d.ts.map +0 -1
  156. package/dist/links/httpSubscriptionLink.js +0 -177
  157. package/dist/links/httpSubscriptionLink.mjs +0 -174
  158. package/dist/links/internals/contentTypes.d.ts +0 -4
  159. package/dist/links/internals/contentTypes.d.ts.map +0 -1
  160. package/dist/links/internals/contentTypes.js +0 -16
  161. package/dist/links/internals/contentTypes.mjs +0 -12
  162. package/dist/links/internals/createChain.d.ts +0 -8
  163. package/dist/links/internals/createChain.d.ts.map +0 -1
  164. package/dist/links/internals/createChain.js +0 -26
  165. package/dist/links/internals/createChain.mjs +0 -24
  166. package/dist/links/internals/dedupeLink.d.ts +0 -7
  167. package/dist/links/internals/dedupeLink.d.ts.map +0 -1
  168. package/dist/links/internals/httpUtils.d.ts +0 -68
  169. package/dist/links/internals/httpUtils.d.ts.map +0 -1
  170. package/dist/links/internals/httpUtils.js +0 -141
  171. package/dist/links/internals/httpUtils.mjs +0 -133
  172. package/dist/links/internals/subscriptions.d.ts +0 -17
  173. package/dist/links/internals/subscriptions.d.ts.map +0 -1
  174. package/dist/links/internals/urlWithConnectionParams.d.ts +0 -23
  175. package/dist/links/internals/urlWithConnectionParams.d.ts.map +0 -1
  176. package/dist/links/internals/urlWithConnectionParams.js +0 -10
  177. package/dist/links/internals/urlWithConnectionParams.mjs +0 -8
  178. package/dist/links/localLink.d.ts +0 -15
  179. package/dist/links/localLink.d.ts.map +0 -1
  180. package/dist/links/localLink.js +0 -333
  181. package/dist/links/localLink.mjs +0 -331
  182. package/dist/links/loggerLink.d.ts +0 -52
  183. package/dist/links/loggerLink.d.ts.map +0 -1
  184. package/dist/links/loggerLink.js +0 -178
  185. package/dist/links/retryLink.d.ts +0 -33
  186. package/dist/links/retryLink.d.ts.map +0 -1
  187. package/dist/links/retryLink.js +0 -72
  188. package/dist/links/retryLink.mjs +0 -70
  189. package/dist/links/splitLink.d.ts +0 -14
  190. package/dist/links/splitLink.d.ts.map +0 -1
  191. package/dist/links/splitLink.js +0 -27
  192. package/dist/links/types.d.ts +0 -63
  193. package/dist/links/types.d.ts.map +0 -1
  194. package/dist/links/wsLink/createWsClient.d.ts +0 -6
  195. package/dist/links/wsLink/createWsClient.d.ts.map +0 -1
  196. package/dist/links/wsLink/createWsClient.js +0 -9
  197. package/dist/links/wsLink/createWsClient.mjs +0 -7
  198. package/dist/links/wsLink/wsClient/options.d.ts +0 -79
  199. package/dist/links/wsLink/wsClient/options.d.ts.map +0 -1
  200. package/dist/links/wsLink/wsClient/options.js +0 -22
  201. package/dist/links/wsLink/wsClient/options.mjs +0 -18
  202. package/dist/links/wsLink/wsClient/requestManager.d.ts +0 -106
  203. package/dist/links/wsLink/wsClient/requestManager.d.ts.map +0 -1
  204. package/dist/links/wsLink/wsClient/requestManager.js +0 -143
  205. package/dist/links/wsLink/wsClient/requestManager.mjs +0 -141
  206. package/dist/links/wsLink/wsClient/utils.d.ts +0 -38
  207. package/dist/links/wsLink/wsClient/utils.d.ts.map +0 -1
  208. package/dist/links/wsLink/wsClient/utils.js +0 -94
  209. package/dist/links/wsLink/wsClient/utils.mjs +0 -88
  210. package/dist/links/wsLink/wsClient/wsClient.d.ts +0 -84
  211. package/dist/links/wsLink/wsClient/wsClient.d.ts.map +0 -1
  212. package/dist/links/wsLink/wsClient/wsClient.js +0 -325
  213. package/dist/links/wsLink/wsClient/wsClient.mjs +0 -323
  214. package/dist/links/wsLink/wsClient/wsConnection.d.ts +0 -79
  215. package/dist/links/wsLink/wsClient/wsConnection.d.ts.map +0 -1
  216. package/dist/links/wsLink/wsClient/wsConnection.js +0 -188
  217. package/dist/links/wsLink/wsClient/wsConnection.mjs +0 -185
  218. package/dist/links/wsLink/wsLink.d.ts +0 -11
  219. package/dist/links/wsLink/wsLink.d.ts.map +0 -1
  220. package/dist/links/wsLink/wsLink.js +0 -35
  221. package/dist/links.d.ts +0 -12
  222. package/dist/links.d.ts.map +0 -1
  223. package/dist/unstable-internals.d.ts +0 -3
  224. package/dist/unstable-internals.d.ts.map +0 -1
  225. package/dist/unstable-internals.js +0 -7
  226. package/links/httpBatchLink/index.d.ts +0 -1
  227. package/links/httpBatchLink/index.js +0 -1
  228. package/links/httpLink/index.d.ts +0 -1
  229. package/links/httpLink/index.js +0 -1
  230. package/links/loggerLink/index.d.ts +0 -1
  231. package/links/loggerLink/index.js +0 -1
  232. package/links/splitLink/index.d.ts +0 -1
  233. package/links/splitLink/index.js +0 -1
  234. package/links/wsLink/wsLink/index.d.ts +0 -1
  235. package/links/wsLink/wsLink/index.js +0 -1
  236. package/unstable-internals/index.d.ts +0 -1
  237. package/unstable-internals/index.js +0 -1
@@ -1,325 +0,0 @@
1
- 'use strict';
2
-
3
- var observable = require('@trpc/server/observable');
4
- var unstableCoreDoNotImport = require('@trpc/server/unstable-core-do-not-import');
5
- var TRPCClientError = require('../../../TRPCClientError.js');
6
- var options = require('./options.js');
7
- var requestManager = require('./requestManager.js');
8
- var utils = require('./utils.js');
9
- var wsConnection = require('./wsConnection.js');
10
-
11
- function _define_property(obj, key, value) {
12
- if (key in obj) {
13
- Object.defineProperty(obj, key, {
14
- value: value,
15
- enumerable: true,
16
- configurable: true,
17
- writable: true
18
- });
19
- } else {
20
- obj[key] = value;
21
- }
22
- return obj;
23
- }
24
- /**
25
- * A WebSocket client for managing TRPC operations, supporting lazy initialization,
26
- * reconnection, keep-alive, and request management.
27
- */ class WsClient {
28
- /**
29
- * Opens the WebSocket connection. Handles reconnection attempts and updates
30
- * the connection state accordingly.
31
- */ async open() {
32
- this.allowReconnect = true;
33
- if (this.connectionState.get().state !== 'connecting') {
34
- this.connectionState.next({
35
- type: 'state',
36
- state: 'connecting',
37
- error: null
38
- });
39
- }
40
- try {
41
- await this.activeConnection.open();
42
- } catch (error) {
43
- this.reconnect(new utils.TRPCWebSocketClosedError({
44
- message: 'Initialization error',
45
- cause: error
46
- }));
47
- return this.reconnecting;
48
- }
49
- }
50
- /**
51
- * Closes the WebSocket connection and stops managing requests.
52
- * Ensures all outgoing and pending requests are properly finalized.
53
- */ async close() {
54
- this.allowReconnect = false;
55
- this.inactivityTimeout.stop();
56
- const requestsToAwait = [];
57
- for (const request of this.requestManager.getRequests()){
58
- if (request.message.method === 'subscription') {
59
- request.callbacks.complete();
60
- } else if (request.state === 'outgoing') {
61
- request.callbacks.error(TRPCClientError.TRPCClientError.from(new utils.TRPCWebSocketClosedError({
62
- message: 'Closed before connection was established'
63
- })));
64
- } else {
65
- requestsToAwait.push(request.end);
66
- }
67
- }
68
- await Promise.all(requestsToAwait).catch(()=>null);
69
- await this.activeConnection.close().catch(()=>null);
70
- this.connectionState.next({
71
- type: 'state',
72
- state: 'idle',
73
- error: null
74
- });
75
- }
76
- /**
77
- * Method to request the server.
78
- * Handles data transformation, batching of requests, and subscription lifecycle.
79
- *
80
- * @param op - The operation details including id, type, path, input and signal
81
- * @param transformer - Data transformer for serializing requests and deserializing responses
82
- * @param lastEventId - Optional ID of the last received event for subscriptions
83
- *
84
- * @returns An observable that emits operation results and handles cleanup
85
- */ request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
86
- return observable.observable((observer)=>{
87
- const abort = this.batchSend({
88
- id,
89
- method: type,
90
- params: {
91
- input: transformer.input.serialize(input),
92
- path,
93
- lastEventId
94
- }
95
- }, {
96
- ...observer,
97
- next (event) {
98
- const transformed = unstableCoreDoNotImport.transformResult(event, transformer.output);
99
- if (!transformed.ok) {
100
- observer.error(TRPCClientError.TRPCClientError.from(transformed.error));
101
- return;
102
- }
103
- observer.next({
104
- result: transformed.result
105
- });
106
- }
107
- });
108
- return ()=>{
109
- abort();
110
- if (type === 'subscription' && this.activeConnection.isOpen()) {
111
- this.send({
112
- id,
113
- method: 'subscription.stop'
114
- });
115
- }
116
- signal?.removeEventListener('abort', abort);
117
- };
118
- });
119
- }
120
- get connection() {
121
- return wsConnection.backwardCompatibility(this.activeConnection);
122
- }
123
- reconnect(closedError) {
124
- this.connectionState.next({
125
- type: 'state',
126
- state: 'connecting',
127
- error: TRPCClientError.TRPCClientError.from(closedError)
128
- });
129
- if (this.reconnecting) return;
130
- const tryReconnect = async (attemptIndex)=>{
131
- try {
132
- await unstableCoreDoNotImport.sleep(this.reconnectRetryDelay(attemptIndex));
133
- if (this.allowReconnect) {
134
- await this.activeConnection.close();
135
- await this.activeConnection.open();
136
- if (this.requestManager.hasPendingRequests()) {
137
- this.send(this.requestManager.getPendingRequests().map(({ message })=>message));
138
- }
139
- }
140
- this.reconnecting = null;
141
- } catch {
142
- await tryReconnect(attemptIndex + 1);
143
- }
144
- };
145
- this.reconnecting = tryReconnect(0);
146
- }
147
- setupWebSocketListeners(ws) {
148
- const handleCloseOrError = (cause)=>{
149
- const reqs = this.requestManager.getPendingRequests();
150
- for (const { message, callbacks } of reqs){
151
- if (message.method === 'subscription') continue;
152
- callbacks.error(TRPCClientError.TRPCClientError.from(cause ?? new utils.TRPCWebSocketClosedError({
153
- message: 'WebSocket closed',
154
- cause
155
- })));
156
- this.requestManager.delete(message.id);
157
- }
158
- };
159
- ws.addEventListener('open', ()=>{
160
- unstableCoreDoNotImport.run(async ()=>{
161
- if (this.lazyMode) {
162
- this.inactivityTimeout.start();
163
- }
164
- this.callbacks.onOpen?.();
165
- this.connectionState.next({
166
- type: 'state',
167
- state: 'pending',
168
- error: null
169
- });
170
- }).catch((error)=>{
171
- ws.close(3000);
172
- handleCloseOrError(error);
173
- });
174
- });
175
- ws.addEventListener('message', ({ data })=>{
176
- this.inactivityTimeout.reset();
177
- if (typeof data !== 'string' || [
178
- 'PING',
179
- 'PONG'
180
- ].includes(data)) return;
181
- const incomingMessage = JSON.parse(data);
182
- if ('method' in incomingMessage) {
183
- this.handleIncomingRequest(incomingMessage);
184
- return;
185
- }
186
- this.handleResponseMessage(incomingMessage);
187
- });
188
- ws.addEventListener('close', (event)=>{
189
- handleCloseOrError(event);
190
- this.callbacks.onClose?.(event);
191
- if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) {
192
- this.reconnect(new utils.TRPCWebSocketClosedError({
193
- message: 'WebSocket closed',
194
- cause: event
195
- }));
196
- }
197
- });
198
- ws.addEventListener('error', (event)=>{
199
- handleCloseOrError(event);
200
- this.callbacks.onError?.(event);
201
- this.reconnect(new utils.TRPCWebSocketClosedError({
202
- message: 'WebSocket closed',
203
- cause: event
204
- }));
205
- });
206
- }
207
- handleResponseMessage(message) {
208
- const request = this.requestManager.getPendingRequest(message.id);
209
- if (!request) return;
210
- request.callbacks.next(message);
211
- let completed = true;
212
- if ('result' in message && request.message.method === 'subscription') {
213
- if (message.result.type === 'data') {
214
- request.message.params.lastEventId = message.result.id;
215
- }
216
- if (message.result.type !== 'stopped') {
217
- completed = false;
218
- }
219
- }
220
- if (completed) {
221
- request.callbacks.complete();
222
- this.requestManager.delete(message.id);
223
- }
224
- }
225
- handleIncomingRequest(message) {
226
- if (message.method === 'reconnect') {
227
- this.reconnect(new utils.TRPCWebSocketClosedError({
228
- message: 'Server requested reconnect'
229
- }));
230
- }
231
- }
232
- /**
233
- * Sends a message or batch of messages directly to the server.
234
- */ send(messageOrMessages) {
235
- if (!this.activeConnection.isOpen()) {
236
- throw new Error('Active connection is not open');
237
- }
238
- const messages = messageOrMessages instanceof Array ? messageOrMessages : [
239
- messageOrMessages
240
- ];
241
- this.activeConnection.ws.send(JSON.stringify(messages.length === 1 ? messages[0] : messages));
242
- }
243
- /**
244
- * Groups requests for batch sending.
245
- *
246
- * @returns A function to abort the batched request.
247
- */ batchSend(message, callbacks) {
248
- this.inactivityTimeout.reset();
249
- unstableCoreDoNotImport.run(async ()=>{
250
- if (!this.activeConnection.isOpen()) {
251
- await this.open();
252
- }
253
- await unstableCoreDoNotImport.sleep(0);
254
- if (!this.requestManager.hasOutgoingRequests()) return;
255
- this.send(this.requestManager.flush().map(({ message })=>message));
256
- }).catch((err)=>{
257
- this.requestManager.delete(message.id);
258
- callbacks.error(TRPCClientError.TRPCClientError.from(err));
259
- });
260
- return this.requestManager.register(message, callbacks);
261
- }
262
- constructor(opts){
263
- /**
264
- * Observable tracking the current connection state, including errors.
265
- */ _define_property(this, "connectionState", void 0);
266
- _define_property(this, "allowReconnect", false);
267
- _define_property(this, "requestManager", new requestManager.RequestManager());
268
- _define_property(this, "activeConnection", void 0);
269
- _define_property(this, "reconnectRetryDelay", void 0);
270
- _define_property(this, "inactivityTimeout", void 0);
271
- _define_property(this, "callbacks", void 0);
272
- _define_property(this, "lazyMode", void 0);
273
- /**
274
- * Manages the reconnection process for the WebSocket using retry logic.
275
- * Ensures that only one reconnection attempt is active at a time by tracking the current
276
- * reconnection state in the `reconnecting` promise.
277
- */ _define_property(this, "reconnecting", null);
278
- // Initialize callbacks, connection parameters, and options.
279
- this.callbacks = {
280
- onOpen: opts.onOpen,
281
- onClose: opts.onClose,
282
- onError: opts.onError
283
- };
284
- const lazyOptions = {
285
- ...options.lazyDefaults,
286
- ...opts.lazy
287
- };
288
- // Set up inactivity timeout for lazy connections.
289
- this.inactivityTimeout = new utils.ResettableTimeout(()=>{
290
- if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
291
- this.inactivityTimeout.reset();
292
- return;
293
- }
294
- this.close().catch(()=>null);
295
- }, lazyOptions.closeMs);
296
- // Initialize the WebSocket connection.
297
- this.activeConnection = new wsConnection.WsConnection({
298
- WebSocketPonyfill: opts.WebSocket,
299
- urlOptions: opts,
300
- keepAlive: {
301
- ...options.keepAliveDefaults,
302
- ...opts.keepAlive
303
- }
304
- });
305
- this.activeConnection.wsObservable.subscribe({
306
- next: (ws)=>{
307
- if (!ws) return;
308
- this.setupWebSocketListeners(ws);
309
- }
310
- });
311
- this.reconnectRetryDelay = opts.retryDelayMs ?? options.exponentialBackoff;
312
- this.lazyMode = lazyOptions.enabled;
313
- this.connectionState = observable.behaviorSubject({
314
- type: 'state',
315
- state: lazyOptions.enabled ? 'idle' : 'connecting',
316
- error: null
317
- });
318
- // Automatically open the connection if lazy mode is disabled.
319
- if (!this.lazyMode) {
320
- this.open().catch(()=>null);
321
- }
322
- }
323
- }
324
-
325
- exports.WsClient = WsClient;
@@ -1,323 +0,0 @@
1
- import { observable, behaviorSubject } from '@trpc/server/observable';
2
- import { transformResult, run, sleep } from '@trpc/server/unstable-core-do-not-import';
3
- import { TRPCClientError } from '../../../TRPCClientError.mjs';
4
- import { lazyDefaults, keepAliveDefaults, exponentialBackoff } from './options.mjs';
5
- import { RequestManager } from './requestManager.mjs';
6
- import { TRPCWebSocketClosedError, ResettableTimeout } from './utils.mjs';
7
- import { backwardCompatibility, WsConnection } from './wsConnection.mjs';
8
-
9
- function _define_property(obj, key, value) {
10
- if (key in obj) {
11
- Object.defineProperty(obj, key, {
12
- value: value,
13
- enumerable: true,
14
- configurable: true,
15
- writable: true
16
- });
17
- } else {
18
- obj[key] = value;
19
- }
20
- return obj;
21
- }
22
- /**
23
- * A WebSocket client for managing TRPC operations, supporting lazy initialization,
24
- * reconnection, keep-alive, and request management.
25
- */ class WsClient {
26
- /**
27
- * Opens the WebSocket connection. Handles reconnection attempts and updates
28
- * the connection state accordingly.
29
- */ async open() {
30
- this.allowReconnect = true;
31
- if (this.connectionState.get().state !== 'connecting') {
32
- this.connectionState.next({
33
- type: 'state',
34
- state: 'connecting',
35
- error: null
36
- });
37
- }
38
- try {
39
- await this.activeConnection.open();
40
- } catch (error) {
41
- this.reconnect(new TRPCWebSocketClosedError({
42
- message: 'Initialization error',
43
- cause: error
44
- }));
45
- return this.reconnecting;
46
- }
47
- }
48
- /**
49
- * Closes the WebSocket connection and stops managing requests.
50
- * Ensures all outgoing and pending requests are properly finalized.
51
- */ async close() {
52
- this.allowReconnect = false;
53
- this.inactivityTimeout.stop();
54
- const requestsToAwait = [];
55
- for (const request of this.requestManager.getRequests()){
56
- if (request.message.method === 'subscription') {
57
- request.callbacks.complete();
58
- } else if (request.state === 'outgoing') {
59
- request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({
60
- message: 'Closed before connection was established'
61
- })));
62
- } else {
63
- requestsToAwait.push(request.end);
64
- }
65
- }
66
- await Promise.all(requestsToAwait).catch(()=>null);
67
- await this.activeConnection.close().catch(()=>null);
68
- this.connectionState.next({
69
- type: 'state',
70
- state: 'idle',
71
- error: null
72
- });
73
- }
74
- /**
75
- * Method to request the server.
76
- * Handles data transformation, batching of requests, and subscription lifecycle.
77
- *
78
- * @param op - The operation details including id, type, path, input and signal
79
- * @param transformer - Data transformer for serializing requests and deserializing responses
80
- * @param lastEventId - Optional ID of the last received event for subscriptions
81
- *
82
- * @returns An observable that emits operation results and handles cleanup
83
- */ request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
84
- return observable((observer)=>{
85
- const abort = this.batchSend({
86
- id,
87
- method: type,
88
- params: {
89
- input: transformer.input.serialize(input),
90
- path,
91
- lastEventId
92
- }
93
- }, {
94
- ...observer,
95
- next (event) {
96
- const transformed = transformResult(event, transformer.output);
97
- if (!transformed.ok) {
98
- observer.error(TRPCClientError.from(transformed.error));
99
- return;
100
- }
101
- observer.next({
102
- result: transformed.result
103
- });
104
- }
105
- });
106
- return ()=>{
107
- abort();
108
- if (type === 'subscription' && this.activeConnection.isOpen()) {
109
- this.send({
110
- id,
111
- method: 'subscription.stop'
112
- });
113
- }
114
- signal?.removeEventListener('abort', abort);
115
- };
116
- });
117
- }
118
- get connection() {
119
- return backwardCompatibility(this.activeConnection);
120
- }
121
- reconnect(closedError) {
122
- this.connectionState.next({
123
- type: 'state',
124
- state: 'connecting',
125
- error: TRPCClientError.from(closedError)
126
- });
127
- if (this.reconnecting) return;
128
- const tryReconnect = async (attemptIndex)=>{
129
- try {
130
- await sleep(this.reconnectRetryDelay(attemptIndex));
131
- if (this.allowReconnect) {
132
- await this.activeConnection.close();
133
- await this.activeConnection.open();
134
- if (this.requestManager.hasPendingRequests()) {
135
- this.send(this.requestManager.getPendingRequests().map(({ message })=>message));
136
- }
137
- }
138
- this.reconnecting = null;
139
- } catch {
140
- await tryReconnect(attemptIndex + 1);
141
- }
142
- };
143
- this.reconnecting = tryReconnect(0);
144
- }
145
- setupWebSocketListeners(ws) {
146
- const handleCloseOrError = (cause)=>{
147
- const reqs = this.requestManager.getPendingRequests();
148
- for (const { message, callbacks } of reqs){
149
- if (message.method === 'subscription') continue;
150
- callbacks.error(TRPCClientError.from(cause ?? new TRPCWebSocketClosedError({
151
- message: 'WebSocket closed',
152
- cause
153
- })));
154
- this.requestManager.delete(message.id);
155
- }
156
- };
157
- ws.addEventListener('open', ()=>{
158
- run(async ()=>{
159
- if (this.lazyMode) {
160
- this.inactivityTimeout.start();
161
- }
162
- this.callbacks.onOpen?.();
163
- this.connectionState.next({
164
- type: 'state',
165
- state: 'pending',
166
- error: null
167
- });
168
- }).catch((error)=>{
169
- ws.close(3000);
170
- handleCloseOrError(error);
171
- });
172
- });
173
- ws.addEventListener('message', ({ data })=>{
174
- this.inactivityTimeout.reset();
175
- if (typeof data !== 'string' || [
176
- 'PING',
177
- 'PONG'
178
- ].includes(data)) return;
179
- const incomingMessage = JSON.parse(data);
180
- if ('method' in incomingMessage) {
181
- this.handleIncomingRequest(incomingMessage);
182
- return;
183
- }
184
- this.handleResponseMessage(incomingMessage);
185
- });
186
- ws.addEventListener('close', (event)=>{
187
- handleCloseOrError(event);
188
- this.callbacks.onClose?.(event);
189
- if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) {
190
- this.reconnect(new TRPCWebSocketClosedError({
191
- message: 'WebSocket closed',
192
- cause: event
193
- }));
194
- }
195
- });
196
- ws.addEventListener('error', (event)=>{
197
- handleCloseOrError(event);
198
- this.callbacks.onError?.(event);
199
- this.reconnect(new TRPCWebSocketClosedError({
200
- message: 'WebSocket closed',
201
- cause: event
202
- }));
203
- });
204
- }
205
- handleResponseMessage(message) {
206
- const request = this.requestManager.getPendingRequest(message.id);
207
- if (!request) return;
208
- request.callbacks.next(message);
209
- let completed = true;
210
- if ('result' in message && request.message.method === 'subscription') {
211
- if (message.result.type === 'data') {
212
- request.message.params.lastEventId = message.result.id;
213
- }
214
- if (message.result.type !== 'stopped') {
215
- completed = false;
216
- }
217
- }
218
- if (completed) {
219
- request.callbacks.complete();
220
- this.requestManager.delete(message.id);
221
- }
222
- }
223
- handleIncomingRequest(message) {
224
- if (message.method === 'reconnect') {
225
- this.reconnect(new TRPCWebSocketClosedError({
226
- message: 'Server requested reconnect'
227
- }));
228
- }
229
- }
230
- /**
231
- * Sends a message or batch of messages directly to the server.
232
- */ send(messageOrMessages) {
233
- if (!this.activeConnection.isOpen()) {
234
- throw new Error('Active connection is not open');
235
- }
236
- const messages = messageOrMessages instanceof Array ? messageOrMessages : [
237
- messageOrMessages
238
- ];
239
- this.activeConnection.ws.send(JSON.stringify(messages.length === 1 ? messages[0] : messages));
240
- }
241
- /**
242
- * Groups requests for batch sending.
243
- *
244
- * @returns A function to abort the batched request.
245
- */ batchSend(message, callbacks) {
246
- this.inactivityTimeout.reset();
247
- run(async ()=>{
248
- if (!this.activeConnection.isOpen()) {
249
- await this.open();
250
- }
251
- await sleep(0);
252
- if (!this.requestManager.hasOutgoingRequests()) return;
253
- this.send(this.requestManager.flush().map(({ message })=>message));
254
- }).catch((err)=>{
255
- this.requestManager.delete(message.id);
256
- callbacks.error(TRPCClientError.from(err));
257
- });
258
- return this.requestManager.register(message, callbacks);
259
- }
260
- constructor(opts){
261
- /**
262
- * Observable tracking the current connection state, including errors.
263
- */ _define_property(this, "connectionState", void 0);
264
- _define_property(this, "allowReconnect", false);
265
- _define_property(this, "requestManager", new RequestManager());
266
- _define_property(this, "activeConnection", void 0);
267
- _define_property(this, "reconnectRetryDelay", void 0);
268
- _define_property(this, "inactivityTimeout", void 0);
269
- _define_property(this, "callbacks", void 0);
270
- _define_property(this, "lazyMode", void 0);
271
- /**
272
- * Manages the reconnection process for the WebSocket using retry logic.
273
- * Ensures that only one reconnection attempt is active at a time by tracking the current
274
- * reconnection state in the `reconnecting` promise.
275
- */ _define_property(this, "reconnecting", null);
276
- // Initialize callbacks, connection parameters, and options.
277
- this.callbacks = {
278
- onOpen: opts.onOpen,
279
- onClose: opts.onClose,
280
- onError: opts.onError
281
- };
282
- const lazyOptions = {
283
- ...lazyDefaults,
284
- ...opts.lazy
285
- };
286
- // Set up inactivity timeout for lazy connections.
287
- this.inactivityTimeout = new ResettableTimeout(()=>{
288
- if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
289
- this.inactivityTimeout.reset();
290
- return;
291
- }
292
- this.close().catch(()=>null);
293
- }, lazyOptions.closeMs);
294
- // Initialize the WebSocket connection.
295
- this.activeConnection = new WsConnection({
296
- WebSocketPonyfill: opts.WebSocket,
297
- urlOptions: opts,
298
- keepAlive: {
299
- ...keepAliveDefaults,
300
- ...opts.keepAlive
301
- }
302
- });
303
- this.activeConnection.wsObservable.subscribe({
304
- next: (ws)=>{
305
- if (!ws) return;
306
- this.setupWebSocketListeners(ws);
307
- }
308
- });
309
- this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;
310
- this.lazyMode = lazyOptions.enabled;
311
- this.connectionState = behaviorSubject({
312
- type: 'state',
313
- state: lazyOptions.enabled ? 'idle' : 'connecting',
314
- error: null
315
- });
316
- // Automatically open the connection if lazy mode is disabled.
317
- if (!this.lazyMode) {
318
- this.open().catch(()=>null);
319
- }
320
- }
321
- }
322
-
323
- export { WsClient };