stream-chat 10.0.0-rc.21 → 10.0.0-rc.23

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 (269) hide show
  1. package/dist/cjs/index.browser.js +2196 -3902
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2197 -3902
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2199 -3905
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/ChannelManager.d.ts +120 -233
  8. package/dist/types/CooldownTimer.d.ts +8 -23
  9. package/dist/types/EventHandlerPipeline.d.ts +17 -37
  10. package/dist/types/LiveLocationManager.d.ts +22 -50
  11. package/dist/types/api-client.d.ts +9 -14
  12. package/dist/types/channel.d.ts +253 -448
  13. package/dist/types/channel_state.d.ts +48 -95
  14. package/dist/types/client.d.ts +245 -370
  15. package/dist/types/client_state.d.ts +1 -3
  16. package/dist/types/configuration/ConfigController.d.ts +30 -124
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
  18. package/dist/types/configuration/keys.d.ts +5 -19
  19. package/dist/types/configuration/shape.d.ts +12 -29
  20. package/dist/types/configuration/types.d.ts +59 -87
  21. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
  22. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  23. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  24. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  25. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  26. package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
  27. package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
  28. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
  29. package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
  30. package/dist/types/connection/networkConnection/types.d.ts +12 -27
  31. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
  32. package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
  33. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
  34. package/dist/types/connection/wsConnection/config.d.ts +8 -28
  35. package/dist/types/connection/wsConnection/types.d.ts +17 -70
  36. package/dist/types/entityStore/EntityStore.d.ts +153 -113
  37. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
  38. package/dist/types/errors.d.ts +7 -19
  39. package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
  40. package/dist/types/gen/chat/ChatApi.d.ts +28 -14
  41. package/dist/types/gen/models/index.d.ts +769 -86
  42. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  43. package/dist/types/index.d.ts +2 -4
  44. package/dist/types/languageNames.d.ts +9 -24
  45. package/dist/types/logger.d.ts +1 -3
  46. package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
  47. package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
  48. package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
  49. package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
  50. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  51. package/dist/types/messageComposer/configuration/types.d.ts +29 -56
  52. package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
  53. package/dist/types/messageComposer/messageComposer.d.ts +30 -164
  54. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
  55. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
  56. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  57. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  58. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
  59. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
  60. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  61. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  62. package/dist/types/messageComposer/pollComposer.d.ts +8 -4
  63. package/dist/types/messageComposer/textComposer.d.ts +3 -9
  64. package/dist/types/messageComposer/types.d.ts +5 -8
  65. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
  66. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
  67. package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
  68. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
  69. package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
  70. package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
  71. package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
  72. package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
  73. package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
  74. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
  75. package/dist/types/messageOperations/types.d.ts +15 -30
  76. package/dist/types/middleware.d.ts +7 -5
  77. package/dist/types/moderation.d.ts +21 -14
  78. package/dist/types/notifications/NotificationManager.d.ts +8 -31
  79. package/dist/types/notifications/types.d.ts +19 -59
  80. package/dist/types/offline-support/offline_support_api.d.ts +145 -539
  81. package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
  82. package/dist/types/offline-support/queueableOperations.d.ts +24 -52
  83. package/dist/types/offline-support/types.d.ts +24 -187
  84. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  85. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  86. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  87. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
  88. package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
  89. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
  90. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
  91. package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
  92. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
  93. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
  94. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
  95. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
  96. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  97. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  98. package/dist/types/pagination/utility.search.d.ts +3 -8
  99. package/dist/types/poll.d.ts +14 -14
  100. package/dist/types/poll_manager.d.ts +11 -2
  101. package/dist/types/poll_optimistic_votes.d.ts +10 -14
  102. package/dist/types/reminders/Reminder.d.ts +4 -4
  103. package/dist/types/reminders/ReminderManager.d.ts +7 -20
  104. package/dist/types/search/BaseSearchSource.d.ts +7 -12
  105. package/dist/types/search/ChannelSearchSource.d.ts +7 -7
  106. package/dist/types/search/MessageSearchSource.d.ts +7 -9
  107. package/dist/types/search/SearchController.d.ts +17 -22
  108. package/dist/types/search/types.d.ts +6 -10
  109. package/dist/types/signing.d.ts +12 -3
  110. package/dist/types/thread.d.ts +23 -71
  111. package/dist/types/thread_manager.d.ts +45 -70
  112. package/dist/types/token_manager.d.ts +8 -13
  113. package/dist/types/types.d.ts +64 -125
  114. package/dist/types/types.utility.d.ts +3 -3
  115. package/dist/types/upload-utils.d.ts +5 -10
  116. package/dist/types/uploadManager.d.ts +17 -45
  117. package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
  118. package/dist/types/utils/WithSubscriptions.d.ts +5 -15
  119. package/dist/types/utils/concurrency.d.ts +11 -19
  120. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  121. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  122. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  123. package/dist/types/utils/objectPath.d.ts +6 -41
  124. package/dist/types/utils/retryable.d.ts +8 -12
  125. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  126. package/dist/types/utils/time.d.ts +24 -64
  127. package/dist/types/utils.d.ts +40 -86
  128. package/package.json +7 -2
  129. package/src/ChannelManager.ts +159 -300
  130. package/src/CooldownTimer.ts +11 -29
  131. package/src/EventHandlerPipeline.ts +21 -44
  132. package/src/LiveLocationManager.ts +35 -74
  133. package/src/api-client.ts +43 -61
  134. package/src/campaign.ts +1 -1
  135. package/src/channel.ts +396 -749
  136. package/src/channel_batch_updater.ts +1 -1
  137. package/src/channel_state.ts +50 -105
  138. package/src/client.ts +360 -588
  139. package/src/client_state.ts +1 -6
  140. package/src/configuration/ConfigController.ts +41 -157
  141. package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
  142. package/src/configuration/index.ts +1 -1
  143. package/src/configuration/keys.ts +13 -32
  144. package/src/configuration/shape.ts +67 -70
  145. package/src/configuration/types.ts +60 -100
  146. package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
  147. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  148. package/src/configuration/utils/declarativeSlices.ts +9 -39
  149. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  150. package/src/configuration/utils/index.ts +2 -4
  151. package/src/configuration/utils/serverAuthority.ts +20 -68
  152. package/src/connection/ConnectionIdManager.ts +20 -49
  153. package/src/connection/ConnectionRecoveryManager.ts +51 -178
  154. package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
  155. package/src/connection/networkConnection/reporters.ts +9 -36
  156. package/src/connection/networkConnection/types.ts +12 -27
  157. package/src/connection/wsConnection/StableWSConnection.ts +73 -193
  158. package/src/connection/wsConnection/WSConnection.ts +56 -131
  159. package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
  160. package/src/connection/wsConnection/config.ts +13 -48
  161. package/src/connection/wsConnection/types.ts +17 -70
  162. package/src/constants.ts +4 -4
  163. package/src/entityStore/EntityStore.ts +162 -167
  164. package/src/entityStore/StoreBackedItemIndex.ts +14 -47
  165. package/src/errors.ts +7 -19
  166. package/src/formatMessageMemo.ts +3 -9
  167. package/src/gen/chat/ChannelApi.ts +19 -0
  168. package/src/gen/chat/ChatApi.ts +87 -13
  169. package/src/gen/models/index.ts +793 -71
  170. package/src/gen/moderation/ModerationApi.ts +0 -4
  171. package/src/index.ts +10 -14
  172. package/src/languageNames.ts +9 -24
  173. package/src/logger.ts +1 -3
  174. package/src/messageComposer/LocationComposer.ts +7 -23
  175. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  176. package/src/messageComposer/attachmentIdentity.ts +2 -13
  177. package/src/messageComposer/attachmentManager.ts +17 -63
  178. package/src/messageComposer/attachmentUtils.ts +3 -17
  179. package/src/messageComposer/configuration/configuration.ts +5 -8
  180. package/src/messageComposer/configuration/types.ts +29 -56
  181. package/src/messageComposer/fileUtils.ts +1 -1
  182. package/src/messageComposer/linkPreviewsManager.ts +8 -20
  183. package/src/messageComposer/messageComposer.ts +54 -222
  184. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
  185. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
  186. package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
  187. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
  188. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  189. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
  190. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  191. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  192. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  193. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
  194. package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
  195. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  196. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  197. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  198. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  199. package/src/messageComposer/pollComposer.ts +11 -8
  200. package/src/messageComposer/textComposer.ts +9 -59
  201. package/src/messageComposer/types.ts +9 -12
  202. package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
  203. package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
  204. package/src/messageOperations/FailedSendCache.ts +4 -9
  205. package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
  206. package/src/messageOperations/MessageOperations.ts +33 -62
  207. package/src/messageOperations/applyReactionLocally.ts +9 -28
  208. package/src/messageOperations/createMessageOperations.ts +17 -33
  209. package/src/messageOperations/reflectReactionEvent.ts +5 -13
  210. package/src/messageOperations/sendOrdering.ts +4 -7
  211. package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
  212. package/src/messageOperations/types.ts +15 -30
  213. package/src/middleware.ts +7 -10
  214. package/src/moderation.ts +25 -21
  215. package/src/notifications/NotificationManager.ts +11 -35
  216. package/src/notifications/types.ts +19 -59
  217. package/src/offline-support/offline_support_api.ts +178 -608
  218. package/src/offline-support/offline_sync_manager.ts +25 -69
  219. package/src/offline-support/queueableOperations.ts +31 -84
  220. package/src/offline-support/types.ts +25 -188
  221. package/src/pagination/ItemIndex.ts +4 -12
  222. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  223. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
  224. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  225. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
  226. package/src/pagination/filterCompiler.ts +11 -25
  227. package/src/pagination/paginators/BasePaginator.ts +422 -976
  228. package/src/pagination/paginators/ChannelPaginator.ts +130 -190
  229. package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
  230. package/src/pagination/paginators/MessagePaginator.ts +135 -175
  231. package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
  232. package/src/pagination/paginators/ReminderPaginator.ts +12 -15
  233. package/src/pagination/paginators/ThreadPaginator.ts +16 -26
  234. package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
  235. package/src/pagination/paginators/stateThrottling.ts +5 -10
  236. package/src/pagination/sortCompiler.ts +23 -50
  237. package/src/pagination/utility.normalization.ts +8 -30
  238. package/src/pagination/utility.search.ts +4 -11
  239. package/src/poll.ts +19 -19
  240. package/src/poll_manager.ts +16 -20
  241. package/src/poll_optimistic_votes.ts +17 -22
  242. package/src/reminders/Reminder.ts +5 -6
  243. package/src/reminders/ReminderManager.ts +9 -34
  244. package/src/reminders/ReminderTimer.ts +1 -2
  245. package/src/search/BaseSearchSource.ts +14 -29
  246. package/src/search/ChannelSearchSource.ts +8 -8
  247. package/src/search/MessageSearchSource.ts +19 -25
  248. package/src/search/SearchController.ts +18 -24
  249. package/src/search/types.ts +6 -10
  250. package/src/segment.ts +1 -1
  251. package/src/signing.ts +23 -3
  252. package/src/thread.ts +72 -173
  253. package/src/thread_manager.ts +59 -76
  254. package/src/token_manager.ts +11 -21
  255. package/src/types.ts +78 -126
  256. package/src/types.utility.ts +3 -3
  257. package/src/upload-utils.ts +5 -10
  258. package/src/uploadManager.ts +22 -54
  259. package/src/utils/FixedSizeQueueCache.ts +13 -21
  260. package/src/utils/WithSubscriptions.ts +5 -15
  261. package/src/utils/concurrency.ts +16 -55
  262. package/src/utils/mergeWith/mergeWith.ts +10 -13
  263. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  264. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  265. package/src/utils/objectPath.ts +6 -41
  266. package/src/utils/retryable.ts +10 -14
  267. package/src/utils/throttling/throttle.ts +9 -25
  268. package/src/utils/time.ts +26 -66
  269. package/src/utils.ts +72 -128
