stream-chat 10.0.0-rc.9 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (361) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +21650 -19790
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +21690 -19798
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +21755 -19895
  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 +237 -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 +513 -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
package/src/client.ts CHANGED
@@ -1,24 +1,25 @@
1
1
  /* eslint no-unused-vars: "off" */
2
2
  /* global process */
3
3
 
4
- import type { AxiosInstance } from 'axios';
4
+ import type { AxiosInstance, AxiosRequestConfig } from 'axios';
5
5
  import axios from 'axios';
6
6
 
7
- import { Channel } from './channel';
7
+ import type { Channel } from './channel';
8
8
  import type { ChannelMuteStatus } from './channel_state';
9
9
  import { ChannelWatchStatus } from './channel_state';
10
10
  import { ClientState } from './client_state';
11
- import { StableWSConnection } from './connection';
12
11
  import { UploadManager } from './uploadManager';
12
+ import { DevToken } from './signing';
13
13
  import { TokenManager, type TokenManagerMinimalUser } from './token_manager';
14
14
  import { ApiClient } from './api-client';
15
15
  import {
16
16
  axiosParamsSerializer,
17
17
  formatMessage,
18
- generateChannelTempCid,
19
18
  getEnv,
19
+ invokeEventListener,
20
20
  isOwnUserBaseProperty,
21
21
  randomId,
22
+ sanitizeOutgoingAttachments,
22
23
  } from './utils';
23
24
  import { nowNs } from './utils/time';
24
25
  import { normalizeUploadFile } from './upload-utils';
@@ -43,44 +44,49 @@ import type {
43
44
  LocalMessage,
44
45
  OwnUserResponse,
45
46
  PartializeAllBut,
47
+ PinMessageOptions,
46
48
  QueryChannelsRequest,
47
49
  QueryChannelsResponse,
48
- QueryReactionsRequestWithId,
49
50
  QueryThreadsRequest,
50
51
  ReactionResponse,
51
52
  SdkIdentifier,
52
- StreamChatOptions,
53
53
  StreamRequestOptions,
54
54
  TokenOrProvider,
55
55
  UnBanUserOptions,
56
56
  UpdateUserPartialRequest,
57
57
  UserMuteResponse,
58
+ UserRequest,
58
59
  UserResponse,
59
60
  } from './types';
60
- import { InsightMetrics, postInsights } from './insights';
61
+ import { isWSFailure } from './errors';
62
+ import type { APIError } from './errors';
61
63
  import { chatLoggerSystem } from './logger';
62
- import { queueOrRun } from './offline-support/queueableOperations';
63
- import { Thread } from './thread';
64
+ import { DEFAULT_THREAD_PARTICIPANT_LIMIT, type Thread } from './thread';
64
65
  import { Moderation } from './moderation';
65
66
  import { ThreadManager } from './thread_manager';
66
67
  import { DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE } from './constants';
67
68
  import { PollManager } from './poll_manager';
68
69
  import { EntityStore } from './entityStore/EntityStore';
69
70
  import { ChannelManager } from './ChannelManager';
70
- import { ConnectionRecoveryManager } from './ConnectionRecoveryManager';
71
+ import {
72
+ ConnectionIdManager,
73
+ ConnectionRecoveryManager,
74
+ NetworkConnectionObserver,
75
+ WSConnection,
76
+ } from './connection';
71
77
  import { MessageDeliveryReporter } from './messageDelivery';
72
78
  import { NotificationManager } from './notifications';
73
79
  import { ReminderManager } from './reminders';
74
80
  import type { AbstractOfflineDB } from './offline-support';
75
- import { getPendingTaskChannelData } from './offline-support/util';
76
81
  import { FixedSizeQueueCache } from './utils/FixedSizeQueueCache';
77
82
  import { isEqual } from './utils/mergeWith/mergeWithCore';
78
83
  import type { MessageComposer } from './messageComposer';
79
- import type { InstanceSetupState } from './configuration';
84
+ import type { InstanceConfigTree, InstanceSetupState } from './configuration';
85
+ import type { DeepPartial } from './types.utility';
80
86
  import { InstanceConfigurationRegistry } from './configuration/InstanceConfigurationRegistry';
81
87
  import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
