stream-chat 10.0.0-rc.9 → 10.0.1

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 (361) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +21653 -19788
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +21693 -19796
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +21651 -19786
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +216 -135
  9. package/dist/types/CooldownTimer.d.ts +13 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +24 -52
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +432 -470
  14. package/dist/types/channel_state.d.ts +68 -112
  15. package/dist/types/client.d.ts +321 -435
  16. package/dist/types/client_state.d.ts +1 -3
  17. package/dist/types/configuration/ConfigController.d.ts +31 -125
  18. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
  19. package/dist/types/configuration/keys.d.ts +5 -19
  20. package/dist/types/configuration/shape.d.ts +12 -29
  21. package/dist/types/configuration/types.d.ts +64 -79
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  26. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  27. package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
  28. package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
  29. package/dist/types/connection/index.d.ts +4 -0
  30. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
  31. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  32. package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
  33. package/dist/types/connection/networkConnection/types.d.ts +40 -0
  34. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
  35. package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
  36. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
  37. package/dist/types/connection/wsConnection/config.d.ts +31 -0
  38. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  39. package/dist/types/connection/wsConnection/types.d.ts +46 -0
  40. package/dist/types/constants.d.ts +2 -0
  41. package/dist/types/custom_types.d.ts +0 -2
  42. package/dist/types/entityStore/EntityStore.d.ts +226 -65
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +16 -19
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
  48. package/dist/types/gen/chat/ChatApi.d.ts +149 -105
  49. package/dist/types/gen/models/index.d.ts +2528 -690
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +33 -14
  52. package/dist/types/index.d.ts +10 -6
  53. package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
  54. package/dist/types/logger.d.ts +1 -3
  55. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  56. package/dist/types/messageComposer/LocationComposer.d.ts +7 -1
  57. package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
  58. package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
  59. package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
  60. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  61. package/dist/types/messageComposer/configuration/types.d.ts +38 -50
  62. package/dist/types/messageComposer/index.d.ts +1 -0
  63. package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
  64. package/dist/types/messageComposer/messageComposer.d.ts +60 -128
  65. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
  66. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
  67. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  68. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
  69. package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  71. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  72. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  73. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  74. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
  75. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +19 -18
  76. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  77. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  78. package/dist/types/messageComposer/pollComposer.d.ts +15 -5
  79. package/dist/types/messageComposer/textComposer.d.ts +14 -7
  80. package/dist/types/messageComposer/types.d.ts +27 -7
  81. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
  82. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +40 -73
  83. package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
  84. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
  85. package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
  86. package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
  87. package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
  88. package/dist/types/messageOperations/index.d.ts +6 -4
  89. package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
  90. package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
  91. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
  92. package/dist/types/messageOperations/types.d.ts +43 -14
  93. package/dist/types/middleware.d.ts +10 -0
  94. package/dist/types/moderation.d.ts +21 -14
  95. package/dist/types/notifications/NotificationManager.d.ts +10 -23
  96. package/dist/types/notifications/types.d.ts +21 -57
  97. package/dist/types/offline-support/offline_support_api.d.ts +150 -528
  98. package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
  99. package/dist/types/offline-support/queueableOperations.d.ts +35 -37
  100. package/dist/types/offline-support/types.d.ts +40 -186
  101. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  102. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  103. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  104. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
  105. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
  106. package/dist/types/pagination/index.d.ts +1 -0
  107. package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
  108. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
  109. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -334
  110. package/dist/types/pagination/paginators/MessagePaginator.d.ts +239 -131
  111. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
  112. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
  113. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
  114. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
  115. package/dist/types/pagination/paginators/index.d.ts +1 -0
  116. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  117. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +34 -8
  120. package/dist/types/poll_manager.d.ts +12 -2
  121. package/dist/types/poll_optimistic_votes.d.ts +57 -0
  122. package/dist/types/reminders/Reminder.d.ts +11 -11
  123. package/dist/types/reminders/ReminderManager.d.ts +13 -25
  124. package/dist/types/search/BaseSearchSource.d.ts +10 -8
  125. package/dist/types/search/ChannelSearchSource.d.ts +16 -0
  126. package/dist/types/search/MessageSearchSource.d.ts +17 -0
  127. package/dist/types/search/SearchController.d.ts +26 -28
  128. package/dist/types/search/types.d.ts +6 -10
  129. package/dist/types/signing.d.ts +12 -3
  130. package/dist/types/thread.d.ts +63 -129
  131. package/dist/types/thread_manager.d.ts +95 -66
  132. package/dist/types/token_manager.d.ts +8 -13
  133. package/dist/types/types.d.ts +81 -199
  134. package/dist/types/types.utility.d.ts +3 -3
  135. package/dist/types/upload-utils.d.ts +5 -10
  136. package/dist/types/uploadManager.d.ts +31 -11
  137. package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
  138. package/dist/types/utils/WithSubscriptions.d.ts +6 -16
  139. package/dist/types/utils/abort.d.ts +17 -0
  140. package/dist/types/utils/concurrency.d.ts +12 -20
  141. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  142. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  143. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  144. package/dist/types/utils/objectPath.d.ts +6 -41
  145. package/dist/types/utils/retryable.d.ts +8 -12
  146. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  147. package/dist/types/utils/time.d.ts +33 -57
  148. package/dist/types/utils.d.ts +72 -91
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +28 -38
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +37 -76
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1067 -1276
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +73 -168
  159. package/src/client.ts +744 -974
  160. package/src/client_state.ts +3 -8
  161. package/src/configuration/ConfigController.ts +42 -158
  162. package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
  163. package/src/configuration/index.ts +1 -1
  164. package/src/configuration/keys.ts +13 -32
  165. package/src/configuration/shape.ts +169 -59
  166. package/src/configuration/types.ts +69 -92
  167. package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
  168. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  169. package/src/configuration/utils/declarativeSlices.ts +9 -39
  170. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  171. package/src/configuration/utils/index.ts +2 -4
  172. package/src/configuration/utils/serverAuthority.ts +20 -68
  173. package/src/connection/ConnectionIdManager.ts +111 -0
  174. package/src/connection/ConnectionRecoveryManager.ts +257 -0
  175. package/src/connection/index.ts +4 -0
  176. package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
  177. package/src/connection/networkConnection/index.ts +3 -0
  178. package/src/connection/networkConnection/reporters.ts +58 -0
  179. package/src/connection/networkConnection/types.ts +45 -0
  180. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -232
  181. package/src/connection/wsConnection/WSConnection.ts +270 -0
  182. package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
  183. package/src/connection/wsConnection/config.ts +73 -0
  184. package/src/connection/wsConnection/index.ts +4 -0
  185. package/src/connection/wsConnection/types.ts +48 -0
  186. package/src/constants.ts +6 -5
  187. package/src/custom_types.ts +0 -1
  188. package/src/entityStore/EntityStore.ts +415 -79
  189. package/src/entityStore/StoreBackedItemIndex.ts +37 -41
  190. package/src/entityStore/index.ts +0 -1
  191. package/src/errors.ts +39 -20
  192. package/src/formatMessageMemo.ts +17 -0
  193. package/src/gen/chat/ChannelApi.ts +122 -36
  194. package/src/gen/chat/ChatApi.ts +578 -1540
  195. package/src/gen/models/index.ts +2498 -3383
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +170 -367
  198. package/src/index.ts +22 -10
  199. package/src/languageNames.ts +88 -0
  200. package/src/logger.ts +1 -3
  201. package/src/messageComposer/CustomDataManager.ts +19 -6
  202. package/src/messageComposer/LocationComposer.ts +19 -23
  203. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  204. package/src/messageComposer/attachmentIdentity.ts +54 -0
  205. package/src/messageComposer/attachmentManager.ts +170 -185
  206. package/src/messageComposer/attachmentUtils.ts +44 -0
  207. package/src/messageComposer/configuration/configuration.ts +15 -8
  208. package/src/messageComposer/configuration/types.ts +38 -50
  209. package/src/messageComposer/fileUtils.ts +1 -1
  210. package/src/messageComposer/index.ts +1 -0
  211. package/src/messageComposer/linkPreviewsManager.ts +18 -21
  212. package/src/messageComposer/messageComposer.ts +223 -174
  213. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  214. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
  215. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
  216. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
  217. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  218. package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
  219. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  220. package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
  221. package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
  222. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
  223. package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
  224. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  225. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  226. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  227. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  228. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  229. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  230. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  231. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  232. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  233. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  234. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  235. package/src/messageComposer/pollComposer.ts +21 -9
  236. package/src/messageComposer/textComposer.ts +37 -57
  237. package/src/messageComposer/types.ts +39 -11
  238. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -125
  239. package/src/messageDelivery/MessageReceiptsTracker.ts +88 -101
  240. package/src/messageOperations/FailedSendCache.ts +85 -0
  241. package/src/messageOperations/MessageOperationStatePolicy.ts +121 -112
  242. package/src/messageOperations/MessageOperations.ts +297 -175
  243. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +9 -28
  244. package/src/messageOperations/createMessageOperations.ts +176 -0
  245. package/src/messageOperations/index.ts +6 -14
  246. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  247. package/src/messageOperations/sendOrdering.ts +25 -0
  248. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  249. package/src/messageOperations/types.ts +51 -13
  250. package/src/middleware.ts +13 -5
  251. package/src/moderation.ts +25 -21
  252. package/src/notifications/NotificationManager.ts +19 -28
  253. package/src/notifications/types.ts +21 -57
  254. package/src/offline-support/offline_support_api.ts +226 -669
  255. package/src/offline-support/offline_sync_manager.ts +51 -80
  256. package/src/offline-support/queueableOperations.ts +98 -73
  257. package/src/offline-support/types.ts +43 -186
  258. package/src/pagination/FilterBuilder.ts +1 -22
  259. package/src/pagination/ItemIndex.ts +4 -12
  260. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  261. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +15 -63
  262. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  263. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  264. package/src/pagination/filterCompiler.ts +11 -25
  265. package/src/pagination/index.ts +1 -0
  266. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  267. package/src/pagination/paginators/ChannelPaginator.ts +479 -217
  268. package/src/pagination/paginators/MessageIntervalPaginator.ts +1351 -772
  269. package/src/pagination/paginators/MessagePaginator.ts +518 -233
  270. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  271. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  272. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  273. package/src/pagination/paginators/UserGroupPaginator.ts +16 -19
  274. package/src/pagination/paginators/index.ts +1 -0
  275. package/src/pagination/paginators/stateThrottling.ts +5 -10
  276. package/src/pagination/sortCompiler.ts +23 -50
  277. package/src/pagination/utility.normalization.ts +8 -30
  278. package/src/pagination/utility.search.ts +4 -11
  279. package/src/poll.ts +177 -98
  280. package/src/poll_manager.ts +24 -22
  281. package/src/poll_optimistic_votes.ts +335 -0
  282. package/src/reminders/Reminder.ts +16 -12
  283. package/src/reminders/ReminderManager.ts +22 -55
  284. package/src/reminders/ReminderTimer.ts +1 -2
  285. package/src/search/BaseSearchSource.ts +19 -25
  286. package/src/search/ChannelSearchSource.ts +43 -1
  287. package/src/search/MessageSearchSource.ts +77 -13
  288. package/src/search/SearchController.ts +39 -36
  289. package/src/search/types.ts +6 -10
  290. package/src/segment.ts +1 -1
  291. package/src/signing.ts +23 -3
  292. package/src/thread.ts +418 -703
  293. package/src/thread_manager.ts +300 -234
  294. package/src/token_manager.ts +12 -22
  295. package/src/types.ts +102 -216
  296. package/src/types.utility.ts +3 -3
  297. package/src/upload-utils.ts +5 -10
  298. package/src/uploadManager.ts +64 -18
  299. package/src/utils/FixedSizeQueueCache.ts +18 -21
  300. package/src/utils/WithSubscriptions.ts +6 -16
  301. package/src/utils/abort.ts +45 -0
  302. package/src/utils/concurrency.ts +16 -55
  303. package/src/utils/mergeWith/mergeWith.ts +10 -13
  304. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  305. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  306. package/src/utils/objectPath.ts +6 -41
  307. package/src/utils/retryable.ts +10 -14
  308. package/src/utils/throttling/throttle.ts +9 -25
  309. package/src/utils/time.ts +40 -60
  310. package/src/utils.ts +181 -174
  311. package/codegen/i18n/callSites.ts +0 -126
  312. package/codegen/i18n/generate.ts +0 -226
  313. package/codegen/i18n/guards.ts +0 -178
  314. package/codegen/i18n/index.ts +0 -29
  315. package/codegen/i18n/stringMaps.ts +0 -91
  316. package/codegen/i18n/types.ts +0 -100
  317. package/dist/cjs/i18n.browser.js +0 -1131
  318. package/dist/cjs/i18n.browser.js.map +0 -7
  319. package/dist/cjs/i18n.node.js +0 -1160
  320. package/dist/cjs/i18n.node.js.map +0 -7
  321. package/dist/esm/i18n-codegen.mjs +0 -409
  322. package/dist/esm/i18n-codegen.mjs.map +0 -7
  323. package/dist/esm/i18n.mjs +0 -1098
  324. package/dist/esm/i18n.mjs.map +0 -7
  325. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  326. package/dist/types/connection.d.ts +0 -139
  327. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -32
  328. package/dist/types/i18n/Streami18n.d.ts +0 -168
  329. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  330. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  331. package/dist/types/i18n/dayjs.d.ts +0 -104
  332. package/dist/types/i18n/formatters.d.ts +0 -91
  333. package/dist/types/i18n/index.d.ts +0 -15
  334. package/dist/types/i18n/translator.d.ts +0 -29
  335. package/dist/types/i18n/types.d.ts +0 -262
  336. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  337. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  338. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  339. package/dist/types/i18n-codegen/index.d.ts +0 -29
  340. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  341. package/dist/types/i18n-codegen/types.d.ts +0 -94
  342. package/dist/types/insights.d.ts +0 -56
  343. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  344. package/dist/types/messageOperations/persistence.d.ts +0 -21
  345. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  346. package/dist/types/store.d.ts +0 -125
  347. package/src/ConnectionRecoveryManager.ts +0 -293
  348. package/src/i18n/Streami18n.ts +0 -520
  349. package/src/i18n/TranslationBuilder.ts +0 -176
  350. package/src/i18n/TranslationStore.ts +0 -96
  351. package/src/i18n/dayjs.ts +0 -228
  352. package/src/i18n/formatters.ts +0 -461
  353. package/src/i18n/index.ts +0 -15
  354. package/src/i18n/languageNames.ts +0 -103
  355. package/src/i18n/translator.ts +0 -76
  356. package/src/i18n/types.ts +0 -375
  357. package/src/insights.ts +0 -82
  358. package/src/messageOperations/optimistic.ts +0 -257
  359. package/src/messageOperations/persistence.ts +0 -40
  360. package/src/pagination/utility.queryChannel.ts +0 -84
  361. package/src/store.ts +0 -304
