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