82
- import { StateStore } from './store';
83
- import type { Unsubscribe } from './store';
88
+ import { StateStore } from '@stream-io/state-store';
89
+ import type { Unsubscribe } from '@stream-io/state-store';
84
90
  import type {
85
91
  ConnectUserDetailsRequest,
86
92
  FileUploadRequest,
@@ -91,11 +97,7 @@ import type {
91
97
  WSEvent,
92
98
  } from './gen/models';
93
99
  import { ChatApi } from './gen-imports';
94
- import type { ConnectedEvent, StreamResponse } from './types';
95
-
96
- function isString(value: unknown): value is string {
97
- return typeof value === 'string' || value instanceof String;
98
- }
100
+ import type { StreamResponse } from './types';
99
101
 
100
102
  const logger = chatLoggerSystem.getLogger('client');
101
103
  const offlineDbLogger = chatLoggerSystem.getLogger('offline-db');
@@ -115,107 +117,115 @@ export type ChannelConfigsState = {
115
117
 
116
118
  export type ClientUser = PartializeAllBut<OwnUserResponse, 'id'> & { anon?: boolean };
117
119
 
120
+ /**
121
+ * After a thread query with `watch: true` the server watches the thread's channel, as for
122
+ * `channel.watch()` and `queryChannels`.
123
+ */
124
+ const markThreadChannelWatched = ({ channel }: Thread) => {
125
+ channel.watchStatus = ChannelWatchStatus.Watching;
126
+ };
127
+
118
128
  export class StreamChat extends ChatApi {
119
129
  private static _instance?: unknown | StreamChat; // type is undefined|StreamChat, unknown is due to TS limitations with statics
120
130
  messageDeliveryReporter: MessageDeliveryReporter;
121
- /**
122
- * @internal
123
- */
131
+ /** @internal */
124
132
  uploadManager: UploadManager;
125
- /**
126
- * @private
127
- */
133
+ /** @private */
128
134
  _user?: ClientUser;
129
135
  appSettingsPromise?: Promise<StreamResponse<Gen_GetApplicationResponse>>;
130
- activeChannels: {
131
- [key: string]: Channel;
132
- };
133
136
  threads: ThreadManager;
134
137
  polls: PollManager;
135
138
  /**
136
- * Channel lists — one or more `ChannelPaginator`s kept in sync with WS events, with ownership
137
- * arbitration between them. Instantiated with the client and living as long as it does; register
138
- * the lists with `client.channelManager.insertPaginator()` and drop them again with
139
- * `removePaginator()`. It only starts handling events once something calls its (ref-counted)
140
- * `registerSubscriptions()`.
141
- *
142
- * It is deliberately not configurable through the client options — everything is set on the
143
- * manager itself (`setOwnershipResolver`, `addEventHandler` / `setEventHandlers` /
144
- * `removeEventHandlers`), which is also the only way to reconfigure it later.
139
+ * Channel lists (`ChannelPaginator`s kept in sync with WS events, with ownership arbitration
140
+ * between them). Register lists with `insertPaginator()` / `removePaginator()`. It handles events
141
+ * only once something calls its ref-counted `registerSubscriptions()`. It is configured on the
142
+ * manager itself (`setOwnershipResolver`, `addEventHandler`, ...), not through the client
143
+ * options.
145
144
  */
146
145
  channelManager: ChannelManager;
147
146
  /**
148
- * Owns connection recovery: on reconnect it re-runs each loaded channel list's own first-page query
149
- * and reloads each active channel, then dispatches `connection.recovered`. Instantiated with the
150
- * client and subscribed for its lifetime.
151
- *
152
- * Turn it off through the declarative configuration if the application recovers state itself:
153
- * `client.config.set({ client: { connectionRecovery: { enabled: false } } })`.
147
+ * On reconnect, re-runs each loaded channel list's first-page query and reloads each active
148
+ * channel and thread, then dispatches `connection.recovered`. Disable it when the app recovers
149
+ * state itself: `client.config.set({ client: { connectionRecovery: { enabled: false } } })`.
154
150
  */
155
151
  connectionRecovery: ConnectionRecoveryManager;
156
152
  /**
157
- * Client-global, normalized store holding one canonical copy of each message. The channel main
158
- * list and thread reply paginators read/write message content through it, so a message held in
159
- * more than one of them stays consistent without copy-to-copy fan-out.
153
+ * The device's network status, separate from the WebSocket's ({@link wsConnection}). Platforms
154
+ * report it through `client.config.set({ client: { networkConnection: { statusReporter } } })` or
155
+ * `client.networkConnection.setStatusReporter(...)`. Browsers get a reporter automatically;
156
+ * elsewhere a stand-in mirrors the WebSocket. `isOnline` is `undefined` (unknown, not offline)
157
+ * until something reports.
158
+ */
159
+ networkConnection: NetworkConnectionObserver;
160
+ /**
161
+ * The connection ID (the WebSocket's, or the long-poll's after an `enableWSFallback` switch). A
162
+ * request with `watch` or `presence` waits here for the handshake (see `requiresConnectionId`).
163
+ */
164
+ connectionIdManager: ConnectionIdManager;
165
+ /**
166
+ * Client-global store with one canonical copy of each message. The channel and thread paginators
167
+ * read and write messages through it, so a message held in several of them stays consistent.
160
168
  */
161
169
  messageStore: EntityStore<LocalMessage>;
162
170
  offlineDb?: AbstractOfflineDB;
163
171
  notifications: NotificationManager;
164
172
  reminders: ReminderManager;
165
- persistUserOnConnectionFailure?: boolean;
166
173
  axiosInstance: AxiosInstance;
167
174
  baseURL?: string;
168
- browser: boolean;
169
175
  cleaningIntervalRef?: ReturnType<typeof setTimeout>;
170
176
  clientId?: string;
171
177
  key: string;
172
178
  listeners: Map<EventType, Set<EventHandler>>;
173
179
  /**
174
- * If true, we will not clean up threads when channel state is in initializing state.
175
- * The main use case for SDKs who do independent state recovery for channels.
180
+ * When true, threads are not cleaned up while the channel state is initializing (for SDKs that
181
+ * recover channel state themselves).
176
182
  */
177
183
  preventThreadCleanup = false;
178
184
  moderation: Moderation;
179
185
  mutedChannels: ChannelMute[];
180
186
  readonly mutedUsersStore: StateStore<{ mutedUsers: UserMuteResponse[] }>;
181
187
  /**
182
- * Reactive store behind {@link channelServerConfigs}. The only reactive way to observe server channel
183
- * configuration today, which is why `stream-chat-react` reads it — a public, per-channel feature
184
- * resolver is the intended replacement.
185
- *
186
- * Named for what it holds plus a `Store` suffix for what it is, matching {@link mutedUsersStore}. These
187
- * are the backend's configs, not the ones you register through {@link config}.
188
+ * Reactive store behind {@link channelServerConfigs}: the backend's channel configs, not the ones
189
+ * registered through {@link config}.
188
190
  *
189
191
  * @internal
190
192
  */
191
193
  readonly channelServerConfigsStore: StateStore<ChannelConfigsState>;
192
194
  blockedUsers: StateStore<BlockedUsersState>;
193
- node: boolean;
194
- options: StreamChatOptions;
195
195
  setUserPromise: ConnectAPIResponse | null;
196
196
  state: ClientState;
197
197
  tokenManager: TokenManager;
198
198
  user?: ClientUser;
199
199
  userAgent?: string;
200
200
  wsBaseURL?: string;
201
- wsConnection: StableWSConnection | null;
201
+ wsConnection: WSConnection;
202
202
  wsPromise: ConnectAPIResponse | null;
203
+ private _wsPromiseSettled = true;
204
+ private _wsConnectId = 0;
205
+ private _resolveWsPromise?: (value: Awaited<ConnectAPIResponse>) => void;
206
+ private _rejectWsPromise?: (reason?: unknown) => void;
203
207
 
208
+ /**
209
+ * Whether the client runs in a browser: the `client.browser` option, else whether `window`
210
+ * exists.
211
+ */
212
+ get browser(): boolean {
213
+ return this.config.getConfig('client')?.browser ?? typeof window !== 'undefined';
214
+ }
215
+ get node(): boolean {
216
+ return !this.browser;
217
+ }
204
218
  get anonymous(): boolean {
205
219
  return this.tokenManager.isAnonymous;
206
220
  }
207
221
  get userId() {
208
222
  return this.user?.id;
209
223
  }
210
- /**
211
- * @deprecated Use `userId` instead.
212
- */
224
+ /** @deprecated Use `userId` instead. */
213
225
  get userID() {
214
226
  return this.user?.id;
215
227
  }
216
- /**
217
- * @deprecated Use `clientId` instead.
218
- */
228
+ /** @deprecated Use `clientId` instead. */
219
229
  get clientID() {
220
230
  return this.clientId;
221
231
  }
@@ -225,19 +235,14 @@ export class StreamChat extends ChatApi {
225
235
  get api() {
226
236
  return this.apiClient;
227
237
  }
228
- insightMetrics: InsightMetrics;
229
- defaultWSTimeout: number;
230
238
  sdkIdentifier?: SdkIdentifier;
231
239
  deviceIdentifier?: DeviceIdentifier;
232
240
  appIdentifier?: AppIdentifier;
233
241
  private cachedUserAgent?: string;
234
242
  readonly messageComposerCache: FixedSizeQueueCache<string, MessageComposer>;
235
243
  /**
236
- * Configuration you register for instances the SDK creates on your behalf — channels, threads,
237
- * composers, and the client's own managers. See `InstanceConfigurationRegistry`.
238
- *
239
- * Not to be confused with {@link channelServerConfigs}, which holds the **server-provided channel
240
- * configs** keyed by cid. This one is yours; that one is the backend's.
244
+ * Configuration registered for the instances the SDK creates (channels, threads, composers, the
245
+ * client's own managers). Not the server-provided channel configs ({@link channelServerConfigs}).
241
246
  */
242
247
  readonly config = new InstanceConfigurationRegistry();
243
248
  /** Teardown for the `'client'` setup function, released by {@link disconnectUser}. */
@@ -246,35 +251,31 @@ export class StreamChat extends ChatApi {
246
251
  /**
247
252
  * Initializes a client.
248
253
  *
249
- * **Only use constructor for advanced usages. It is strongly advised to use `StreamChat.getInstance()` instead of `new StreamChat()` to reduce integration issues due to multiple WebSocket connections.**
254
+ * **Prefer `StreamChat.getInstance()`: a second client opens a second WebSocket connection.**
250
255
  *
251
256
  * @example <caption>initialize the client in user mode</caption>
252
257
  * new StreamChat('api_key')
253
- * @example <caption>initialize the client in user mode with options</caption>
254
- * new StreamChat('api_key', { warmUp: true, timeout: 5000 })
255
- * @example <caption>secret is optional and only used in server side mode</caption>
256
- * new StreamChat('api_key', 'secret', { httpsAgent: customAgent })
258
+ * @example <caption>initialize the client with configuration</caption>
259
+ * new StreamChat('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
257
260
  *
258
261
  * @param key - The API key.
259
- * @param options - Additional options; here you can pass custom options to the axios instance (optional).
260
- * @param options.browser - Enforce the client to be in browser mode (optional).
261
- * @param options.warmUp - If `true`, the client will open a connection as soon as possible to speed up following requests (optional, defaults to `false`).
262
- * @param options.logLevel - Minimum log level for the default sink (optional, defaults to `'info'`).
263
- * @param options.logOptions - Per-scope sink/level overrides for `chatLoggerSystem` (optional).
264
- * @param options.timeout - Request timeout (optional, defaults to `3000`).
265
- * @param options.httpsAgent - Custom `httpsAgent` (optional).
262
+ * @param config - Declarative configuration, the tree `client.config.set()` takes (optional).
263
+ * Applied before anything is built, so it reaches the managers and the options read once at
264
+ * construction (`client.baseURL`, `client.axiosRequestConfig`, `client.notificationManager`).
266
265
  */
267
- constructor(key: string, options: StreamChatOptions = {}) {
268
- // generated client requires ApiClient right away
266
+ constructor(key: string, config?: DeepPartial<InstanceConfigTree>) {
267
+ // The generated base class needs the ApiClient before `this` exists, so it is bound afterwards.
269
268
  super(new ApiClient());
270
- // but ApiClient relies on properties defined here so we set it after (can't pass `this` in super call)
271
269
  this.apiClient.client = this;
272
270
 
273
- // set the key
274
271
  this.key = key;
272
+
273
+ // Seeded first: the options read below come from the `client` slice.
274
+ if (config) this.config.set(config);
275
+ const clientConfig = this.config.getConfig('client');
275
276
  this.listeners = new Map();
276
277
  this.state = new ClientState({ client: this });
277
- // a list of channels to hide ws events from
278
+ // channels to hide ws events from
278
279
  this.mutedChannels = [];
279
280
  this.mutedUsersStore = new StateStore<{ mutedUsers: UserMuteResponse[] }>({
280
281
  mutedUsers: [],
@@ -286,28 +287,17 @@ export class StreamChat extends ChatApi {
286
287
 
287
288
  this.moderation = new Moderation(this);
288
289
 
289
- this.notifications = options?.notifications ?? new NotificationManager();
290
+ this.notifications = clientConfig?.notificationManager ?? new NotificationManager();
290
291
  this.uploadManager = new UploadManager(this);
291
292
 
292
- this.browser = options.browser ?? typeof window !== 'undefined';
293
- this.node = !this.browser;
294
-
295
- this.options = {
296
- warmUp: false,
297
- disableCache: false,
298
- isLocalUnreadCountEnabled: false,
299
- wsUrlParams: new URLSearchParams({}),
300
- ...options,
301
- };
302
-
303
293
  this.axiosInstance = axios.create({
304
294
  timeout: 3000,
305
295
  withCredentials: false,
306
- ...this.options.axiosRequestConfig,
296
+ ...(clientConfig?.axiosRequestConfig as AxiosRequestConfig | undefined),
307
297
  paramsSerializer: axiosParamsSerializer,
308
298
  });
309
299
 
310
- this.setBaseURL(this.options.baseURL || 'https://chat.stream-io-api.com');
300
+ this.setBaseURL(clientConfig?.baseURL || 'https://chat.stream-io-api.com');
311
301
 
312
302
  const streamLocalTestRun = getEnv('STREAM_LOCAL_TEST_RUN');
313
303
  const streamLocalTestHost = getEnv('STREAM_LOCAL_TEST_HOST');
@@ -318,57 +308,48 @@ export class StreamChat extends ChatApi {
318
308
  this.setBaseURL(`http://${streamLocalTestHost}`);
319
309
  }
320
310
 
321
- // WS connection is initialized when setUser is called
322
- this.wsConnection = null;
311
+ // Both before the WebSocket, which subscribes to the network store and drives the ID's
312
+ // lifecycle.
313
+ this.connectionIdManager = new ConnectionIdManager();
314
+ this.networkConnection = new NetworkConnectionObserver({ client: this });
315
+ this.networkConnection.registerSubscriptions();
316
+
317
+ // The socket itself opens in `connectUser`.
318
+ this.wsConnection = new WSConnection({ client: this });
319
+ this.wsConnection.registerSubscriptions();
323
320
  this.wsPromise = null;
324
321
  this.setUserPromise = null;
325
- // keeps a reference to all the channels that are in use
326
- this.activeChannels = {};
327
-
328
- this.persistUserOnConnectionFailure = this.options?.persistUserOnConnectionFailure;
329
322
 
330
- // If its a server-side client, then lets initialize the tokenManager, since token will be
331
- // generated from secret.
332
323
  this.tokenManager = new TokenManager();
333
- this.insightMetrics = new InsightMetrics();
334
-
335
- this.defaultWSTimeout = 15 * 1000;
336
324
 
337
325
  this.messageStore = new EntityStore<LocalMessage>({
338
326
  getEntityId: (message) => message.id,
339
327
  });
328
+ // Before the managers that claim channels in its store.
329
+ this.channelManager = new ChannelManager({ client: this });
340
330
  this.threads = new ThreadManager({ client: this });
341
331
  this.polls = new PollManager({ client: this });
342
- this.channelManager = new ChannelManager({ client: this });
343
332
  this.connectionRecovery = new ConnectionRecoveryManager({ client: this });
344
333
  this.connectionRecovery.registerSubscriptions();
345
334
  this.reminders = new ReminderManager({ client: this });
346
335
  this.messageDeliveryReporter = new MessageDeliveryReporter({ client: this });
347
336
  this.messageComposerCache = new FixedSizeQueueCache<string, MessageComposer>(64);
337
+ // a cached composer, such as a message edit's, keeps the channel it was built with
338
+ this.channelManager.channelStore.addClaim({
339
+ heldBy: () =>
340
+ this.messageComposerCache.values().map((composer) => composer.channel),
341
+ name: 'message-composer-cache',
342
+ });
348
343
 
349
- // Seed the declarative configuration before wiring, so a tree passed via `options.config` reaches
350
- // the managers above. `'client'` is the one key that cannot be configured after construction —
351
- // this registry is born here, so there is no earlier moment for a caller to register anything.
352
- if (this.options.config) this.config.set(this.options.config);
353
- this.initializeManagerConfig();
354
-
355
- // Last statement: everything a setup function might reach now exists. `StateStore.subscribe` fires
356
- // immediately, so a function registered later still applies at once.
344
+ // Last: everything a setup function might reach exists now. Subscribing applies the current
345
+ // configuration at once, so deriving it here too would run every `initializeConfig` twice.
357
346
  this.wireClientConfiguration();
358
347
  }
359
348
 
360
349
  /**
361
- * Subscribes the client's managers to the `'client'` configuration key.
362
- *
363
- * Called by the constructor and again by {@link _setUser}, because {@link disconnectUser} releases this
364
- * subscription to run the setup function's teardown. A client is reusable — `getInstance` hands the same
365
- * object back, and disconnect/connect is the documented multi-user and mobile-background flow — and the
366
- * managers this key configures (`reminders`, `threads`, `messageDeliveryReporter`, `notifications`)
367
- * outlive the user. Without the re-arm the key went permanently dead on the second connect: `setConfig`,
368
- * `setSetupFunction` and `reset` all stopped reaching any manager, silently.
369
- *
370
- * Idempotent through the `unsubscribeClientConfiguration` guard, so the constructor's wiring is not
371
- * duplicated by the first `connectUser`.
350
+ * Subscribes the client's managers to the `'client'` configuration key. Called by the constructor
351
+ * and by {@link _setUser}, because {@link disconnectUser} releases the subscription (to run the
352
+ * setup function's teardown) while the managers outlive the user. Idempotent.
372
353
  */
373
354
  private wireClientConfiguration() {
374
355
  if (this.unsubscribeClientConfiguration) return;
@@ -382,19 +363,17 @@ export class StreamChat extends ChatApi {
382
363
  }
383
364
 
384
365
  /**
385
- * Derives each manager's configuration from package defaults plus the `client` declarative subtree.
386
- * Shared by the constructor and `config.reset()`, so the two cannot drift.
387
- *
388
- * Defaults are spread first, and every manager is written unconditionally, because this is a
389
- * derivation* rather than a patch — the same rule `Channel.initializeConfig` follows. Guarding on
390
- * `if (config?.reminders)` and merging made `reset()` a no-op for this key: the store is cleared
391
- * before instances re-derive, so the guards all failed and the registered values stayed in force.
392
- * It also meant a field *removed* from the tree lingered, which is exactly what a merge cannot express.
366
+ * Derives each manager's configuration from the package defaults plus the `client` subtree. Every
367
+ * manager is written unconditionally: it is a derivation, not a merge, so `config.reset()` and
368
+ * removed fields take effect.
393
369
  */
394
370
  private initializeManagerConfig() {
395
371
  const config = this.config.getConfig('client');
396
372
 
397
373
  this.connectionRecovery.initializeConfig(config?.connectionRecovery);
374
+ // Installs the platform listener named by the slice, falling back to the browser default.
375
+ this.networkConnection.initializeConfig(config?.networkConnection);
376
+ this.wsConnection.initializeConfig(config?.wsConnection);
398
377
  this.reminders.initializeConfig(config?.reminders);
399
378
  this.threads.initializeConfig(config?.threads);
400
379
  this.messageDeliveryReporter.initializeConfig(config?.messageDelivery);
@@ -410,21 +389,10 @@ export class StreamChat extends ChatApi {
410
389
  }
411
390
 
412
391
  /**
413
- * Cache of server-provided channel configuration, keyed by **cid** — a channel's own
414
- * `config_overrides` can make it differ from every other channel of its type, so one entry per
415
- * channel is the only key space that can represent the answer. See {@link _addChannelConfig}.
416
- *
417
- * Read it through {@link Channel.serverConfig} rather than here. Not to be confused with
418
- * {@link config}, which is the configuration *you* register for SDK-created instances.
419
- *
420
- * This is `client.configs` from v9 under a name that says whose configuration it is — the key space is
421
- * unchanged, so a v9 `client.configs[cid]` lookup translates directly. There is deliberately no
422
- * `configs` alias: it read as a sibling of the integrator-facing {@link config} while holding the
423
- * backend's answer, and the two being one letter apart is what made `channel.getConfig()` ambiguous
424
- * enough to rename as well.
425
- *
426
- * Assigning through this setter notifies subscribers; mutating the returned record in place does not.
427
- * Prefer {@link _addChannelConfig}.
392
+ * Cache of server-provided channel configuration, keyed by cid (a channel's `config_overrides`
393
+ * can make it differ from other channels of its type). Read it through
394
+ * {@link Channel.serverConfig}. Assigning through the setter notifies subscribers, mutating the
395
+ * record in place does not (prefer {@link _addChannelConfig}).
428
396
  *
429
397
  * @internal
430
398
  */
@@ -438,32 +406,25 @@ export class StreamChat extends ChatApi {
438
406
  }
439
407
 
440
408
  /**
441
- * Returns a client instance.
442
- *
443
- * This function always returns the same client instance to avoid issues raised by multiple client and WS connections.
409
+ * Returns the shared client instance, so there is only one client and WebSocket connection.
444
410
  *
445
- * **After the first call, the client configuration will not change if the key or options parameters change.**
411
+ * **After the first call, the `key` and `config` parameters are ignored.**
446
412
  *
447
413
  * @example <caption>initialize the client in user mode</caption>
448
414
  * StreamChat.getInstance('api_key')
449
- * @example <caption>initialize the client in user mode with options</caption>
450
- * StreamChat.getInstance('api_key', { timeout: 5000 })
451
- * @example <caption>secret is optional and only used in server side mode</caption>
452
- * StreamChat.getInstance('api_key', 'secret', { httpsAgent: customAgent })
415
+ * @example <caption>initialize the client with configuration</caption>
416
+ * StreamChat.getInstance('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
453
417
  *
454
418
  * @param key - The API key.
455
- * @param options - Additional options; here you can pass custom options to the axios instance (optional).
456
- * @param options.browser - Enforce the client to be in browser mode (optional).
457
- * @param options.warmUp - If `true`, the client will open a connection as soon as possible to speed up following requests (optional, defaults to `false`).
458
- * @param options.logLevel - Minimum log level for the default sink (optional, defaults to `'info'`).
459
- * @param options.logOptions - Per-scope sink/level overrides for `chatLoggerSystem` (optional).
460
- * @param options.timeout - Request timeout (optional, defaults to `3000`).
461
- * @param options.httpsAgent - Custom `httpsAgent` (optional, in Node defaults to `https.agent()`).
419
+ * @param config - Declarative configuration, as for the constructor (optional).
462
420
  * @returns The shared client instance.
463
421
  */
464
- public static getInstance(key: string, options?: StreamChatOptions): StreamChat {
422
+ public static getInstance(
423
+ key: string,
424
+ config?: DeepPartial<InstanceConfigTree>,
425
+ ): StreamChat {
465
426
  if (!StreamChat._instance) {
466
- StreamChat._instance = new StreamChat(key, options);
427
+ StreamChat._instance = new StreamChat(key, config);
467
428
  }
468
429
 
469
430
  return StreamChat._instance as StreamChat;
@@ -477,6 +438,17 @@ export class StreamChat extends ChatApi {
477
438
  this.offlineDb = offlineDBInstance;
478
439
  }
479
440
 
441
+ /**
442
+ * Creates a development token for apps with auth checks disabled. Never use one in production.
443
+ * See {@link DevToken}.
444
+ *
445
+ * @param userId - The ID of the user the token is for.
446
+ * @returns The development token.
447
+ */
448
+ devToken(userId: string) {
449
+ return DevToken(userId);
450
+ }
451
+
480
452
  getAuthType() {
481
453
  return this.anonymous ? 'anonymous' : 'jwt';
482
454
  }
@@ -486,13 +458,11 @@ export class StreamChat extends ChatApi {
486
458
  this.wsBaseURL = this.baseURL.replace('http', 'ws').replace(':3030', ':8800');
487
459
  }
488
460
 
489
- _getConnectionID = () => this.wsConnection?.connectionID;
461
+ _getConnectionID = () => this.connectionIdManager.connectionId;
490
462
 
491
463
  _hasConnectionID = () => Boolean(this._getConnectionID());
492
464
 
493
- /**
494
- * @deprecated Use `client.config.setSetupFunction('messageComposer', fn)`.
495
- */
465
+ /** @deprecated Use `client.config.setSetupFunction('messageComposer', fn)`. */
496
466
  public setMessageComposerSetupFunction = (
497
467
  setupFunction: InstanceSetupState<'messageComposer'>['setupFunction'],
498
468
  ) => {
@@ -500,21 +470,19 @@ export class StreamChat extends ChatApi {
500
470
  };
501
471
 
502
472
  /**
503
- * Sets the current user and opens a WebSocket connection.
473
+ * Sets the current user and opens the WebSocket connection.
504
474
  *
505
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
506
- * @param userTokenOrProvider - A token string or an async provider that returns one.
475
+ * @param user - The user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
476
+ * @param userTokenOrProvider - A token string, or an async provider that resolves to one.
507
477
  * @returns A promise that resolves when the connection is set up.
478
+ * @throws For a different user, unless `disconnectUser()` ran first.
508
479
  */
509
480
  connectUser = async (user: ClientUser, userTokenOrProvider: TokenOrProvider) => {
510
481
  if (!user.id) {
511
482
  throw new Error('The "id" field on the user is missing');
512
483
  }
513
484
 
514
- /**
515
- * Calling connectUser multiple times is potentially the result of a bad integration; however,
516
- * if the user ID remains the same we don't throw an error.
517
- */
485
+ // Repeated calls for the same user warn and return the existing promise.
518
486
  if (this.userId === user.id && this.setUserPromise) {
519
487
  logger
520
488
  .withExtraTags('connectUser')
@@ -530,11 +498,11 @@ export class StreamChat extends ChatApi {
530
498
  );
531
499
  }
532
500
 
533
- if (this.node && !this.options.allowServerSideConnect) {
501
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
534
502
  logger
535
503
  .withExtraTags('connectUser')
536
504
  .warn(
537
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
505
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
538
506
  );
539
507
  }
540
508
 
@@ -543,30 +511,38 @@ export class StreamChat extends ChatApi {
543
511
 
544
512
  const wsPromise = this.openConnection();
545
513
 
546
- this.setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
547
- (result) => result[1], // We only return connection promise;
514
+ const setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
515
+ (result) => result[1], // only the connection promise
548
516
  );
517
+ this.setUserPromise = setUserPromise;
549
518
 
550
519
  try {
551
- return await this.setUserPromise;
520
+ return await setUserPromise;
552
521
  } catch (err) {
553
- if (this.persistUserOnConnectionFailure) {
554
- // cleanup client to allow the user to retry connectUser again
555
- this.closeConnection();
556
- } else {
557
- this.disconnectUser();
522
+ // `disconnectUser()` rejects an in-flight handshake, so clean up only if nothing has taken
523
+ // over: a newer `connectUser()` changes `setUserPromise`; `connectAnonymousUser()` (which
524
+ // never sets it) or a bare `disconnectUser()` changes `userId`.
525
+ if (this.setUserPromise === setUserPromise && this.userId === user.id) {
526
+ if (!this.config.getConfig('client')?.persistUserOnConnectionFailure) {
527
+ // No user is kept: the app is expected to call `connectUser` again.
528
+ this.disconnectUser();
529
+ } else if (!isWSFailure(err as APIError)) {
530
+ // A terminal failure (rejected token, bad API key) will not fix itself: close the socket
531
+ // so `StableWSConnection` stops retrying.
532
+ this.closeConnection();
533
+ }
558
534
  }
559
535
  throw err;
560
536
  }
561
537
  };
562
538
 
563
539
  /**
564
- * Sets the current user and opens a WebSocket connection.
540
+ * Sets the current user and opens the WebSocket connection.
565
541
  *
566
- * @deprecated Use {@link StreamChat.connectUser} instead. Its naming is more consistent with its functionality.
542
+ * @deprecated Use {@link StreamChat.connectUser} instead.
567
543
  *
568
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
569
- * @param userTokenOrProvider - A token string or an async provider that returns one.
544
+ * @param user - The user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
545
+ * @param userTokenOrProvider - A token string, or an async provider that resolves to one.
570
546
  * @returns A promise that resolves when the connection is set up.
571
547
  */
572
548
  setUser = this.connectUser;
@@ -575,34 +551,27 @@ export class StreamChat extends ChatApi {
575
551
  this.tokenManager.setTokenOrProvider(userTokenOrProvider, user);
576
552
 
577
553
  _setUser(user: TokenManagerMinimalUser) {
578
- /**
579
- * This one is used by the frontend. This is a copy of the current user object stored on backend.
580
- * It contains reserved properties and own user properties which are not present in `this._user`.
581
- */
554
+ // Mirrors the backend's copy of the user, with reserved and own-user properties.
582
555
  this.user = user;
583
- // this one is actually used for requests. This is a copy of current user provided to `connectUser` function.
556
+ // The copy given to `connectUser`, used for requests.
584
557
  this._user = { ...user };
585
- // Re-arm the `'client'` key if a previous `disconnectUser` released it. Teardown at disconnect,
586
- // setup at connect — see {@link wireClientConfiguration}.
558
+ // Re-arms the `'client'` key if a previous `disconnectUser` released it.
587
559
  this.wireClientConfiguration();
588
560
  }
589
561
 
590
562
  /**
591
- * Disconnects the WebSocket connection, without removing the user set on client.
592
- * client.closeConnection will not trigger default auto-retry mechanism for reconnection. You need
593
- * to call `client.openConnection` to reconnect to the WebSocket.
563
+ * Closes the WebSocket without removing the user, and without auto-reconnect: call
564
+ * `openConnection` to reconnect. Mainly for mobile: push notifications arrive only while no
565
+ * WebSocket is active, so close on background and reopen on foreground. After an
566
+ * `enableWSFallback` switch it also closes the long-poll, telling the server to close its
567
+ * connection ID.
594
568
  *
595
- * This is mainly useful on mobile side. You can only receive push notifications
596
- * if you don't have an active WebSocket connection.
597
- * So when your app goes to background, you can call `client.closeConnection`.
598
- * And when app comes back to foreground, call `client.openConnection`.
599
- *
600
- * @param timeout - Max number of milliseconds to wait for the WebSocket close event before forcefully assuming
601
- * successful disconnection. See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent (optional).
569
+ * @param timeout - Milliseconds to wait for the WebSocket close event and for the long-poll close
570
+ * request. Defaults to 1s and 2s respectively.
602
571
  */
603
572
  closeConnection = async (timeout?: number) => {
604
- this._resetAIStateOnActiveChannels();
605
- this._markActiveChannelsWatchInterrupted();
573
+ this.channelManager.resetAIStateOnChannels();
574
+ this.channelManager.markChannelsWatchInterrupted();
606
575
 
607
576
  if (this.cleaningIntervalRef != null) {
608
577
  clearInterval(this.cleaningIntervalRef);
@@ -627,9 +596,10 @@ export class StreamChat extends ChatApi {
627
596
  };
628
597
 
629
598
  /**
630
- * Creates a new WebSocket connection with the current user.
599
+ * Opens a WebSocket connection for the current user. After an `enableWSFallback` switch it
600
+ * reconnects the long-poll instead: the client never goes back to the WebSocket.
631
601
  *
632
- * @returns The WebSocket connect promise, or an empty resolved promise if a connection is already active.
602
+ * @returns The connect promise, or `undefined` when a healthy connection already exists.
633
603
  */
634
604
  openConnection = () => {
635
605
  if (!this.userId) {
@@ -645,7 +615,7 @@ export class StreamChat extends ChatApi {
645
615
  return this.wsPromise;
646
616
  }
647
617
 
648
- if (this.wsConnection?.isHealthy && this._hasConnectionID()) {
618
+ if (this.wsConnection?.isHealthy && this.connectionIdManager.connectionId) {
649
619
  logger
650
620
  .withExtraTags('openConnection')
651
621
  .debug('openConnection was called twice; a healthy connection already exists.');
@@ -654,15 +624,63 @@ export class StreamChat extends ChatApi {
654
624
  }
655
625
 
656
626
  this.clientId = `${this.userId}--${randomId()}`;
657
- this.wsPromise = this.connect();
627
+ const wsPromise = this._bindWsPromise(this.connect());
658
628
  this._startCleaning();
659
- return this.wsPromise;
629
+ return wsPromise;
630
+ };
631
+
632
+ /** Rejects the shared `wsPromise` and invalidates any in-flight connect attempt. */
633
+ private _rejectPendingWsPromise = (reason: Error) => {
634
+ if (!this._wsPromiseSettled) {
635
+ // invalidate in-flight attempts so a late settle cannot revive this promise
636
+ this._wsConnectId += 1;
637
+ this._wsPromiseSettled = true;
638
+ // Avoid unhandled promise rejection errors
639
+ this.wsPromise?.catch(() => {
640
+ // noop - real awaiters still observe the rejection
641
+ });
642
+ this._rejectWsPromise?.(reason);
643
+ }
644
+ };
645
+
646
+ /**
647
+ * Keeps a single pending `wsPromise` across close/reopen, so callers already awaiting it are not
648
+ * stranded when `openConnection` starts a new connect.
649
+ */
650
+ private _bindWsPromise = (connectPromise: ConnectAPIResponse): ConnectAPIResponse => {
651
+ const connectId = ++this._wsConnectId;
652
+
653
+ let pending = this.wsPromise;
654
+ if (this._wsPromiseSettled || !pending) {
655
+ this._wsPromiseSettled = false;
656
+ pending = new Promise((resolve, reject) => {
657
+ this._resolveWsPromise = resolve;
658
+ this._rejectWsPromise = reject;
659
+ });
660
+ this.wsPromise = pending;
661
+ }
662
+
663
+ connectPromise.then(
664
+ (value) => {
665
+ if (connectId !== this._wsConnectId) return;
666
+ this._wsPromiseSettled = true;
667
+ this._resolveWsPromise?.(value);
668
+ },
669
+ (error) => {
670
+ if (connectId !== this._wsConnectId) return;
671
+ this._wsPromiseSettled = true;
672
+ this._rejectWsPromise?.(error);
673
+ },
674
+ );
675
+
676
+ return pending;
660
677
  };
678
+
661
679
  /**
662
- * Revokes tokens for a connected user issued before the given time.
680
+ * Revokes the connected user's tokens issued before the given time.
663
681
  *
664
- * @param before - Cutoff date; tokens issued before this are revoked (optional, defaults to the current time).
665
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
682
+ * @param before - Cutoff date; tokens issued before it are revoked (optional). Defaults to now.
683
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
666
684
  * into the request (optional).
667
685
  * @returns The updated users response.
668
686
  */
@@ -687,56 +705,80 @@ export class StreamChat extends ChatApi {
687
705
  /**
688
706
  * Retrieves application settings.
689
707
  *
708
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
709
+ * second argument, as on the generated methods; pass `undefined`.
690
710
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
691
711
  * into the request (optional).
692
- * @returns The application settings response.
712
+ * @returns The application settings response. A failed request is not kept in
713
+ * {@link appSettingsPromise}, so the next call fetches again.
693
714
  */
694
- async getAppSettings(requestOptions?: StreamRequestOptions) {
695
- return await (this.appSettingsPromise = this.getApp(requestOptions));
715
+ async getAppSettings(
716
+ _request?: Record<string, never>,
717
+ requestOptions?: StreamRequestOptions,
718
+ ) {
719
+ const promise = this.getApp(undefined, requestOptions);
720
+ this.appSettingsPromise = promise;
721
+ try {
722
+ return await promise;
723
+ } catch (error) {
724
+ if (this.appSettingsPromise === promise) this.appSettingsPromise = undefined;
725
+ throw error;
726
+ }
696
727
  }
697
728
 
698
729
  /**
699
- * Disconnects the WebSocket and removes the user from client.
730
+ * Disconnects the WebSocket and removes the user and its state.
700
731
  *
701
- * @param timeout - Max number of milliseconds to wait for the WebSocket close event before forcefully assuming
702
- * successful disconnection. See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent (optional).
703
- * @returns The close-connection promise.
732
+ * @param timeout - Passed to {@link closeConnection} (optional).
704
733
  */
705
734
  disconnectUser = (timeout?: number) => {
706
735
  logger.withExtraTags('disconnectUser').info('Disconnecting the client.');
707
736
 
708
- // remove the user specific fields
709
737
  delete this.user;
710
738
  delete this._user;
711
739
 
740
+ const teardownReason = new Error(
741
+ 'Connection was closed because disconnectUser() was called',
742
+ );
743
+
744
+ this._rejectPendingWsPromise(teardownReason);
745
+ this.wsPromise = null;
746
+
712
747
  const closePromise = this.closeConnection(timeout);
748
+ // After starting the close, which reads the connection ID synchronously (the long-poll's close
749
+ // request carries it).
750
+ this.connectionIdManager.rejectConnectionId(teardownReason);
713
751
 
714
- for (const channel of Object.values(this.activeChannels)) {
715
- channel._disconnect();
752
+ // Empties the channel lists (they hold the disconnected user's channels) but keeps them
753
+ // registered: which lists exist is app configuration. Reset first so each list empties in one
754
+ // update.
755
+ this.channelManager.resetPaginatorStates();
756
+ // Disconnects every channel and empties the store, then rethrows the first error a holder
757
+ // threw. Logged, not propagated, so the rest of the logout still runs.
758
+ try {
759
+ this.channelManager.clearChannels();
760
+ } catch (error) {
761
+ logger
762
+ .withExtraTags('disconnectUser')
763
+ .error('Clearing the channels failed during disconnect.', { error });
716
764
  }
717
- // ensure we no longer return inactive channels
718
- this.activeChannels = {};
719
- // reset client state
720
765
  this.state = new ClientState({ client: this });
721
- // reset thread manager
722
766
  this.threads.resetState();
723
- // drop the channels loaded into the channel lists — they belong to the user being disconnected
724
- // and have just been disconnected themselves. The lists stay registered: which lists exist is
725
- // the application's configuration, not user data.
726
- this.channelManager.resetPaginatorStates();
727
- // channel mutes are per-user; leaving them would let `muted` filters resolve against the
728
- // previous user until the next health check replaces them
767
+ // Channel mutes are per-user: stale ones would resolve `muted` filters against the previous
768
+ // user.
729
769
  this.mutedChannels = [];
730
770
  this.uploadManager.reset();
731
771
  this.messageComposerCache.clear();
732
- // Runs the `'client'` setup function's teardown. Cleared so repeated calls cannot double-run it.
772
+ // Runs the `'client'` setup function's teardown. Cleared so repeated calls cannot double-run
773
+ // it.
733
774
  this.unsubscribeClientConfiguration?.();
734
775
  this.unsubscribeClientConfiguration = undefined;
735
776
 
736
- // Since we wipe all user data already, we should reset token manager as well
777
+ // Deferred so the long-poll close can still authenticate; a newer connect may have set the next
778
+ // user and token by then.
737
779
  closePromise
738
780
  .finally(() => {
739
- this.tokenManager.reset();
781
+ if (!this.userId) this.tokenManager.reset();
740
782
  })
741
783
  .catch((err) =>
742
784
  logger
@@ -744,29 +786,23 @@ export class StreamChat extends ChatApi {
744
786
  .error('The close promise rejected during disconnect.', { error: err }),
745
787
  );
746
788
 
747
- // close the WS connection
748
789
  return closePromise;
749
790
  };
750
791
 
751
- /**
752
- *
753
- * @deprecated Please use client.disconnectUser instead.
754
- *
755
- * Disconnects the WebSocket and removes the user from client.
756
- */
792
+ /** @deprecated Use `client.disconnectUser` instead. */
757
793
  disconnect = this.disconnectUser;
758
794
 
759
795
  /**
760
- * Sets an anonymous user and opens a WebSocket connection.
796
+ * Sets an anonymous user and opens the WebSocket connection.
761
797
  *
762
798
  * @returns A promise that resolves when the connection is set up.
763
799
  */
764
800
  connectAnonymousUser = () => {
765
- if (this.node && !this.options.allowServerSideConnect) {
801
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
766
802
  logger
767
803
  .withExtraTags('connectAnonymousUser')
768
804
  .warn(
769
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
805
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
770
806
  );
771
807
  }
772
808
 
@@ -782,9 +818,11 @@ export class StreamChat extends ChatApi {
782
818
  };
783
819
 
784
820
  /**
785
- * Creates a guest user and returns its access token.
821
+ * Creates a guest user.
786
822
  *
787
- * @param args - The guest creation request, plus optional per-request options.
823
+ * @param ...args - `[request, requestOptions]`. `request.user` is the guest user to create;
824
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
825
+ * serialized into the request.
788
826
  * @returns The created guest user and its access token.
789
827
  */
790
828
  override async createGuest(...args: Parameters<ChatApi['createGuest']>) {
@@ -806,14 +844,14 @@ export class StreamChat extends ChatApi {
806
844
  }
807
845
 
808
846
  /**
809
- * Sets up a temporary guest user.
847
+ * Creates a temporary guest user and connects as it.
810
848
  *
811
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
812
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
849
+ * @param user - The guest user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
850
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
813
851
  * into the request (optional).
814
852
  * @returns A promise that resolves when the connection is set up.
815
853
  */
816
- async setGuestUser(user: UserResponse, requestOptions?: StreamRequestOptions) {
854
+ async setGuestUser(user: UserRequest, requestOptions?: StreamRequestOptions) {
817
855
  const response = await this.createGuest({ user }, requestOptions);
818
856
 
819
857
  const {
@@ -840,17 +878,23 @@ export class StreamChat extends ChatApi {
840
878
  * console.log(event.type);
841
879
  * });
842
880
  *
843
- * @param callbackOrString - The event type to listen for, or the callback when listening to all events.
844
- * @param callbackOrNothing - The callback to call when an event type was provided (optional).
881
+ * @param callback - Called with every event.
845
882
  * @returns An object with an `unsubscribe()` method.
846
883
  */
847
884
  on(callback: EventHandler): { unsubscribe: () => void };
848
- on<T extends EventType | string>(
885
+ /**
886
+ * Listens to one event type on all channels and users you're watching.
887
+ *
888
+ * @param eventType - The event type to listen for.
889
+ * @param callback - Called with each event of that type.
890
+ * @returns An object with an `unsubscribe()` method.
891
+ */
892
+ on<T extends EventType>(
849
893
  eventType: T,
850
894
  callback: EventHandler<T>,
851
895
  ): { unsubscribe: () => void };
852
896
  on(
853
- callbackOrString: EventHandler | string,
897
+ callbackOrString: EventHandler | EventType,
854
898
  callbackOrNothing?: EventHandler,
855
899
  ): { unsubscribe: () => void } {
856
900
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
@@ -879,14 +923,19 @@ export class StreamChat extends ChatApi {
879
923
  }
880
924
 
881
925
  /**
882
- * Removes the event handler.
926
+ * Removes a listener for all events.
883
927
  *
884
- * @param callbackOrString - The event type, or the callback when removing an all-events listener.
885
- * @param callbackOrNothing - The callback to remove when an event type was provided (optional).
928
+ * @param callback - The listener to remove.
886
929
  */
887
930
  off(callback: EventHandler): void;
888
- off(eventType: string, callback: EventHandler): void;
889
- off(callbackOrString: EventHandler | string, callbackOrNothing?: EventHandler) {
931
+ /**
932
+ * Removes a listener for one event type.
933
+ *
934
+ * @param eventType - The event type it listens to.
935
+ * @param callback - The listener to remove.
936
+ */
937
+ off<T extends EventType>(eventType: T, callback: EventHandler<T>): void;
938
+ off(callbackOrString: EventHandler | EventType, callbackOrNothing?: EventHandler) {
890
939
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
891
940
  const callback = callbackOrNothing
892
941
  ? callbackOrNothing
@@ -906,23 +955,33 @@ export class StreamChat extends ChatApi {
906
955
  dispatchEvent = (event: Event) => {
907
956
  if (event.received_at == null) event.received_at = nowNs();
908
957
 
909
- // client event handlers
910
958
  const postListenerCallbacks = this._handleClientEvent(event as WSEvent);
911
959
 
912
- // channel event handlers
913
960
  const cid = (event as Extract<Event, { cid?: any }>).cid;
914
- const channel = cid ? this.activeChannels[cid] : undefined;
915
- if (channel) {
916
- channel._handleChannelEvent(event as WSEvent);
961
+ const channel = cid ? this.channelManager.get(cid) : undefined;
962
+ // A disconnected channel (`pendingDisposal`) may stay stored until `releaseUnusedChannels()`.
963
+ // Its handlers would throw at `getClient()`, so they are skipped (its own listeners below still
964
+ // hear it).
965
+ if (channel && !channel.pendingDisposal) {
966
+ channel._handleChannelEvent(event);
917
967
  }
918
968
 
919
969
  this._callClientListeners(event);
920
970
 
921
971
  if (channel) {
922
- channel._callChannelListeners(event as WSEvent);
972
+ channel._callChannelListeners(event);
923
973
  }
924
974
 
925
- postListenerCallbacks.forEach((c) => c());
975
+ // A failing in-memory cleanup must not skip the other callbacks or the offline DB write below.
976
+ for (const callback of postListenerCallbacks) {
977
+ try {
978
+ callback();
979
+ } catch (error) {
980
+ logger
981
+ .withExtraTags('dispatchEvent', event.type)
982
+ .error('A post-listener callback failed.', { error });
983
+ }
984
+ }
926
985
 
927
986
  this.offlineDb?.executeQuerySafely((db) => db.handleEvent({ event }), {
928
987
  method: `handleEvent;${event.type}`,
@@ -930,25 +989,41 @@ export class StreamChat extends ChatApi {
930
989
  };
931
990
 
932
991
  /**
933
- * Updates the members, watchers and read references of the currently active channels that contain this user.
992
+ * Puts `user`'s new object into the members, watchers, own membership and (with `readEntries`)
993
+ * read entries of the channels that list them, in one state update per channel.
934
994
  *
935
- * @param user - The updated user.
995
+ * @param options.readEntries - Also replace the user in read entries, refreshing read receipts.
996
+ * Off for presence changes: receipts never show online status. Defaults to `true`.
936
997
  */
937
- _updateMemberWatcherReferences = (user: UserResponse) => {
998
+ _updateMemberWatcherReferences = (
999
+ user: UserResponse,
1000
+ { readEntries = true }: { readEntries?: boolean } = {},
1001
+ ) => {
938
1002
  const refMap = this.state.userChannelReferences[user.id] || {};
939
1003
  for (const channelId in refMap) {
940
- const channel = this.activeChannels[channelId];
941
- if (channel?.state) {
942
- if (channel.state.members[user.id]) {
943
- channel.state.members[user.id].user = user;
944
- }
945
- if (channel.state.watchers[user.id]) {
946
- channel.state.watchers[user.id] = user;
947
- }
948
- if (channel.state.read[user.id]) {
949
- channel.state.read[user.id].user = user;
950
- }
1004
+ const channel = this.channelManager.get(channelId);
1005
+ if (!channel?.state) continue;
1006
+ const { members, membership, watchers, read } = channel.state.getLatestValue();
1007
+ const member = members[user.id];
1008
+ const readState = readEntries ? read[user.id] : undefined;
1009
+ const hasWatcher = !!watchers[user.id];
1010
+ const isOwnMembership = membership?.user?.id === user.id;
1011
+ if (!member && !hasWatcher && !readState && !isOwnMembership) continue;
1012
+ // The receipts tracker applies a read-state change only with metadata naming the changed
1013
+ // users.
1014
+ if (readState) {
1015
+ channel.messageReceiptsTracker.setPendingReadStoreReconcileMeta({
1016
+ changedUserIds: [user.id],
1017
+ });
951
1018
  }
1019
+ channel.state.partialNext({
1020
+ ...(member && { members: { ...members, [user.id]: { ...member, user } } }),
1021
+ ...(hasWatcher && { watchers: { ...watchers, [user.id]: user } }),
1022
+ ...(isOwnMembership && { membership: { ...membership, user } }),
1023
+ ...(readState && { read: { ...read, [user.id]: { ...readState, user } } }),
1024
+ });
1025
+ // consumed by the tracker's read subscription; cleared in case it isn't subscribed
1026
+ channel.messageReceiptsTracker.setPendingReadStoreReconcileMeta(undefined);
952
1027
  }
953
1028
  };
954
1029
 
@@ -959,54 +1034,42 @@ export class StreamChat extends ChatApi {
959
1034
  _updateUserReferences = this._updateMemberWatcherReferences;
960
1035
 
961
1036
  /**
962
- * Updates the messages from the currently active channels that contain this user, with the updated user object.
1037
+ * Replaces the user's object in the messages of the loaded channels.
963
1038
  *
964
1039
  * @private
965
- *
966
- * @param user - The updated user.
967
1040
  */
968
1041
  _updateUserMessageReferences = (user: UserResponse) => {
969
- // Scan all active channels rather than a user->channel reference map. MessageRequest authors are no
970
- // longer registered as channel references (that registration was removed along with
971
- // `Channel._trackLatestMessage`); `reflectUserUpdate` filters by author id internally, so it is
972
- // a no-op on channels without this user's messages.
973
- // The next step is to have user ItemIndex, where the update would be O(1) complexity
974
- for (const channel of Object.values(this.activeChannels)) {
1042
+ // Scans all loaded channels: `reflectUserUpdate` filters by author ID, so it is a no-op for
1043
+ // channels without this user's messages.
1044
+ for (const channel of this.channelManager.values()) {
975
1045
  if (!channel) continue;
976
1046
 
977
- /** update the messages from this user. */
978
1047
  channel.pinnedMessagesPaginator.reflectUserUpdate(user);
979
1048
  channel.messagePaginator.reflectUserUpdate(user);
980
1049
  }
981
1050
  };
982
1051
 
983
1052
  /**
984
- * Deletes the messages from the currently active channels that contain this user.
985
- *
986
- * If `hardDelete` is `true`, all the content of the message will be stripped down.
987
- * Otherwise, only `message.type` will be set as `'deleted'`.
1053
+ * Deletes the user's messages in the loaded channels: stripped of their content with
1054
+ * `hardDelete`, otherwise marked as deleted. `deletedAt` defaults to now.
988
1055
  *
989
1056
  * @private
990
- *
991
- * @param user - The user whose messages should be deleted.
992
- * @param hardDelete - Whether to fully strip the message content (optional, defaults to `false`).
993
- * @param deletedAt - Timestamp to mark messages as deleted at (optional).
994
1057
  */
995
1058
  _deleteUserMessageReference = (
996
1059
  user: UserResponse,
997
1060
  hardDelete = false,
998
1061
  deletedAt?: LocalMessage['deleted_at'],
999
1062
  ) => {
1000
- // Scan all active channels rather than a user->channel reference map (see
1001
- // `_updateUserMessageReferences`); `applyMessageDeletionForUser` filters by author id internally.
1002
- for (const channel of Object.values(this.activeChannels)) {
1063
+ // Scans all loaded channels; `applyMessageDeletionForUser` filters by author ID.
1064
+ for (const channel of this.channelManager.values()) {
1003
1065
  if (channel) {
1004
- /** deleted the messages from this user. */
1005
- channel.messagePaginator.applyMessageDeletionForUser({
1066
+ const deletedMessages = channel.messagePaginator.applyMessageDeletionForUser({
1006
1067
  userId: user.id,
1007
1068
  hardDelete,
1008
1069
  deletedAt: deletedAt ?? nowNs(),
1009
1070
  });
1071
+ // the server keeps the unread count on a soft bulk delete
1072
+ if (hardDelete) channel._lowerUnreadCountForDeletedMessages(deletedMessages);
1010
1073
  channel.pinnedMessagesPaginator.applyMessageDeletionForUser({
1011
1074
  userId: user.id,
1012
1075
  hardDelete,
@@ -1016,16 +1079,7 @@ export class StreamChat extends ChatApi {
1016
1079
  }
1017
1080
  };
1018
1081
 
1019
- /**
1020
- * Handle the following user-related events:
1021
- * - `user.presence.changed`
1022
- * - `user.updated`
1023
- * - `user.deleted`
1024
- *
1025
- * @private
1026
- *
1027
- * @param event - The user event.
1028
- */
1082
+ /** @private */
1029
1083
  _handleUserEvent = (
1030
1084
  event: Extract<
1031
1085
  WSEvent,
@@ -1036,13 +1090,12 @@ export class StreamChat extends ChatApi {
1036
1090
  return;
1037
1091
  }
1038
1092
 
1039
- /** update the client.state with any changes to users */
1040
1093
  if (event.type === 'user.presence.changed' || event.type === 'user.updated') {
1041
1094
  if (event.user.id === this.userId) {
1042
1095
  const user = { ...this.user } as NonNullable<StreamChat['user']>;
1043
1096
  const _user = { ...this._user } as NonNullable<StreamChat['_user']>;
1044
1097
 
1045
- // Remove deleted properties from user objects.
1098
+ // Drop properties absent from the event, except own-user-only ones.
1046
1099
  for (const key in this.user) {
1047
1100
  if (key in event.user || isOwnUserBaseProperty(key)) {
1048
1101
  continue;
@@ -1054,7 +1107,7 @@ export class StreamChat extends ChatApi {
1054
1107
  delete _user[deleteKey];
1055
1108
  }
1056
1109
 
1057
- /** Updating only available properties in _user object. */
1110
+ // Update only the properties `_user` already has.
1058
1111
  for (const key in _user) {
1059
1112
  const updateKey = key as keyof typeof _user;
1060
1113
 
@@ -1069,7 +1122,9 @@ export class StreamChat extends ChatApi {
1069
1122
  }
1070
1123
 
1071
1124
  this.state.updateUser(event.user);
1072
- this._updateMemberWatcherReferences(event.user);
1125
+ this._updateMemberWatcherReferences(event.user, {
1126
+ readEntries: event.type === 'user.updated',
1127
+ });
1073
1128
  }
1074
1129
 
1075
1130
  if (event.type === 'user.updated') {
@@ -1089,7 +1144,7 @@ export class StreamChat extends ChatApi {
1089
1144
  }
1090
1145
  };
1091
1146
 
1092
- _handleClientEvent(event: WSEvent | ConnectedEvent) {
1147
+ _handleClientEvent(event: WSEvent) {
1093
1148
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1094
1149
  const client = this;
1095
1150
  const postListenerCallbacks = [];
@@ -1113,7 +1168,7 @@ export class StreamChat extends ChatApi {
1113
1168
  client.user = event.me;
1114
1169
  client.state.updateUser(event.me);
1115
1170
  client.mutedChannels = event.me.channel_mutes;
1116
- client._reflectMutedChannelsToActiveChannels();
1171
+ client.channelManager.reflectMutedChannels();
1117
1172
  client.mutedUsers = event.me.mutes;
1118
1173
  client.blockedUsers.partialNext({ userIds: event.me.blocked_user_ids ?? [] });
1119
1174
  }
@@ -1125,7 +1180,7 @@ export class StreamChat extends ChatApi {
1125
1180
 
1126
1181
  if (event.type === 'notification.channel_mutes_updated' && event.me?.channel_mutes) {
1127
1182
  this.mutedChannels = event.me.channel_mutes;
1128
- this._reflectMutedChannelsToActiveChannels();
1183
+ this.channelManager.reflectMutedChannels();
1129
1184
  }
1130
1185
 
1131
1186
  if (event.type === 'notification.mutes_updated' && event.me?.mutes) {
@@ -1133,9 +1188,8 @@ export class StreamChat extends ChatApi {
1133
1188
  }
1134
1189
 
1135
1190
  if (event.type === 'notification.mark_read' && event.unread_channels === 0) {
1136
- Object.values(this.activeChannels).forEach((channel) => {
1137
- // resets `read[userId].unread_messages`, which is what the unread badge reads, so it does
1138
- // not stay stale.
1191
+ this.channelManager.values().forEach((channel) => {
1192
+ // Resets `read[userId].unread_messages`, which the unread badge reads.
1139
1193
  if (!channel._setOwnUnreadCount(0)) return;
1140
1194
  // the event may name no channel (mark-all-read), but here we know which ones changed
1141
1195
  this.channelManager.dropFromUnmatchedLists(channel);
@@ -1149,83 +1203,44 @@ export class StreamChat extends ChatApi {
1149
1203
  ) {
1150
1204
  const { cid } = event;
1151
1205
  client.state.deleteAllChannelReference(cid);
1152
- this.activeChannels[event.cid]?._disconnect();
1206
+ const ended = this.channelManager.get(cid);
1207
+ ended?.disconnect();
1153
1208
 
1154
1209
  postListenerCallbacks.push(() => {
1155
- if (!cid) return;
1156
-
1157
- delete this.activeChannels[cid];
1210
+ // Only the instance disconnected above: a listener that got the channel again keeps its
1211
+ // fresh instance (`ensure()` replaces a disposed one).
1212
+ if (ended && this.channelManager.get(cid) === ended) {
1213
+ this.channelManager.removeChannel(cid);
1214
+ }
1158
1215
  });
1159
1216
  }
1160
1217
 
1161
- // Current user removed from a channel: evict it like channel.deleted so
1162
- // connection recovery won't re-watch it and no further events reach it (#2599).
1163
- // Type-agnostic. We skip deleteAllChannelReference (unlike deletion) since
1164
- // the channel still exists for its remaining members.
1218
+ // Current user removed from a channel: evict it like channel.deleted so connection recovery
1219
+ // does not re-watch it. `deleteAllChannelReference` is skipped: the channel still
1220
+ // exists for its other members.
1165
1221
  if (event.type === 'notification.removed_from_channel' && event.cid) {
1166
1222
  const { cid } = event;
1167
- this.activeChannels[cid]?._disconnect();
1223
+ const ended = this.channelManager.get(cid);
1224
+ ended?.disconnect();
1168
1225
 
1169
1226
  postListenerCallbacks.push(() => {
1170
- delete this.activeChannels[cid];
1227
+ // only the instance disconnected above, as for channel.deleted
1228
+ if (ended && this.channelManager.get(cid) === ended) {
1229
+ this.channelManager.removeChannel(cid);
1230
+ }
1171
1231
  });
1172
1232
  }
1173
1233
 
1174
1234
  return postListenerCallbacks;
1175
1235
  }
1176
1236
 
1177
- /**
1178
- * Fans the client-owned `mutedChannels` out to every active channel's reactive `state.muteStatus`.
1179
- * Each channel republishes only when its own mute status actually changed, so this stays cheap on
1180
- * the frequent `health.check` path.
1181
- */
1182
- _reflectMutedChannelsToActiveChannels() {
1183
- for (const cid in this.activeChannels) {
1184
- this.activeChannels[cid]?._syncMuteStatus();
1185
- }
1186
- }
1187
-
1188
- /**
1189
- * Resets the AI indicator state to `Idle` on every active channel. Invoked from `closeConnection`
1190
- * as it's a deliberate shutdown and will not natively trigger a WS event.
1191
- */
1192
- _resetAIStateOnActiveChannels() {
1193
- for (const cid in this.activeChannels) {
1194
- this.activeChannels[cid]?.state.resetAIState();
1195
- }
1196
- }
1197
-
1198
- /**
1199
- * Demotes every actively-watched channel to `WasWatching`. The server keys watches by connection
1200
- * ID, so losing the socket ends every watch this client held — a reconnect issues a NEW id and the
1201
- * channels have to be re-queried to watch again. `WasWatching` is what records that they should be.
1202
- *
1203
- * Only `Watching` is demoted: a channel the consumer stopped on purpose, or one that was torn
1204
- * down, stays `NotWatching` and must not be resurrected by a reconnect.
1205
- *
1206
- * Invoked from two places, because neither covers the other: `StableWSConnection._setHealth(false)`
1207
- * for an abnormal close/error (immediately — NOT via the `connection.changed` event, which is
1208
- * 5s-debounced when going offline and is skipped entirely on a quick flap, both of which would
1209
- * leave the status lying), and `closeConnection()` for a deliberate shutdown (e.g. mobile
1210
- * backgrounding), which sets `isHealthy` directly and so never reaches `_setHealth`.
1211
- */
1212
- _markActiveChannelsWatchInterrupted() {
1213
- for (const cid in this.activeChannels) {
1214
- const channel = this.activeChannels[cid];
1215
- if (channel?.watchStatus === ChannelWatchStatus.Watching) {
1216
- channel.watchStatus = ChannelWatchStatus.WasWatching;
1217
- }
1218
- }
1219
- }
1220
-
1221
1237
  _muteStatus(cid: string): ChannelMuteStatus {
1222
1238
  let muteStatus: ChannelMuteStatus | undefined;
1223
1239
  for (let i = 0; i < this.mutedChannels.length; i++) {
1224
1240
  const mute = this.mutedChannels[i];
1225
1241
  if (mute.channel?.cid === cid) {
1226
1242
  muteStatus = {
1227
- // `expires` is a wire timestamp, so it compares directly against the local clock in the
1228
- // same unit. Comparing it against `Date.now()` would make every expiry look far future.
1243
+ // `expires` is in unix nanoseconds: compare it against `nowNs()`, not `Date.now()`.
1229
1244
  muted: mute.expires != null ? mute.expires > nowNs() : true,
1230
1245
  createdAt: mute.created_at ?? nowNs(),
1231
1246
  expiresAt: mute.expires ?? null,
@@ -1246,37 +1261,42 @@ export class StreamChat extends ChatApi {
1246
1261
  }
1247
1262
 
1248
1263
  _callClientListeners = (event: Event) => {
1249
- const allSet = this.listeners.get('all');
1250
- const targetSet = this.listeners.get(event.type);
1264
+ // Snapshot first: a listener subscribed while handling an event must not be invoked for it.
1265
+ const listeners = [
1266
+ ...(this.listeners.get('all') ?? []),
1267
+ ...(this.listeners.get(event.type) ?? []),
1268
+ ];
1251
1269
 
1252
- [allSet, targetSet].forEach((set) =>
1253
- set?.forEach((handleEvent) => handleEvent(event)),
1254
- );
1270
+ for (const listener of listeners) {
1271
+ invokeEventListener(listener, event, logger);
1272
+ }
1255
1273
  };
1256
1274
 
1257
1275
  /**
1258
- * Settles the connect promises after a successful reconnect, so the `await this.wsPromise` gates
1259
- * spread across the client stop resolving against a superseded (possibly rejected) attempt.
1260
- *
1261
- * Called by `StableWSConnection._reconnect()`. Recovery itself is owned by
1262
- * {@link ConnectionRecoveryManager}, which subscribes to the connection lifecycle and so covers
1263
- * every reconnect path — including `closeConnection()` → `openConnection()` (mobile backgrounding),
1264
- * which never reaches `_reconnect()` at all.
1276
+ * Settles the connect promises after a successful reconnect, so a held `wsPromise` /
1277
+ * `setUserPromise` stops resolving against a superseded (possibly rejected) attempt. Called by
1278
+ * `StableWSConnection._reconnect()` and `WSConnectionFallback.connect(true)`. Recovery itself
1279
+ * belongs to {@link ConnectionRecoveryManager}.
1265
1280
  *
1266
1281
  * @internal
1267
1282
  */
1268
1283
  _settleConnectPromises = () => {
1269
1284
  logger
1270
1285
  .withExtraTags('_settleConnectPromises')
1271
- .info(`Connection re-established with connection ID ${this._getConnectionID()}.`);
1286
+ .info(
1287
+ `Connection re-established with connection ID ${this.connectionIdManager.connectionId}.`,
1288
+ );
1272
1289
 
1273
- this.wsPromise = Promise.resolve();
1290
+ // After a failed connect (e.g. `persistUserOnConnectionFailure: true`) recovery must flip
1291
+ // `wsPromise` from rejected to resolved, or calls waiting on it fail. An unsettled promise is
1292
+ // left to the connect sequence.
1293
+ if (this._wsPromiseSettled) {
1294
+ this.wsPromise = Promise.resolve();
1295
+ }
1274
1296
  this.setUserPromise = Promise.resolve();
1275
1297
  };
1276
1298
 
1277
- /**
1278
- * @private
1279
- */
1299
+ /** @private */
1280
1300
  async connect() {
1281
1301
  if (!this.userId || !this._user) {
1282
1302
  throw Error(
@@ -1290,56 +1310,24 @@ export class StreamChat extends ChatApi {
1290
1310
  throw Error('Property clientId is not set');
1291
1311
  }
1292
1312
 
1293
- if (!this.wsConnection && (this.options.warmUp || this.options.enableInsights)) {
1294
- this._sayHi();
1295
- }
1296
- // The StableWSConnection handles all the reconnection logic.
1297
- if (this.options.wsConnection && this.node) {
1298
- // Intentionally avoiding adding ts generics on wsConnection in options since its only useful for unit test purpose.
1299
- (this.options.wsConnection as unknown as StableWSConnection).setClient(this);
1300
- this.wsConnection = this.options.wsConnection as unknown as StableWSConnection;
1301
- } else {
1302
- this.wsConnection = new StableWSConnection({
1303
- client: this,
1304
- });
1305
- }
1306
-
1307
- return await this.wsConnection.connect(this.defaultWSTimeout);
1313
+ // `wsConnection` owns the socket, the long-poll fallback (`enableWSFallback`), reconnection and
1314
+ // the connect timeout.
1315
+ return await this.wsConnection.connect();
1308
1316
  }
1309
1317
 
1310
1318
  /**
1311
- * Checks connectivity with the server for warmup purposes.
1312
- *
1313
- * @private
1314
- */
1315
- _sayHi() {
1316
- const client_request_id = randomId();
1317
- const opts = { headers: { 'x-client-request-id': client_request_id } };
1318
- this.api.doAxiosRequest('get', this.baseURL + '/hi', null, opts).catch((e) => {
1319
- if (this.options.enableInsights) {
1320
- postInsights('http_hi_failed', {
1321
- api_key: this.key,
1322
- err: e,
1323
- client_request_id,
1324
- });
1325
- }
1326
- });
1327
- }
1328
-
1329
- /**
1330
- * Queries users and watches user presence.
1319
+ * Queries users and stores them in `client.state.users`. Watches presence only when
1320
+ * `request.payload.presence` is set.
1331
1321
  *
1332
1322
  * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts
1333
- * MongoDB-style filter conditions, sort directions (e.g. `[{ field: 'last_active', direction: -1 }]`),
1334
- * and options such as `presence`. `requestOptions` carries per-request options such as an
1335
- * abort `signal` and is never serialized into the request.
1323
+ * MongoDB-style filter conditions, sort directions (e.g.
1324
+ * `[{ field: 'last_active', direction: -1 }]`), and options such as `presence`.
1325
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1326
+ * serialized into the request.
1336
1327
  * @returns The user query response.
1337
1328
  */
1338
1329
  override async queryUsers(...args: Parameters<ChatApi['queryUsers']>) {
1339
1330
  const [request, requestOptions] = args;
1340
- // Make sure we wait for the connect promise if there is a pending one
1341
- await this.wsPromise;
1342
-
1343
1331
  const data = await super.queryUsers(request ?? {}, requestOptions);
1344
1332
  this.state.updateUsers(data.users);
1345
1333
 
@@ -1347,19 +1335,42 @@ export class StreamChat extends ChatApi {
1347
1335
  }
1348
1336
 
1349
1337
  /**
1350
- * Queries channels and returns the full API response including top-level metadata such as
1351
- * `predefined_filter`.
1338
+ * Stops watching a channel on this client's connection. It carries no `watch` flag, but it waits
1339
+ * for the connection ID like a watching request (through a handshake or reconnect, until the
1340
+ * caller's abort signal fires) and throws when there is no connection and none is being
1341
+ * established.
1352
1342
  *
1353
- * This exists as a compatibility bridge, as changing `queryChannelsRequest()` to return
1354
- * `QueryChannelsResponse` would be a breaking change because it currently returns
1355
- * only the channel list. In the next major release, the request/response APIs should
1356
- * be consolidated so callers can access the full response through the primary API.
1343
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams` identifies the channel
1344
+ * (`{ type, id }`); `request.connection_id` is replaced by this client's connection ID.
1345
+ * @returns The server response.
1346
+ */
1347
+ override async stopWatchingChannel(
1348
+ ...args: Parameters<ChatApi['stopWatchingChannel']>
1349
+ ) {
1350
+ const [pathParams, request, requestOptions] = args;
1351
+ const signal = requestOptions?.signal;
1352
+ const connectionId = await this.connectionIdManager.getConnectionId(
1353
+ // A signal revived from the offline DB has lost `addEventListener`.
1354
+ typeof signal?.addEventListener === 'function' ? signal : undefined,
1355
+ );
1356
+
1357
+ return super.stopWatchingChannel(
1358
+ pathParams,
1359
+ { ...request, connection_id: connectionId },
1360
+ requestOptions,
1361
+ );
1362
+ }
1363
+
1364
+ /**
1365
+ * Queries channels and returns the raw API response. See {@link queryChannelsAndHydrate} for
1366
+ * `Channel` instances.
1357
1367
  *
1358
1368
  * @param ...args - `[request, requestOptions]`. The optional `request` accepts MongoDB-style
1359
1369
  * filter conditions, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`), and
1360
- * options such as `predefined_filter`, `filter_values`, and `sort_values`. `requestOptions`
1361
- * carries per-request options such as an abort `signal` and is never serialized into the request.
1362
- * @returns The full query channels response.
1370
+ * options such as `predefined_filter`, `filter_values`, and `sort_values`. `state`, `watch` and
1371
+ * `presence` default to `true`, `true` and `false`. `requestOptions` carries per-request
1372
+ * options such as an abort `signal` and is never serialized into the request.
1373
+ * @returns The full query channels response, including metadata such as `predefined_filter`.
1363
1374
  */
1364
1375
  override async queryChannels(...args: Parameters<ChatApi['queryChannels']>) {
1365
1376
  const [request, requestOptions] = args;
@@ -1369,14 +1380,6 @@ export class StreamChat extends ChatApi {
1369
1380
  presence: false,
1370
1381
  };
1371
1382
 
1372
- // Make sure we wait for the connect promise if there is a pending one
1373
- await this.wsPromise;
1374
-
1375
- // TODO: probably serverside only thing, remove at some point
1376
- if (!this._hasConnectionID()) {
1377
- defaultOptions.watch = false;
1378
- }
1379
-
1380
1383
  const {
1381
1384
  predefined_filter,
1382
1385
  filter_values,
@@ -1385,7 +1388,7 @@ export class StreamChat extends ChatApi {
1385
1388
  ...restOptions
1386
1389
  } = request ?? {};
1387
1390
 
1388
- // Build payload based on whether we're using a predefined filter or traditional filters
1391
+ // With a predefined filter, `filter_conditions` is not sent.
1389
1392
  const payload: QueryChannelsRequest = predefined_filter
1390
1393
  ? {
1391
1394
  predefined_filter,
@@ -1400,35 +1403,29 @@ export class StreamChat extends ChatApi {
1400
1403
  ...restOptions,
1401
1404
  };
1402
1405
 
1406
+ // `ApiClient` waits for a connection ID only when the payload sets `watch` or `presence`.
1403
1407
  return await super.queryChannels(payload, requestOptions);
1404
1408
  }
1405
1409
 
1406
1410
  /**
1407
- * Queries channels and hydrates them into `Channel` instances on this client.
1408
- *
1409
- * Use the inherited `queryChannels()` from `ChatApi` when only the raw API response
1410
- * is needed; this method wraps it with state hydration, `channels.queried` dispatch,
1411
- * and offline-db sync.
1411
+ * Queries channels and hydrates them into `Channel` instances on this client, dispatching
1412
+ * `channels.queried` and syncing the offline DB. Use `queryChannels()` for the raw API response.
1412
1413
  *
1413
1414
  * @param options - The query channels request payload (optional). Accepts MongoDB-style filter
1414
1415
  * conditions, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`), and options
1415
1416
  * such as `predefined_filter`, `filter_values`, and `sort_values`.
1416
- * @param stateOptions - Options that only affect state management and aren't sent in the request
1417
- * (optional, defaults to `{}`).
1418
- * @param stateOptions.skipInitialization - Skips the initialization of the state for the
1419
- * channels matching the IDs in the list (optional).
1420
- * @param stateOptions.skipHydration - Skips returning the channels as instances of the `Channel`
1421
- * class and instead returns the raw query response (optional).
1422
- * @param stateOptions.withResponse - Returns the full query response with hydrated channels.
1423
- * This is a compatibility bridge for internal callers that need response-level metadata while
1424
- * the default return value remains `Channel[]` (optional).
1425
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1417
+ * @param stateOptions - Options that only affect state management and are not sent in the
1418
+ * request. Defaults to `{}`.
1419
+ * @param stateOptions.skipHydration - Not read: it has no effect.
1420
+ * @param stateOptions.withResponse - Returns the full query response (with hydrated `channels`)
1421
+ * instead of `Channel[]`.
1422
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1426
1423
  * into the request (optional).
1427
1424
  * @returns The hydrated channel list, or the full response when `withResponse` is `true`.
1428
1425
  */
1429
1426
  async queryChannelsAndHydrate(
1430
- options?: QueryChannelsRequest,
1431
- stateOptions?: ChannelStateOptions & { withResponse: true },
1427
+ options: QueryChannelsRequest | undefined,
1428
+ stateOptions: ChannelStateOptions & { withResponse: true },
1432
1429
  requestOptions?: StreamRequestOptions,
1433
1430
  ): Promise<QueryChannelsResponseWithChannels>;
1434
1431
  async queryChannelsAndHydrate(
@@ -1441,13 +1438,10 @@ export class StreamChat extends ChatApi {
1441
1438
  stateOptions: ChannelStateOptions = {},
1442
1439
  requestOptions?: StreamRequestOptions,
1443
1440
  ): Promise<Channel[] | QueryChannelsResponseWithChannels> {
1444
- // TODO(perf/cleanup): prefer a `memberIds` snapshot over `headItems.map` here too — see the
1445
- // matching TODO in channel.query() for the full rationale.
1446
- const candidateIdsByCid = new Map<string, ReadonlySet<string>>();
1447
- for (const cid of Object.keys(this.activeChannels)) {
1448
- const head = this.activeChannels[cid]?.messagePaginator?.headItems;
1449
- if (head?.length)
1450
- candidateIdsByCid.set(cid, new Set(head.map((message) => message.id)));
1441
+ const headIntervalItemIdsAtRequestByCid = new Map<string, ReadonlySet<string>>();
1442
+ for (const channel of this.channelManager.values()) {
1443
+ const idsAtRequest = channel.messagePaginator?.getHeadIntervalItemIdsAtRequest();
1444
+ if (idsAtRequest) headIntervalItemIdsAtRequestByCid.set(channel.cid, idsAtRequest);
1451
1445
  }
1452
1446
  const queryChannelsResponse = await this.queryChannels(options, requestOptions);
1453
1447
  const channels = queryChannelsResponse.channels;
@@ -1466,11 +1460,11 @@ export class StreamChat extends ChatApi {
1466
1460
  });
1467
1461
  }
1468
1462
 
1469
- const hydratedChannels = this.hydrateActiveChannels(
1463
+ const hydratedChannels = this.hydrateChannels(
1470
1464
  channels,
1471
1465
  stateOptions,
1472
1466
  options,
1473
- candidateIdsByCid,
1467
+ headIntervalItemIdsAtRequestByCid,
1474
1468
  );
1475
1469
 
1476
1470
  if (stateOptions.withResponse) {
@@ -1484,21 +1478,18 @@ export class StreamChat extends ChatApi {
1484
1478
  }
1485
1479
 
1486
1480
  /**
1487
- * Queries reactions for a message and hydrates any cached offline reactions before the network
1488
- * request.
1481
+ * Queries a message's reactions. On the first page, cached offline reactions are dispatched
1482
+ * (`offline_reactions.queried`) before the network request.
1489
1483
  *
1490
- * @param request - The query reactions request payload, including the target message ID,
1491
- * MongoDB-style filters, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`),
1492
- * and pagination options.
1493
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1494
- * into the request (optional).
1484
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the target message
1485
+ * ID; `request` carries MongoDB-style filters, sort directions (e.g.
1486
+ * `[{ field: 'created_at', direction: -1 }]`) and pagination options; `requestOptions` carries
1487
+ * per-request options such as an abort `signal` and is never serialized into the request.
1495
1488
  * @returns The query reactions response.
1496
1489
  */
1497
- async queryReactionsAndHydrate(
1498
- request: QueryReactionsRequestWithId,
1499
- requestOptions?: StreamRequestOptions,
1500
- ) {
1501
- const { filter, next, id: messageId, sort, limit } = request;
1490
+ async queryReactionsAndHydrate(...args: Parameters<ChatApi['queryReactions']>) {
1491
+ const [{ id: messageId }, request] = args;
1492
+ const { filter, next, sort, limit } = request ?? {};
1502
1493
 
1503
1494
  if (this.offlineDb?.getReactions && !next) {
1504
1495
  try {
@@ -1522,84 +1513,83 @@ export class StreamChat extends ChatApi {
1522
1513
  }
1523
1514
  }
1524
1515
 
1525
- // Make sure we wait for the connect promise if there is a pending one
1526
- await this.wsPromise;
1527
-
1528
- return await this.queryReactions(request, requestOptions);
1516
+ return await this.queryReactions(...args);
1529
1517
  }
1530
1518
 
1531
- hydrateActiveChannels(
1519
+ hydrateChannels(
1532
1520
  channelsFromApi: ChannelStateResponseFields[] = [],
1533
1521
  stateOptions: ChannelStateOptions = {},
1534
1522
  queryChannelsOptions?: ChannelOptions,
1535
- candidateIdsByCid?: Map<string, ReadonlySet<string>>,
1523
+ headIntervalItemIdsAtRequestByCid?: Map<string, ReadonlySet<string>>,
1536
1524
  ) {
1537
- const { skipInitialization, offlineMode = false } = stateOptions;
1525
+ const { offlineMode = false } = stateOptions;
1538
1526
  const channels: Channel[] = [];
1539
1527
 
1540
1528
  for (const channelState of channelsFromApi) {
1541
1529
  if (!channelState.channel) continue;
1542
1530
 
1543
1531
  this._addChannelConfig(channelState.channel);
1544
- const c = this.channel(channelState.channel.type, channelState.channel.id);
1545
- const previousData = c.data;
1532
+ const c = this.channelManager.ensure({
1533
+ type: channelState.channel.type,
1534
+ id: channelState.channel.id,
1535
+ });
1546
1536
  c.data = channelState.channel;
1547
- c.state.syncStateFromChannelData(c.data, previousData);
1548
- c.offlineMode = offlineMode;
1549
- c.initialized = !offlineMode;
1550
- // Same precedence `queryChannels` applies to the request: an explicit caller choice wins,
1551
- // otherwise we watch only if there is a connection to watch on. Offline hydration populates
1552
- // state without a live watch, so it never counts - and a query that did not watch leaves the
1553
- // status untouched (it neither starts nor ends a watch).
1554
- if (!offlineMode && (queryChannelsOptions?.watch ?? this._hasConnectionID())) {
1537
+ // A live result initializes the channel; one restored from the offline database doesn't.
1538
+ c.state.partialNext(
1539
+ offlineMode
1540
+ ? { initialized: false, offlineMode: true }
1541
+ : { initialized: true, offlineMode: false },
1542
+ );
1543
+ // Unless events were arriving before this response, the loaded messages may lack newer ones.
1544
+ const wasWatching = c.watchStatus === ChannelWatchStatus.Watching;
1545
+ // An explicit `watch` choice wins, otherwise watch only on a healthy socket
1546
+ // (`hydrateChannels` is public, so there may be no gated request behind it). Offline
1547
+ // hydration never counts, and a query that did not watch leaves the status untouched.
1548
+ if (!offlineMode && (queryChannelsOptions?.watch ?? this.wsConnection.isHealthy)) {
1555
1549
  c.watchStatus = ChannelWatchStatus.Watching;
1556
1550
  }
1557
1551
  c.push_preferences = channelState.push_preferences;
1558
1552
 
1559
- const willInitialize =
1560
- skipInitialization === undefined ||
1561
- !skipInitialization.includes(channelState.channel.id);
1562
1553
  const requestedPageSize =
1563
1554
  queryChannelsOptions?.message_limit ??
1564
1555
  DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE;
1565
1556
 
1566
- // Seed the paginator BEFORE _initializeState, which hydrates read state and (via
1567
- // MessageReceiptsTracker) resolves read/delivered cursors against this paginator. Seeding
1568
- // first guarantees the tracker sees a populated timeline; a later async seed would run after
1569
- // the reconcile and mislabel delivery status.
1570
- //
1571
- // Skip the re-seed when this (shared) channel's paginator is already loaded AND the user has
1572
- // jumped to an older window (active interval is not the head): a first-page re-seed forces the
1573
- // newest page to merge into that jumped interval across the gap (missing messages in the
1574
- // middle). A cold paginator, or one still at the head (offline/at-latest), re-seeds normally so
1575
- // cursors/hasMoreTail get (re)derived and pagination keeps working.
1576
- // Also skip the re-seed for an ACTIVE (on-screen) channel: its own `channel.reload()` owns the
1577
- // loaded window (up to 100 msgs), so a 25-msg list re-seed here is a redundant second update
1578
- // that could perturb the fuller window. (Inert until a UI SDK calls `channel.activate()`.)
1579
- if (
1580
- willInitialize &&
1581
- !c.active &&
1582
- (!c.messagePaginator.isInitialized || c.messagePaginator.isActiveIntervalAtHead)
1583
- ) {
1584
- c.messagePaginator.seedFirstPageSync(
1557
+ // Place the page before _initializeState applies the read state, which reads the loaded
1558
+ // messages: read and delivery positions that come without a message id are looked up among
1559
+ // them (see `Channel.runChannelQuery`). Not for an active channel, whose own
1560
+ // `channel.reload()` owns its message list (see `Channel.activate()`).
1561
+ const placesNewestPage = !c.active;
1562
+ let placedFirstPage = false;
1563
+ if (placesNewestPage) {
1564
+ // The response's `last_message_at` first, so the paginator can tell whether the page
1565
+ // reaches it.
1566
+ c.messagePaginator.setQueriedLatestMessageAt(
1567
+ channelState.channel?.last_message_at,
1568
+ );
1569
+ placedFirstPage = c.messagePaginator.placeExternalNewestPage(
1585
1570
  channelState.messages.map(formatMessage),
1586
- requestedPageSize,
1587
- undefined,
1588
- { reconcile: true, candidateIds: candidateIdsByCid?.get(c.cid) },
1571
+ {
1572
+ headIntervalItemIdsAtRequest: headIntervalItemIdsAtRequestByCid?.get(c.cid),
1573
+ requestedLimit: requestedPageSize,
1574
+ },
1589
1575
  );
1590
1576
  }
1591
1577
 
1592
- if (skipInitialization === undefined) {
1593
- c._initializeState(channelState);
1594
- } else if (!skipInitialization.includes(channelState.channel.id)) {
1595
- // The paginators are (re)seeded above and via _initializeState → seedFirstPageSync.
1596
- c._initializeState(channelState);
1578
+ // The message list's page is placed above; the pinned list's comes with _initializeState.
1579
+ // An active channel takes the response's members, read state and pinned messages as well:
1580
+ // they are newer than the ones it holds.
1581
+ c._initializeState(channelState);
1582
+ // from the read state the response brought, as `channel.watch()` does
1583
+ if (placedFirstPage) c.messagePaginator.seedUnreadSnapshot();
1584
+ // Unless the newest page was placed, which brings the interval up to date, the head interval
1585
+ // is checked against this response's `last_message_at`, as `Channel.requestChannelState` does
1586
+ // for a channel query; an on-screen channel is left to its own `channel.reload()`, as above.
1587
+ if (placesNewestPage && !wasWatching && !channelState.messages.length) {
1588
+ c.messagePaginator.unmarkStaleHead();
1597
1589
  }
1598
1590
 
1599
- if (willInitialize) {
1600
- this.polls.hydratePollCache(channelState.messages, true);
1601
- this.reminders.hydrateState(channelState.messages);
1602
- }
1591
+ this.polls.hydratePollCache(channelState.messages, true);
1592
+ this.reminders.hydrateState(channelState.messages);
1603
1593
  c.messageComposer.initStateFromChannelResponse(channelState);
1604
1594
  c.cooldownTimer.refresh();
1605
1595
  channels.push(c);
@@ -1609,64 +1599,31 @@ export class StreamChat extends ChatApi {
1609
1599
  }
1610
1600
 
1611
1601
  /**
1612
- * Queries messages.
1602
+ * Returns the channel with the given type and ID: the stored instance for the cid, or a new one,
1603
+ * stored (one instance per cid; a channel disposed with `disconnect()` is replaced by a fresh
1604
+ * one). Use it instead of `new Channel()`.
1613
1605
  *
1614
- * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts
1615
- * MongoDB-style filter conditions, a search query, and options such as `user_id`.
1616
- * `requestOptions` carries per-request options such as an abort `signal` and is never
1617
- * serialized into the request.
1618
- * @returns The search messages response.
1619
- */
1620
- override async search(...args: Parameters<ChatApi['search']>) {
1621
- const [request, requestOptions] = args;
1622
- if (request?.payload?.offset && request?.payload?.next) {
1623
- throw Error(`Cannot specify "offset" with "next"`);
1624
- }
1625
-
1626
- // Make sure we wait for the connect promise if there is a pending one
1627
- await this.wsPromise;
1628
-
1629
- return await super.search(request, requestOptions);
1630
- }
1631
-
1632
- /**
1633
- * Caches one channel's server configuration, read through {@link Channel.serverConfig}.
1634
- *
1635
- * Keyed by **cid** rather than by channel type: a channel's own `config_overrides` narrow its type's
1636
- * settings for that channel alone, so two channels of one type can disagree.
1606
+ * For a distinct channel between users, leave out the ID and pass the members. It is stored under
1607
+ * a temporary cid until the response of `channel.watch()`, `query()` or `create()` brings the
1608
+ * real one; a stored distinct channel with the same loaded members is returned instead. If
1609
+ * another instance holds the real cid by then, it stays stored and takes over from this one
1610
+ * (`channel.supersededBy`; `watch()` resolves with it). A group with the same members as another
1611
+ * needs its own ID. Until its query is answered such a channel is
1612
+ * {@link Channel.isProvisional}: it has no ID yet, so nothing but that query can be sent for it.
1637
1613
  *
1638
- * Two writes are skipped. A response with no `config` — `notification.message_new` is one route that
1639
- * omits it — would otherwise un-learn a config already known for the channel. A config deep-equal to
1640
- * the stored one keeps a repeated query from waking that channel's subscribers, which matters because
1641
- * the API returns a fresh object every time and the store compares by reference.
1642
- *
1643
- * @internal
1644
- */
1645
- _addChannelConfig({ cid, config }: Pick<ChannelResponse, 'cid' | 'config'>) {
1646
- if (!config) return;
1647
- if (!this._cacheEnabled()) return;
1648
- if (isEqual(this.channelServerConfigs[cid], config)) return;
1649
-
1650
- this.channelServerConfigs = {
1651
- ...this.channelServerConfigs,
1652
- [cid]: config,
1653
- };
1654
- }
1655
-
1656
- /**
1657
- * Returns a new channel with the given type, ID and custom data.
1658
- *
1659
- * If you want to create a unique conversation between 2 or more users, you can leave out the ID
1660
- * parameter and provide the list of members.
1661
- * Make sure to await `channel.create()` or `channel.watch()` before accessing channel functions,
1662
- * i.e. `channel = client.channel('messaging', { members: ['tommaso', 'thierry'] })` then
1663
- * `await channel.create()` to assign an ID to the channel.
1614
+ * ```ts
1615
+ * const general = client.channel('messaging', 'general');
1616
+ * const dm = await client
1617
+ * .channel('messaging', { members: [{ user_id: 'ann' }, { user_id: 'bob' }] })
1618
+ * .watch();
1619
+ * ```
1664
1620
  *
1665
1621
  * @param channelType - The channel type.
1666
- * @param channelIdOrCustom - The channel ID; you can leave this out if you want to create a
1667
- * conversation channel (optional).
1668
- * @param custom - Custom data to attach to the channel (optional, defaults to `{}`).
1669
- * @returns The channel object; initialize it using `channel.watch()`.
1622
+ * @param channelId - The channel ID; leave it out for a distinct channel created from members
1623
+ * (optional).
1624
+ * @param custom - Data for a new channel, e.g. `members` or `custom`; for a stored channel only
1625
+ * `custom` is applied. Defaults to `{}`.
1626
+ * @returns The channel; initialize it with `channel.watch()`.
1670
1627
  */
1671
1628
  channel(channelType: string, channelId?: string | null, custom?: ChannelInput): Channel;
1672
1629
  channel(channelType: string, custom?: ChannelInput): Channel;
@@ -1674,157 +1631,57 @@ export class StreamChat extends ChatApi {
1674
1631
  channelType: string,
1675
1632
  channelIdOrCustom?: string | ChannelInput | null,
1676
1633
  custom: ChannelInput = {},
1677
- ) {
1678
- if (!this.userId) {
1679
- throw Error('Call connectUser or connectAnonymousUser before creating a channel');
1680
- }
1681
-
1682
- if (~channelType.indexOf(':')) {
1683
- throw new Error(
1684
- `Invalid channel group ${channelType}, can't contain the : character`,
1685
- );
1686
- }
1687
-
1688
- // support channel("messaging", {options})
1634
+ ): Channel {
1635
+ // channel('messaging', { members }): the data takes the ID's place
1689
1636
  if (channelIdOrCustom && typeof channelIdOrCustom === 'object') {
1690
- return this.getChannelByMembers(channelType, channelIdOrCustom);
1691
- }
1692
-
1693
- // support channel("messaging", undefined, {options})
1694
- if (!channelIdOrCustom && typeof custom === 'object' && custom.members?.length) {
1695
- return this.getChannelByMembers(channelType, custom);
1696
- }
1697
-
1698
- // support channel("messaging", null, {options})
1699
- // support channel("messaging", undefined, {options})
1700
- // support channel("messaging", "", {options})
1701
- if (!channelIdOrCustom) {
1702
- return new Channel(this, channelType, undefined, custom);
1637
+ return this.channelManager.ensure({ data: channelIdOrCustom, type: channelType });
1703
1638
  }
1704
-
1705
- return this.getChannelById(channelType, channelIdOrCustom, custom);
1639
+ return this.channelManager.ensure({
1640
+ data: custom,
1641
+ id: channelIdOrCustom || undefined,
1642
+ type: channelType,
1643
+ });
1706
1644
  }
1707
1645
 
1708
1646
  /**
1709
- * It's a helper method for `client.channel()` method, used to create unique conversation or
1710
- * channel based on member list instead of ID.
1711
- *
1712
- * If the channel already exists in `activeChannels` list, then we simply return it, since that
1713
- * means the same channel was already requested or created.
1647
+ * Searches messages.
1714
1648
  *
1715
- * Otherwise we create a new instance of Channel class and return it.
1716
- *
1717
- * @private
1718
- *
1719
- * @param channelType - The channel type.
1720
- * @param custom - Custom data to attach to the channel.
1721
- * @returns The channel object; initialize it using `channel.watch()`.
1649
+ * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts channel
1650
+ * `filter_conditions`, `message_filter_conditions`, a `query`, and options such as `limit`,
1651
+ * `offset`, `next` and `sort`. `requestOptions` carries per-request options such as an abort
1652
+ * `signal` and is never serialized into the request.
1653
+ * @returns The search messages response.
1654
+ * @throws When both `offset` and `next` are given.
1722
1655
  */
1723
- getChannelByMembers = (channelType: string, custom: ChannelInput) => {
1724
- // Check if the channel already exists.
1725
- // Only allow 1 channel object per cid
1726
- // Mirrors the same expression in `channel.ts` (`_initializeState`), which recomputes this
1727
- // temp cid to evict the stale `activeChannels` entry once the server assigns a real id —
1728
- // the two must agree exactly. `user_id` became optional in the v2 spec while
1729
- // `MemberUserRequest.id` is required, so `{ user: { id } }` is now a valid member spec.
1730
- const memberIds = (custom.members ?? []).map((member) =>
1731
- typeof member === 'string' ? member : member.user_id || member.user?.id || '',
1732
- );
1733
- const membersStr = memberIds.sort().join(',');
1734
- const tempCid = generateChannelTempCid(channelType, memberIds);
1735
-
1736
- if (!tempCid) {
1737
- throw Error('Please specify atleast one member when creating unique conversation');
1738
- }
1739
-
1740
- // channel could exist in `activeChannels` list with either one of the following two keys:
1741
- // 1. cid - Which gets set on channel only after calling channel.query or channel.watch or channel.create
1742
- // 2. Sorted membersStr - E.g., "messaging:amin,vishal" OR "messaging:amin,jaap,tom"
1743
- // This is set when you create a channel, but haven't queried yet. After query,
1744
- // we will replace it with `cid`
1745
- for (const key in this.activeChannels) {
1746
- const channel = this.activeChannels[key];
1747
- if (channel.pendingDisposal) {
1748
- continue;
1749
- }
1750
-
1751
- if (key === tempCid) {
1752
- return channel;
1753
- }
1754
-
1755
- if (key.indexOf(`${channelType}:!members-`) === 0) {
1756
- const membersStrInExistingChannel = Object.keys(channel.state.members)
1757
- .sort()
1758
- .join(',');
1759
- if (membersStrInExistingChannel === membersStr) {
1760
- return channel;
1761
- }
1762
- }
1763
- }
1764
-
1765
- const channel = new Channel(this, channelType, undefined, custom);
1766
-
1767
- // For the time being set the key as membersStr, since we don't know the cid yet.
1768
- // In channel.query, we will replace it with 'cid'.
1769
- if (this._cacheEnabled()) {
1770
- this.activeChannels[tempCid] = channel;
1656
+ override async search(...args: Parameters<ChatApi['search']>) {
1657
+ const [request, requestOptions] = args;
1658
+ if (request?.payload?.offset && request?.payload?.next) {
1659
+ throw Error(`Cannot specify "offset" with "next"`);
1771
1660
  }
1772
1661
 
1773
- return channel;
1774
- };
1662
+ return await super.search(request, requestOptions);
1663
+ }
1775
1664
 
1776
1665
  /**
1777
- * It's a helper method for `client.channel()`, used to retrieve a channel given its ID.
1666
+ * Caches one channel's server configuration, keyed by cid (see {@link Channel.serverConfig}).
1667
+ * Skips the write for a response without `config` (`notification.message_new` omits it) and for a
1668
+ * config deep-equal to the stored one: the API returns a fresh object each time and the store
1669
+ * compares by reference.
1778
1670
  *
1779
- * If the channel already exists in `activeChannels` list, then we simply return it, since that
1780
- * means the same channel was already requested or created.
1781
- *
1782
- * Otherwise we create a new instance of `Channel` class and return it.
1783
- *
1784
- * @private
1785
- *
1786
- * @param channelType - The channel type.
1787
- * @param channelId - The channel ID.
1788
- * @param custom - Custom data to attach to the channel.
1789
- * @returns The channel object; initialize it using `channel.watch()`.
1671
+ * @internal
1790
1672
  */
1791
- getChannelById = (channelType: string, channelId: string, custom: ChannelInput) => {
1792
- if (typeof channelId === 'string' && ~channelId.indexOf(':')) {
1793
- throw Error(`Invalid channel id ${channelId}, can't contain the : character`);
1794
- }
1795
-
1796
- // only allow 1 channel object per cid
1797
- const cid = `${channelType}:${channelId}`;
1798
- if (
1799
- cid in this.activeChannels &&
1800
- this.activeChannels[cid] &&
1801
- !this.activeChannels[cid].pendingDisposal
1802
- ) {
1803
- const channel = this.activeChannels[cid];
1804
- // Only overwrite the existing channel's custom data when the caller actually provided some.
1805
- // A caller passing other fields (e.g. `{ members }`, or even `{ members: undefined }`) yields a
1806
- // non-empty object with no `.custom`; the previous `Object.keys(custom).length > 0` guard let
1807
- // that through and then set `custom: custom.custom` (undefined), wiping the channel's existing
1808
- // custom data (e.g. its name). Guarding on `custom.custom` keeps genuine custom updates while
1809
- // leaving the existing custom intact when the caller omits it.
1810
- if (custom.custom !== undefined) {
1811
- const previousData = channel.data;
1812
- channel.data = { ...channel.data, custom: custom.custom };
1813
- channel.state.syncStateFromChannelData(channel.data, previousData);
1814
- channel._data = { ...channel._data, custom: custom.custom };
1815
- }
1816
- return channel;
1817
- }
1818
- const channel = new Channel(this, channelType, channelId, custom);
1819
- if (this._cacheEnabled()) {
1820
- this.activeChannels[channel.cid] = channel;
1821
- }
1673
+ _addChannelConfig({ cid, config }: Pick<ChannelResponse, 'cid' | 'config'>) {
1674
+ if (!config) return;
1675
+ if (isEqual(this.channelServerConfigs[cid], config)) return;
1822
1676
 
1823
- return channel;
1824
- };
1677
+ this.channelServerConfigs = {
1678
+ ...this.channelServerConfigs,
1679
+ [cid]: config,
1680
+ };
1681
+ }
1825
1682
 
1826
1683
  /**
1827
- * Revoke a global ban for a user.
1684
+ * Revokes a global ban.
1828
1685
  *
1829
1686
  * @param targetUserId - The user to unban.
1830
1687
  * @param options - Unban options (optional).
@@ -1844,21 +1701,17 @@ export class StreamChat extends ChatApi {
1844
1701
  },
1845
1702
  requestOptions,
1846
1703
  );
1847
- if (this._cacheEnabled()) {
1848
- this.blockedUsers.next(({ userIds }) => ({
1849
- userIds: userIds.concat(blockedUserId),
1850
- }));
1851
- }
1704
+ this.blockedUsers.next(({ userIds }) => ({
1705
+ userIds: userIds.concat(blockedUserId),
1706
+ }));
1852
1707
  return result;
1853
1708
  }
1854
1709
 
1855
1710
  override async getBlockedUsers(...args: Parameters<ChatApi['getBlockedUsers']>) {
1856
1711
  const result = await super.getBlockedUsers(...args);
1857
- if (this._cacheEnabled()) {
1858
- this.blockedUsers.partialNext({
1859
- userIds: result.blocks.map(({ blocked_user_id }) => blocked_user_id),
1860
- });
1861
- }
1712
+ this.blockedUsers.partialNext({
1713
+ userIds: result.blocks.map(({ blocked_user_id }) => blocked_user_id),
1714
+ });
1862
1715
  return result;
1863
1716
  }
1864
1717
 
@@ -1869,19 +1722,18 @@ export class StreamChat extends ChatApi {
1869
1722
  },
1870
1723
  requestOptions,
1871
1724
  );
1872
- if (this._cacheEnabled()) {
1873
- this.blockedUsers.next(({ userIds }) => ({
1874
- userIds: userIds.filter((id) => id !== blockedUserId),
1875
- }));
1876
- }
1725
+ this.blockedUsers.next(({ userIds }) => ({
1726
+ userIds: userIds.filter((id) => id !== blockedUserId),
1727
+ }));
1877
1728
  return result;
1878
1729
  }
1879
1730
 
1880
1731
  /**
1881
- * Checks whether a user is muted. Can be used after `connectUser()` is called.
1732
+ * Checks whether a user is muted.
1882
1733
  *
1883
1734
  * @param targetId - The user ID to check.
1884
1735
  * @returns `true` if the user is muted, otherwise `false`.
1736
+ * @throws When no user is connected.
1885
1737
  */
1886
1738
  userMuteStatus(targetId: string) {
1887
1739
  if (!this.user || !this.wsPromise) {
@@ -1894,91 +1746,28 @@ export class StreamChat extends ChatApi {
1894
1746
  return false;
1895
1747
  }
1896
1748
 
1897
- /**
1898
- * Transforms an expiration value into an ISO string.
1899
- *
1900
- * A `number` is an offset in SECONDS, not a timestamp — passing a wire `pin_expires` overflows
1901
- * `Date`, which used to surface as an opaque `RangeError` from `toISOString()`.
1902
- *
1903
- * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1904
- * in seconds, `string` or `Date` to set the exact expiration date (optional).
1905
- * @returns The expiration as an ISO string, or `null`.
1906
- * @throws If a numeric offset does not resolve to a representable date.
1907
- */
1908
- _normalizeExpiration(timeoutOrExpirationDate?: null | number | string | Date) {
1909
- let pinExpires: null | string = null;
1910
- if (typeof timeoutOrExpirationDate === 'number') {
1911
- const expiresAt = new Date();
1912
- expiresAt.setSeconds(expiresAt.getSeconds() + timeoutOrExpirationDate);
1913
- if (Number.isNaN(expiresAt.getTime())) {
1914
- throw new Error(
1915
- `Expiration offset ${timeoutOrExpirationDate} does not resolve to a valid date`,
1916
- );
1917
- }
1918
- pinExpires = expiresAt.toISOString();
1919
- } else if (isString(timeoutOrExpirationDate)) {
1920
- pinExpires = timeoutOrExpirationDate;
1921
- } else if (timeoutOrExpirationDate instanceof Date) {
1922
- pinExpires = timeoutOrExpirationDate.toISOString();
1923
- }
1924
- return pinExpires;
1925
- }
1926
-
1927
- /**
1928
- * Extracts a string message ID from either a message object or a message ID.
1929
- *
1930
- * @param messageOrMessageId - MessageRequest object or message ID.
1931
- * @param errorText - Error message to report in case of message ID absence.
1932
- * @returns The extracted message ID.
1933
- */
1934
- _validateAndGetMessageId(
1935
- messageOrMessageId: string | { id: string },
1936
- errorText: string,
1937
- ) {
1938
- let messageId: string;
1939
- if (typeof messageOrMessageId === 'string') {
1940
- messageId = messageOrMessageId;
1941
- } else {
1942
- if (!messageOrMessageId.id) {
1943
- throw Error(errorText);
1944
- }
1945
- messageId = messageOrMessageId.id;
1946
- }
1947
- return messageId;
1948
- }
1949
-
1950
1749
  /**
1951
1750
  * Pins the message.
1952
1751
  *
1953
- * @param messageOrMessageId - MessageRequest object or message ID.
1954
- * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1955
- * in seconds, `string` or `Date` to set the exact expiration date (optional).
1956
- * @param pinnedAt - Date when the message should be pinned. It affects the order of pinned
1957
- * messages. Use a negative number to set relative time in the past, `string` or `Date` to
1958
- * set the exact date of pin (optional).
1752
+ * @param message - The message to pin, or just its `{ id }`.
1753
+ * @param options - When the pin expires and where it sorts (optional).
1754
+ * @param options.pin_expires - When the pin expires, as a `Date` or an RFC3339 string; `null` or
1755
+ * leaving it out pins without expiry. Hand a server-sent timestamp back with `nsToDate(timestamp)`.
1756
+ * @param options.pinned_at - The pin time, which orders the pinned messages, as a `Date` or an
1757
+ * RFC3339 string (optional). Defaults to now.
1959
1758
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1960
1759
  * into the request (optional).
1961
1760
  * @returns The updated message response.
1962
1761
  */
1963
1762
  pinMessage(
1964
- messageOrMessageId: string | { id: string },
1965
- timeoutOrExpirationDate?: null | number | string | Date,
1966
- pinnedAt?: number | string | Date,
1763
+ { id }: { id: string },
1764
+ { pin_expires = null, pinned_at }: PinMessageOptions = {},
1967
1765
  requestOptions?: StreamRequestOptions,
1968
1766
  ) {
1969
- const id = this._validateAndGetMessageId(
1970
- messageOrMessageId,
1971
- 'Please specify the message id when calling pinMessage',
1972
- );
1767
+ if (!id) throw new Error('Please specify the message id when calling pinMessage');
1973
1768
  return this.updateMessagePartial(
1974
- {
1975
- id,
1976
- set: {
1977
- pinned: true,
1978
- pin_expires: this._normalizeExpiration(timeoutOrExpirationDate),
1979
- pinned_at: this._normalizeExpiration(pinnedAt),
1980
- },
1981
- },
1769
+ { id },
1770
+ { set: { pinned: true, pin_expires, pinned_at: pinned_at ?? null } },
1982
1771
  requestOptions,
1983
1772
  );
1984
1773
  }
@@ -1986,78 +1775,52 @@ export class StreamChat extends ChatApi {
1986
1775
  /**
1987
1776
  * Unpins the message that was previously pinned.
1988
1777
  *
1989
- * @param messageOrMessageId - MessageRequest object or message ID.
1778
+ * @param message - The message to unpin, or just its `{ id }`.
1990
1779
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1991
1780
  * into the request (optional).
1992
1781
  * @returns The updated message response.
1993
1782
  */
1994
- unpinMessage(
1995
- messageOrMessageId: string | { id: string },
1996
- requestOptions?: StreamRequestOptions,
1997
- ) {
1998
- const id = this._validateAndGetMessageId(
1999
- messageOrMessageId,
2000
- 'Please specify the message id when calling unpinMessage',
2001
- );
2002
- return this.updateMessagePartial(
2003
- {
2004
- id,
2005
- set: { pinned: false },
2006
- },
2007
- requestOptions,
2008
- );
1783
+ unpinMessage({ id }: { id: string }, requestOptions?: StreamRequestOptions) {
1784
+ if (!id) throw new Error('Please specify the message id when calling unpinMessage');
1785
+ return this.updateMessagePartial({ id }, { set: { pinned: false } }, requestOptions);
2009
1786
  }
2010
1787
 
2011
1788
  /**
2012
- * Updates the given message. When an `offlineDb` is registered the call is queued
2013
- * so it is replayed on reconnect.
1789
+ * Updates a message over HTTP only: no offline queueing and no local state.
1790
+ * `messageOperations.update` on a channel or thread is the full edit.
1791
+ *
1792
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the message ID;
1793
+ * `request.message` is the updated message; `requestOptions` carries per-request options such
1794
+ * as an abort `signal` and is never serialized into the request.
1795
+ * @returns The update message response.
2014
1796
  */
2015
- override async updateMessage(
2016
- ...args: [
2017
- request: Parameters<ChatApi['updateMessage']>[0] & { message: { cid?: string } },
2018
- requestOptions?: StreamRequestOptions,
2019
- ]
2020
- ) {
2021
- const [request] = args;
2022
-
2023
- return await queueOrRun({
2024
- client: this,
2025
- task: {
2026
- ...getPendingTaskChannelData(request.message?.cid),
2027
- messageId: request.id,
2028
- payload: args,
2029
- type: 'update-message',
2030
- },
2031
- });
2032
- }
1797
+ override async updateMessage(...args: Parameters<ChatApi['updateMessage']>) {
1798
+ const [pathParams, request, requestOptions] = args;
2033
1799
 
2034
- async _updateMessage(...args: Parameters<ChatApi['updateMessage']>) {
2035
- return await super.updateMessage(...args);
1800
+ // Sanitized at the wire, which every path reaches: the full edit and an offline replay alike.
1801
+ return await super.updateMessage(
1802
+ pathParams,
1803
+ { ...request, message: sanitizeOutgoingAttachments(request.message) },
1804
+ requestOptions,
1805
+ );
2036
1806
  }
2037
1807
 
2038
1808
  /**
2039
- * Deletes a message. When an `offlineDb` is registered the call is queued so it
2040
- * is replayed on reconnect.
1809
+ * Deletes a message over HTTP only: no offline queueing and no local state.
1810
+ * `messageOperations.delete` on a channel or thread is the full delete.
1811
+ *
1812
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the message ID;
1813
+ * `request.hard` deletes it permanently and `request.delete_for_me` deletes it for the current
1814
+ * user only; `requestOptions` carries per-request options such as an abort `signal` and is
1815
+ * never serialized into the request.
1816
+ * @returns The delete message response.
2041
1817
  */
2042
1818
  override async deleteMessage(...args: Parameters<ChatApi['deleteMessage']>) {
2043
- const [request] = args;
2044
-
2045
- return await queueOrRun({
2046
- client: this,
2047
- task: {
2048
- messageId: request.id,
2049
- payload: args,
2050
- type: 'delete-message',
2051
- },
2052
- });
2053
- }
2054
-
2055
- async _deleteMessage(...args: Parameters<ChatApi['deleteMessage']>) {
2056
- const [request] = args;
1819
+ const [, request] = args;
2057
1820
  const result = await super.deleteMessage(...args);
2058
1821
 
2059
- // necessary to populate the below values as the server does not return the message in the response as deleted
2060
- if (request.delete_for_me) {
1822
+ // The server does not return the message as deleted here.
1823
+ if (request?.delete_for_me) {
2061
1824
  result.message.deleted_for_me = true;
2062
1825
  result.message.type = 'deleted';
2063
1826
  }
@@ -2066,19 +1829,18 @@ export class StreamChat extends ChatApi {
2066
1829
  }
2067
1830
 
2068
1831
  /**
2069
- * Returns the list of threads of the current user.
1832
+ * Returns the current user's threads as hydrated `Thread` instances.
2070
1833
  *
2071
- * @param options - Options object for pagination and limiting the participants and replies
2072
- * (optional, defaults to `{}`).
2073
- * @param options.limit - Limits the number of threads to be returned (optional).
2074
- * @param options.watch - Subscribes the user to the channels of the threads (optional).
2075
- * @param options.participant_limit - Limits the number of participants returned per thread (optional).
2076
- * @param options.reply_limit - Limits the number of replies returned per thread (optional).
2077
- * @param options.filter - MongoDB style filters for threads (optional).
2078
- * @param options.sort - MongoDB style sort for threads (optional).
2079
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1834
+ * @param options - Pagination and limits for the participants and replies. Defaults to `{}`.
1835
+ * @param options.limit - Limits the number of threads returned. Defaults to 10.
1836
+ * @param options.watch - Subscribes the user to the channels of the threads. Defaults to `true`.
1837
+ * @param options.participant_limit - Limits the participants returned per thread. Defaults to 10.
1838
+ * @param options.reply_limit - Limits the replies returned per thread. Defaults to 3.
1839
+ * @param options.filter - MongoDB-style filters for threads (optional).
1840
+ * @param options.sort - MongoDB-style sort for threads (optional).
1841
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2080
1842
  * into the request (optional).
2081
- * @returns The list of threads and the next cursor.
1843
+ * @returns The threads and the next cursor.
2082
1844
  */
2083
1845
  async queryThreadsAndHydrate(
2084
1846
  options: QueryThreadsRequest = {},
@@ -2109,34 +1871,34 @@ export class StreamChat extends ChatApi {
2109
1871
 
2110
1872
  const response = await this.queryThreads(requestBody, requestOptions);
2111
1873
 
2112
- // Hydrate the polls for the parent messages of the threads
2113
1874
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2114
1875
  const parentMessages = response.threads.map((thread) => thread.parent_message!);
2115
1876
  this.polls.hydratePollCache(parentMessages);
2116
1877
 
2117
- return {
2118
- threads: response.threads.map(
2119
- (thread) => new Thread({ client: this, threadData: thread }),
2120
- ),
2121
- next: response.next,
2122
- };
1878
+ const threads = response.threads.map((threadData) =>
1879
+ this.threads.resolveQueried(threadData),
1880
+ );
1881
+ if (optionsWithDefaults.watch) threads.forEach(markThreadChannelWatched);
1882
+
1883
+ return { threads, next: response.next };
2123
1884
  }
2124
1885
 
2125
1886
  /**
2126
1887
  * Returns the thread of a message by its ID, wrapped in a hydrated `Thread` instance.
2127
1888
  *
2128
- * @param messageId - The message ID.
2129
- * @param options - Options object for pagination and limiting the participants and replies
2130
- * (optional, defaults to `{}`).
2131
- * @param options.watch - Subscribes the user to the channel of the thread (optional).
2132
- * @param options.participant_limit - Limits the number of participants returned per thread (optional).
2133
- * @param options.reply_limit - Limits the number of replies returned per thread (optional).
1889
+ * @param pathParams - The thread's parent message, as for `getThread`.
1890
+ * @param pathParams.message_id - The parent message ID.
1891
+ * @param options - Options object for pagination and limiting the participants and replies.
1892
+ * Defaults to `{}`.
1893
+ * @param options.watch - Subscribes the user to the channel of the thread. Defaults to `true`.
1894
+ * @param options.participant_limit - Limits the participants returned. Defaults to 100.
1895
+ * @param options.reply_limit - Limits the replies returned. Defaults to 3.
2134
1896
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2135
1897
  * into the request (optional).
2136
1898
  * @returns The thread.
2137
1899
  */
2138
1900
  async getThreadAndHydrate(
2139
- messageId: string,
1901
+ { message_id: messageId }: { message_id: string },
2140
1902
  options: GetThreadOptions = {},
2141
1903
  requestOptions?: StreamRequestOptions,
2142
1904
  ) {
@@ -2145,21 +1907,22 @@ export class StreamChat extends ChatApi {
2145
1907
  }
2146
1908
 
2147
1909
  const optionsWithDefaults = {
2148
- participant_limit: 100,
1910
+ participant_limit: DEFAULT_THREAD_PARTICIPANT_LIMIT,
2149
1911
  reply_limit: 3,
2150
1912
  watch: true,
2151
1913
  ...options,
2152
1914
  };
2153
1915
 
2154
1916
  const response = await this.getThread(
2155
- {
2156
- message_id: messageId,
2157
- ...optionsWithDefaults,
2158
- },
1917
+ { message_id: messageId },
1918
+ optionsWithDefaults,
2159
1919
  requestOptions,
2160
1920
  );
2161
1921
 
2162
- return new Thread({ client: this, threadData: response.thread });
1922
+ const thread = this.threads.resolveQueried(response.thread);
1923
+ if (optionsWithDefaults.watch) markThreadChannelWatched(thread);
1924
+
1925
+ return thread;
2163
1926
  }
2164
1927
 
2165
1928
  getUserAgent = (): string => {
@@ -2168,8 +1931,7 @@ export class StreamChat extends ChatApi {
2168
1931
  return this.userAgent;
2169
1932
  }
2170
1933
 
2171
- // Computed once, then memoized for the client's lifetime - inputs read on
2172
- // the first call (sdk/device identifiers, build-time env) are not re-read.
1934
+ // Memoized on the first call: later changes to the identifiers are not picked up.
2173
1935
  if (!this.cachedUserAgent) {
2174
1936
  const version = process.env.PKG_VERSION;
2175
1937
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
@@ -2182,8 +1944,7 @@ export class StreamChat extends ChatApi {
2182
1944
 
2183
1945
  this.cachedUserAgent = [
2184
1946
  head,
2185
- // reports the host app, the device OS, the device model, and the picked
2186
- // exports bundle, each only when a value is present
1947
+ // Each only when a value is present.
2187
1948
  ...Object.entries({
2188
1949
  app: appName,
2189
1950
  app_version: appVersion,
@@ -2210,75 +1971,81 @@ export class StreamChat extends ChatApi {
2210
1971
  this.userAgent = userAgent;
2211
1972
  }
2212
1973
 
2213
- _cacheEnabled = () => !this.options.disableCache;
2214
-
2215
1974
  _startCleaning() {
2216
- // eslint-disable-next-line @typescript-eslint/no-this-alias
2217
- const that = this;
2218
1975
  if (this.cleaningIntervalRef != null) {
2219
1976
  return;
2220
1977
  }
2221
1978
  this.cleaningIntervalRef = setInterval(() => {
2222
- // call clean on the channel, used for calling the stop.typing event etc.
2223
- for (const channel of Object.values(that.activeChannels)) {
2224
- channel.clean();
1979
+ // `clean()` sends the stop-typing event, among other things.
1980
+ for (const channel of this.channelManager.values()) {
1981
+ // A disposed channel has nothing to clean, and `clean()` would throw on it.
1982
+ if (channel.pendingDisposal) continue;
1983
+ // One channel failing to clean must not stop the others (typing indicators would stick).
1984
+ try {
1985
+ channel.clean();
1986
+ } catch (error) {
1987
+ logger
1988
+ .withExtraTags('clean', channel.cid)
1989
+ .error('Cleaning the channel failed.', { error });
1990
+ }
2225
1991
  }
2226
1992
  }, 500);
2227
1993
  }
2228
1994
 
2229
1995
  /**
2230
- * Encodes the WebSocket auth message, sent as the first frame once the socket opens.
1996
+ * The JSON-encoded WebSocket auth message, sent as the first frame once the socket opens.
2231
1997
  *
2232
- * `products` is not optional in practice: without `'chat'` the server treats the
2233
- * connection as video-only, which drops every chat event and unread count.
1998
+ * @private
1999
+ */
2000
+ _buildWSAuthMessage = () =>
2001
+ JSON.stringify(this._buildWSAuthPayload(this.tokenManager.getToken()));
2002
+
2003
+ /**
2004
+ * The auth message that {@link _buildWSAuthMessage} encodes for the WebSocket and the long-poll
2005
+ * fallback sends as `longPoll()`'s `json` query param.
2234
2006
  *
2235
2007
  * @private
2236
2008
  *
2237
- * @returns The JSON-encoded auth message.
2009
+ * @param token - The long-poll passes none: it authenticates through the `Authorization` header.
2238
2010
  */
2239
- _buildWSAuthMessage = () =>
2240
- JSON.stringify({
2241
- // The server requires a non-empty token even for anonymous connections, but
2242
- // skips JWT parsing for any string that is not shaped like one. Anonymous users
2243
- // have no token, so send a placeholder the server accepts and ignores.
2244
- token: this.tokenManager.getToken() || 'anonymous',
2245
- // `connect()` rejects before reaching this when `_user` is unset.
2246
- user_details: this._user as ConnectUserDetailsRequest,
2247
- products: ['chat'],
2248
- } satisfies WSAuthMessage);
2011
+ _buildWSAuthPayload = (token?: string): WSAuthMessage => ({
2012
+ // The server requires a non-empty token but ignores one that is not JWT-shaped, so anonymous
2013
+ // users and the long-poll send a placeholder.
2014
+ token: token || 'anonymous',
2015
+ // `connect()` rejects before reaching this when `_user` is unset.
2016
+ user_details: this._user as ConnectUserDetailsRequest,
2017
+ // Without 'chat' the server treats the connection as video-only and drops chat events and
2018
+ // unread counts.
2019
+ products: ['chat'],
2020
+ });
2249
2021
 
2250
2022
  /**
2251
- * Queries poll answers.
2023
+ * Queries poll answers: the votes with `is_answer: true`.
2252
2024
  *
2253
- * @param request - The query poll answers request payload, including the poll ID, optional vote
2254
- * filter conditions, sort directions, and pagination options (`limit`, `offset`).
2255
- * @param request.poll_id - The poll ID.
2256
- * @param request.filter - Vote filter conditions.
2025
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.poll_id` is the poll ID;
2026
+ * `request` carries optional vote filter conditions, sort directions, and pagination options
2027
+ * (`limit`, `next`, `prev`); `requestOptions` carries per-request options such as an abort
2028
+ * `signal` and is never serialized into the request.
2257
2029
  * @returns The poll answers.
2258
2030
  */
2259
- async queryPollAnswers(
2260
- { poll_id, filter, ...options }: Parameters<ChatApi['queryPollVotes']>[0],
2261
- requestOptions?: StreamRequestOptions,
2262
- ) {
2031
+ async queryPollAnswers(...args: Parameters<ChatApi['queryPollVotes']>) {
2032
+ const [pathParams, request, requestOptions] = args;
2033
+ const { filter, ...options } = request ?? {};
2034
+
2263
2035
  return await this.queryPollVotes(
2264
- {
2265
- poll_id,
2266
- filter: {
2267
- ...filter,
2268
- is_answer: true,
2269
- },
2270
- ...options,
2271
- },
2036
+ pathParams,
2037
+ { ...options, filter: { ...filter, is_answer: true } },
2272
2038
  requestOptions,
2273
2039
  );
2274
2040
  }
2275
2041
 
2276
2042
  /**
2277
- * Uploads a file to the Stream CDN
2043
+ * Uploads a file to the Stream CDN.
2278
2044
  *
2279
2045
  * @param request - Upload payload. `request.file` is the file to upload.
2280
- * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
2281
- * @returns Response containing the file URL.
2046
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
2047
+ * (optional).
2048
+ * @returns The upload response, with the file URL.
2282
2049
  */
2283
2050
  override async uploadFile(
2284
2051
  request?: Omit<FileUploadRequest, 'file'> & { file?: FileUploadInput },
@@ -2291,11 +2058,12 @@ export class StreamChat extends ChatApi {
2291
2058
  }
2292
2059
 
2293
2060
  /**
2294
- * Uploads an image to Stream CDN
2061
+ * Uploads an image to the Stream CDN.
2295
2062
  *
2296
2063
  * @param request - Upload payload. `request.file` is the image to upload.
2297
- * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
2298
- * @returns Response containing the image URL.
2064
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
2065
+ * (optional).
2066
+ * @returns The upload response, with the image URL.
2299
2067
  */
2300
2068
  override async uploadImage(
2301
2069
  request?: Omit<ImageUploadRequest, 'file'> & { file?: FileUploadInput },
@@ -2308,9 +2076,11 @@ export class StreamChat extends ChatApi {
2308
2076
  }
2309
2077
 
2310
2078
  /**
2311
- * Marks the channels as delivered for the given messages and the user.
2079
+ * Marks channels as delivered for the given messages.
2312
2080
  *
2313
2081
  * @param request - Mark delivered options.
2082
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2083
+ * into the request (optional).
2314
2084
  * @returns The server response, or `undefined` if there are no messages to mark.
2315
2085
  */
2316
2086
  async markChannelsDelivered(