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

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 (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
package/src/client.ts CHANGED
@@ -1,34 +1,32 @@
1
1
  /* eslint no-unused-vars: "off" */
2
2
  /* global process */
3
3
 
4
- import type { AxiosInstance, AxiosRequestConfig } from 'axios';
4
+ import type { AxiosInstance } from 'axios';
5
5
  import axios from 'axios';
6
- import https from 'https';
7
6
 
8
- import { Channel } from './channel';
7
+ import type { Channel } from './channel';
8
+ import type { ChannelMuteStatus } from './channel_state';
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
12
  import { TokenManager, type TokenManagerMinimalUser } from './token_manager';
13
- import { WSConnectionFallback } from './connection_fallback';
14
- import { isWSFailure } from './errors';
15
13
  import { ApiClient } from './api-client';
16
14
  import {
17
15
  axiosParamsSerializer,
18
16
  formatMessage,
19
- generateChannelTempCid,
20
17
  getEnv,
21
- isOnline,
18
+ invokeEventListener,
22
19
  isOwnUserBaseProperty,
23
20
  randomId,
21
+ sanitizeOutgoingAttachments,
24
22
  } from './utils';
23
+ import { nowNs } from './utils/time';
24
+ import { normalizeUploadFile } from './upload-utils';
25
25
 
26
26
  import type {
27
27
  APIResponse,
28
28
  AppIdentifier,
29
- BanUserOptions,
30
- BaseDeviceFields,
31
- ChannelData,
29
+ ChannelInput,
32
30
  ChannelMute,
33
31
  ChannelOptions,
34
32
  ChannelResponse,
@@ -40,31 +38,27 @@ import type {
40
38
  Event,
41
39
  EventHandler,
42
40
  EventType,
43
- FlagMessageResponse,
44
- FlagUserResponse,
41
+ FileUploadInput,
45
42
  GetThreadOptions,
46
43
  LocalMessage,
47
- MuteUserOptions,
48
- MuteUserResponse,
49
44
  OwnUserResponse,
50
45
  PartializeAllBut,
51
- PartialThreadUpdate,
52
- QueryBannedUsersPayload,
53
46
  QueryChannelsRequest,
54
47
  QueryChannelsResponse,
55
- QueryReactionsRequestWithId,
56
48
  QueryThreadsRequest,
57
49
  ReactionResponse,
58
50
  SdkIdentifier,
59
- SearchPayload,
60
51
  StreamChatOptions,
52
+ StreamRequestOptions,
53
+ TimestampNS,
61
54
  TokenOrProvider,
62
55
  UnBanUserOptions,
63
56
  UpdateUserPartialRequest,
64
57
  UserMuteResponse,
65
58
  UserResponse,
66
59
  } from './types';
67
- import { InsightMetrics, postInsights } from './insights';
60
+ import { isWSFailure } from './errors';
61
+ import type { APIError } from './errors';
68
62
  import { chatLoggerSystem } from './logger';
69
63
  import { Thread } from './thread';
70
64
  import { Moderation } from './moderation';
@@ -73,23 +67,31 @@ import { DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE } from './constants';
73
67
  import { PollManager } from './poll_manager';
74
68
  import { EntityStore } from './entityStore/EntityStore';
75
69
  import { ChannelManager } from './ChannelManager';
70
+ import {
71
+ ConnectionIdManager,
72
+ ConnectionRecoveryManager,
73
+ NetworkConnectionObserver,
74
+ WSConnection,
75
+ } from './connection';
76
76
  import { MessageDeliveryReporter } from './messageDelivery';
77
77
  import { NotificationManager } from './notifications';
78
78
  import { ReminderManager } from './reminders';
79
79
  import type { AbstractOfflineDB } from './offline-support';
80
- import { getPendingTaskChannelData } from './offline-support/util';
81
80
  import { FixedSizeQueueCache } from './utils/FixedSizeQueueCache';
81
+ import { isEqual } from './utils/mergeWith/mergeWithCore';
82
82
  import type { MessageComposer } from './messageComposer';
83
+ import type { InstanceSetupState } from './configuration';
84
+ import { InstanceConfigurationRegistry } from './configuration/InstanceConfigurationRegistry';
85
+ import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
86
+ import { StateStore } from '@stream-io/state-store';
87
+ import type { Unsubscribe } from '@stream-io/state-store';
83
88
  import type {
84
- MessageComposerSetupState,
85
- SetInstanceConfigurationFunctions,
86
- } from './configuration';
87
- import { InstanceConfigurationService } from './configuration/InstanceConfigurationService';
88
- import { StateStore } from './store';
89
- import type {
89
+ ConnectUserDetailsRequest,
90
+ FileUploadRequest,
90
91
  GetApplicationResponse as Gen_GetApplicationResponse,
91
92
  MarkDeliveredRequest as Gen_MarkDeliveredRequest,
92
- QueryUsersPayload as Gen_QueryUsersPayload,
93
+ ImageUploadRequest,
94
+ WSAuthMessage,
93
95
  WSEvent,
94
96
  } from './gen/models';
95
97
  import { ChatApi } from './gen-imports';
@@ -117,6 +119,21 @@ export type ChannelConfigsState = {
117
119
 
118
120
  export type ClientUser = PartializeAllBut<OwnUserResponse, 'id'> & { anon?: boolean };
119
121
 
122
+ /**
123
+ * `T`, unless it is a server-sent {@link TimestampNS}: for parameters where a bare `number` means a
124
+ * relative offset rather than an instant. `any` passes through (`0 extends 1 & T`), so untyped
125
+ * callers are not suddenly rejected.
126
+ */
127
+ type NotATimestampNS<T> = 0 extends 1 & T ? T : T extends TimestampNS ? never : T;
128
+
129
+ /**
130
+ * A thread query that asked for `watch: true` came back, so the server now watches the thread's
131
+ * channel, the same rule `channel.watch()` and `queryChannels` apply.
132
+ */
133
+ const markThreadChannelWatched = ({ channel }: Thread) => {
134
+ channel.watchStatus = ChannelWatchStatus.Watching;
135
+ };
136
+
120
137
  export class StreamChat extends ChatApi {
121
138
  private static _instance?: unknown | StreamChat; // type is undefined|StreamChat, unknown is due to TS limitations with statics
122
139
  messageDeliveryReporter: MessageDeliveryReporter;
@@ -129,9 +146,6 @@ export class StreamChat extends ChatApi {
129
146
  */
130
147
  _user?: ClientUser;
131
148
  appSettingsPromise?: Promise<StreamResponse<Gen_GetApplicationResponse>>;
132
- activeChannels: {
133
- [key: string]: Channel;
134
- };
135
149
  threads: ThreadManager;
136
150
  polls: PollManager;
137
151
  /**
@@ -146,6 +160,40 @@ export class StreamChat extends ChatApi {
146
160
  * `removeEventHandlers`), which is also the only way to reconfigure it later.
147
161
  */
148
162
  channelManager: ChannelManager;
163
+ /**
164
+ * Owns connection recovery: on reconnect it re-runs each loaded channel list's own first-page query
165
+ * and reloads each active channel, then dispatches `connection.recovered`. Instantiated with the
166
+ * client and subscribed for its lifetime.
167
+ *
168
+ * Turn it off through the declarative configuration if the application recovers state itself:
169
+ * `client.config.set({ client: { connectionRecovery: { enabled: false } } })`.
170
+ */
171
+ connectionRecovery: ConnectionRecoveryManager;
172
+ /**
173
+ * The device's own network status — whether this machine has a network at all, which is a different
174
+ * fact from whether our WebSocket is up ({@link wsConnection}). The two disagree routinely: a
175
+ * socket dies on a working network (server close, expired token, health-check timeout), and a
176
+ * device goes offline while the socket has not noticed yet.
177
+ *
178
+ * The SDK cannot detect this itself — every platform reports it differently — so it has to be told:
179
+ * `client.config.set({ client: { networkConnection: { statusReporter } } })`, or
180
+ * `client.networkConnection.setStatusReporter(…)` afterwards.
181
+ *
182
+ * A browser answers the question properly and its reporter is installed automatically. Everywhere
183
+ * else a stand-in mirrors the WebSocket until a real one arrives, which is coarse but better than
184
+ * nothing at all on an integration that forgot the line of setup. Either way `isOnline` is
185
+ * `undefined` — *unknown*, not offline — until something has reported.
186
+ */
187
+ networkConnection: NetworkConnectionObserver;
188
+ /**
189
+ * The connection id — the WebSocket's, or the long-poll's after an `enableWSFallback`
190
+ * switch — and the one place the rest of the client reads it from.
191
+ *
192
+ * The server keys channel watches and presence subscriptions by it, so a request carrying either
193
+ * waits here for the handshake rather than racing it. See `requiresConnectionId` in
194
+ * `api-client.ts`.
195
+ */
196
+ connectionIdManager: ConnectionIdManager;
149
197
  /**
150
198
  * Client-global, normalized store holding one canonical copy of each message. The channel main
151
199
  * list and thread reply paginators read/write message content through it, so a message held in
@@ -159,20 +207,10 @@ export class StreamChat extends ChatApi {
159
207
  axiosInstance: AxiosInstance;
160
208
  baseURL?: string;
161
209
  browser: boolean;
162
- cleaningIntervalRef?: NodeJS.Timeout;
210
+ cleaningIntervalRef?: ReturnType<typeof setTimeout>;
163
211
  clientId?: string;
164
212
  key: string;
165
213
  listeners: Map<EventType, Set<EventHandler>>;
166
- /**
167
- * When network is recovered, we re-query the active channels on client. But in single query, you can recover
168
- * only 30 channels. So its not guaranteed that all the channels in activeChannels object have updated state.
169
- * Thus in UI sdks, state recovery is managed by components themselves, they don't rely on js client for this.
170
- *
171
- * `recoverStateOnReconnect` parameter can be used in such cases, to disable state recovery within js client.
172
- * When false, user/consumer of this client will need to make sure all the channels present on UI by
173
- * manually calling queryChannels endpoint.
174
- */
175
- recoverStateOnReconnect?: boolean;
176
214
  /**
177
215
  * If true, we will not clean up threads when channel state is in initializing state.
178
216
  * The main use case for SDKs who do independent state recovery for channels.
@@ -181,7 +219,17 @@ export class StreamChat extends ChatApi {
181
219
  moderation: Moderation;
182
220
  mutedChannels: ChannelMute[];
183
221
  readonly mutedUsersStore: StateStore<{ mutedUsers: UserMuteResponse[] }>;
184
- readonly configsStore: StateStore<ChannelConfigsState>;
222
+ /**
223
+ * Reactive store behind {@link channelServerConfigs}. The only reactive way to observe server channel
224
+ * configuration today, which is why `stream-chat-react` reads it — a public, per-channel feature
225
+ * resolver is the intended replacement.
226
+ *
227
+ * Named for what it holds plus a `Store` suffix for what it is, matching {@link mutedUsersStore}. These
228
+ * are the backend's configs, not the ones you register through {@link config}.
229
+ *
230
+ * @internal
231
+ */
232
+ readonly channelServerConfigsStore: StateStore<ChannelConfigsState>;
185
233
  blockedUsers: StateStore<BlockedUsersState>;
186
234
  node: boolean;
187
235
  options: StreamChatOptions;
@@ -191,11 +239,15 @@ export class StreamChat extends ChatApi {
191
239
  user?: ClientUser;
192
240
  userAgent?: string;
193
241
  wsBaseURL?: string;
194
- wsConnection: StableWSConnection | null;
195
- wsFallback?: WSConnectionFallback;
242
+ wsConnection: WSConnection;
196
243
  wsPromise: ConnectAPIResponse | null;
244
+ private _wsPromiseSettled = true;
245
+ private _wsConnectId = 0;
246
+ private _resolveWsPromise?: (value: Awaited<ConnectAPIResponse>) => void;
247
+ private _rejectWsPromise?: (reason?: unknown) => void;
248
+
197
249
  get anonymous(): boolean {
198
- return this.user?.anon ?? false;
250
+ return this.tokenManager.isAnonymous;
199
251
  }
200
252
  get userId() {
201
253
  return this.user?.id;
@@ -218,16 +270,21 @@ export class StreamChat extends ChatApi {
218
270
  get api() {
219
271
  return this.apiClient;
220
272
  }
221
- insightMetrics: InsightMetrics;
222
- defaultWSTimeoutWithFallback: number;
223
- defaultWSTimeout: number;
224
273
  sdkIdentifier?: SdkIdentifier;
225
274
  deviceIdentifier?: DeviceIdentifier;
226
275
  appIdentifier?: AppIdentifier;
227
276
  private cachedUserAgent?: string;
228
277
  readonly messageComposerCache: FixedSizeQueueCache<string, MessageComposer>;
229
- private nextRequestAbortController: AbortController | null = null;
230
- instanceConfigurationService = new InstanceConfigurationService();
278
+ /**
279
+ * Configuration you register for instances the SDK creates on your behalf — channels, threads,
280
+ * composers, and the client's own managers. See `InstanceConfigurationRegistry`.
281
+ *
282
+ * Not to be confused with {@link channelServerConfigs}, which holds the **server-provided channel
283
+ * configs** keyed by cid. This one is yours; that one is the backend's.
284
+ */
285
+ readonly config = new InstanceConfigurationRegistry();
286
+ /** Teardown for the `'client'` setup function, released by {@link disconnectUser}. */
287
+ private unsubscribeClientConfiguration?: Unsubscribe;
231
288
 
232
289
  /**
233
290
  * Initializes a client.
@@ -236,19 +293,14 @@ export class StreamChat extends ChatApi {
236
293
  *
237
294
  * @example <caption>initialize the client in user mode</caption>
238
295
  * new StreamChat('api_key')
239
- * @example <caption>initialize the client in user mode with options</caption>
240
- * new StreamChat('api_key', { warmUp: true, timeout: 5000 })
241
- * @example <caption>secret is optional and only used in server side mode</caption>
242
- * new StreamChat('api_key', 'secret', { httpsAgent: customAgent })
296
+ * @example <caption>initialize the client with options</caption>
297
+ * new StreamChat('api_key', { axiosRequestConfig: { timeout: 5000 } })
243
298
  *
244
299
  * @param key - The API key.
245
- * @param options - Additional options; here you can pass custom options to the axios instance (optional).
300
+ * @param options - Additional options (optional).
246
301
  * @param options.browser - Enforce the client to be in browser mode (optional).
247
- * @param options.warmUp - If `true`, the client will open a connection as soon as possible to speed up following requests (optional, defaults to `false`).
248
- * @param options.logLevel - Minimum log level for the default sink (optional, defaults to `'info'`).
249
- * @param options.logOptions - Per-scope sink/level overrides for `chatLoggerSystem` (optional).
250
- * @param options.timeout - Request timeout (optional, defaults to `3000`).
251
- * @param options.httpsAgent - Custom `httpsAgent` (optional, in Node defaults to `https.agent()`).
302
+ * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
303
+ * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
252
304
  */
253
305
  constructor(key: string, options: StreamChatOptions = {}) {
254
306
  // generated client requires ApiClient right away
@@ -265,7 +317,7 @@ export class StreamChat extends ChatApi {
265
317
  this.mutedUsersStore = new StateStore<{ mutedUsers: UserMuteResponse[] }>({
266
318
  mutedUsers: [],
267
319
  });
268
- this.configsStore = new StateStore<{ configs: Configs }>({
320
+ this.channelServerConfigsStore = new StateStore<ChannelConfigsState>({
269
321
  configs: {},
270
322
  });
271
323
  this.blockedUsers = new StateStore<BlockedUsersState>({ userIds: [] });
@@ -278,21 +330,11 @@ export class StreamChat extends ChatApi {
278
330
  this.browser = options.browser ?? typeof window !== 'undefined';
279
331
  this.node = !this.browser;
280
332
 
281
- this.options = {
282
- warmUp: false,
283
- recoverStateOnReconnect: true,
284
- disableCache: false,
285
- isLocalUnreadCountEnabled: false,
286
- wsUrlParams: new URLSearchParams({}),
287
- ...options,
288
- };
333
+ this.options = { ...options };
289
334
 
290
335
  this.axiosInstance = axios.create({
291
336
  timeout: 3000,
292
337
  withCredentials: false,
293
- httpsAgent: this.node
294
- ? new https.Agent({ keepAlive: true, keepAliveMsecs: 3000 })
295
- : undefined,
296
338
  ...this.options.axiosRequestConfig,
297
339
  paramsSerializer: axiosParamsSerializer,
298
340
  });
@@ -308,35 +350,98 @@ export class StreamChat extends ChatApi {
308
350
  this.setBaseURL(`http://${streamLocalTestHost}`);
309
351
  }
310
352
 
353
+ // Both before the WebSocket, which subscribes to the network store and drives the id's lifecycle.
354
+ this.connectionIdManager = new ConnectionIdManager();
355
+ this.networkConnection = new NetworkConnectionObserver({ client: this });
356
+ this.networkConnection.registerSubscriptions();
357
+
311
358
  // WS connection is initialized when setUser is called
312
- this.wsConnection = null;
359
+ this.wsConnection = new WSConnection({ client: this });
360
+ this.wsConnection.registerSubscriptions();
313
361
  this.wsPromise = null;
314
362
  this.setUserPromise = null;
315
363
  // keeps a reference to all the channels that are in use
316
- this.activeChannels = {};
317
364
 
318
- // mapping between channel groups and configs
319
- this.configs = {};
320
365
  this.persistUserOnConnectionFailure = this.options?.persistUserOnConnectionFailure;
321
366
 
322
- // If its a server-side client, then lets initialize the tokenManager, since token will be
323
- // generated from secret.
324
367
  this.tokenManager = new TokenManager();
325
- this.insightMetrics = new InsightMetrics();
326
-
327
- this.defaultWSTimeoutWithFallback = 6 * 1000;
328
- this.defaultWSTimeout = 15 * 1000;
329
368
 
330
- this.recoverStateOnReconnect = this.options.recoverStateOnReconnect;
331
369
  this.messageStore = new EntityStore<LocalMessage>({
332
370
  getEntityId: (message) => message.id,
333
371
  });
372
+ // before the managers that hold channels in its store
373
+ this.channelManager = new ChannelManager({ client: this });
334
374
  this.threads = new ThreadManager({ client: this });
335
375
  this.polls = new PollManager({ client: this });
336
- this.channelManager = new ChannelManager({ client: this });
376
+ this.connectionRecovery = new ConnectionRecoveryManager({ client: this });
377
+ this.connectionRecovery.registerSubscriptions();
337
378
  this.reminders = new ReminderManager({ client: this });
338
379
  this.messageDeliveryReporter = new MessageDeliveryReporter({ client: this });
339
380
  this.messageComposerCache = new FixedSizeQueueCache<string, MessageComposer>(64);
381
+ // a cached composer, such as a message edit's, keeps the channel it was built with
382
+ this.channelManager.channelStore.addClaim({
383
+ heldBy: () =>
384
+ this.messageComposerCache.values().map((composer) => composer.channel),
385
+ name: 'message-composer-cache',
386
+ });
387
+
388
+ // Seed the declarative configuration before wiring, so a tree passed via `options.config` reaches
389
+ // the managers above. `'client'` is the one key that cannot be configured after construction —
390
+ // this registry is born here, so there is no earlier moment for a caller to register anything.
391
+ if (this.options.config) this.config.set(this.options.config);
392
+
393
+ // Last statement: everything a setup function might reach now exists. Subscribing applies the
394
+ // current configuration on the spot, which is the managers' one derivation — deriving here as
395
+ // well would run every `initializeConfig` twice per construction. `StateStore.subscribe` fires
396
+ // immediately, so a setup function registered later still applies at once.
397
+ this.wireClientConfiguration();
398
+ }
399
+
400
+ /**
401
+ * Subscribes the client's managers to the `'client'` configuration key.
402
+ *
403
+ * Called by the constructor and again by {@link _setUser}, because {@link disconnectUser} releases this
404
+ * subscription to run the setup function's teardown. A client is reusable — `getInstance` hands the same
405
+ * object back, and disconnect/connect is the documented multi-user and mobile-background flow — and the
406
+ * managers this key configures (`reminders`, `threads`, `messageDeliveryReporter`, `notifications`)
407
+ * outlive the user. Without the re-arm the key went permanently dead on the second connect: `setConfig`,
408
+ * `setSetupFunction` and `reset` all stopped reaching any manager, silently.
409
+ *
410
+ * Idempotent through the `unsubscribeClientConfiguration` guard, so the constructor's wiring is not
411
+ * duplicated by the first `connectUser`.
412
+ */
413
+ private wireClientConfiguration() {
414
+ if (this.unsubscribeClientConfiguration) return;
415
+ this.unsubscribeClientConfiguration = applyInstanceConfiguration({
416
+ args: { client: this },
417
+ config: this.config,
418
+ key: 'client',
419
+ applyConfig: () => this.initializeManagerConfig(),
420
+ reinitializeConfig: () => this.initializeManagerConfig(),
421
+ });
422
+ }
423
+
424
+ /**
425
+ * Derives each manager's configuration from package defaults plus the `client` declarative subtree.
426
+ * Shared by the constructor and `config.reset()`, so the two cannot drift.
427
+ *
428
+ * Defaults are spread first, and every manager is written unconditionally, because this is a
429
+ * derivation* rather than a patch — the same rule `Channel.initializeConfig` follows. Guarding on
430
+ * `if (config?.reminders)` and merging made `reset()` a no-op for this key: the store is cleared
431
+ * before instances re-derive, so the guards all failed and the registered values stayed in force.
432
+ * It also meant a field *removed* from the tree lingered, which is exactly what a merge cannot express.
433
+ */
434
+ private initializeManagerConfig() {
435
+ const config = this.config.getConfig('client');
436
+
437
+ this.connectionRecovery.initializeConfig(config?.connectionRecovery);
438
+ // Installs the platform listener named by the slice, falling back to the browser default.
439
+ this.networkConnection.initializeConfig(config?.networkConnection);
440
+ this.wsConnection.initializeConfig(config?.wsConnection);
441
+ this.reminders.initializeConfig(config?.reminders);
442
+ this.threads.initializeConfig(config?.threads);
443
+ this.messageDeliveryReporter.initializeConfig(config?.messageDelivery);
444
+ this.notifications.initializeConfig(config?.notifications);
340
445
  }
341
446
 
342
447
  get mutedUsers() {
@@ -347,12 +452,32 @@ export class StreamChat extends ChatApi {
347
452
  this.mutedUsersStore.next({ mutedUsers });
348
453
  }
349
454
 
350
- get configs() {
351
- return this.configsStore.getLatestValue().configs;
455
+ /**
456
+ * Cache of server-provided channel configuration, keyed by **cid** — a channel's own
457
+ * `config_overrides` can make it differ from every other channel of its type, so one entry per
458
+ * channel is the only key space that can represent the answer. See {@link _addChannelConfig}.
459
+ *
460
+ * Read it through {@link Channel.serverConfig} rather than here. Not to be confused with
461
+ * {@link config}, which is the configuration *you* register for SDK-created instances.
462
+ *
463
+ * This is `client.configs` from v9 under a name that says whose configuration it is — the key space is
464
+ * unchanged, so a v9 `client.configs[cid]` lookup translates directly. There is deliberately no
465
+ * `configs` alias: it read as a sibling of the integrator-facing {@link config} while holding the
466
+ * backend's answer, and the two being one letter apart is what made `channel.getConfig()` ambiguous
467
+ * enough to rename as well.
468
+ *
469
+ * Assigning through this setter notifies subscribers; mutating the returned record in place does not.
470
+ * Prefer {@link _addChannelConfig}.
471
+ *
472
+ * @internal
473
+ */
474
+ get channelServerConfigs() {
475
+ return this.channelServerConfigsStore.getLatestValue().configs;
352
476
  }
353
477
 
354
- set configs(configs: Configs) {
355
- this.configsStore.next({ configs });
478
+ /** @internal */
479
+ set channelServerConfigs(configs: Configs) {
480
+ this.channelServerConfigsStore.next({ configs });
356
481
  }
357
482
 
358
483
  /**
@@ -364,19 +489,14 @@ export class StreamChat extends ChatApi {
364
489
  *
365
490
  * @example <caption>initialize the client in user mode</caption>
366
491
  * StreamChat.getInstance('api_key')
367
- * @example <caption>initialize the client in user mode with options</caption>
368
- * StreamChat.getInstance('api_key', { timeout: 5000 })
369
- * @example <caption>secret is optional and only used in server side mode</caption>
370
- * StreamChat.getInstance('api_key', 'secret', { httpsAgent: customAgent })
492
+ * @example <caption>initialize the client with options</caption>
493
+ * StreamChat.getInstance('api_key', { axiosRequestConfig: { timeout: 5000 } })
371
494
  *
372
495
  * @param key - The API key.
373
- * @param options - Additional options; here you can pass custom options to the axios instance (optional).
496
+ * @param options - Additional options (optional).
374
497
  * @param options.browser - Enforce the client to be in browser mode (optional).
375
- * @param options.warmUp - If `true`, the client will open a connection as soon as possible to speed up following requests (optional, defaults to `false`).
376
- * @param options.logLevel - Minimum log level for the default sink (optional, defaults to `'info'`).
377
- * @param options.logOptions - Per-scope sink/level overrides for `chatLoggerSystem` (optional).
378
- * @param options.timeout - Request timeout (optional, defaults to `3000`).
379
- * @param options.httpsAgent - Custom `httpsAgent` (optional, in Node defaults to `https.agent()`).
498
+ * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
499
+ * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
380
500
  * @returns The shared client instance.
381
501
  */
382
502
  public static getInstance(key: string, options?: StreamChatOptions): StreamChat {
@@ -404,23 +524,17 @@ export class StreamChat extends ChatApi {
404
524
  this.wsBaseURL = this.baseURL.replace('http', 'ws').replace(':3030', ':8800');
405
525
  }
406
526
 
407
- _getConnectionID = () =>
408
- this.wsConnection?.connectionID || this.wsFallback?.connectionID;
527
+ _getConnectionID = () => this.connectionIdManager.connectionId;
409
528
 
410
529
  _hasConnectionID = () => Boolean(this._getConnectionID());
411
530
 
531
+ /**
532
+ * @deprecated Use `client.config.setSetupFunction('messageComposer', fn)`.
533
+ */
412
534
  public setMessageComposerSetupFunction = (
413
- setupFunction: MessageComposerSetupState['setupFunction'],
414
- ) => {
415
- this.instanceConfigurationService.setSetupFunctions({
416
- MessageComposer: setupFunction,
417
- });
418
- };
419
-
420
- public setInstanceConfigurationFunction = (
421
- setupFunctions: SetInstanceConfigurationFunctions,
535
+ setupFunction: InstanceSetupState<'messageComposer'>['setupFunction'],
422
536
  ) => {
423
- this.instanceConfigurationService.setSetupFunctions(setupFunctions);
537
+ this.config.setSetupFunction('messageComposer', setupFunction);
424
538
  };
425
539
 
426
540
  /**
@@ -467,18 +581,29 @@ export class StreamChat extends ChatApi {
467
581
 
468
582
  const wsPromise = this.openConnection();
469
583
 
470
- this.setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
584
+ const setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
471
585
  (result) => result[1], // We only return connection promise;
472
586
  );
587
+ this.setUserPromise = setUserPromise;
473
588
 
474
589
  try {
475
- return await this.setUserPromise;
590
+ return await setUserPromise;
476
591
  } catch (err) {
477
- if (this.persistUserOnConnectionFailure) {
478
- // cleanup client to allow the user to retry connectUser again
479
- this.closeConnection();
480
- } else {
481
- this.disconnectUser();
592
+ // disconnectUser() rejects an in-flight handshake, so this catch can run *after* something
593
+ // else has taken over. Cleaning up then would tear down whatever replaced us.
594
+ // `setUserPromise` catches a newer connectUser(); `userId` additionally catches
595
+ // connectAnonymousUser(), which never sets setUserPromise, and a bare disconnectUser()
596
+ // that already cleaned up.
597
+ if (this.setUserPromise === setUserPromise && this.userId === user.id) {
598
+ if (!this.persistUserOnConnectionFailure) {
599
+ // No user is kept, so there is nothing left to reconnect as. Tearing the socket down with
600
+ // it is the point: the application is expected to call `connectUser` again.
601
+ this.disconnectUser();
602
+ } else if (!isWSFailure(err as APIError)) {
603
+ // A terminal failure, so a rejected token or a bad API key will not fix itself, thus we close the
604
+ // socket instead of leaving `StableWSConnection` retrying against it.
605
+ this.closeConnection();
606
+ }
482
607
  }
483
608
  throw err;
484
609
  }
@@ -506,6 +631,9 @@ export class StreamChat extends ChatApi {
506
631
  this.user = user;
507
632
  // this one is actually used for requests. This is a copy of current user provided to `connectUser` function.
508
633
  this._user = { ...user };
634
+ // Re-arm the `'client'` key if a previous `disconnectUser` released it. Teardown at disconnect,
635
+ // setup at connect — see {@link wireClientConfiguration}.
636
+ this.wireClientConfiguration();
509
637
  }
510
638
 
511
639
  /**
@@ -518,19 +646,23 @@ export class StreamChat extends ChatApi {
518
646
  * So when your app goes to background, you can call `client.closeConnection`.
519
647
  * And when app comes back to foreground, call `client.openConnection`.
520
648
  *
649
+ * After an `enableWSFallback` switch it closes the long-poll as well, telling the server to
650
+ * close its connection id.
651
+ *
521
652
  * @param timeout - Max number of milliseconds to wait for the WebSocket close event before forcefully assuming
522
653
  * successful disconnection. See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent (optional).
654
+ * The long-poll's close request uses it as its timeout (2s when omitted).
523
655
  */
524
656
  closeConnection = async (timeout?: number) => {
657
+ this.channelManager.resetAIStateOnChannels();
658
+ this.channelManager.markChannelsWatchInterrupted();
659
+
525
660
  if (this.cleaningIntervalRef != null) {
526
661
  clearInterval(this.cleaningIntervalRef);
527
662
  this.cleaningIntervalRef = undefined;
528
663
  }
529
664
 
530
- await Promise.all([
531
- this.wsConnection?.disconnect(timeout),
532
- this.wsFallback?.disconnect(timeout),
533
- ]);
665
+ await this.wsConnection?.disconnect(timeout);
534
666
 
535
667
  this.offlineDb?.executeQuerySafely(
536
668
  async (db) => {
@@ -548,7 +680,8 @@ export class StreamChat extends ChatApi {
548
680
  };
549
681
 
550
682
  /**
551
- * Creates a new WebSocket connection with the current user.
683
+ * Creates a new WebSocket connection with the current user. After an `enableWSFallback` switch it
684
+ * reconnects the long-poll instead: the client never goes back to the WebSocket.
552
685
  *
553
686
  * @returns The WebSocket connect promise, or an empty resolved promise if a connection is already active.
554
687
  */
@@ -566,10 +699,7 @@ export class StreamChat extends ChatApi {
566
699
  return this.wsPromise;
567
700
  }
568
701
 
569
- if (
570
- (this.wsConnection?.isHealthy || this.wsFallback?.isHealthy()) &&
571
- this._hasConnectionID()
572
- ) {
702
+ if (this.wsConnection?.isHealthy && this.connectionIdManager.connectionId) {
573
703
  logger
574
704
  .withExtraTags('openConnection')
575
705
  .debug('openConnection was called twice; a healthy connection already exists.');
@@ -578,17 +708,69 @@ export class StreamChat extends ChatApi {
578
708
  }
579
709
 
580
710
  this.clientId = `${this.userId}--${randomId()}`;
581
- this.wsPromise = this.connect();
711
+ const wsPromise = this._bindWsPromise(this.connect());
582
712
  this._startCleaning();
583
- return this.wsPromise;
713
+ return wsPromise;
584
714
  };
715
+
716
+ /**
717
+ * Rejects the shared `wsPromise`, invalidates any in-flight connect attempt
718
+ */
719
+ private _rejectPendingWsPromise = (reason: Error) => {
720
+ if (!this._wsPromiseSettled) {
721
+ // invalidate in-flight attempts so a late settle cannot revive this promise
722
+ this._wsConnectId += 1;
723
+ this._wsPromiseSettled = true;
724
+ // Avoid unhandled promise rejection errors
725
+ this.wsPromise?.catch(() => {
726
+ // noop - real awaiters still observe the rejection
727
+ });
728
+ this._rejectWsPromise?.(reason);
729
+ }
730
+ };
731
+
732
+ /**
733
+ * Keep a single pending `wsPromise` across close/reopen so callers that already
734
+ * `await this.wsPromise` are not stranded when `openConnection` starts a new connect.
735
+ */
736
+ private _bindWsPromise = (connectPromise: ConnectAPIResponse): ConnectAPIResponse => {
737
+ const connectId = ++this._wsConnectId;
738
+
739
+ let pending = this.wsPromise;
740
+ if (this._wsPromiseSettled || !pending) {
741
+ this._wsPromiseSettled = false;
742
+ pending = new Promise((resolve, reject) => {
743
+ this._resolveWsPromise = resolve;
744
+ this._rejectWsPromise = reject;
745
+ });
746
+ this.wsPromise = pending;
747
+ }
748
+
749
+ connectPromise.then(
750
+ (value) => {
751
+ if (connectId !== this._wsConnectId) return;
752
+ this._wsPromiseSettled = true;
753
+ this._resolveWsPromise?.(value);
754
+ },
755
+ (error) => {
756
+ if (connectId !== this._wsConnectId) return;
757
+ this._wsPromiseSettled = true;
758
+ this._rejectWsPromise?.(error);
759
+ },
760
+ );
761
+
762
+ return pending;
763
+ };
764
+
585
765
  /**
586
766
  * Revokes tokens for a connected user issued before the given time.
587
767
  *
588
768
  * @param before - Cutoff date; tokens issued before this are revoked (optional, defaults to the current time).
769
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
770
+ * into the request (optional).
589
771
  * @returns The updated users response.
590
772
  */
591
- async revokeTokens(before?: Date | null) {
773
+ async revokeTokens(before?: Date | null, requestOptions?: StreamRequestOptions) {
592
774
  if (!before) {
593
775
  before = new Date();
594
776
  }
@@ -603,16 +785,23 @@ export class StreamChat extends ChatApi {
603
785
  },
604
786
  ];
605
787
 
606
- return await this.updateUsersPartial({ users });
788
+ return await this.updateUsersPartial({ users }, requestOptions);
607
789
  }
608
790
 
609
791
  /**
610
792
  * Retrieves application settings.
611
793
  *
794
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
795
+ * second argument, as on the generated methods; pass `undefined`.
796
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
797
+ * into the request (optional).
612
798
  * @returns The application settings response.
613
799
  */
614
- async getAppSettings() {
615
- return await (this.appSettingsPromise = this.getApp());
800
+ async getAppSettings(
801
+ _request?: Record<string, never>,
802
+ requestOptions?: StreamRequestOptions,
803
+ ) {
804
+ return await (this.appSettingsPromise = this.getApp(undefined, requestOptions));
616
805
  }
617
806
 
618
807
  /**
@@ -629,31 +818,51 @@ export class StreamChat extends ChatApi {
629
818
  delete this.user;
630
819
  delete this._user;
631
820
 
632
- const closePromise = this.closeConnection(timeout);
821
+ const teardownReason = new Error(
822
+ 'Connection was closed because disconnectUser() was called',
823
+ );
633
824
 
634
- for (const channel of Object.values(this.activeChannels)) {
635
- channel._disconnect();
825
+ this._rejectPendingWsPromise(teardownReason);
826
+ this.wsPromise = null;
827
+
828
+ const closePromise = this.closeConnection(timeout);
829
+ // After starting the close, which reads the connection id synchronously: after an
830
+ // `enableWSFallback` switch the long-poll's close request has to carry it.
831
+ this.connectionIdManager.rejectConnectionId(teardownReason);
832
+
833
+ // Drop the channels loaded into the channel lists, which belong to the user being disconnected.
834
+ // The lists stay registered: which lists exist is the application's configuration, not user data.
835
+ // Reset first, so each list empties in one update and no longer holds its channels; clearing the
836
+ // store then has no list to remove them from one by one.
837
+ this.channelManager.resetPaginatorStates();
838
+ // disconnects every channel (`disconnect()`) and ensures we no longer return inactive channels.
839
+ // It always empties the store, then rethrows the first error a holder threw; logged rather than
840
+ // propagated, so the rest of the logout below still runs.
841
+ try {
842
+ this.channelManager.clearChannels();
843
+ } catch (error) {
844
+ logger
845
+ .withExtraTags('disconnectUser')
846
+ .error('Clearing the channels failed during disconnect.', { error });
636
847
  }
637
- // ensure we no longer return inactive channels
638
- this.activeChannels = {};
639
848
  // reset client state
640
849
  this.state = new ClientState({ client: this });
641
850
  // reset thread manager
642
851
  this.threads.resetState();
643
- // drop the channels loaded into the channel lists — they belong to the user being disconnected
644
- // and have just been disconnected themselves. The lists stay registered: which lists exist is
645
- // the application's configuration, not user data.
646
- this.channelManager.resetPaginatorStates();
647
852
  // channel mutes are per-user; leaving them would let `muted` filters resolve against the
648
853
  // previous user until the next health check replaces them
649
854
  this.mutedChannels = [];
650
855
  this.uploadManager.reset();
651
856
  this.messageComposerCache.clear();
857
+ // Runs the `'client'` setup function's teardown. Cleared so repeated calls cannot double-run it.
858
+ this.unsubscribeClientConfiguration?.();
859
+ this.unsubscribeClientConfiguration = undefined;
652
860
 
653
- // Since we wipe all user data already, we should reset token manager as well
861
+ // Deferred so the long-poll close can still authenticate. By the time it settles a
862
+ // connectUser() / connectAnonymousUser() may have set the next user and their token.
654
863
  closePromise
655
864
  .finally(() => {
656
- this.tokenManager.reset();
865
+ if (!this.userId) this.tokenManager.reset();
657
866
  })
658
867
  .catch((err) =>
659
868
  logger
@@ -698,14 +907,40 @@ export class StreamChat extends ChatApi {
698
907
  return this.openConnection();
699
908
  };
700
909
 
910
+ /**
911
+ * Creates a guest user and returns its access token.
912
+ *
913
+ * @param args - The guest creation request, plus optional per-request options.
914
+ * @returns The created guest user and its access token.
915
+ */
916
+ override async createGuest(...args: Parameters<ChatApi['createGuest']>) {
917
+ if (this.tokenManager.token || this.tokenManager.tokenProvider) {
918
+ return await super.createGuest(...args);
919
+ }
920
+
921
+ // Set token to anonymous so API accepts the request
922
+ await this.tokenManager.setTokenOrProvider('', {
923
+ id: this.userId ?? '!anon',
924
+ anon: true,
925
+ });
926
+
927
+ try {
928
+ return await super.createGuest(...args);
929
+ } finally {
930
+ this.tokenManager.reset();
931
+ }
932
+ }
933
+
701
934
  /**
702
935
  * Sets up a temporary guest user.
703
936
  *
704
937
  * @param user - Data about this user, e.g. `{ name: 'john' }`.
938
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
939
+ * into the request (optional).
705
940
  * @returns A promise that resolves when the connection is set up.
706
941
  */
707
- async setGuestUser(user: UserResponse) {
708
- const response = await this.createGuest({ user });
942
+ async setGuestUser(user: UserResponse, requestOptions?: StreamRequestOptions) {
943
+ const response = await this.createGuest({ user }, requestOptions);
709
944
 
710
945
  const {
711
946
  created_at: _created_at,
@@ -795,15 +1030,18 @@ export class StreamChat extends ChatApi {
795
1030
  }
796
1031
 
797
1032
  dispatchEvent = (event: Event) => {
798
- if (!event.received_at) event.received_at = new Date();
1033
+ if (event.received_at == null) event.received_at = nowNs();
799
1034
 
800
1035
  // client event handlers
801
1036
  const postListenerCallbacks = this._handleClientEvent(event as WSEvent);
802
1037
 
803
1038
  // channel event handlers
804
1039
  const cid = (event as Extract<Event, { cid?: any }>).cid;
805
- const channel = cid ? this.activeChannels[cid] : undefined;
806
- if (channel) {
1040
+ const channel = cid ? this.channelManager.get(cid) : undefined;
1041
+ // A disconnected channel (`pendingDisposal`) may stay stored until `releaseUnusedChannels()`.
1042
+ // Its state is not updated any more, and its handlers would throw at `getClient()`, so the
1043
+ // event skips them; the channel's own listeners below still hear it.
1044
+ if (channel && !channel.pendingDisposal) {
807
1045
  channel._handleChannelEvent(event as WSEvent);
808
1046
  }
809
1047
 
@@ -813,7 +1051,18 @@ export class StreamChat extends ChatApi {
813
1051
  channel._callChannelListeners(event as WSEvent);
814
1052
  }
815
1053
 
816
- postListenerCallbacks.forEach((c) => c());
1054
+ // A failing in-memory cleanup (such as a holder throwing while a removed channel is unlinked)
1055
+ // must not skip the other callbacks or the offline DB write below, or the offline DB would keep
1056
+ // what the event ended.
1057
+ for (const callback of postListenerCallbacks) {
1058
+ try {
1059
+ callback();
1060
+ } catch (error) {
1061
+ logger
1062
+ .withExtraTags('dispatchEvent', event.type)
1063
+ .error('A post-listener callback failed.', { error });
1064
+ }
1065
+ }
817
1066
 
818
1067
  this.offlineDb?.executeQuerySafely((db) => db.handleEvent({ event }), {
819
1068
  method: `handleEvent;${event.type}`,
@@ -821,25 +1070,44 @@ export class StreamChat extends ChatApi {
821
1070
  };
822
1071
 
823
1072
  /**
824
- * Updates the members, watchers and read references of the currently active channels that contain this user.
1073
+ * Puts `user`'s new object into the members, watchers, own membership and (with `readEntries`)
1074
+ * read entries of the channels that list them. Each channel gets new objects in one state update,
1075
+ * so its subscribers re-render.
825
1076
  *
826
1077
  * @param user - The updated user.
1078
+ * @param options.readEntries - Also replace the user in read entries, refreshing the read receipts
1079
+ * (defaults to `true`). Off for a presence change: receipts show a user's name and image, never
1080
+ * their online status, so they would rebuild for nothing.
827
1081
  */
828
- _updateMemberWatcherReferences = (user: UserResponse) => {
1082
+ _updateMemberWatcherReferences = (
1083
+ user: UserResponse,
1084
+ { readEntries = true }: { readEntries?: boolean } = {},
1085
+ ) => {
829
1086
  const refMap = this.state.userChannelReferences[user.id] || {};
830
1087
  for (const channelId in refMap) {
831
- const channel = this.activeChannels[channelId];
832
- if (channel?.state) {
833
- if (channel.state.members[user.id]) {
834
- channel.state.members[user.id].user = user;
835
- }
836
- if (channel.state.watchers[user.id]) {
837
- channel.state.watchers[user.id] = user;
838
- }
839
- if (channel.state.read[user.id]) {
840
- channel.state.read[user.id].user = user;
841
- }
1088
+ const channel = this.channelManager.get(channelId);
1089
+ if (!channel?.state) continue;
1090
+ const { members, membership, watchers, read } = channel.state.getLatestValue();
1091
+ const member = members[user.id];
1092
+ const readState = readEntries ? read[user.id] : undefined;
1093
+ const hasWatcher = !!watchers[user.id];
1094
+ const isOwnMembership = membership?.user?.id === user.id;
1095
+ if (!member && !hasWatcher && !readState && !isOwnMembership) continue;
1096
+ // The receipts tracker applies a read-state change only with metadata naming the changed
1097
+ // users; without it, its readers would keep the user's old object.
1098
+ if (readState) {
1099
+ channel.messageReceiptsTracker.setPendingReadStoreReconcileMeta({
1100
+ changedUserIds: [user.id],
1101
+ });
842
1102
  }
1103
+ channel.state.partialNext({
1104
+ ...(member && { members: { ...members, [user.id]: { ...member, user } } }),
1105
+ ...(hasWatcher && { watchers: { ...watchers, [user.id]: user } }),
1106
+ ...(isOwnMembership && { membership: { ...membership, user } }),
1107
+ ...(readState && { read: { ...read, [user.id]: { ...readState, user } } }),
1108
+ });
1109
+ // consumed by the tracker's read subscription; cleared in case it isn't subscribed
1110
+ channel.messageReceiptsTracker.setPendingReadStoreReconcileMeta(undefined);
843
1111
  }
844
1112
  };
845
1113
 
@@ -850,19 +1118,19 @@ export class StreamChat extends ChatApi {
850
1118
  _updateUserReferences = this._updateMemberWatcherReferences;
851
1119
 
852
1120
  /**
853
- * Updates the messages from the currently active channels that contain this user, with the updated user object.
1121
+ * Updates the messages from the loaded channels that contain this user, with the updated user object.
854
1122
  *
855
1123
  * @private
856
1124
  *
857
1125
  * @param user - The updated user.
858
1126
  */
859
1127
  _updateUserMessageReferences = (user: UserResponse) => {
860
- // Scan all active channels rather than a user->channel reference map. MessageRequest authors are no
1128
+ // Scan all loaded channels rather than a user->channel reference map. MessageRequest authors are no
861
1129
  // longer registered as channel references (that registration was removed along with
862
1130
  // `Channel._trackLatestMessage`); `reflectUserUpdate` filters by author id internally, so it is
863
1131
  // a no-op on channels without this user's messages.
864
1132
  // The next step is to have user ItemIndex, where the update would be O(1) complexity
865
- for (const channel of Object.values(this.activeChannels)) {
1133
+ for (const channel of this.channelManager.values()) {
866
1134
  if (!channel) continue;
867
1135
 
868
1136
  /** update the messages from this user. */
@@ -872,7 +1140,7 @@ export class StreamChat extends ChatApi {
872
1140
  };
873
1141
 
874
1142
  /**
875
- * Deletes the messages from the currently active channels that contain this user.
1143
+ * Deletes the messages from the loaded channels that contain this user.
876
1144
  *
877
1145
  * If `hardDelete` is `true`, all the content of the message will be stripped down.
878
1146
  * Otherwise, only `message.type` will be set as `'deleted'`.
@@ -888,20 +1156,20 @@ export class StreamChat extends ChatApi {
888
1156
  hardDelete = false,
889
1157
  deletedAt?: LocalMessage['deleted_at'],
890
1158
  ) => {
891
- // Scan all active channels rather than a user->channel reference map (see
1159
+ // Scan all loaded channels rather than a user->channel reference map (see
892
1160
  // `_updateUserMessageReferences`); `applyMessageDeletionForUser` filters by author id internally.
893
- for (const channel of Object.values(this.activeChannels)) {
1161
+ for (const channel of this.channelManager.values()) {
894
1162
  if (channel) {
895
1163
  /** deleted the messages from this user. */
896
1164
  channel.messagePaginator.applyMessageDeletionForUser({
897
1165
  userId: user.id,
898
1166
  hardDelete,
899
- deletedAt: deletedAt ?? new Date(),
1167
+ deletedAt: deletedAt ?? nowNs(),
900
1168
  });
901
1169
  channel.pinnedMessagesPaginator.applyMessageDeletionForUser({
902
1170
  userId: user.id,
903
1171
  hardDelete,
904
- deletedAt: deletedAt ?? new Date(),
1172
+ deletedAt: deletedAt ?? nowNs(),
905
1173
  });
906
1174
  }
907
1175
  }
@@ -960,7 +1228,9 @@ export class StreamChat extends ChatApi {
960
1228
  }
961
1229
 
962
1230
  this.state.updateUser(event.user);
963
- this._updateMemberWatcherReferences(event.user);
1231
+ this._updateMemberWatcherReferences(event.user, {
1232
+ readEntries: event.type === 'user.updated',
1233
+ });
964
1234
  }
965
1235
 
966
1236
  if (event.type === 'user.updated') {
@@ -969,7 +1239,7 @@ export class StreamChat extends ChatApi {
969
1239
 
970
1240
  if (
971
1241
  event.type === 'user.deleted' &&
972
- event.user.deleted_at &&
1242
+ event.user.deleted_at != null &&
973
1243
  (event.mark_messages_deleted || event.hard_delete)
974
1244
  ) {
975
1245
  this._deleteUserMessageReference(
@@ -1000,10 +1270,11 @@ export class StreamChat extends ChatApi {
1000
1270
  this._deleteUserMessageReference(event.user, event.hard_delete, event.created_at);
1001
1271
  }
1002
1272
 
1003
- if (event.type === 'health.check' && event.me) {
1273
+ if ((event.type === 'health.check' || event.type === 'connection.ok') && event.me) {
1004
1274
  client.user = event.me;
1005
1275
  client.state.updateUser(event.me);
1006
1276
  client.mutedChannels = event.me.channel_mutes;
1277
+ client.channelManager.reflectMutedChannels();
1007
1278
  client.mutedUsers = event.me.mutes;
1008
1279
  client.blockedUsers.partialNext({ userIds: event.me.blocked_user_ids ?? [] });
1009
1280
  }
@@ -1015,6 +1286,7 @@ export class StreamChat extends ChatApi {
1015
1286
 
1016
1287
  if (event.type === 'notification.channel_mutes_updated' && event.me?.channel_mutes) {
1017
1288
  this.mutedChannels = event.me.channel_mutes;
1289
+ this.channelManager.reflectMutedChannels();
1018
1290
  }
1019
1291
 
1020
1292
  if (event.type === 'notification.mutes_updated' && event.me?.mutes) {
@@ -1022,11 +1294,13 @@ export class StreamChat extends ChatApi {
1022
1294
  }
1023
1295
 
1024
1296
  if (event.type === 'notification.mark_read' && event.unread_channels === 0) {
1025
- const activeChannelKeys = Object.keys(this.activeChannels);
1026
- activeChannelKeys.forEach(
1027
- (activeChannelKey) =>
1028
- (this.activeChannels[activeChannelKey].state.unreadCount = 0),
1029
- );
1297
+ this.channelManager.values().forEach((channel) => {
1298
+ // resets `read[userId].unread_messages`, which is what the unread badge reads, so it does
1299
+ // not stay stale.
1300
+ if (!channel._setOwnUnreadCount(0)) return;
1301
+ // the event may name no channel (mark-all-read), but here we know which ones changed
1302
+ this.channelManager.dropFromUnmatchedLists(channel);
1303
+ });
1030
1304
  }
1031
1305
 
1032
1306
  if (
@@ -1036,42 +1310,49 @@ export class StreamChat extends ChatApi {
1036
1310
  ) {
1037
1311
  const { cid } = event;
1038
1312
  client.state.deleteAllChannelReference(cid);
1039
- this.activeChannels[event.cid]?._disconnect();
1313
+ const ended = this.channelManager.get(cid);
1314
+ ended?.disconnect();
1040
1315
 
1041
1316
  postListenerCallbacks.push(() => {
1042
- if (!cid) return;
1043
-
1044
- delete this.activeChannels[cid];
1317
+ // only the instance disconnected above: a listener that got the channel again keeps its
1318
+ // fresh instance (`ensure()` replaces a disposed one)
1319
+ if (ended && this.channelManager.get(cid) === ended) {
1320
+ this.channelManager.removeChannel(cid);
1321
+ }
1045
1322
  });
1046
1323
  }
1047
1324
 
1048
1325
  // Current user removed from a channel: evict it like channel.deleted so
1049
- // recoverState won't re-watch it and no further events reach it (#2599).
1326
+ // connection recovery won't re-watch it and no further events reach it (#2599).
1050
1327
  // Type-agnostic. We skip deleteAllChannelReference (unlike deletion) since
1051
1328
  // the channel still exists for its remaining members.
1052
1329
  if (event.type === 'notification.removed_from_channel' && event.cid) {
1053
1330
  const { cid } = event;
1054
- this.activeChannels[cid]?._disconnect();
1331
+ const ended = this.channelManager.get(cid);
1332
+ ended?.disconnect();
1055
1333
 
1056
1334
  postListenerCallbacks.push(() => {
1057
- delete this.activeChannels[cid];
1335
+ // only the instance disconnected above, as for channel.deleted
1336
+ if (ended && this.channelManager.get(cid) === ended) {
1337
+ this.channelManager.removeChannel(cid);
1338
+ }
1058
1339
  });
1059
1340
  }
1060
1341
 
1061
1342
  return postListenerCallbacks;
1062
1343
  }
1063
1344
 
1064
- _muteStatus(cid: string) {
1065
- let muteStatus;
1345
+ _muteStatus(cid: string): ChannelMuteStatus {
1346
+ let muteStatus: ChannelMuteStatus | undefined;
1066
1347
  for (let i = 0; i < this.mutedChannels.length; i++) {
1067
1348
  const mute = this.mutedChannels[i];
1068
1349
  if (mute.channel?.cid === cid) {
1069
1350
  muteStatus = {
1070
- muted: mute.expires
1071
- ? new Date(mute.expires).getTime() > new Date().getTime()
1072
- : true,
1073
- createdAt: mute.created_at ? new Date(mute.created_at) : new Date(),
1074
- expiresAt: mute.expires ? new Date(mute.expires) : null,
1351
+ // `expires` is a wire timestamp, so it compares directly against the local clock in the
1352
+ // same unit. Comparing it against `Date.now()` would make every expiry look far future.
1353
+ muted: mute.expires != null ? mute.expires > nowNs() : true,
1354
+ createdAt: mute.created_at ?? nowNs(),
1355
+ expiresAt: mute.expires ?? null,
1075
1356
  };
1076
1357
  break;
1077
1358
  }
@@ -1089,44 +1370,48 @@ export class StreamChat extends ChatApi {
1089
1370
  }
1090
1371
 
1091
1372
  _callClientListeners = (event: Event) => {
1092
- const allSet = this.listeners.get('all');
1093
- const targetSet = this.listeners.get(event.type);
1373
+ // Snapshot before dispatching: `on` adds to these sets in place and `Set.forEach` visits
1374
+ // entries appended mid-iteration, so a listener that subscribes while handling an event
1375
+ // must not be invoked for it.
1376
+ const listeners = [
1377
+ ...(this.listeners.get('all') ?? []),
1378
+ ...(this.listeners.get(event.type) ?? []),
1379
+ ];
1094
1380
 
1095
- [allSet, targetSet].forEach((set) =>
1096
- set?.forEach((handleEvent) => handleEvent(event)),
1097
- );
1381
+ for (const listener of listeners) {
1382
+ invokeEventListener(listener, event, logger);
1383
+ }
1098
1384
  };
1099
1385
 
1100
- recoverState = async () => {
1386
+ /**
1387
+ * Settles the connect promises after a successful reconnect, so `connectUser()` and the
1388
+ * `wsPromise`/`setUserPromise` a caller may still be holding stop resolving against a superseded
1389
+ * (possibly rejected) attempt.
1390
+ *
1391
+ * Requests no longer settle against these: waiting for a connection id is the
1392
+ * {@link ConnectionIdManager}'s job, applied centrally in `ApiClient`.
1393
+ *
1394
+ * Called by `StableWSConnection._reconnect()`, and by `WSConnectionFallback.connect(true)`
1395
+ * for the long-poll's own reconnects. Recovery itself is owned by
1396
+ * {@link ConnectionRecoveryManager}, which subscribes to the connection lifecycle and so
1397
+ * covers every reconnect path — including `closeConnection()` → `openConnection()` (mobile
1398
+ * backgrounding), which reaches neither.
1399
+ *
1400
+ * @internal
1401
+ */
1402
+ _settleConnectPromises = () => {
1101
1403
  logger
1102
- .withExtraTags('recoverState')
1103
- .info(`Starting state recovery with connection ID ${this._getConnectionID()}.`);
1104
-
1105
- const cids = Object.keys(this.activeChannels);
1106
- if (cids.length && this.recoverStateOnReconnect) {
1107
- logger
1108
- .withExtraTags('recoverState')
1109
- .info(`Starting the query for ${cids.length} channel(s).`);
1110
-
1111
- await this.queryChannelsAndHydrate({
1112
- filter_conditions: {
1113
- cid: { $in: cids },
1114
- },
1115
- limit: 30,
1116
- sort: [{ field: 'last_message_at', direction: -1 }],
1117
- });
1404
+ .withExtraTags('_settleConnectPromises')
1405
+ .info(
1406
+ `Connection re-established with connection ID ${this.connectionIdManager.connectionId}.`,
1407
+ );
1118
1408
 
1119
- logger.withExtraTags('recoverState').info('Finished querying channels.');
1120
- this.dispatchEvent({
1121
- type: 'connection.recovered',
1122
- });
1123
- } else {
1124
- this.dispatchEvent({
1125
- type: 'connection.recovered',
1126
- });
1409
+ // If state recovery happens afer a failed connect (for example on persistUserOnConnectionFailure: true) we need to flip the wsPromise from rejected to resolved
1410
+ // Otherwise all API calls that wait for the promise will fail
1411
+ // If promise is not yet settled - we leave it for the connect sequence to resolve the promise
1412
+ if (this._wsPromiseSettled) {
1413
+ this.wsPromise = Promise.resolve();
1127
1414
  }
1128
-
1129
- this.wsPromise = Promise.resolve();
1130
1415
  this.setUserPromise = Promise.resolve();
1131
1416
  };
1132
1417
 
@@ -1146,102 +1431,57 @@ export class StreamChat extends ChatApi {
1146
1431
  throw Error('Property clientId is not set');
1147
1432
  }
1148
1433
 
1149
- if (!this.wsConnection && (this.options.warmUp || this.options.enableInsights)) {
1150
- this._sayHi();
1151
- }
1152
- // The StableWSConnection handles all the reconnection logic.
1153
- if (this.options.wsConnection && this.node) {
1154
- // Intentionally avoiding adding ts generics on wsConnection in options since its only useful for unit test purpose.
1155
- (this.options.wsConnection as unknown as StableWSConnection).setClient(this);
1156
- this.wsConnection = this.options.wsConnection as unknown as StableWSConnection;
1157
- } else {
1158
- this.wsConnection = new StableWSConnection({
1159
- client: this,
1160
- });
1161
- }
1162
-
1163
- try {
1164
- // if fallback is used before, continue using it instead of waiting for WS to fail
1165
- if (this.wsFallback) {
1166
- return await this.wsFallback.connect();
1167
- }
1168
-
1169
- // if WSFallback is enabled, ws connect should timeout faster so fallback can try
1170
- return await this.wsConnection.connect(
1171
- this.options.enableWSFallback
1172
- ? this.defaultWSTimeoutWithFallback
1173
- : this.defaultWSTimeout,
1174
- );
1175
- } catch (error: any) {
1176
- // run fallback only if it's WS/Network error and not a normal API error
1177
- // make sure browser is online before even trying the longpoll
1178
- if (this.options.enableWSFallback && isWSFailure(error) && isOnline()) {
1179
- logger
1180
- .withExtraTags('connect')
1181
- .warn('The WebSocket connection failed; falling back to long-polling.');
1182
- this.dispatchEvent({ type: 'transport.changed', mode: 'longpoll' });
1183
-
1184
- this.wsConnection._destroyCurrentWSConnection();
1185
- this.wsConnection.disconnect().then(); // close WS so no retry
1186
- this.wsFallback = new WSConnectionFallback({
1187
- client: this,
1188
- });
1189
- return await this.wsFallback.connect();
1190
- }
1191
-
1192
- throw error;
1193
- }
1194
- }
1195
-
1196
- /**
1197
- * Checks connectivity with the server for warmup purposes.
1198
- *
1199
- * @private
1200
- */
1201
- _sayHi() {
1202
- const client_request_id = randomId();
1203
- const opts = { headers: { 'x-client-request-id': client_request_id } };
1204
- this.api.doAxiosRequest('get', this.baseURL + '/hi', null, opts).catch((e) => {
1205
- if (this.options.enableInsights) {
1206
- postInsights('http_hi_failed', {
1207
- api_key: this.key,
1208
- err: e,
1209
- client_request_id,
1210
- });
1211
- }
1212
- });
1434
+ // `wsConnection` builds and owns the socket — and, with `enableWSFallback`, the long-poll it
1435
+ // switches to; the reconnection logic and the connect timeout (`config.connectTimeoutMs`) live
1436
+ // in there.
1437
+ return await this.wsConnection.connect();
1213
1438
  }
1214
1439
 
1215
1440
  /**
1216
1441
  * Queries users and watches user presence.
1217
1442
  *
1218
- * @param request - The query users request payload (optional). The inner `payload` accepts
1443
+ * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts
1219
1444
  * MongoDB-style filter conditions, sort directions (e.g. `[{ field: 'last_active', direction: -1 }]`),
1220
- * and options such as `presence`.
1445
+ * and options such as `presence`. `requestOptions` carries per-request options such as an
1446
+ * abort `signal` and is never serialized into the request.
1221
1447
  * @returns The user query response.
1222
1448
  */
1223
- override async queryUsers(request?: { payload?: Gen_QueryUsersPayload }) {
1224
- // Make sure we wait for the connect promise if there is a pending one
1225
- await this.wsPromise;
1226
-
1227
- const data = await super.queryUsers(request);
1449
+ override async queryUsers(...args: Parameters<ChatApi['queryUsers']>) {
1450
+ const [request, requestOptions] = args;
1451
+ const data = await super.queryUsers(request ?? {}, requestOptions);
1228
1452
  this.state.updateUsers(data.users);
1229
1453
 
1230
1454
  return data;
1231
1455
  }
1232
1456
 
1233
1457
  /**
1234
- * Queries user bans.
1458
+ * Stops watching a channel on this client's connection.
1459
+ *
1460
+ * It carries no `watch` flag, so the request layer does not hold it, but it is connection-scoped
1461
+ * by definition: it tells the server which connection should stop watching. So it waits for this
1462
+ * client's connection id exactly as a watching request does — through a handshake or a reconnect,
1463
+ * until the caller's abort signal fires — and throws when there is no connection and none is being
1464
+ * established.
1235
1465
  *
1236
- * @param request - The query banned users request payload (optional). The inner `payload`
1237
- * accepts MongoDB-style filter conditions, sort directions
1238
- * (e.g. `[{ field: 'created_at', direction: 1 }]`), and options such as `limit`, `offset`,
1239
- * and `exclude_expired_bans`.
1240
- * @returns The ban query response.
1466
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams` identifies the channel
1467
+ * (`{ type, id }`); `request.connection_id` is replaced by this client's connection id.
1468
+ * @returns The server response.
1241
1469
  */
1242
- async queryBannedUsers(request?: { payload?: QueryBannedUsersPayload }) {
1243
- // Return a list of user bans
1244
- return await super.queryBannedUsers(request);
1470
+ override async stopWatchingChannel(
1471
+ ...args: Parameters<ChatApi['stopWatchingChannel']>
1472
+ ) {
1473
+ const [pathParams, request, requestOptions] = args;
1474
+ const signal = requestOptions?.signal;
1475
+ const connectionId = await this.connectionIdManager.getConnectionId(
1476
+ // Check if signal is still usable - if it is read from offline DB, it has lost `addEventListener`.
1477
+ typeof signal?.addEventListener === 'function' ? signal : undefined,
1478
+ );
1479
+
1480
+ return super.stopWatchingChannel(
1481
+ pathParams,
1482
+ { ...request, connection_id: connectionId },
1483
+ requestOptions,
1484
+ );
1245
1485
  }
1246
1486
 
1247
1487
  /**
@@ -1253,26 +1493,20 @@ export class StreamChat extends ChatApi {
1253
1493
  * only the channel list. In the next major release, the request/response APIs should
1254
1494
  * be consolidated so callers can access the full response through the primary API.
1255
1495
  *
1256
- * @param request - The query channels request payload (optional). Accepts MongoDB-style filter
1257
- * conditions, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`), and options
1258
- * such as `predefined_filter`, `filter_values`, and `sort_values`.
1496
+ * @param ...args - `[request, requestOptions]`. The optional `request` accepts MongoDB-style
1497
+ * filter conditions, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`), and
1498
+ * options such as `predefined_filter`, `filter_values`, and `sort_values`. `requestOptions`
1499
+ * carries per-request options such as an abort `signal` and is never serialized into the request.
1259
1500
  * @returns The full query channels response.
1260
1501
  */
1261
- override async queryChannels(request?: QueryChannelsRequest) {
1502
+ override async queryChannels(...args: Parameters<ChatApi['queryChannels']>) {
1503
+ const [request, requestOptions] = args;
1262
1504
  const defaultOptions: ChannelOptions = {
1263
1505
  state: true,
1264
1506
  watch: true,
1265
1507
  presence: false,
1266
1508
  };
1267
1509
 
1268
- // Make sure we wait for the connect promise if there is a pending one
1269
- await this.wsPromise;
1270
-
1271
- // TODO: probably serverside only thing, remove at some point
1272
- if (!this._hasConnectionID()) {
1273
- defaultOptions.watch = false;
1274
- }
1275
-
1276
1510
  const {
1277
1511
  predefined_filter,
1278
1512
  filter_values,
@@ -1296,7 +1530,9 @@ export class StreamChat extends ChatApi {
1296
1530
  ...restOptions,
1297
1531
  };
1298
1532
 
1299
- return await super.queryChannels(payload);
1533
+ // No wait here either — see `channel.watch()`. `ApiClient` gates on the flags this payload
1534
+ // carries, so a watched query waits for a connection id and a plain read does not.
1535
+ return await super.queryChannels(payload, requestOptions);
1300
1536
  }
1301
1537
 
1302
1538
  /**
@@ -1318,21 +1554,35 @@ export class StreamChat extends ChatApi {
1318
1554
  * @param stateOptions.withResponse - Returns the full query response with hydrated channels.
1319
1555
  * This is a compatibility bridge for internal callers that need response-level metadata while
1320
1556
  * the default return value remains `Channel[]` (optional).
1557
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1558
+ * into the request (optional).
1321
1559
  * @returns The hydrated channel list, or the full response when `withResponse` is `true`.
1322
1560
  */
1323
1561
  async queryChannelsAndHydrate(
1324
1562
  options?: QueryChannelsRequest,
1325
1563
  stateOptions?: ChannelStateOptions & { withResponse: true },
1564
+ requestOptions?: StreamRequestOptions,
1326
1565
  ): Promise<QueryChannelsResponseWithChannels>;
1327
1566
  async queryChannelsAndHydrate(
1328
1567
  options?: QueryChannelsRequest,
1329
1568
  stateOptions?: ChannelStateOptions,
1569
+ requestOptions?: StreamRequestOptions,
1330
1570
  ): Promise<Channel[]>;
1331
1571
  async queryChannelsAndHydrate(
1332
1572
  options?: QueryChannelsRequest,
1333
1573
  stateOptions: ChannelStateOptions = {},
1574
+ requestOptions?: StreamRequestOptions,
1334
1575
  ): Promise<Channel[] | QueryChannelsResponseWithChannels> {
1335
- const queryChannelsResponse = await this.queryChannels(options);
1576
+ // TODO(perf/cleanup): prefer a `memberIds` snapshot over `headItems.map` here too — see the
1577
+ // matching TODO in channel.query() for the full rationale.
1578
+ const candidateIdsByCid = new Map<string, ReadonlySet<string>>();
1579
+ for (const channel of this.channelManager.values()) {
1580
+ const { cid } = channel;
1581
+ const head = channel.messagePaginator?.headItems;
1582
+ if (head?.length)
1583
+ candidateIdsByCid.set(cid, new Set(head.map((message) => message.id)));
1584
+ }
1585
+ const queryChannelsResponse = await this.queryChannels(options, requestOptions);
1336
1586
  const channels = queryChannelsResponse.channels;
1337
1587
 
1338
1588
  this.dispatchEvent({
@@ -1349,7 +1599,12 @@ export class StreamChat extends ChatApi {
1349
1599
  });
1350
1600
  }
1351
1601
 
1352
- const hydratedChannels = this.hydrateActiveChannels(channels, stateOptions, options);
1602
+ const hydratedChannels = this.hydrateChannels(
1603
+ channels,
1604
+ stateOptions,
1605
+ options,
1606
+ candidateIdsByCid,
1607
+ );
1353
1608
 
1354
1609
  if (stateOptions.withResponse) {
1355
1610
  return {
@@ -1365,13 +1620,15 @@ export class StreamChat extends ChatApi {
1365
1620
  * Queries reactions for a message and hydrates any cached offline reactions before the network
1366
1621
  * request.
1367
1622
  *
1368
- * @param request - The query reactions request payload, including the target message ID,
1369
- * MongoDB-style filters, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`),
1370
- * and pagination options.
1623
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the target message ID;
1624
+ * `request` carries MongoDB-style filters, sort directions (e.g.
1625
+ * `[{ field: 'created_at', direction: -1 }]`) and pagination options; `requestOptions` carries
1626
+ * per-request options such as an abort `signal` and is never serialized into the request.
1371
1627
  * @returns The query reactions response.
1372
1628
  */
1373
- async queryReactionsAndHydrate(request: QueryReactionsRequestWithId) {
1374
- const { filter, next, id: messageId, sort, limit } = request;
1629
+ async queryReactionsAndHydrate(...args: Parameters<ChatApi['queryReactions']>) {
1630
+ const [{ id: messageId }, request] = args;
1631
+ const { filter, next, sort, limit } = request ?? {};
1375
1632
 
1376
1633
  if (this.offlineDb?.getReactions && !next) {
1377
1634
  try {
@@ -1395,16 +1652,14 @@ export class StreamChat extends ChatApi {
1395
1652
  }
1396
1653
  }
1397
1654
 
1398
- // Make sure we wait for the connect promise if there is a pending one
1399
- await this.wsPromise;
1400
-
1401
- return await this.queryReactions(request);
1655
+ return await this.queryReactions(...args);
1402
1656
  }
1403
1657
 
1404
- hydrateActiveChannels(
1658
+ hydrateChannels(
1405
1659
  channelsFromApi: ChannelStateResponseFields[] = [],
1406
1660
  stateOptions: ChannelStateOptions = {},
1407
1661
  queryChannelsOptions?: ChannelOptions,
1662
+ candidateIdsByCid?: Map<string, ReadonlySet<string>>,
1408
1663
  ) {
1409
1664
  const { skipInitialization, offlineMode = false } = stateOptions;
1410
1665
  const channels: Channel[] = [];
@@ -1413,12 +1668,25 @@ export class StreamChat extends ChatApi {
1413
1668
  if (!channelState.channel) continue;
1414
1669
 
1415
1670
  this._addChannelConfig(channelState.channel);
1416
- const c = this.channel(channelState.channel.type, channelState.channel.id);
1417
- const previousData = c.data;
1671
+ const c = this.channelManager.ensure({
1672
+ type: channelState.channel.type,
1673
+ id: channelState.channel.id,
1674
+ });
1418
1675
  c.data = channelState.channel;
1419
- c._syncStateFromChannelData(c.data, previousData);
1420
- c.offlineMode = offlineMode;
1421
- c.initialized = !offlineMode;
1676
+ // A live result initializes the channel; one restored from the offline database doesn't.
1677
+ c.state.partialNext(
1678
+ offlineMode
1679
+ ? { initialized: false, offlineMode: true }
1680
+ : { initialized: true, offlineMode: false },
1681
+ );
1682
+ // Same precedence `queryChannels` applies to the request: an explicit caller choice wins,
1683
+ // otherwise we watch only if there is a connection to watch on: `hydrateChannels` is
1684
+ // public, so a direct caller has no gated request behind it to imply a watch. Offline
1685
+ // hydration populates state without a live watch, so it never counts - and a query that did
1686
+ // not watch leaves the status untouched (it neither starts nor ends a watch).
1687
+ if (!offlineMode && (queryChannelsOptions?.watch ?? this.wsConnection.isHealthy)) {
1688
+ c.watchStatus = ChannelWatchStatus.Watching;
1689
+ }
1422
1690
  c.push_preferences = channelState.push_preferences;
1423
1691
 
1424
1692
  const willInitialize =
@@ -1438,13 +1706,19 @@ export class StreamChat extends ChatApi {
1438
1706
  // newest page to merge into that jumped interval across the gap (missing messages in the
1439
1707
  // middle). A cold paginator, or one still at the head (offline/at-latest), re-seeds normally so
1440
1708
  // cursors/hasMoreTail get (re)derived and pagination keeps working.
1709
+ // Also skip the re-seed for an ACTIVE (on-screen) channel: its own `channel.reload()` owns the
1710
+ // loaded window (up to 100 msgs), so a 25-msg list re-seed here is a redundant second update
1711
+ // that could perturb the fuller window. (Inert until a UI SDK calls `channel.activate()`.)
1441
1712
  if (
1442
1713
  willInitialize &&
1714
+ !c.active &&
1443
1715
  (!c.messagePaginator.isInitialized || c.messagePaginator.isActiveIntervalAtHead)
1444
1716
  ) {
1445
1717
  c.messagePaginator.seedFirstPageSync(
1446
1718
  channelState.messages.map(formatMessage),
1447
1719
  requestedPageSize,
1720
+ undefined,
1721
+ { reconcile: true, candidateIds: candidateIdsByCid?.get(c.cid) },
1448
1722
  );
1449
1723
  }
1450
1724
 
@@ -1468,229 +1742,77 @@ export class StreamChat extends ChatApi {
1468
1742
  }
1469
1743
 
1470
1744
  /**
1471
- * Queries messages.
1472
- *
1473
- * @param request - The search request payload (optional). The inner `payload` accepts
1474
- * MongoDB-style filter conditions, a search query, and options such as `user_id`.
1475
- * @returns The search messages response.
1476
- */
1477
- override async search(request?: { payload?: SearchPayload }) {
1478
- if (request?.payload?.offset && request?.payload?.next) {
1479
- throw Error(`Cannot specify "offset" with "next"`);
1480
- }
1481
-
1482
- // Make sure we wait for the connect promise if there is a pending one
1483
- await this.wsPromise;
1484
-
1485
- return await super.search(request);
1486
- }
1487
-
1488
- /**
1489
- * Sets the device info for the current client. It will be sent via the WS connection automatically.
1745
+ * Returns the channel with the given type, ID and custom data: a shorthand for
1746
+ * {@link ChannelManager.ensure} (`client.channelManager.ensure({ type, id, data })`), so it returns
1747
+ * the stored instance for the cid, or creates and stores it.
1490
1748
  *
1491
- * @param device - The device object.
1492
- * @param device.id - Device ID.
1493
- * @param device.push_provider - The push provider.
1494
- */
1495
- setLocalDevice(device: BaseDeviceFields) {
1496
- if (
1497
- (this.wsConnection?.isConnecting && this.wsPromise) ||
1498
- ((this.wsConnection?.isHealthy || this.wsFallback?.isHealthy()) &&
1499
- this._hasConnectionID())
1500
- ) {
1501
- throw new Error('Device cannot be set before opening a WebSocket connection');
1502
- }
1503
-
1504
- this.options.device = device;
1505
- }
1506
-
1507
- _addChannelConfig({ cid, config }: ChannelResponse) {
1508
- if (this._cacheEnabled()) {
1509
- this.configs = {
1510
- ...this.configs,
1511
- [cid]: config,
1512
- };
1513
- }
1514
- }
1515
-
1516
- /**
1517
- * Returns a new channel with the given type, ID and custom data.
1518
- *
1519
- * If you want to create a unique conversation between 2 or more users, you can leave out the ID
1520
- * parameter and provide the list of members.
1521
- * Make sure to await `channel.create()` or `channel.watch()` before accessing channel functions,
1522
- * i.e. `channel = client.channel('messaging', { members: ['tommaso', 'thierry'] })` then
1523
- * `await channel.create()` to assign an ID to the channel.
1749
+ * To get a distinct channel between two or more users, leave out the ID and pass the members:
1750
+ * `client.channel('messaging', { members: [{ user_id: 'tommaso' }, { user_id: 'thierry' }] })`.
1751
+ * It has no ID until `channel.watch()`, `query()` or `create()` returns one.
1524
1752
  *
1525
1753
  * @param channelType - The channel type.
1526
- * @param channelIdOrCustom - The channel ID; you can leave this out if you want to create a
1527
- * conversation channel (optional).
1528
- * @param custom - Custom data to attach to the channel (optional, defaults to `{}`).
1529
- * @returns The channel object; initialize it using `channel.watch()`.
1754
+ * @param channelIdOrCustom - The channel ID; leave it out for a distinct channel created from
1755
+ * members (optional).
1756
+ * @param custom - Data for a new channel, e.g. `members` or `custom` (optional, defaults to `{}`).
1757
+ * @returns The channel; initialize it with `channel.watch()`.
1530
1758
  */
1531
- channel(channelType: string, channelId?: string | null, custom?: ChannelData): Channel;
1532
- channel(channelType: string, custom?: ChannelData): Channel;
1759
+ channel(channelType: string, channelId?: string | null, custom?: ChannelInput): Channel;
1760
+ channel(channelType: string, custom?: ChannelInput): Channel;
1533
1761
  channel(
1534
1762
  channelType: string,
1535
- channelIdOrCustom?: string | ChannelData | null,
1536
- custom: ChannelData = {},
1537
- ) {
1538
- if (!this.userId) {
1539
- throw Error('Call connectUser or connectAnonymousUser before creating a channel');
1540
- }
1541
-
1542
- if (~channelType.indexOf(':')) {
1543
- throw new Error(
1544
- `Invalid channel group ${channelType}, can't contain the : character`,
1545
- );
1546
- }
1547
-
1548
- // support channel("messaging", {options})
1763
+ channelIdOrCustom?: string | ChannelInput | null,
1764
+ custom: ChannelInput = {},
1765
+ ): Channel {
1766
+ // channel('messaging', { members }): the data takes the ID's place
1549
1767
  if (channelIdOrCustom && typeof channelIdOrCustom === 'object') {
1550
- return this.getChannelByMembers(channelType, channelIdOrCustom);
1551
- }
1552
-
1553
- // support channel("messaging", undefined, {options})
1554
- if (!channelIdOrCustom && typeof custom === 'object' && custom.members?.length) {
1555
- return this.getChannelByMembers(channelType, custom);
1768
+ return this.channelManager.ensure({ data: channelIdOrCustom, type: channelType });
1556
1769
  }
1557
-
1558
- // support channel("messaging", null, {options})
1559
- // support channel("messaging", undefined, {options})
1560
- // support channel("messaging", "", {options})
1561
- if (!channelIdOrCustom) {
1562
- return new Channel(this, channelType, undefined, custom);
1563
- }
1564
-
1565
- return this.getChannelById(channelType, channelIdOrCustom, custom);
1770
+ return this.channelManager.ensure({
1771
+ data: custom,
1772
+ id: channelIdOrCustom || undefined,
1773
+ type: channelType,
1774
+ });
1566
1775
  }
1567
1776
 
1568
1777
  /**
1569
- * It's a helper method for `client.channel()` method, used to create unique conversation or
1570
- * channel based on member list instead of ID.
1571
- *
1572
- * If the channel already exists in `activeChannels` list, then we simply return it, since that
1573
- * means the same channel was already requested or created.
1574
- *
1575
- * Otherwise we create a new instance of Channel class and return it.
1576
- *
1577
- * @private
1778
+ * Queries messages.
1578
1779
  *
1579
- * @param channelType - The channel type.
1580
- * @param custom - Custom data to attach to the channel.
1581
- * @returns The channel object; initialize it using `channel.watch()`.
1582
- */
1583
- getChannelByMembers = (channelType: string, custom: ChannelData) => {
1584
- // Check if the channel already exists.
1585
- // Only allow 1 channel object per cid
1586
- const memberIds = (custom.members ?? []).map((member) =>
1587
- typeof member === 'string' ? member : member.user_id,
1588
- );
1589
- const membersStr = memberIds.sort().join(',');
1590
- const tempCid = generateChannelTempCid(channelType, memberIds);
1591
-
1592
- if (!tempCid) {
1593
- throw Error('Please specify atleast one member when creating unique conversation');
1594
- }
1595
-
1596
- // channel could exist in `activeChannels` list with either one of the following two keys:
1597
- // 1. cid - Which gets set on channel only after calling channel.query or channel.watch or channel.create
1598
- // 2. Sorted membersStr - E.g., "messaging:amin,vishal" OR "messaging:amin,jaap,tom"
1599
- // This is set when you create a channel, but haven't queried yet. After query,
1600
- // we will replace it with `cid`
1601
- for (const key in this.activeChannels) {
1602
- const channel = this.activeChannels[key];
1603
- if (channel.disconnected) {
1604
- continue;
1605
- }
1606
-
1607
- if (key === tempCid) {
1608
- return channel;
1609
- }
1610
-
1611
- if (key.indexOf(`${channelType}:!members-`) === 0) {
1612
- const membersStrInExistingChannel = Object.keys(channel.state.members)
1613
- .sort()
1614
- .join(',');
1615
- if (membersStrInExistingChannel === membersStr) {
1616
- return channel;
1617
- }
1618
- }
1619
- }
1620
-
1621
- const channel = new Channel(this, channelType, undefined, custom);
1622
-
1623
- // For the time being set the key as membersStr, since we don't know the cid yet.
1624
- // In channel.query, we will replace it with 'cid'.
1625
- if (this._cacheEnabled()) {
1626
- this.activeChannels[tempCid] = channel;
1780
+ * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts
1781
+ * MongoDB-style filter conditions, a search query, and options such as `user_id`.
1782
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1783
+ * serialized into the request.
1784
+ * @returns The search messages response.
1785
+ */
1786
+ override async search(...args: Parameters<ChatApi['search']>) {
1787
+ const [request, requestOptions] = args;
1788
+ if (request?.payload?.offset && request?.payload?.next) {
1789
+ throw Error(`Cannot specify "offset" with "next"`);
1627
1790
  }
1628
1791
 
1629
- return channel;
1630
- };
1792
+ return await super.search(request, requestOptions);
1793
+ }
1631
1794
 
1632
1795
  /**
1633
- * It's a helper method for `client.channel()`, used to retrieve a channel given its ID.
1634
- *
1635
- * If the channel already exists in `activeChannels` list, then we simply return it, since that
1636
- * means the same channel was already requested or created.
1796
+ * Caches one channel's server configuration, read through {@link Channel.serverConfig}.
1637
1797
  *
1638
- * Otherwise we create a new instance of `Channel` class and return it.
1798
+ * Keyed by **cid** rather than by channel type: a channel's own `config_overrides` narrow its type's
1799
+ * settings for that channel alone, so two channels of one type can disagree.
1639
1800
  *
1640
- * @private
1801
+ * Two writes are skipped. A response with no `config` — `notification.message_new` is one route that
1802
+ * omits it — would otherwise un-learn a config already known for the channel. A config deep-equal to
1803
+ * the stored one keeps a repeated query from waking that channel's subscribers, which matters because
1804
+ * the API returns a fresh object every time and the store compares by reference.
1641
1805
  *
1642
- * @param channelType - The channel type.
1643
- * @param channelId - The channel ID.
1644
- * @param custom - Custom data to attach to the channel.
1645
- * @returns The channel object; initialize it using `channel.watch()`.
1806
+ * @internal
1646
1807
  */
1647
- getChannelById = (channelType: string, channelId: string, custom: ChannelData) => {
1648
- if (typeof channelId === 'string' && ~channelId.indexOf(':')) {
1649
- throw Error(`Invalid channel id ${channelId}, can't contain the : character`);
1650
- }
1808
+ _addChannelConfig({ cid, config }: Pick<ChannelResponse, 'cid' | 'config'>) {
1809
+ if (!config) return;
1810
+ if (isEqual(this.channelServerConfigs[cid], config)) return;
1651
1811
 
1652
- // only allow 1 channel object per cid
1653
- const cid = `${channelType}:${channelId}`;
1654
- if (
1655
- cid in this.activeChannels &&
1656
- this.activeChannels[cid] &&
1657
- !this.activeChannels[cid].disconnected
1658
- ) {
1659
- const channel = this.activeChannels[cid];
1660
- // Only overwrite the existing channel's custom data when the caller actually provided some.
1661
- // A caller passing other fields (e.g. `{ members }`, or even `{ members: undefined }`) yields a
1662
- // non-empty object with no `.custom`; the previous `Object.keys(custom).length > 0` guard let
1663
- // that through and then set `custom: custom.custom` (undefined), wiping the channel's existing
1664
- // custom data (e.g. its name). Guarding on `custom.custom` keeps genuine custom updates while
1665
- // leaving the existing custom intact when the caller omits it.
1666
- if (custom.custom !== undefined) {
1667
- const previousData = channel.data;
1668
- channel.data = { ...channel.data, custom: custom.custom };
1669
- channel._syncStateFromChannelData(channel.data, previousData);
1670
- channel._data = { ...channel._data, custom: custom.custom };
1671
- }
1672
- return channel;
1673
- }
1674
- const channel = new Channel(this, channelType, channelId, custom);
1675
- if (this._cacheEnabled()) {
1676
- this.activeChannels[channel.cid] = channel;
1677
- }
1678
-
1679
- return channel;
1680
- };
1681
-
1682
- /**
1683
- * Bans a user from all channels.
1684
- *
1685
- * @param targetUserId - The user to ban.
1686
- * @param options - Ban options (optional).
1687
- * @returns The server response.
1688
- */
1689
- async banUser(targetUserId: string, options?: BanUserOptions) {
1690
- return await this.api.post<APIResponse>(this.baseURL + '/moderation/ban', {
1691
- target_user_id: targetUserId,
1692
- ...options,
1693
- });
1812
+ this.channelServerConfigs = {
1813
+ ...this.channelServerConfigs,
1814
+ [cid]: config,
1815
+ };
1694
1816
  }
1695
1817
 
1696
1818
  /**
@@ -1707,91 +1829,38 @@ export class StreamChat extends ChatApi {
1707
1829
  });
1708
1830
  }
1709
1831
 
1710
- /**
1711
- * Shadow bans a user from all channels.
1712
- *
1713
- * @param targetUserId - The user to shadow ban.
1714
- * @param options - Ban options (optional).
1715
- * @returns The server response.
1716
- */
1717
- async shadowBan(targetUserId: string, options?: BanUserOptions) {
1718
- return await this.banUser(targetUserId, {
1719
- shadow: true,
1720
- ...options,
1721
- });
1722
- }
1723
-
1724
- /**
1725
- * Revoke a global shadow ban for a user.
1726
- *
1727
- * @param targetUserId - The user to remove the shadow ban for.
1728
- * @param options - Unban options (optional).
1729
- * @returns The server response.
1730
- */
1731
- async removeShadowBan(targetUserId: string, options?: UnBanUserOptions) {
1732
- return await this.unbanUser(targetUserId, {
1733
- shadow: true,
1734
- ...options,
1735
- });
1736
- }
1737
- async blockUser(blockedUserId: string) {
1738
- const result = await this.blockUsers({
1739
- blocked_user_id: blockedUserId,
1740
- });
1741
- if (this._cacheEnabled()) {
1742
- this.blockedUsers.next(({ userIds }) => ({
1743
- userIds: userIds.concat(blockedUserId),
1744
- }));
1745
- }
1746
- return result;
1747
- }
1748
-
1749
- override async getBlockedUsers() {
1750
- const result = await super.getBlockedUsers();
1751
- if (this._cacheEnabled()) {
1752
- this.blockedUsers.partialNext({
1753
- userIds: result.blocks.map(({ blocked_user_id }) => blocked_user_id),
1754
- });
1755
- }
1832
+ async blockUser(blockedUserId: string, requestOptions?: StreamRequestOptions) {
1833
+ const result = await this.blockUsers(
1834
+ {
1835
+ blocked_user_id: blockedUserId,
1836
+ },
1837
+ requestOptions,
1838
+ );
1839
+ this.blockedUsers.next(({ userIds }) => ({
1840
+ userIds: userIds.concat(blockedUserId),
1841
+ }));
1756
1842
  return result;
1757
1843
  }
1758
1844
 
1759
- async unblockUser(blockedUserId: string) {
1760
- const result = await this.unblockUsers({
1761
- blocked_user_id: blockedUserId,
1845
+ override async getBlockedUsers(...args: Parameters<ChatApi['getBlockedUsers']>) {
1846
+ const result = await super.getBlockedUsers(...args);
1847
+ this.blockedUsers.partialNext({
1848
+ userIds: result.blocks.map(({ blocked_user_id }) => blocked_user_id),
1762
1849
  });
1763
- if (this._cacheEnabled()) {
1764
- this.blockedUsers.next(({ userIds }) => ({
1765
- userIds: userIds.filter((id) => id !== blockedUserId),
1766
- }));
1767
- }
1768
1850
  return result;
1769
1851
  }
1770
1852
 
1771
- /**
1772
- * Mutes a user.
1773
- *
1774
- * @param targetId - The user to mute.
1775
- * @param options - UserMuteResponse options (optional, defaults to `{}`).
1776
- * @returns The server response.
1777
- */
1778
- async muteUser(targetId: string, options: MuteUserOptions = {}) {
1779
- return await this.api.post<MuteUserResponse>(this.baseURL + '/moderation/mute', {
1780
- target_id: targetId,
1781
- ...options,
1782
- });
1783
- }
1784
-
1785
- /**
1786
- * Unmutes a user.
1787
- *
1788
- * @param targetId - The user to unmute.
1789
- * @returns The server response.
1790
- */
1791
- async unmuteUser(targetId: string) {
1792
- return await this.api.post<APIResponse>(this.baseURL + '/moderation/unmute', {
1793
- target_id: targetId,
1794
- });
1853
+ async unblockUser(blockedUserId: string, requestOptions?: StreamRequestOptions) {
1854
+ const result = await this.unblockUsers(
1855
+ {
1856
+ blocked_user_id: blockedUserId,
1857
+ },
1858
+ requestOptions,
1859
+ );
1860
+ this.blockedUsers.next(({ userIds }) => ({
1861
+ userIds: userIds.filter((id) => id !== blockedUserId),
1862
+ }));
1863
+ return result;
1795
1864
  }
1796
1865
 
1797
1866
  /**
@@ -1811,88 +1880,28 @@ export class StreamChat extends ChatApi {
1811
1880
  return false;
1812
1881
  }
1813
1882
 
1814
- /**
1815
- * Flag a message.
1816
- *
1817
- * @param targetMessageId - The message to flag.
1818
- * @param options - Flag options (optional, defaults to `{}`).
1819
- * @param options.reason - Reason for flagging (optional).
1820
- * @returns The server response.
1821
- */
1822
- async flagMessage(targetMessageId: string, options: { reason?: string } = {}) {
1823
- return await this.api.post<FlagMessageResponse>(this.baseURL + '/moderation/flag', {
1824
- target_message_id: targetMessageId,
1825
- ...options,
1826
- });
1827
- }
1828
-
1829
- /**
1830
- * Flag a user.
1831
- *
1832
- * @param targetId - The user to flag.
1833
- * @param options - Flag options (optional, defaults to `{}`).
1834
- * @param options.reason - Reason for flagging (optional).
1835
- * @returns The server response.
1836
- */
1837
- async flagUser(targetId: string, options: { reason?: string } = {}) {
1838
- return await this.api.post<FlagUserResponse>(this.baseURL + '/moderation/flag', {
1839
- target_user_id: targetId,
1840
- ...options,
1841
- });
1842
- }
1843
-
1844
- /**
1845
- * Unflag a message.
1846
- *
1847
- * @param targetMessageId - The message to unflag.
1848
- * @returns The server response.
1849
- */
1850
- async unflagMessage(targetMessageId: string) {
1851
- return await this.api.post<FlagMessageResponse>(this.baseURL + '/moderation/unflag', {
1852
- target_message_id: targetMessageId,
1853
- });
1854
- }
1855
-
1856
- /**
1857
- * Unflag a user.
1858
- *
1859
- * @param targetId - The user to unflag.
1860
- * @returns The server response.
1861
- */
1862
- async unflagUser(targetId: string) {
1863
- return await this.api.post<FlagUserResponse>(this.baseURL + '/moderation/unflag', {
1864
- target_user_id: targetId,
1865
- });
1866
- }
1867
-
1868
- /**
1869
- * Unblocks a message blocked by automod.
1870
- *
1871
- * @param targetMessageId - The message to unblock.
1872
- * @returns The server response.
1873
- */
1874
- async unblockMessage(targetMessageId: string) {
1875
- return await this.api.post<APIResponse>(
1876
- this.baseURL + '/moderation/unblock_message',
1877
- {
1878
- target_message_id: targetMessageId,
1879
- },
1880
- );
1881
- }
1882
-
1883
1883
  /**
1884
1884
  * Transforms an expiration value into an ISO string.
1885
1885
  *
1886
+ * A `number` is an offset in SECONDS, not a timestamp — passing a wire `pin_expires` overflows
1887
+ * `Date`, which used to surface as an opaque `RangeError` from `toISOString()`.
1888
+ *
1886
1889
  * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1887
1890
  * in seconds, `string` or `Date` to set the exact expiration date (optional).
1888
1891
  * @returns The expiration as an ISO string, or `null`.
1892
+ * @throws If a numeric offset does not resolve to a representable date.
1889
1893
  */
1890
1894
  _normalizeExpiration(timeoutOrExpirationDate?: null | number | string | Date) {
1891
1895
  let pinExpires: null | string = null;
1892
1896
  if (typeof timeoutOrExpirationDate === 'number') {
1893
- const now = new Date();
1894
- now.setSeconds(now.getSeconds() + timeoutOrExpirationDate);
1895
- pinExpires = now.toISOString();
1897
+ const expiresAt = new Date();
1898
+ expiresAt.setSeconds(expiresAt.getSeconds() + timeoutOrExpirationDate);
1899
+ if (Number.isNaN(expiresAt.getTime())) {
1900
+ throw new Error(
1901
+ `Expiration offset ${timeoutOrExpirationDate} does not resolve to a valid date`,
1902
+ );
1903
+ }
1904
+ pinExpires = expiresAt.toISOString();
1896
1905
  } else if (isString(timeoutOrExpirationDate)) {
1897
1906
  pinExpires = timeoutOrExpirationDate;
1898
1907
  } else if (timeoutOrExpirationDate instanceof Date) {
@@ -1927,122 +1936,90 @@ export class StreamChat extends ChatApi {
1927
1936
  /**
1928
1937
  * Pins the message.
1929
1938
  *
1939
+ * A `number` is a relative offset in SECONDS, so a server-sent timestamp (`message.pinned_at`,
1940
+ * `message.pin_expires`) is rejected at compile time rather than read as ~1.79e18 seconds from now.
1941
+ * Hand one back as a date with `nsToDate(timestamp)`.
1942
+ *
1930
1943
  * @param messageOrMessageId - MessageRequest object or message ID.
1931
1944
  * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1932
1945
  * in seconds, `string` or `Date` to set the exact expiration date (optional).
1933
1946
  * @param pinnedAt - Date when the message should be pinned. It affects the order of pinned
1934
1947
  * messages. Use a negative number to set relative time in the past, `string` or `Date` to
1935
1948
  * set the exact date of pin (optional).
1949
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1950
+ * into the request (optional).
1936
1951
  * @returns The updated message response.
1937
1952
  */
1938
- pinMessage(
1953
+ pinMessage<
1954
+ Expiration extends null | number | string | Date | undefined = undefined,
1955
+ PinnedAt extends number | string | Date | undefined = undefined,
1956
+ >(
1939
1957
  messageOrMessageId: string | { id: string },
1940
- timeoutOrExpirationDate?: null | number | string | Date,
1941
- pinnedAt?: number | string | Date,
1958
+ timeoutOrExpirationDate?: NotATimestampNS<Expiration>,
1959
+ pinnedAt?: NotATimestampNS<PinnedAt>,
1960
+ requestOptions?: StreamRequestOptions,
1942
1961
  ) {
1943
1962
  const id = this._validateAndGetMessageId(
1944
1963
  messageOrMessageId,
1945
1964
  'Please specify the message id when calling pinMessage',
1946
1965
  );
1947
- return this.updateMessagePartial({
1948
- id,
1949
- set: {
1950
- pinned: true,
1951
- pin_expires: this._normalizeExpiration(timeoutOrExpirationDate),
1952
- pinned_at: this._normalizeExpiration(pinnedAt),
1966
+ return this.updateMessagePartial(
1967
+ { id },
1968
+ {
1969
+ set: {
1970
+ pinned: true,
1971
+ pin_expires: this._normalizeExpiration(timeoutOrExpirationDate),
1972
+ pinned_at: this._normalizeExpiration(pinnedAt),
1973
+ },
1953
1974
  },
1954
- });
1975
+ requestOptions,
1976
+ );
1955
1977
  }
1956
1978
 
1957
1979
  /**
1958
1980
  * Unpins the message that was previously pinned.
1959
1981
  *
1960
1982
  * @param messageOrMessageId - MessageRequest object or message ID.
1983
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1984
+ * into the request (optional).
1961
1985
  * @returns The updated message response.
1962
1986
  */
1963
- unpinMessage(messageOrMessageId: string | { id: string }) {
1987
+ unpinMessage(
1988
+ messageOrMessageId: string | { id: string },
1989
+ requestOptions?: StreamRequestOptions,
1990
+ ) {
1964
1991
  const id = this._validateAndGetMessageId(
1965
1992
  messageOrMessageId,
1966
1993
  'Please specify the message id when calling unpinMessage',
1967
1994
  );
1968
- return this.updateMessagePartial({
1969
- id,
1970
- set: { pinned: false },
1971
- });
1995
+ return this.updateMessagePartial({ id }, { set: { pinned: false } }, requestOptions);
1972
1996
  }
1973
1997
 
1974
1998
  /**
1975
- * Updates the given message. When an `offlineDb` is registered the call is queued
1976
- * so it is replayed on reconnect.
1999
+ * Updates the given message — the HTTP request and nothing else: no offline queueing and no local
2000
+ * state. `messageOperations.update` on a channel or thread is the full edit.
1977
2001
  */
1978
- override async updateMessage(
1979
- request: Parameters<ChatApi['updateMessage']>[0] & { message: { cid?: string } },
1980
- ) {
1981
- try {
1982
- if (this.offlineDb) {
1983
- return await this.offlineDb.queueTask<
1984
- Awaited<ReturnType<ChatApi['updateMessage']>>
1985
- >({
1986
- task: {
1987
- ...getPendingTaskChannelData(request.message?.cid),
1988
- messageId: request.id,
1989
- payload: [request],
1990
- type: 'update-message',
1991
- },
1992
- });
1993
- }
1994
- } catch (error) {
1995
- offlineDbLogger
1996
- .withExtraTags('updateMessage')
1997
- .error('Updating the message failed.', { error });
1998
- }
1999
-
2000
- return await this._updateMessage(request);
2001
- }
2002
+ override async updateMessage(...args: Parameters<ChatApi['updateMessage']>) {
2003
+ const [pathParams, request, requestOptions] = args;
2002
2004
 
2003
- async _updateMessage(request: Parameters<ChatApi['updateMessage']>[0]) {
2004
- return await super.updateMessage(request);
2005
+ // Sanitized at the wire, which every path reaches: the full edit and an offline replay alike.
2006
+ return await super.updateMessage(
2007
+ pathParams,
2008
+ { ...request, message: sanitizeOutgoingAttachments(request.message) },
2009
+ requestOptions,
2010
+ );
2005
2011
  }
2006
2012
 
2007
2013
  /**
2008
- * Deletes a message. When an `offlineDb` is registered the call is queued so it
2009
- * is replayed on reconnect.
2014
+ * Deletes a message — the HTTP request and nothing else: no offline queueing and no local state.
2015
+ * `messageOperations.delete` on a channel or thread is the full delete.
2010
2016
  */
2011
- override async deleteMessage(request: Parameters<ChatApi['deleteMessage']>[0]) {
2012
- try {
2013
- if (this.offlineDb) {
2014
- if (request.hard) {
2015
- await this.offlineDb.hardDeleteMessage({ id: request.id });
2016
- } else {
2017
- await this.offlineDb.softDeleteMessage({
2018
- id: request.id,
2019
- deleteForMe: request.delete_for_me,
2020
- });
2021
- }
2022
- return await this.offlineDb.queueTask<
2023
- Awaited<ReturnType<ChatApi['deleteMessage']>>
2024
- >({
2025
- task: {
2026
- messageId: request.id,
2027
- payload: [request],
2028
- type: 'delete-message',
2029
- },
2030
- });
2031
- }
2032
- } catch (error) {
2033
- offlineDbLogger
2034
- .withExtraTags('deleteMessage')
2035
- .error('Deleting the message failed.', { error });
2036
- }
2037
-
2038
- return this._deleteMessage(request);
2039
- }
2040
-
2041
- async _deleteMessage(request: Parameters<ChatApi['deleteMessage']>[0]) {
2042
- const result = await super.deleteMessage(request);
2017
+ override async deleteMessage(...args: Parameters<ChatApi['deleteMessage']>) {
2018
+ const [, request] = args;
2019
+ const result = await super.deleteMessage(...args);
2043
2020
 
2044
2021
  // 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) {
2022
+ if (request?.delete_for_me) {
2046
2023
  result.message.deleted_for_me = true;
2047
2024
  result.message.type = 'deleted';
2048
2025
  }
@@ -2061,9 +2038,14 @@ export class StreamChat extends ChatApi {
2061
2038
  * @param options.reply_limit - Limits the number of replies returned per thread (optional).
2062
2039
  * @param options.filter - MongoDB style filters for threads (optional).
2063
2040
  * @param options.sort - MongoDB style sort for threads (optional).
2041
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2042
+ * into the request (optional).
2064
2043
  * @returns The list of threads and the next cursor.
2065
2044
  */
2066
- async queryThreadsAndHydrate(options: QueryThreadsRequest = {}) {
2045
+ async queryThreadsAndHydrate(
2046
+ options: QueryThreadsRequest = {},
2047
+ requestOptions?: StreamRequestOptions,
2048
+ ) {
2067
2049
  const optionsWithDefaults = {
2068
2050
  limit: 10,
2069
2051
  participant_limit: 10,
@@ -2087,19 +2069,19 @@ export class StreamChat extends ChatApi {
2087
2069
  requestBody.sort = optionsWithDefaults.sort;
2088
2070
  }
2089
2071
 
2090
- const response = await this.queryThreads(requestBody);
2072
+ const response = await this.queryThreads(requestBody, requestOptions);
2091
2073
 
2092
2074
  // Hydrate the polls for the parent messages of the threads
2093
2075
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2094
2076
  const parentMessages = response.threads.map((thread) => thread.parent_message!);
2095
2077
  this.polls.hydratePollCache(parentMessages);
2096
2078
 
2097
- return {
2098
- threads: response.threads.map(
2099
- (thread) => new Thread({ client: this, threadData: thread }),
2100
- ),
2101
- next: response.next,
2102
- };
2079
+ const threads = response.threads.map(
2080
+ (thread) => new Thread({ client: this, threadData: thread }),
2081
+ );
2082
+ if (optionsWithDefaults.watch) threads.forEach(markThreadChannelWatched);
2083
+
2084
+ return { threads, next: response.next };
2103
2085
  }
2104
2086
 
2105
2087
  /**
@@ -2111,9 +2093,15 @@ export class StreamChat extends ChatApi {
2111
2093
  * @param options.watch - Subscribes the user to the channel of the thread (optional).
2112
2094
  * @param options.participant_limit - Limits the number of participants returned per thread (optional).
2113
2095
  * @param options.reply_limit - Limits the number of replies returned per thread (optional).
2096
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2097
+ * into the request (optional).
2114
2098
  * @returns The thread.
2115
2099
  */
2116
- async getThreadAndHydrate(messageId: string, options: GetThreadOptions = {}) {
2100
+ async getThreadAndHydrate(
2101
+ messageId: string,
2102
+ options: GetThreadOptions = {},
2103
+ requestOptions?: StreamRequestOptions,
2104
+ ) {
2117
2105
  if (!messageId) {
2118
2106
  throw new Error('Please specify the messageId when calling getThreadAndHydrate');
2119
2107
  }
@@ -2125,53 +2113,16 @@ export class StreamChat extends ChatApi {
2125
2113
  ...options,
2126
2114
  };
2127
2115
 
2128
- const response = await this.getThread({
2129
- message_id: messageId,
2130
- ...optionsWithDefaults,
2131
- });
2132
-
2133
- return new Thread({ client: this, threadData: response.thread });
2134
- }
2135
-
2136
- /**
2137
- * Updates the given thread.
2138
- *
2139
- * @param messageId - The ID of the thread message which needs to be updated.
2140
- * @param partialThreadObject - Should contain `set` or `unset` params for any of the thread's non-reserved fields.
2141
- * @returns The updated thread.
2142
- */
2143
- async partialUpdateThread(messageId: string, partialThreadObject: PartialThreadUpdate) {
2144
- if (!messageId) {
2145
- throw Error('Please specify the message id when calling partialUpdateThread');
2146
- }
2147
-
2148
- // check for reserved fields from ThreadResponse type within partialThreadObject's set and unset.
2149
- // Throw error if any of the reserved field is found.
2150
- const reservedThreadFields = [
2151
- 'created_at',
2152
- 'id',
2153
- 'last_message_at',
2154
- 'type',
2155
- 'updated_at',
2156
- 'user',
2157
- 'reply_count',
2158
- 'participants',
2159
- 'channel',
2160
- 'custom',
2161
- ];
2116
+ const response = await this.getThread(
2117
+ { message_id: messageId },
2118
+ optionsWithDefaults,
2119
+ requestOptions,
2120
+ );
2162
2121
 
2163
- for (const key in { ...partialThreadObject.set, ...partialThreadObject.unset }) {
2164
- if (reservedThreadFields.includes(key)) {
2165
- throw Error(
2166
- `You cannot set ${key} field on Thread object. ${key} is reserved for server-side use. Please omit ${key} from your set object.`,
2167
- );
2168
- }
2169
- }
2122
+ const thread = new Thread({ client: this, threadData: response.thread });
2123
+ if (optionsWithDefaults.watch) markThreadChannelWatched(thread);
2170
2124
 
2171
- return await this.updateThreadPartial({
2172
- message_id: messageId,
2173
- ...partialThreadObject,
2174
- });
2125
+ return thread;
2175
2126
  }
2176
2127
 
2177
2128
  getUserAgent = (): string => {
@@ -2222,124 +2173,124 @@ export class StreamChat extends ChatApi {
2222
2173
  this.userAgent = userAgent;
2223
2174
  }
2224
2175
 
2225
- _cacheEnabled = () => !this.options.disableCache;
2226
-
2227
2176
  _startCleaning() {
2228
- // eslint-disable-next-line @typescript-eslint/no-this-alias
2229
- const that = this;
2230
2177
  if (this.cleaningIntervalRef != null) {
2231
2178
  return;
2232
2179
  }
2233
2180
  this.cleaningIntervalRef = setInterval(() => {
2234
2181
  // call clean on the channel, used for calling the stop.typing event etc.
2235
- for (const channel of Object.values(that.activeChannels)) {
2236
- channel.clean();
2182
+ for (const channel of this.channelManager.values()) {
2183
+ // a disposed channel has nothing to clean, and `clean()` would throw on it
2184
+ if (channel.pendingDisposal) continue;
2185
+ // one channel failing to clean must not stop the others (typing indicators would stick)
2186
+ try {
2187
+ channel.clean();
2188
+ } catch (error) {
2189
+ logger
2190
+ .withExtraTags('clean', channel.cid)
2191
+ .error('Cleaning the channel failed.', { error });
2192
+ }
2237
2193
  }
2238
2194
  }, 500);
2239
2195
  }
2240
2196
 
2241
2197
  /**
2242
- * Encodes the WS URL payload.
2198
+ * Encodes the WebSocket auth message, sent as the first frame once the socket opens.
2199
+ *
2200
+ * `products` is not optional in practice: without `'chat'` the server treats the
2201
+ * connection as video-only, which drops every chat event and unread count.
2243
2202
  *
2244
2203
  * @private
2245
2204
  *
2246
- * @param client_request_id - The client request ID (optional).
2247
- * @returns The JSON-encoded payload string.
2205
+ * @returns The JSON-encoded auth message.
2248
2206
  */
2249
- _buildWSPayload = (client_request_id?: string) =>
2250
- JSON.stringify({
2251
- user_id: this.userId,
2252
- user_details: this._user,
2253
- device: this.options.device,
2254
- client_request_id,
2255
- });
2207
+ _buildWSAuthMessage = () =>
2208
+ JSON.stringify(this._buildWSAuthPayload(this.tokenManager.getToken()));
2209
+
2210
+ /**
2211
+ * The auth message itself — what {@link _buildWSAuthMessage} encodes for the WebSocket, and what
2212
+ * the long-poll fallback sends as `longPoll()`'s `json` query param.
2213
+ *
2214
+ * @private
2215
+ *
2216
+ * @param token - The token the message carries. The long-poll passes none: it authenticates
2217
+ * through the request's `Authorization` header instead.
2218
+ */
2219
+ _buildWSAuthPayload = (token?: string): WSAuthMessage => ({
2220
+ // The server requires a non-empty token, but skips JWT parsing for any string that is not
2221
+ // shaped like one. Anonymous users have no token, and the long-poll does not send one, so both
2222
+ // send a placeholder the server accepts and ignores.
2223
+ token: token || 'anonymous',
2224
+ // `connect()` rejects before reaching this when `_user` is unset.
2225
+ user_details: this._user as ConnectUserDetailsRequest,
2226
+ products: ['chat'],
2227
+ });
2256
2228
 
2257
2229
  /**
2258
2230
  * Queries poll answers.
2259
2231
  *
2260
- * @param request - The query poll answers request payload, including the poll ID, optional vote
2261
- * filter conditions, sort directions, and pagination options (`limit`, `offset`).
2262
- * @param request.poll_id - The poll ID.
2263
- * @param request.filter - Vote filter conditions.
2232
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.poll_id` is the poll ID;
2233
+ * `request` carries optional vote filter conditions, sort directions, and pagination options
2234
+ * (`limit`, `offset`).
2264
2235
  * @returns The poll answers.
2265
2236
  */
2266
- async queryPollAnswers({
2267
- poll_id,
2268
- filter,
2269
- ...options
2270
- }: Parameters<ChatApi['queryPollVotes']>[0]) {
2271
- return await this.queryPollVotes({
2272
- poll_id,
2273
- filter: {
2274
- ...filter,
2275
- is_answer: true,
2276
- },
2277
- ...options,
2278
- });
2237
+ async queryPollAnswers(...args: Parameters<ChatApi['queryPollVotes']>) {
2238
+ const [pathParams, request, requestOptions] = args;
2239
+ const { filter, ...options } = request ?? {};
2240
+
2241
+ return await this.queryPollVotes(
2242
+ pathParams,
2243
+ { ...options, filter: { ...filter, is_answer: true } },
2244
+ requestOptions,
2245
+ );
2279
2246
  }
2280
2247
 
2281
2248
  /**
2282
- * Uploads a file to the configured storage (defaults to Stream CDN).
2249
+ * Uploads a file to the Stream CDN
2283
2250
  *
2284
- * @param uri - The file to upload.
2285
- * @param name - The name of the file (optional).
2286
- * @param contentType - The content type of the file (optional).
2287
- * @param user - User information (optional).
2288
- * @param axiosRequestConfig - Axios config, e.g. `onUploadProgress` for progress tracking (optional).
2251
+ * @param request - Upload payload. `request.file` is the file to upload.
2252
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
2289
2253
  * @returns Response containing the file URL.
2290
2254
  */
2291
- uploadFile_(
2292
- uri: string | NodeJS.ReadableStream | Buffer | File,
2293
- name?: string,
2294
- contentType?: string,
2295
- user?: UserResponse,
2296
- axiosRequestConfig?: AxiosRequestConfig,
2255
+ override async uploadFile(
2256
+ request?: Omit<FileUploadRequest, 'file'> & { file?: FileUploadInput },
2257
+ requestOptions?: StreamRequestOptions,
2297
2258
  ) {
2298
- return this.api.sendFile(
2299
- `${this.baseURL}/uploads/file`,
2300
- uri,
2301
- name,
2302
- contentType,
2303
- user,
2304
- axiosRequestConfig,
2259
+ return await super.uploadFile(
2260
+ { ...request, file: normalizeUploadFile(request?.file) as unknown as string },
2261
+ requestOptions,
2305
2262
  );
2306
2263
  }
2307
2264
 
2308
2265
  /**
2309
- * Uploads an image to the configured storage (defaults to Stream CDN).
2266
+ * Uploads an image to Stream CDN
2310
2267
  *
2311
- * @param uri - The image to upload.
2312
- * @param name - The name of the image (optional).
2313
- * @param contentType - The content type of the image (optional).
2314
- * @param user - User information (optional).
2315
- * @param axiosRequestConfig - Axios config, e.g. `onUploadProgress` for progress tracking (optional).
2268
+ * @param request - Upload payload. `request.file` is the image to upload.
2269
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal` (optional).
2316
2270
  * @returns Response containing the image URL.
2317
2271
  */
2318
- uploadImage_(
2319
- uri: string | NodeJS.ReadableStream | File,
2320
- name?: string,
2321
- contentType?: string,
2322
- user?: UserResponse,
2323
- axiosRequestConfig?: AxiosRequestConfig,
2272
+ override async uploadImage(
2273
+ request?: Omit<ImageUploadRequest, 'file'> & { file?: FileUploadInput },
2274
+ requestOptions?: StreamRequestOptions,
2324
2275
  ) {
2325
- return this.api.sendFile(
2326
- `${this.baseURL}/uploads/image`,
2327
- uri,
2328
- name,
2329
- contentType,
2330
- user,
2331
- axiosRequestConfig,
2276
+ return await super.uploadImage(
2277
+ { ...request, file: normalizeUploadFile(request?.file) as unknown as string },
2278
+ requestOptions,
2332
2279
  );
2333
2280
  }
2281
+
2334
2282
  /**
2335
2283
  * Marks the channels as delivered for the given messages and the user.
2336
2284
  *
2337
2285
  * @param request - Mark delivered options.
2338
2286
  * @returns The server response, or `undefined` if there are no messages to mark.
2339
2287
  */
2340
- async markChannelsDelivered(request?: Gen_MarkDeliveredRequest) {
2288
+ async markChannelsDelivered(
2289
+ request?: Gen_MarkDeliveredRequest,
2290
+ requestOptions?: StreamRequestOptions,
2291
+ ) {
2341
2292
  if (!request?.latest_delivered_messages?.length) return;
2342
- return await this.markDelivered(request);
2293
+ return await this.markDelivered(request, requestOptions);
2343
2294
  }
2344
2295
 
2345
2296
  syncDeliveredCandidates(collections: Channel[]) {