@@ -10,7 +10,6 @@ import type { WSConnectionConfig } from './types';
10
10
 
11
11
  const logger = chatLoggerSystem.getLogger('connection');
12
12
 
13
- // Type guards to check WebSocket error type
14
13
  const isCloseEvent = (
15
14
  res: CloseEvent | MessageEvent | ErrorEvent | Event,
16
15
  ): res is CloseEvent => (res as CloseEvent).code !== undefined;
@@ -30,31 +29,18 @@ class WSCloseError extends Error {
30
29
  }
31
30
 
32
31
  /**
33
- * A WS connection that reconnects upon failure.
32
+ * A WS connection that reconnects upon failure. A ping goes out every `pingIntervalMs`, and the
33
+ * connection goes down on `onerror`, `onclose`, no frame within `connectionCheckTimeout`, or when
34
+ * `client.networkConnection` reports the device offline (this class consumes that status, it does not
35
+ * detect it).
34
36
  *
35
- * - the WS connection can break and fail; a ping goes out every 25s (`pingInterval`)
36
- * - sometimes the WS connection seems to work while the device is in fact offline
37
- * - the device's own network status is a separate fact, owned by `client.networkConnection` and fed by a
38
- * platform listener the integrator registers; this class consumes it, it does not detect it
39
- *
40
- * There are 4 ways in which this connection can go down:
41
- * - WebSocket.onerror is called
42
- * - WebSocket.onclose is called
43
- * - no frame arrives for 35s, so the health-check loop gives up (`connectionCheckTimeout`)
44
- * - the device reports its network went offline
45
- *
46
- * There are 2 assumptions we make about the server:
47
- * - state can be recovered by querying the channel again
48
- * - if the servers fails to publish a message to the client, the WS connection is destroyed
37
+ * It assumes state can be recovered by querying the channel again, and that the server destroys the
38
+ * connection when it fails to publish a message to the client.
49
39
  */