@@ -1,43 +1,15 @@
1
- import {
2
- addConnectionEventListeners,
3
- chatCodes,
4
- convertErrorToJson,
5
- randomId,
6
- removeConnectionEventListeners,
7
- retryInterval,
8
- sleep,
9
- } from './utils';
10
- import {
11
- buildWsFatalInsight,
12
- buildWsSuccessAfterFailureInsight,
13
- postInsights,
14
- } from './insights';
15
- import { chatLoggerSystem } from './logger';
16
- import type { ConnectAPIResponse, ConnectedEvent, ConnectionOpen } from './types';
17
- import type { StreamChat } from './client';
18
- import type { APIError } from './errors';
19
- import type { WSEvent } from './gen/models';
1
+ import { chatCodes, randomId, retryInterval, sleep } from '../../utils';
2
+ import { chatLoggerSystem } from '../../logger';
3
+ import { WS_NETWORK_RECOVERY_RETRY_MS } from './config';
4
+ import type { ConnectAPIResponse, ConnectionOpen } from '../../types';
5
+ import type { WSConnection } from './WSConnection';
6
+ import type { StreamChat } from '../../client';
7
+ import type { APIError } from '../../errors';
8
+ import type { Event as StreamEvent } from '../../types';
9
+ import type { WSConnectionConfig } from './types';
20
10
 