50
40
  export class StableWSConnection {
51
- /**
52
- * The `WSConnection` this socket belongs to. Held instead of the client, because the status store
53
- * lives here and everything the socket needs from the client is reachable through it.
54
- */
41
+ /** The owning `WSConnection`, through which the client is reached. */
55
42
  wsConnection: WSConnection;
56
43
 
57
- // local vars
58
44
  connectionOpen?: ConnectAPIResponse;
59
45
  consecutiveFailures: number;
60
46
  healthCheckTimeoutRef?: NodeJS.Timeout;
@@ -78,58 +64,38 @@ export class StableWSConnection {
78
64
  wsID: number;
79
65
 
80
66
  constructor({ wsConnection }: { wsConnection: WSConnection }) {
81
- /** The `WSConnection` that owns this socket */
82
67
  this.wsConnection = wsConnection;
83
- /** consecutive failures influence the duration of the timeout */
84
68
  this.consecutiveFailures = 0;
85
- /** keep track of the total number of failures */
86
69
  this.totalFailures = 0;
87
- /** We only make 1 attempt to reconnect at the same time.. */
88
70
  this.isConnecting = false;
89
- /** To avoid reconnect if client is disconnected */
71
+ /** Set by `disconnect()` so a pending reconnect gives up. */
90
72
  this.isDisconnected = false;
91
- /** Boolean that indicates if the connection promise is resolved */
92
73
  this.isResolved = false;
93
- /** Boolean that indicates if we have a working connection to the server */
94
74
  this.isHealthy = false;
95
- /** Incremented when a new WS connection is made */
75
+ /** Incremented when the current socket is closed or destroyed; older IDs' callbacks are ignored. */
96
76
  this.wsID = 1;
97
- /** Store the last event time for health checks */
98
77
  this.lastEvent = null;
99
78
  }
100
79
 
101
- /**
102
- * The timing knobs, read from the parent **live** rather than snapshotted, so an `updateConfig`
103
- * reaches the socket that is already open instead of only the next one.
104
- */
80
+ /** Read live from the parent, so a config update reaches an already open socket. */
105
81
  private get config(): WSConnectionConfig {
106
82
  return this.wsConnection.config;
107
83
  }
108
84
 
109
- /** How often a health-check ping goes out. Configurable as `pingIntervalMs`. */
110
85
  get pingInterval(): number {
111
86
  return this.config.pingIntervalMs;
112
87
  }
113
88
 
114
- /**
115
- * How long the connection check tolerates silence before tearing the socket down.
116
- *
117
- * Derived at read time rather than stored, so changing the ping interval moves the connection check
118
- * with it instead of leaving the socket to kill itself between pings.
119
- */
89
+ /** Silence tolerated before the socket is torn down: `pingIntervalMs + healthCheckGracePeriodMs`. */
120
90
  get connectionCheckTimeout(): number {
121
91
  return this.config.pingIntervalMs + this.config.healthCheckGracePeriodMs;
122
92
  }
123
93
 
124
- /** The client, reached through the parent. See {@link wsConnection}. */
125
94
  get client(): StreamChat {
126
95
  return this.wsConnection.client;
127
96
  }
128
97
 
129
- /**
130
- * Re-parents this socket, for one supplied through `config.connection` and built against a
131
- * different `WSConnection` than the client adopting it.
132
- */
98
+ /** Re-parents a socket supplied through `config.connection`. */
133
99
  setWSConnection(wsConnection: WSConnection) {
134
100
  this.wsConnection = wsConnection;
135
101
  }
@@ -137,8 +103,7 @@ export class StableWSConnection {
137
103
  /**
138
104
  * Connects to the WS URL.
139
105
  *
140
- * @param timeout - Connect timeout in milliseconds. Defaults to `config.connectTimeoutMs` (15s),
141
- * which allows between 2 and 3 tries.
106
+ * @param timeout - Connect timeout in milliseconds. Defaults to `config.connectTimeoutMs`.
142
107
  * @returns A promise that resolves once the server's `connection.ok` hello event arrives.
143
108
  */
144
109
  async connect(timeout: number = this.config.connectTimeoutMs) {
@@ -187,10 +152,8 @@ export class StableWSConnection {
187
152
  }
188
153
 
189
154
  /**
190
- * _waitForHealthy polls the promise connection to see if its resolved until it times out.
191
- *
192
- * @param timeout - duration (ms). Defaults to `config.connectTimeoutMs` (15s), which allows
193
- * between 2~3 tries.
155
+ * Polls the connection promise until it resolves or `timeout` (ms) elapses. `timeout` defaults to
156
+ * `config.connectTimeoutMs`.
194
157
  */
195
158
  _waitForHealthy(timeout: number = this.config.connectTimeoutMs) {
196
159
  return Promise.race([
@@ -229,27 +192,20 @@ export class StableWSConnection {
229
192
  ]);
230
193
  }
231
194
 
232
- /**
233
- * Builds and returns the URL for the WebSocket connection.
234
- *
235
- * @private
236
- * @returns url string
237
- */
238
195
  _buildUrl = () => {
239
196
  const params = new URLSearchParams(this.config.urlParams);
240
197
  params.set('api_key', this.client.key);
241
198
  params.set('stream-auth-type', this.client.getAuthType());
242
- // Browsers cannot set headers on the WS handshake, so the server reads this
243
- // from the query string too.
199
+ // Browsers cannot set headers on the WS handshake, so the server reads this from the query too.
244
200
  params.set('X-Stream-Client', this.client.getUserAgent());
245
201
 
246
202
  return `${this.client.wsBaseURL}/api/v2/connect?${params.toString()}`;
247
203
  };
248
204
 
249
205
  /**
250
- * Disconnects the connection without attempting to recover.
206
+ * Closes the socket without attempting to recover.
251
207
  *
252
- * @param timeout - Optional timeout in milliseconds to wait for the close frame from the server.
208
+ * @param timeout - How long to wait for the server's close frame, in milliseconds. Defaults to 1s.
253
209
  */
254
210
  disconnect(timeout?: number) {
255
211
  logger
@@ -259,27 +215,23 @@ export class StableWSConnection {
259
215
  this.wsID += 1;
260
216
  this.isConnecting = false;
261
217
  this.isDisconnected = true;
262
- // A deliberate close still expects a reopen - mobile backgrounding is the reason this method
263
- // exists - so anything already waiting for a connection id keeps waiting. Invalidating drops the
264
- // dead id and arms a fresh deferred for the socket `openConnection()` will build.
218
+ // A deliberate close still expects a reopen (mobile backgrounding), so waiters keep waiting:
219
+ // invalidating drops the dead ID and arms a fresh deferred for the next socket.
265
220
  this.client.connectionIdManager.invalidate();
266
221
 
267
- // start by removing all the listeners
222
+ // Stop the ping and connection-check timers.
268
223
  if (this.healthCheckTimeoutRef) {
269
- clearInterval(this.healthCheckTimeoutRef);
224
+ clearTimeout(this.healthCheckTimeoutRef);
270
225
  }
271
226
  if (this.connectionCheckTimeoutRef) {
272
- clearInterval(this.connectionCheckTimeoutRef);
227
+ clearTimeout(this.connectionCheckTimeoutRef);
273
228
  }
274
229
 
275
- // Through `_applyHealth`, not a bare assignment: the store must tell the truth on this path too.
276
- // It is what `closeConnection()` uses, and a deliberate shutdown is still a transition.
230
+ // Through `_applyHealth` so the store records a deliberate close as a transition too.
277
231
  this._applyHealth(false);
278
232
 
279
233
  let isClosedPromise: Promise<void>;
280
- // and finally close...
281
- // Assigning to local here because we will remove it from this before the
282
- // promise resolves.
234
+ // Local copy: `this.ws` is deleted before the promise resolves.
283
235
  const { ws } = this;
284
236
  if (ws && ws.close && ws.readyState === ws.OPEN) {
285
237
  isClosedPromise = new Promise((resolve) => {
@@ -294,8 +246,7 @@ export class StableWSConnection {
294
246
  };
295
247
 
296
248
  ws.onclose = onclose;
297
- // In case we don't receive a close frame from the WebSocket server in time,
298
- // lets not wait for more than 1 seconds.
249
+ // Don't wait longer than the timeout for the server's close frame.
299
250
  setTimeout(onclose, timeout != null ? timeout : 1000);
300
251
  });
301
252
 
@@ -319,18 +270,13 @@ export class StableWSConnection {
319
270
  return isClosedPromise;
320
271
  }
321
272
 
322
- /**
323
- * Connects to the WS endpoint.
324
- *
325
- * @returns A promise that resolves once the server's `connection.ok` hello event arrives.
326
- */
273
+ /** Connects to the WS endpoint, resolving with the server's `connection.ok` hello event. */
327
274
  async _connect() {
328
- // simply ignore _connect if it's currently connecting, or if disconnect() was called
275
+ // Ignored while connecting, or after `disconnect()`.
329
276
  if (this.isConnecting || this.isDisconnected) return;
330
277
  this.isConnecting = true;
331
278
  this.requestID = randomId();
332
- // Arm before anything can await a connection id. A no-op on a reconnect that still holds one -
333
- // those requests keep flowing against the old id rather than blocking for the whole outage.
279
+ // Arm before anything can await a connection ID. A no-op while one is still held.
334
280
  this.client.connectionIdManager.arm();
335
281
  let isTokenReady = false;
336
282
  try {
@@ -351,9 +297,8 @@ export class StableWSConnection {
351
297
 
352
298
  this._setupConnectionPromise();
353
299
  const wsURL = this._buildUrl();
354
- // Built before the socket exists on purpose: the token is guaranteed loaded by
355
- // this point, and a failure here must reject _connect rather than leave an open
356
- // socket to die against the server's 10s auth-message deadline.
300
+ // Built before the socket exists, so a failure rejects `_connect` instead of leaving an open
301
+ // socket to hit the server's 10s auth-message deadline.
357
302
  const authMessage = this.client._buildWSAuthMessage();
358
303
  logger.withExtraTags('_connect').info(`Connecting to ${wsURL}.`, {
359
304
  wsURL,
@@ -371,10 +316,7 @@ export class StableWSConnection {
371
316
  this.isConnecting = false;
372
317
 
373
318
  if (response) {
374
- // The id is published to the ConnectionIdManager and nowhere else. A copy kept here would
375
- // outlive the socket it belongs to - `invalidate()` / `reset()` cannot reach it - which is
376
- // exactly the staleness this manager exists to end.
377
- this.client.connectionIdManager.resolveConnectionId(response.connection_id);
319
+ // `onmessage` already published the ID; publishing it again could revive an invalidated one.
378
320
  return response;
379
321
  }
380
322
  } catch (error: any) {
@@ -387,18 +329,16 @@ export class StableWSConnection {
387
329
  }
388
330
 
389
331
  /**
390
- * Retries the connection to the WS endpoint.
332
+ * Retries the connection.
391
333
  *
392
- * @param options - Reconnect options.
393
- * @param options.interval - Number of milliseconds to wait before reconnecting.
394
- * @param options.refreshToken - Reload/refresh the user token before attempting to reconnect.
334
+ * @param options.interval - Milliseconds to wait first. Defaults to a randomised backoff.
335
+ * @param options.refreshToken - Reload the user token before reconnecting.
395
336
  */
396
337
  async _reconnect(
397
338
  options: { interval?: number; refreshToken?: boolean } = {},
398
339
  ): Promise<void> {
399
340
  logger.withExtraTags('_reconnect').info('Initiating a reconnect.');
400
341
 
401
- // only allow 1 connection at the time
402
342
  if (this.isConnecting || this.isHealthy) {
403
343
  logger
404
344
  .withExtraTags('_reconnect')
@@ -406,17 +346,13 @@ export class StableWSConnection {
406
346
  return;
407
347
  }
408
348
 
409
- // reconnect in case of on error or on close
410
- // also reconnect if the health check cycle fails
411
349
  let interval = options.interval;
412
350
  if (!interval) {
413
351
  interval = retryInterval(this.consecutiveFailures);
414
352
  }
415
- // reconnect, or try again after a little while...
416
353
  await sleep(interval);
417
354
 
418
- // Check once again if by some other call to _reconnect is active or connection is
419
- // already restored, then no need to proceed.
355
+ // Re-check: another `_reconnect` may have started, or the connection been restored, meanwhile.
420
356
  if (this.isConnecting || this.isHealthy) {
421
357
  logger
422
358
  .withExtraTags('_reconnect')
@@ -435,7 +371,6 @@ export class StableWSConnection {
435
371
  .withExtraTags('_reconnect')
436
372
  .info('Destroying the current WebSocket connection.');
437
373
 
438
- // cleanup the old connection
439
374
  this._destroyCurrentWSConnection();
440
375
 
441
376
  if (options.refreshToken) {
@@ -471,9 +406,7 @@ export class StableWSConnection {
471
406
 
472
407
  this._reconnect();
473
408
  } else {
474
- // Giving up. Going down armed a deferred on the assumption that a reconnect would settle it,
475
- // and nothing will now — leaving it pending hangs every request waiting for an id, with no
476
- // retry coming and no error to show for it.
409
+ // Giving up: reject the deferred armed when the socket went down, or waiting requests hang.
477
410
  this.client.connectionIdManager.rejectConnectionId(error);
478
411
  }
479
412
  }
@@ -481,23 +414,12 @@ export class StableWSConnection {
481
414
  }
482
415
 
483
416
  /**
484
- * Handles a change reported for the `'network'` connection — the device's own — and applies it to
485
- * the `'ws'` connection this class owns.
486
- *
487
- * The logs name both by their {@link ConnectionType} value rather than by prose, so a reader is
488
- * never left guessing which connection a line is about. The effect clause is conditional because there may not be an effect: `_setHealth` returns
489
- * early when the status is unchanged, and a `'network'` report commonly arrives after the socket has
490
- * already died on its own.
491
- *
492
- * @deprecated Report network status through `client.networkConnection.setStatus(isOnline)` instead, or
493
- * register a listener with `client.networkConnection.setStatusReporter(…)`. This entry point takes
494
- * a DOM-shaped object and reaches into the socket, neither of which a caller should need. Kept
495
- * for one major because `stream-chat-react-native` calls it directly.
417
+ * Applies a device network status change to this socket.
496
418
  *
497
- * @param event - A DOM-shaped object whose `type` is `'online'` or `'offline'`. It carries no
498
- * connection identifier and never has: it was fed by `window`'s own `online`/`offline` events,
499
- * which are always about the device's network, and React Native synthesizes the same shape from
500
- * `NetInfo`.
419
+ * @param event - A DOM-shaped object whose `type` is `'online'` or `'offline'`. Only `type` is
420
+ * read.
421
+ * @deprecated Use `client.networkConnection.setStatus(isOnline)` or
422
+ * `client.networkConnection.setStatusReporter(…)` instead.
501
423
  */
502
424
  onlineStatusChanged = (event: Event) => {
503
425
  if (event.type === 'offline') this._applyNetworkStatus(false);
@@ -505,11 +427,8 @@ export class StableWSConnection {
505
427
  };
506
428
 
507
429
  /**
508
- * Applies a reported change in the `'network'` connection to the `'ws'` connection this class owns.
509
- *
510
- * The single body behind both entry points — the network-store subscription the parent owns, and
511
- * the deprecated {@link onlineStatusChanged} shim React Native still calls — so the two cannot
512
- * drift.
430
+ * Applies a network status change to this socket. Shared by the parent's network-store
431
+ * subscription and the deprecated {@link onlineStatusChanged}.
513
432
  *
514
433
  * @internal
515
434
  */
@@ -522,8 +441,7 @@ export class StableWSConnection {
522
441
  return;
523
442
  }
524
443
 
525
- // A socket still carrying traffic has probably missed nothing, so replacing it would cost a
526
- // handshake and a fresh connection ID for no gain. Only reconnect if it is actually down.
444
+ // A socket still carrying traffic has probably missed nothing: reconnect only if it is down.
527
445
  logger
528
446
  .withExtraTags('onlineStatusChanged')
529
447
  .info(
@@ -546,11 +464,11 @@ export class StableWSConnection {
546
464
  wsID: wsId,
547
465
  });
548
466
 
549
- // `/api/v2/connect` authenticates off the first frame the client sends, not off
550
- // the query string. The server closes the socket if it does not arrive in 10s.
467
+ // `/api/v2/connect` authenticates off the first frame the client sends, not the query string.
468
+ // The server closes the socket if it does not arrive in 10s.
551
469
  const { ws } = this;
552
- // disconnect() deletes this.ws synchronously; the wsID guard above covers
553
- // reconnects, this covers a socket torn down before `open` was dispatched.
470
+ // `disconnect()` deletes `this.ws` synchronously: the wsID guard above covers reconnects, this
471
+ // covers a socket torn down before `open` was dispatched.
554
472
  if (!ws || ws.readyState !== ws.OPEN) return;
555
473
 
556
474
  try {
@@ -575,9 +493,8 @@ export class StableWSConnection {
575
493
  const data = JSON.parse(event.data);
576
494
  const decodedData = data as WSEvent;
577
495
 
578
- // we wait till the first message before we consider the connection open..
579
- // the reason for this is that auth errors and similar errors trigger a ws.onopen and immediately
580
- // after that a ws.onclose..
496
+ // The first message, not `onopen`, marks the connection open: auth errors fire `onopen` and
497
+ // then `onclose`.
581
498
  if (!this.isResolved) {
582
499
  this.isResolved = true;
583
500
  if (data.error) {
@@ -585,7 +502,7 @@ export class StableWSConnection {
585
502
  return;
586
503
  }
587
504
 
588
- // Published before going online, so "the socket is up" implies "there is an id to watch on".
505
+ // Published before going online, so "the socket is up" implies "there is an ID to watch on".
589
506
  this.client.connectionIdManager.resolveConnectionId(
590
507
  (decodedData as ConnectionOpen).connection_id,
591
508
  );
@@ -594,12 +511,11 @@ export class StableWSConnection {
594
511
  this._setHealth(true);
595
512
  }
596
513
 
597
- // trigger the event..
598
514
  this.lastEvent = new Date();
599
515
 
600
- // `connection.ok` is the v2 hello event. The server only echoes health checks in
601
- // response to an inbound frame, so failing to schedule here means we never ping
602
- // and scheduleConnectionCheck tears the socket down 35s later, in a loop.
516
+ // The server sends a health check only in reply to a client frame, so the ping loop starts from
517
+ // the hello and continues on each health check. Without it the connection check tears the socket
518
+ // down every `connectionCheckTimeout`.
603
519
  if (data.type === 'health.check' || data.type === 'connection.ok') {
604
520
  this.scheduleNextPing();
605
521
  }
@@ -619,8 +535,7 @@ export class StableWSConnection {
619
535
  });
620
536
 
621
537
  if (event.code === chatCodes.WS_CLOSED_SUCCESS) {
622
- // this is a permanent error raised by stream..
623
- // usually caused by invalid auth details
538
+ // A permanent error raised by Stream, usually invalid auth details.
624
539
  const error = new WSCloseError(`WS connection reject with error ${event.reason}`);
625
540
 
626
541
  error.reason = event.reason;
@@ -646,7 +561,6 @@ export class StableWSConnection {
646
561
  event,
647
562
  });
648
563
 
649
- // reconnect if its an abnormal failure
650
564
  this._reconnect();
651
565
  }
652
566
  };
@@ -668,15 +582,10 @@ export class StableWSConnection {
668
582
  };
669
583
 
670
584
  /**
671
- * Writes this connection's status to the field and to `client.wsConnection.state`, and drops the
672
- * connection id when it goes down. Returns whether the status changed.
673
- *
674
- * Every path that transitions the status goes through here — including `disconnect()`, which
675
- * `closeConnection()` uses, and the two error paths. Covering all of them is why the store exists,
676
- * and why invalidating the id belongs here rather than beside any one of those paths.
677
- *
678
- * Construction is not routed through here: initializing the field is not a transition, and stamping
679
- * `lastUnhealthyAt` because a socket object was built would be a lie.
585
+ * Writes the status to the field and to `client.wsConnection.state`, and drops the connection ID
586
+ * when it goes down. Returns whether the status changed. Every transition goes through here
587
+ * (`disconnect()` and the error paths included); the constructor does not, since initializing the
588
+ * field is not a transition.
680
589
  */
681
590
  private _applyHealth(healthy: boolean): boolean {
682
591
  if (healthy === this.isHealthy) return false;
@@ -684,9 +593,7 @@ export class StableWSConnection {
684
593
  this.isHealthy = healthy;
685
594
 
686
595
  if (!healthy) {
687
- // The id those watches were keyed by is dead, so no further request may carry it. Invalidating
688
- // arms a fresh deferred, so requests needing one wait for the reconnect instead of racing
689
- // ahead with the old one.
596
+ // The ID is dead; invalidating arms a fresh deferred so requests wait for the reconnect.
690
597
  this.client.connectionIdManager.invalidate();
691
598
  }
692
599
 
@@ -695,17 +602,7 @@ export class StableWSConnection {
695
602
  return true;
696
603
  }
697
604
 
698
- /**
699
- * Applies a status change and does the bookkeeping that goes with it.
700
- *
701
- * Announcing it is not this class's job. The status lives in `client.wsConnection.state`, which
702
- * {@link _applyHealth} writes on every transition — including the ones that were always silent —
703
- * so a consumer subscribes there rather than waiting to be told.
704
- *
705
- * The five-second wait before announcing a drop moved to whoever renders the banner, its length
706
- * configurable as `offlineNotificationDisplayDelayMs`. The timer here outlived the socket that
707
- * armed it, so a replaced connection announced a drop its replacement had already recovered from.
708
- */
605
+ /** Applies a status change; on a drop, marks the channel watches as interrupted. */
709
606
  _setHealth = (healthy: boolean) => {
710
607
  if (!this._applyHealth(healthy)) return;
711
608
  if (this.isHealthy) return;
@@ -715,11 +612,8 @@ export class StableWSConnection {
715
612
  };
716
613
 
717
614
  /**
718
- * Creates an error object for the WS event.
719
- *
720
- * @param event - The raw WebSocket close / data / error event.
721
- * @param isWSFailure - Whether the underlying cause is a WebSocket failure (optional, defaults to `true`).
722
- * @returns A normalized error describing the WS failure.
615
+ * Turns a raw WebSocket close, message or error event into an `Error` carrying `code`,
616
+ * `StatusCode` and `isWSFailure`.
723
617
  */
724
618
  _errorFromWSEvent = (
725
619
  event: CloseEvent | MessageEvent | ErrorEvent | Event,
@@ -740,7 +634,7 @@ export class StableWSConnection {
740
634
  message = event.error.message;
741
635
  }
742
636
 
743
- // Keeping this `warn` level log, to avoid cluttering of error logs from ws failures.
637
+ // `warn`, not `error`, to avoid cluttering error logs with WS failures.
744
638
  logger
745
639
  .withExtraTags('_errorFromWSEvent')
746
640
  .warn(`The WebSocket failed with code ${code}.`, { event });
@@ -753,21 +647,14 @@ export class StableWSConnection {
753
647
  StatusCode?: string | number;
754
648
  };
755
649
  error.code = code;
756
- /**
757
- * StatusCode does not exist on any event types but has been left
758
- * as is to preserve JS functionality during the TS implementation
759
- */
650
+ // `StatusCode` is not on any event type; kept for JS compatibility.
760
651
  error.StatusCode = statusCode;
761
652
  error.isWSFailure = isWSFailure;
762
653
  return error;
763
654
  };
764
655
 
765
- /**
766
- * Removes the current WS connection.
767
- */
768
656
  _destroyCurrentWSConnection() {
769
- // increment the ID, meaning we will ignore all messages from the old
770
- // ws connection from now on.
657
+ // Callbacks bound to the old ID are ignored.
771
658
  this.wsID += 1;
772
659
 
773
660
  try {
@@ -777,12 +664,9 @@ export class StableWSConnection {
777
664
  }
778
665
  }
779
666
 
780
- /**
781
- * Sets up the `this.connectionOpen` promise.
782
- */
783
667
  _setupConnectionPromise = () => {
784
668
  this.isResolved = false;
785
- /** a promise that is resolved once ws.open is called */
669
+ // Resolved by the first message (`connection.ok`), rejected on an error or close.
786
670
  this.connectionOpen = new Promise<ConnectionOpen>((resolve, reject) => {
787
671
  this.resolvePromise = resolve;
788
672
  this.rejectPromise = reject;
@@ -790,18 +674,18 @@ export class StableWSConnection {
790
674
  };
791
675
 
792
676
  /**
793
- * Schedules the next health check ping for the WebSocket connection.
677
+ * Schedules the next health-check ping `pingIntervalMs` from now, replacing a pending one.
678
+ *
679
+ * @internal
794
680
  */
795
681
  scheduleNextPing = () => {
796
682
  if (this.healthCheckTimeoutRef) {
797
683
  clearTimeout(this.healthCheckTimeoutRef);
798
684
  }
799
685
 
800
- // Sent every `config.pingIntervalMs` (25s by default); the server answers with a health check event.
801
686
  this.healthCheckTimeoutRef = setTimeout(() => {
802
- // send the healthcheck.., server replies with a health check event
687
+ // The server answers with a health check event.
803
688
  const data = [{ type: 'health.check', client_id: this.client.clientId }];
804
- // try to send on the connection
805
689
  try {
806
690
  this.ws?.send(JSON.stringify(data));
807
691
  } catch (e) {
@@ -810,11 +694,7 @@ export class StableWSConnection {
810
694
  }, this.pingInterval);
811
695
  };
812
696
 
813
- /**
814
- * Schedules a check for the time difference between the last received event and now. If the
815
- * difference is more than 35 seconds, it means our health check logic has failed and the
816
- * WebSocket needs to be reconnected.
817
- */
697
+ /** Reconnects when no event has arrived for more than `connectionCheckTimeout`. */
818
698
  scheduleConnectionCheck = () => {
819
699
  if (this.connectionCheckTimeoutRef) {
820
700
  clearTimeout(this.connectionCheckTimeoutRef);