21
11
  const logger = chatLoggerSystem.getLogger('connection');
22
12
 
23
- /**
24
- * Wire frames are handed through as they arrive. Every server-sent date is the unix-nanosecond
25
- * number the API puts on the wire (the generator runs with `response_dates_as_number=true`), so
26
- * there is nothing left to decode — the per-model decoders that used to turn those numbers into
27
- * `Date` objects no longer exist.
28
- *
29
- * `connection.ok` is still not published in the OpenAPI spec, so it is typed by the hand-written
30
- * `ConnectedEvent` overlay in `types.ts` rather than by `src/gen`. Remove that overlay, and this
31
- * branch, once the backend adds the event to the spec and `src/gen` is regenerated.
32
- */
33
- const decodeConnectionEvent = (
34
- data: { type: string } & Record<string, unknown>,
35
- ): WSEvent | ConnectedEvent =>
36
- data.type === 'connection.ok'
37
- ? (data as unknown as ConnectedEvent)
38
- : (data as unknown as WSEvent);
39
-
40
- // Type guards to check WebSocket error type
41
13
  const isCloseEvent = (
42
14
  res: CloseEvent | MessageEvent | ErrorEvent | Event,
43
15
  ): res is CloseEvent => (res as CloseEvent).code !== undefined;
@@ -57,40 +29,27 @@ class WSCloseError extends Error {
57
29
  }
58
30
 
59
31
  /**
60
- * 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).
61
36
  *
62
- * - the browser will sometimes report that you're online or offline
63
- * - the WS connection can break and fail (there is a 30s health check)
64
- * - sometimes your WS connection will seem to work while the user is in fact offline
65
- * - to speed up online/offline detection you can use the `window.addEventListener('offline')`
66
- *
67
- * There are 4 ways in which a connection can become unhealthy:
68
- * - WebSocket.onerror is called
69
- * - WebSocket.onclose is called
70
- * - the health check fails and no event is received for ~40 seconds
71
- * - the browser indicates the connection is now offline
72
- *
73
- * There are 2 assumptions we make about the server:
74
- * - state can be recovered by querying the channel again
75
- * - 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.
76
39
  */
77
40
  export class StableWSConnection {
78
- // global from constructor
79
- client: StreamChat;
41
+ /** The owning `WSConnection`, through which the client is reached. */
42
+ wsConnection: WSConnection;
80
43
 
81
- // local vars
82
- connectionID?: string;
83
44
  connectionOpen?: ConnectAPIResponse;
84
45
  consecutiveFailures: number;
85
- pingInterval: number;
86
- healthCheckTimeoutRef?: NodeJS.Timeout;
46
+ healthCheckTimeoutRef?: ReturnType<typeof setTimeout>;
87
47
  isConnecting: boolean;
88
48
  isDisconnected: boolean;
89
49
  isHealthy: boolean;
90
50
  isResolved?: boolean;
91
51
  lastEvent: Date | null;
92
- connectionCheckTimeout: number;
93
- connectionCheckTimeoutRef?: NodeJS.Timeout;
52
+ connectionCheckTimeoutRef?: ReturnType<typeof setTimeout>;
94
53
  rejectPromise?: (
95
54
  reason?: Error & {
96
55
  code?: string | number;
@@ -99,48 +58,63 @@ export class StableWSConnection {
99
58
  },
100
59
  ) => void;
101
60
  requestID: string | undefined;
61
+ /**
62
+ * Set when the server sent a `connection.error` with code 40 (token expired) on an
63
+ * already established socket. The server closes the socket right after it, and the
64
+ * reconnect that follows must use a fresh token from the tokenProvider.
65
+ */
66
+ tokenExpiredByServer: boolean;
102
67
  resolvePromise?: (value: ConnectionOpen) => void;
103
68
  totalFailures: number;
104
69
  ws?: WebSocket;
105
70
  wsID: number;
106
71
 
107
- constructor({ client }: { client: StreamChat }) {
108
- /** StreamChat client */
109
- this.client = client;
110
- /** consecutive failures influence the duration of the timeout */
72
+ constructor({ wsConnection }: { wsConnection: WSConnection }) {
73
+ this.wsConnection = wsConnection;
111
74
  this.consecutiveFailures = 0;
112
- /** keep track of the total number of failures */
113
75
  this.totalFailures = 0;
114
- /** We only make 1 attempt to reconnect at the same time.. */
115
76
  this.isConnecting = false;
116
- /** To avoid reconnect if client is disconnected */
77
+ /** Set by `disconnect()` so a pending reconnect gives up. */
117
78
  this.isDisconnected = false;
118
- /** Boolean that indicates if the connection promise is resolved */
119
79
  this.isResolved = false;
120
- /** Boolean that indicates if we have a working connection to the server */
121
80
  this.isHealthy = false;
122
- /** Incremented when a new WS connection is made */
81
+ /** Incremented when the current socket is closed or destroyed; older IDs' callbacks are ignored. */
123
82
  this.wsID = 1;
124
- /** Store the last event time for health checks */
125
83
  this.lastEvent = null;
126
- /** Send a health check message every 25 seconds */
127
- this.pingInterval = 25 * 1000;
128
- this.connectionCheckTimeout = this.pingInterval + 10 * 1000;
84
+ /** Set when the server reports that the token of the open socket expired */
85
+ this.tokenExpiredByServer = false;
86
+ }
87
+
88
+ /** Read live from the parent, so a config update reaches an already open socket. */
89
+ private get config(): WSConnectionConfig {
90
+ return this.wsConnection.config;
91
+ }
92
+
93
+ get pingInterval(): number {
94
+ return this.config.pingIntervalMs;
95
+ }
129
96
 
130
- addConnectionEventListeners(this.onlineStatusChanged);
97
+ /** Silence tolerated before the socket is torn down: `pingIntervalMs + healthCheckGracePeriodMs`. */
98
+ get connectionCheckTimeout(): number {
99
+ return this.config.pingIntervalMs + this.config.healthCheckGracePeriodMs;
131
100
  }
132
101
 
133
- setClient(client: StreamChat) {
134
- this.client = client;
102
+ get client(): StreamChat {
103
+ return this.wsConnection.client;
104
+ }
105
+
106
+ /** Re-parents a socket supplied through `config.connection`. */
107
+ setWSConnection(wsConnection: WSConnection) {
108
+ this.wsConnection = wsConnection;
135
109
  }
136
110
 
137
111
  /**
138
- * Connects to the WS URL. The default 15s timeout allows between 2 and 3 tries.
112
+ * Connects to the WS URL.
139
113
  *
140
- * @param timeout - Connect timeout in milliseconds (optional, defaults to `15000`).
141
- * @returns A promise that resolves once the first health check message is received.
114
+ * @param timeout - Connect timeout in milliseconds. Defaults to `config.connectTimeoutMs`.
115
+ * @returns A promise that resolves once the server's `connection.ok` hello event arrives.
142
116
  */
143
- async connect(timeout = 15000) {
117
+ async connect(timeout: number = this.config.connectTimeoutMs) {
144
118
  if (this.isConnecting) {
145
119
  throw Error(
146
120
  `You've called connect twice, can only attempt 1 connection at the time`,
@@ -157,7 +131,7 @@ export class StableWSConnection {
157
131
  .withExtraTags('connect')
158
132
  .info(`Established a WebSocket connection. Health check: ${healthCheck}.`);
159
133
  } catch (error: any) {
160
- this.isHealthy = false;
134
+ this._applyHealth(false);
161
135
  this.consecutiveFailures += 1;
162
136
 
163
137
  const e = error as APIError;
@@ -186,12 +160,10 @@ export class StableWSConnection {
186
160
  }
187
161
 
188
162
  /**
189
- * _waitForHealthy polls the promise connection to see if its resolved until it times out
190
- * the default 15s timeout allows between 2~3 tries
191
- *
192
- * @param timeout - duration (ms)
163
+ * Polls the connection promise until it resolves or `timeout` (ms) elapses. `timeout` defaults to
164
+ * `config.connectTimeoutMs`.
193
165
  */
194
- _waitForHealthy(timeout = 15000) {
166
+ _waitForHealthy(timeout: number = this.config.connectTimeoutMs) {
195
167
  return Promise.race([
196
168
  (async () => {
197
169
  const interval = 50; // ms
@@ -228,27 +200,20 @@ export class StableWSConnection {
228
200
  ]);
229
201
  }
230
202
 
231
- /**
232
- * Builds and returns the URL for the WebSocket connection.
233
- *
234
- * @private
235
- * @returns url string
236
- */
237
203
  _buildUrl = () => {
238
- const params = new URLSearchParams(this.client.options.wsUrlParams);
204
+ const params = new URLSearchParams(this.config.urlParams);
239
205
  params.set('api_key', this.client.key);
240
206
  params.set('stream-auth-type', this.client.getAuthType());
241
- // Browsers cannot set headers on the WS handshake, so the server reads this
242
- // from the query string too.
207
+ // Browsers cannot set headers on the WS handshake, so the server reads this from the query too.
243
208
  params.set('X-Stream-Client', this.client.getUserAgent());
244
209
 
245
210
  return `${this.client.wsBaseURL}/api/v2/connect?${params.toString()}`;
246
211
  };
247
212
 
248
213
  /**
249
- * Disconnects the connection without attempting to recover.
214
+ * Closes the socket without attempting to recover.
250
215
  *
251
- * @param timeout - Optional timeout in milliseconds to wait for the close frame from the server.
216
+ * @param timeout - How long to wait for the server's close frame, in milliseconds. Defaults to 1s.
252
217
  */
253
218
  disconnect(timeout?: number) {
254
219
  logger
@@ -258,23 +223,24 @@ export class StableWSConnection {
258
223
  this.wsID += 1;
259
224
  this.isConnecting = false;
260
225
  this.isDisconnected = true;
226
+ this.tokenExpiredByServer = false;
227
+ // A deliberate close still expects a reopen (mobile backgrounding), so waiters keep waiting:
228
+ // invalidating drops the dead ID and arms a fresh deferred for the next socket.
229
+ this.client.connectionIdManager.invalidate();
261
230
 
262
- // start by removing all the listeners
231
+ // Stop the ping and connection-check timers.
263
232
  if (this.healthCheckTimeoutRef) {
264
- clearInterval(this.healthCheckTimeoutRef);
233
+ clearTimeout(this.healthCheckTimeoutRef);
265
234
  }
266
235
  if (this.connectionCheckTimeoutRef) {
267
- clearInterval(this.connectionCheckTimeoutRef);
236
+ clearTimeout(this.connectionCheckTimeoutRef);
268
237
  }
269
238
 
270
- removeConnectionEventListeners(this.onlineStatusChanged);
271
-
272
- this.isHealthy = false;
239
+ // Through `_applyHealth` so the store records a deliberate close as a transition too.
240
+ this._applyHealth(false);
273
241
 
274
242
  let isClosedPromise: Promise<void>;
275
- // and finally close...
276
- // Assigning to local here because we will remove it from this before the
277
- // promise resolves.
243
+ // Local copy: `this.ws` is deleted before the promise resolves.
278
244
  const { ws } = this;
279
245
  if (ws && ws.close && ws.readyState === ws.OPEN) {
280
246
  isClosedPromise = new Promise((resolve) => {
@@ -289,8 +255,7 @@ export class StableWSConnection {
289
255
  };
290
256
 
291
257
  ws.onclose = onclose;
292
- // In case we don't receive a close frame from the WebSocket server in time,
293
- // lets not wait for more than 1 seconds.
258
+ // Don't wait longer than the timeout for the server's close frame.
294
259
  setTimeout(onclose, timeout != null ? timeout : 1000);
295
260
  });
296
261
 
@@ -314,17 +279,14 @@ export class StableWSConnection {
314
279
  return isClosedPromise;
315
280
  }
316
281
 
317
- /**
318
- * Connects to the WS endpoint.
319
- *
320
- * @returns A promise that resolves once the first health check message is received.
321
- */
282
+ /** Connects to the WS endpoint, resolving with the server's `connection.ok` hello event. */
322
283
  async _connect() {
323
- // simply ignore _connect if it's currently connecting, or if disconnect() was called
284
+ // Ignored while connecting, or after `disconnect()`.
324
285
  if (this.isConnecting || this.isDisconnected) return;
325
286
  this.isConnecting = true;
326
287
  this.requestID = randomId();
327
- this.client.insightMetrics.connectionStartTimestamp = new Date().getTime();
288
+ // Arm before anything can await a connection ID. A no-op while one is still held.
289
+ this.client.connectionIdManager.arm();
328
290
  let isTokenReady = false;
329
291
  try {
330
292
  logger.withExtraTags('_connect').debug('Waiting for the auth token.');
@@ -344,16 +306,15 @@ export class StableWSConnection {
344
306
 
345
307
  this._setupConnectionPromise();
346
308
  const wsURL = this._buildUrl();
347
- // Built before the socket exists on purpose: the token is guaranteed loaded by
348
- // this point, and a failure here must reject _connect rather than leave an open
349
- // socket to die against the server's 10s auth-message deadline.
309
+ // Built before the socket exists, so a failure rejects `_connect` instead of leaving an open
310
+ // socket to hit the server's 10s auth-message deadline.
350
311
  const authMessage = this.client._buildWSAuthMessage();
351
312
  logger.withExtraTags('_connect').info(`Connecting to ${wsURL}.`, {
352
313
  wsURL,
353
314
  requestID: this.requestID,
354
315
  });
355
316
 
356
- const WS = this.client.options.WebSocketImpl ?? WebSocket;
317
+ const WS = this.config.webSocketImpl ?? WebSocket;
357
318
  this.ws = new WS(wsURL);
358
319
 
359
320
  this.ws.onopen = this.onopen.bind(this, this.wsID, authMessage);
@@ -364,17 +325,7 @@ export class StableWSConnection {
364
325
  this.isConnecting = false;
365
326
 
366
327
  if (response) {
367
- this.connectionID = response.connection_id;
368
- if (
369
- this.client.insightMetrics.wsConsecutiveFailures > 0 &&
370
- this.client.options.enableInsights
371
- ) {
372
- postInsights(
373
- 'ws_success_after_failure',
374
- buildWsSuccessAfterFailureInsight(this as unknown as StableWSConnection),
375
- );
376
- this.client.insightMetrics.wsConsecutiveFailures = 0;
377
- }
328
+ // `onmessage` already published the ID; publishing it again could revive an invalidated one.
378
329
  return response;
379
330
  }
380
331
  } catch (error: any) {
@@ -382,33 +333,21 @@ export class StableWSConnection {
382
333
  logger
383
334
  .withExtraTags('_connect')
384
335
  .warn('An error occurred while connecting.', { error });
385
- if (this.client.options.enableInsights) {
386
- this.client.insightMetrics.wsConsecutiveFailures++;
387
- this.client.insightMetrics.wsTotalFailures++;
388
-
389
- const insights = buildWsFatalInsight(
390
- this as unknown as StableWSConnection,
391
- convertErrorToJson(error as Error),
392
- );
393
- postInsights?.('ws_fatal', insights);
394
- }
395
336
  throw error;
396
337
  }
397
338
  }
398
339
 
399
340
  /**
400
- * Retries the connection to the WS endpoint.
341
+ * Retries the connection.
401
342
  *
402
- * @param options - Reconnect options.
403
- * @param options.interval - Number of milliseconds to wait before reconnecting.
404
- * @param options.refreshToken - Reload/refresh the user token before attempting to reconnect.
343
+ * @param options.interval - Milliseconds to wait first. Defaults to a randomised backoff.
344
+ * @param options.refreshToken - Reload the user token before reconnecting.
405
345
  */
406
346
  async _reconnect(
407
347
  options: { interval?: number; refreshToken?: boolean } = {},
408
348
  ): Promise<void> {
409
349
  logger.withExtraTags('_reconnect').info('Initiating a reconnect.');
410
350
 
411
- // only allow 1 connection at the time
412
351
  if (this.isConnecting || this.isHealthy) {
413
352
  logger
414
353
  .withExtraTags('_reconnect')
@@ -416,17 +355,13 @@ export class StableWSConnection {
416
355
  return;
417
356
  }
418
357
 
419
- // reconnect in case of on error or on close
420
- // also reconnect if the health check cycle fails
421
358
  let interval = options.interval;
422
359
  if (!interval) {
423
360
  interval = retryInterval(this.consecutiveFailures);
424
361
  }
425
- // reconnect, or try again after a little while...
426
362
  await sleep(interval);
427
363
 
428
- // Check once again if by some other call to _reconnect is active or connection is
429
- // already restored, then no need to proceed.
364
+ // Re-check: another `_reconnect` may have started, or the connection been restored, meanwhile.
430
365
  if (this.isConnecting || this.isHealthy) {
431
366
  logger
432
367
  .withExtraTags('_reconnect')
@@ -445,11 +380,33 @@ export class StableWSConnection {
445
380
  .withExtraTags('_reconnect')
446
381
  .info('Destroying the current WebSocket connection.');
447
382
 
448
- // cleanup the old connection
449
383
  this._destroyCurrentWSConnection();
450
384
 
451
385
  if (options.refreshToken) {
452
- await this.client.tokenManager.loadToken();
386
+ try {
387
+ await this.client.tokenManager.loadToken();
388
+ } catch (error) {
389
+ // `_reconnect` is not awaited by its callers, so a rejection here would be unhandled.
390
+ // Treat a failed refresh like a failed connect and retry with backoff; the retry
391
+ // aborts on its own once disconnect() is called.
392
+ this._applyHealth(false);
393
+ this.consecutiveFailures += 1;
394
+ logger
395
+ .withExtraTags('_reconnect')
396
+ .warn('Failed to reload the token. Retrying the reconnect.', { error });
397
+
398
+ this._reconnect({ refreshToken: true });
399
+ return;
400
+ }
401
+
402
+ // Another reconnect may have started while the token was loading, e.g. when
403
+ // the socket fires both an error and a close event.
404
+ if (this.isConnecting || this.isHealthy) {
405
+ logger
406
+ .withExtraTags('_reconnect')
407
+ .debug('Aborting the reconnect: already connecting or healthy.');
408
+ return;
409
+ }
453
410
  }
454
411
 
455
412
  try {
@@ -458,7 +415,7 @@ export class StableWSConnection {
458
415
 
459
416
  this.consecutiveFailures = 0;
460
417
  } catch (error: any) {
461
- this.isHealthy = false;
418
+ this._applyHealth(false);
462
419
  this.consecutiveFailures += 1;
463
420
  if (
464
421
  error.code === chatCodes.TOKEN_EXPIRED &&
@@ -480,36 +437,57 @@ export class StableWSConnection {
480
437
  .warn('WebSocket connection failed. Retrying the reconnect.');
481
438
 
482
439
  this._reconnect();
440
+ } else {
441
+ // Giving up: reject the deferred armed when the socket went down, or waiting requests hang.
442
+ this.client.connectionIdManager.rejectConnectionId(error);
483
443
  }
484
444
  }
485
445
  logger.withExtraTags('_reconnect').debug('Reconnect attempt finished.');
486
446
  }
487
447
 
488
448
  /**
489
- * Called when the browser connects or disconnects from the internet.
449
+ * Applies a device network status change to this socket.
490
450
  *
491
- * @param event - The DOM event whose `type` is `'online'` or `'offline'`.
451
+ * @param event - A DOM-shaped object whose `type` is `'online'` or `'offline'`. Only `type` is
452
+ * read.
453
+ * @deprecated Use `client.networkConnection.setStatus(isOnline)` or
454
+ * `client.networkConnection.setStatusReporter(…)` instead.
492
455
  */
493
456
  onlineStatusChanged = (event: Event) => {
494
- if (event.type === 'offline') {
495
- // mark the connection as down
457
+ if (event.type === 'offline') this._applyNetworkStatus(false);
458
+ else if (event.type === 'online') this._applyNetworkStatus(true);
459
+ };
460
+
461
+ /**
462
+ * Applies a network status change to this socket. Shared by the parent's network-store
463
+ * subscription and the deprecated {@link onlineStatusChanged}.
464
+ *
465
+ * @internal
466
+ */
467
+ public _applyNetworkStatus(online: boolean) {
468
+ if (!online) {
496
469
  logger
497
470
  .withExtraTags('onlineStatusChanged')
498
- .info('Network status changed to offline.');
471
+ .info(`The 'network' connection went offline.`);
499
472
  this._setHealth(false);
500
- } else if (event.type === 'online') {
501
- // retry right now...
502
- // We check this.isHealthy, not sure if it's always
503
- // smart to create a new WS connection if the old one is still up and running.
504
- // it's possible we didn't miss any messages, so this process is just expensive and not needed.
505
- logger
506
- .withExtraTags('onlineStatusChanged')
507
- .info(`Network status changed to online. isHealthy: ${this.isHealthy}.`);
508
- if (!this.isHealthy) {
509
- this._reconnect({ interval: 10 });
510
- }
473
+ return;
511
474
  }
512
- };
475
+
476
+ // A socket still carrying traffic has probably missed nothing: reconnect only if it is down.
477
+ logger
478
+ .withExtraTags('onlineStatusChanged')
479
+ .info(
480
+ `The 'network' connection went online; ${
481
+ this.isHealthy
482
+ ? `leaving the 'ws' connection as it is`
483
+ : `reconnecting the 'ws' connection now`
484
+ }.`,
485
+ );
486
+
487
+ if (!this.isHealthy) {
488
+ this._reconnect({ interval: WS_NETWORK_RECOVERY_RETRY_MS });
489
+ }
490
+ }
513
491
 
514
492
  onopen = (wsId: number, authMessage: string) => {
515
493
  if (this.wsID !== wsId) return;
@@ -518,11 +496,11 @@ export class StableWSConnection {
518
496
  wsID: wsId,
519
497
  });
520
498
 
521
- // `/api/v2/connect` authenticates off the first frame the client sends, not off
522
- // the query string. The server closes the socket if it does not arrive in 10s.
499
+ // `/api/v2/connect` authenticates off the first frame the client sends, not the query string.
500
+ // The server closes the socket if it does not arrive in 10s.
523
501
  const { ws } = this;
524
- // disconnect() deletes this.ws synchronously; the wsID guard above covers
525
- // reconnects, this covers a socket torn down before `open` was dispatched.
502
+ // `disconnect()` deletes `this.ws` synchronously: the wsID guard above covers reconnects, this
503
+ // covers a socket torn down before `open` was dispatched.
526
504
  if (!ws || ws.readyState !== ws.OPEN) return;
527
505
 
528
506
  try {
@@ -545,11 +523,11 @@ export class StableWSConnection {
545
523
  });
546
524
  if (typeof event.data !== 'string') return;
547
525
  const data = JSON.parse(event.data);
548
- const decodedData = decodeConnectionEvent(data);
526
+ // Typed as `Event`, which leaves out the spec's never-sent `'*'` placeholder member.
527
+ const decodedData = data as StreamEvent;
549
528
 
550
- // we wait till the first message before we consider the connection open..
551
- // the reason for this is that auth errors and similar errors trigger a ws.onopen and immediately
552
- // after that a ws.onclose..
529
+ // The first message, not `onopen`, marks the connection open: auth errors fire `onopen` and
530
+ // then `onclose`.
553
531
  if (!this.isResolved) {
554
532
  this.isResolved = true;
555
533
  if (data.error) {
@@ -557,20 +535,37 @@ export class StableWSConnection {
557
535
  return;
558
536
  }
559
537
 
538
+ // Published before going online, so "the socket is up" implies "there is an ID to watch on".
539
+ this.client.connectionIdManager.resolveConnectionId(
540
+ (decodedData as ConnectionOpen).connection_id,
541
+ );
542
+
560
543
  this.resolvePromise?.(decodedData as ConnectionOpen);
561
544
  this._setHealth(true);
562
545
  }
563
546
 
564
- // trigger the event..
565
547
  this.lastEvent = new Date();
566
548
 
567
- // `connection.ok` is the v2 hello event. The server only echoes health checks in
568
- // response to an inbound frame, so failing to schedule here means we never ping
569
- // and scheduleConnectionCheck tears the socket down 35s later, in a loop.
549
+ // The server sends a health check only in reply to a client frame, so the ping loop starts from
550
+ // the hello and continues on each health check. Without it the connection check tears the socket
551
+ // down every `connectionCheckTimeout`.
570
552
  if (data.type === 'health.check' || data.type === 'connection.ok') {
571
553
  this.scheduleNextPing();
572
554
  }
573
555
 
556
+ // The server reports a token that expired after the connection was established
557
+ // (auto_disconnect_ws) and then closes the socket. Remember it so the reconnect
558
+ // refreshes the token first instead of retrying once with the expired token.
559
+ if (
560
+ data?.type === 'connection.error' &&
561
+ data?.error?.code === chatCodes.TOKEN_EXPIRED
562
+ ) {
563
+ logger
564
+ .withExtraTags('onmessage')
565
+ .debug('The server reported that the token expired.', { wsID: wsId });
566
+ this.tokenExpiredByServer = true;
567
+ }
568
+
574
569
  this.client.dispatchEvent(decodedData);
575
570
  this.scheduleConnectionCheck();
576
571
  };
@@ -586,8 +581,7 @@ export class StableWSConnection {
586
581
  });
587
582
 
588
583
  if (event.code === chatCodes.WS_CLOSED_SUCCESS) {
589
- // this is a permanent error raised by stream..
590
- // usually caused by invalid auth details
584
+ // A permanent error raised by Stream, usually invalid auth details.
591
585
  const error = new WSCloseError(`WS connection reject with error ${event.reason}`);
592
586
 
593
587
  error.reason = event.reason;
@@ -613,8 +607,7 @@ export class StableWSConnection {
613
607
  event,
614
608
  });
615
609
 
616
- // reconnect if its an abnormal failure
617
- this._reconnect();
610
+ this._reconnectAfterFailure();
618
611
  }
619
612
  };
620
613
 
@@ -631,41 +624,59 @@ export class StableWSConnection {
631
624
  .withExtraTags('onerror')
632
625
  .warn('The WebSocket connection raised an error.', { event });
633
626
 
634
- this._reconnect();
627
+ this._reconnectAfterFailure();
635
628
  };
636
629
 
637
630
  /**
638
- * Sets the connection to healthy or unhealthy. Broadcasts an event if the connection status changed.
639
- *
640
- * @param healthy - Whether the connection is healthy.
631
+ * _reconnectAfterFailure - Reconnects after the socket closed or failed. If the server
632
+ * reported that the token expired, the token is refreshed before reconnecting.
633
+ * Static tokens cannot be refreshed and reconnect as before.
641
634
  */
642
- _setHealth = (healthy: boolean) => {
643
- if (healthy === this.isHealthy) return;
635
+ _reconnectAfterFailure() {
636
+ if (this.tokenExpiredByServer && !this.client.tokenManager.isStatic()) {
637
+ logger
638
+ .withExtraTags('_reconnectAfterFailure')
639
+ .info('The token expired. Reloading the token and reconnecting.');
640
+ this._reconnect({ refreshToken: true });
641
+ return;
642
+ }
643
+
644
+ this._reconnect();
645
+ }
646
+
647
+ /**
648
+ * Writes the status to the field and to `client.wsConnection.state`, and drops the connection ID
649
+ * when it goes down. Returns whether the status changed. Every transition goes through here
650
+ * (`disconnect()` and the error paths included); the constructor does not, since initializing the
651
+ * field is not a transition.
652
+ */
653
+ private _applyHealth(healthy: boolean): boolean {
654
+ if (healthy === this.isHealthy) return false;
644
655
 
645
656
  this.isHealthy = healthy;
646
657
 
647
- if (this.isHealthy) {
648
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
649
- return;
658
+ if (!healthy) {
659
+ // The ID is dead; invalidating arms a fresh deferred so requests wait for the reconnect.
660
+ this.client.connectionIdManager.invalidate();
650
661
  }
651
662
 
663
+ this.wsConnection._setStatus({ isHealthy: healthy });
664
+
665
+ return true;
666
+ }
667
+
668
+ /** Applies a status change; on a drop, marks the channel watches as interrupted. */
669
+ _setHealth = (healthy: boolean) => {
670
+ if (!this._applyHealth(healthy)) return;
671
+ if (this.isHealthy) return;
672
+
652
673
  // The server keys channel watches by connection ID, so they are gone the moment the socket is.
653
- // Done here rather than off the `connection.changed` event below, which is debounced by 5s.
654
- this.client._markActiveChannelsWatchInterrupted();
655
-
656
- // we're offline, wait few seconds and fire and event if still offline
657
- setTimeout(() => {
658
- if (this.isHealthy) return;
659
- this.client.dispatchEvent({ type: 'connection.changed', online: this.isHealthy });
660
- }, 5000);
674
+ this.client.channelManager.markChannelsWatchInterrupted();
661
675
  };
662
676
 
663
677
  /**
664
- * Creates an error object for the WS event.
665
- *
666
- * @param event - The raw WebSocket close / data / error event.
667
- * @param isWSFailure - Whether the underlying cause is a WebSocket failure (optional, defaults to `true`).
668
- * @returns A normalized error describing the WS failure.
678
+ * Turns a raw WebSocket close, message or error event into an `Error` carrying `code`,
679
+ * `StatusCode` and `isWSFailure`.
669
680
  */
670
681
  _errorFromWSEvent = (
671
682
  event: CloseEvent | MessageEvent | ErrorEvent | Event,
@@ -686,7 +697,7 @@ export class StableWSConnection {
686
697
  message = event.error.message;
687
698
  }
688
699
 
689
- // Keeping this `warn` level log, to avoid cluttering of error logs from ws failures.
700
+ // `warn`, not `error`, to avoid cluttering error logs with WS failures.
690
701
  logger
691
702
  .withExtraTags('_errorFromWSEvent')
692
703
  .warn(`The WebSocket failed with code ${code}.`, { event });
@@ -699,21 +710,14 @@ export class StableWSConnection {
699
710
  StatusCode?: string | number;
700
711
  };
701
712
  error.code = code;
702
- /**
703
- * StatusCode does not exist on any event types but has been left
704
- * as is to preserve JS functionality during the TS implementation
705
- */
713
+ // `StatusCode` is not on any event type; kept for JS compatibility.
706
714
  error.StatusCode = statusCode;
707
715
  error.isWSFailure = isWSFailure;
708
716
  return error;
709
717
  };
710
718
 
711
- /**
712
- * Removes the current WS connection.
713
- */
714
719
  _destroyCurrentWSConnection() {
715
- // increment the ID, meaning we will ignore all messages from the old
716
- // ws connection from now on.
720
+ // Callbacks bound to the old ID are ignored.
717
721
  this.wsID += 1;
718
722
 
719
723
  try {
@@ -723,12 +727,10 @@ export class StableWSConnection {
723
727
  }
724
728
  }
725
729
 
726
- /**
727
- * Sets up the `this.connectionOpen` promise.
728
- */
729
730
  _setupConnectionPromise = () => {
730
731
  this.isResolved = false;
731
- /** a promise that is resolved once ws.open is called */
732
+ this.tokenExpiredByServer = false;
733
+ // Resolved by the first message (`connection.ok`), rejected on an error or close.
732
734
  this.connectionOpen = new Promise<ConnectionOpen>((resolve, reject) => {
733
735
  this.resolvePromise = resolve;
734
736
  this.rejectPromise = reject;
@@ -736,18 +738,18 @@ export class StableWSConnection {
736
738
  };
737
739
 
738
740
  /**
739
- * Schedules the next health check ping for the WebSocket connection.
741
+ * Schedules the next health-check ping `pingIntervalMs` from now, replacing a pending one.
742
+ *
743
+ * @internal
740
744
  */
741
745
  scheduleNextPing = () => {
742
746
  if (this.healthCheckTimeoutRef) {
743
747
  clearTimeout(this.healthCheckTimeoutRef);
744
748
  }
745
749
 
746
- // 30 seconds is the recommended interval (messenger uses this)
747
750
  this.healthCheckTimeoutRef = setTimeout(() => {
748
- // send the healthcheck.., server replies with a health check event
751
+ // The server answers with a health check event.
749
752
  const data = [{ type: 'health.check', client_id: this.client.clientId }];
750
- // try to send on the connection
751
753
  try {
752
754
  this.ws?.send(JSON.stringify(data));
753
755
  } catch (e) {
@@ -756,11 +758,7 @@ export class StableWSConnection {
756
758
  }, this.pingInterval);
757
759
  };
758
760
 
759
- /**
760
- * Schedules a check for the time difference between the last received event and now. If the
761
- * difference is more than 35 seconds, it means our health check logic has failed and the
762
- * WebSocket needs to be reconnected.
763
- */
761
+ /** Reconnects when no event has arrived for more than `connectionCheckTimeout`. */
764
762
  scheduleConnectionCheck = () => {
765
763
  if (this.connectionCheckTimeoutRef) {
766
764
  clearTimeout(this.connectionCheckTimeoutRef);