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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/cjs/index.browser.js +2196 -3902
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2197 -3902
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2199 -3905
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/ChannelManager.d.ts +120 -233
  8. package/dist/types/CooldownTimer.d.ts +8 -23
  9. package/dist/types/EventHandlerPipeline.d.ts +17 -37
  10. package/dist/types/LiveLocationManager.d.ts +22 -50
  11. package/dist/types/api-client.d.ts +9 -14
  12. package/dist/types/channel.d.ts +253 -448
  13. package/dist/types/channel_state.d.ts +48 -95
  14. package/dist/types/client.d.ts +245 -370
  15. package/dist/types/client_state.d.ts +1 -3
  16. package/dist/types/configuration/ConfigController.d.ts +30 -124
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
  18. package/dist/types/configuration/keys.d.ts +5 -19
  19. package/dist/types/configuration/shape.d.ts +12 -29
  20. package/dist/types/configuration/types.d.ts +59 -87
  21. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
  22. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  23. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  24. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  25. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  26. package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
  27. package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
  28. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
  29. package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
  30. package/dist/types/connection/networkConnection/types.d.ts +12 -27
  31. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
  32. package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
  33. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
  34. package/dist/types/connection/wsConnection/config.d.ts +8 -28
  35. package/dist/types/connection/wsConnection/types.d.ts +17 -70
  36. package/dist/types/entityStore/EntityStore.d.ts +153 -113
  37. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
  38. package/dist/types/errors.d.ts +7 -19
  39. package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
  40. package/dist/types/gen/chat/ChatApi.d.ts +28 -14
  41. package/dist/types/gen/models/index.d.ts +769 -86
  42. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  43. package/dist/types/index.d.ts +2 -4
  44. package/dist/types/languageNames.d.ts +9 -24
  45. package/dist/types/logger.d.ts +1 -3
  46. package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
  47. package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
  48. package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
  49. package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
  50. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  51. package/dist/types/messageComposer/configuration/types.d.ts +29 -56
  52. package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
  53. package/dist/types/messageComposer/messageComposer.d.ts +30 -164
  54. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
  55. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
  56. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  57. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  58. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
  59. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
  60. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  61. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  62. package/dist/types/messageComposer/pollComposer.d.ts +8 -4
  63. package/dist/types/messageComposer/textComposer.d.ts +3 -9
  64. package/dist/types/messageComposer/types.d.ts +5 -8
  65. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
  66. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
  67. package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
  68. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
  69. package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
  70. package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
  71. package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
  72. package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
  73. package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
  74. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
  75. package/dist/types/messageOperations/types.d.ts +15 -30
  76. package/dist/types/middleware.d.ts +7 -5
  77. package/dist/types/moderation.d.ts +21 -14
  78. package/dist/types/notifications/NotificationManager.d.ts +8 -31
  79. package/dist/types/notifications/types.d.ts +19 -59
  80. package/dist/types/offline-support/offline_support_api.d.ts +145 -539
  81. package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
  82. package/dist/types/offline-support/queueableOperations.d.ts +24 -52
  83. package/dist/types/offline-support/types.d.ts +24 -187
  84. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  85. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  86. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  87. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
  88. package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
  89. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
  90. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
  91. package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
  92. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
  93. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
  94. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
  95. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
  96. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  97. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  98. package/dist/types/pagination/utility.search.d.ts +3 -8
  99. package/dist/types/poll.d.ts +14 -14
  100. package/dist/types/poll_manager.d.ts +11 -2
  101. package/dist/types/poll_optimistic_votes.d.ts +10 -14
  102. package/dist/types/reminders/Reminder.d.ts +4 -4
  103. package/dist/types/reminders/ReminderManager.d.ts +7 -20
  104. package/dist/types/search/BaseSearchSource.d.ts +7 -12
  105. package/dist/types/search/ChannelSearchSource.d.ts +7 -7
  106. package/dist/types/search/MessageSearchSource.d.ts +7 -9
  107. package/dist/types/search/SearchController.d.ts +17 -22
  108. package/dist/types/search/types.d.ts +6 -10
  109. package/dist/types/signing.d.ts +12 -3
  110. package/dist/types/thread.d.ts +23 -71
  111. package/dist/types/thread_manager.d.ts +45 -70
  112. package/dist/types/token_manager.d.ts +8 -13
  113. package/dist/types/types.d.ts +64 -125
  114. package/dist/types/types.utility.d.ts +3 -3
  115. package/dist/types/upload-utils.d.ts +5 -10
  116. package/dist/types/uploadManager.d.ts +17 -45
  117. package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
  118. package/dist/types/utils/WithSubscriptions.d.ts +5 -15
  119. package/dist/types/utils/concurrency.d.ts +11 -19
  120. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  121. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  122. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  123. package/dist/types/utils/objectPath.d.ts +6 -41
  124. package/dist/types/utils/retryable.d.ts +8 -12
  125. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  126. package/dist/types/utils/time.d.ts +24 -64
  127. package/dist/types/utils.d.ts +40 -86
  128. package/package.json +7 -2
  129. package/src/ChannelManager.ts +159 -300
  130. package/src/CooldownTimer.ts +11 -29
  131. package/src/EventHandlerPipeline.ts +21 -44
  132. package/src/LiveLocationManager.ts +35 -74
  133. package/src/api-client.ts +43 -61
  134. package/src/campaign.ts +1 -1
  135. package/src/channel.ts +396 -749
  136. package/src/channel_batch_updater.ts +1 -1
  137. package/src/channel_state.ts +50 -105
  138. package/src/client.ts +360 -588
  139. package/src/client_state.ts +1 -6
  140. package/src/configuration/ConfigController.ts +41 -157
  141. package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
  142. package/src/configuration/index.ts +1 -1
  143. package/src/configuration/keys.ts +13 -32
  144. package/src/configuration/shape.ts +67 -70
  145. package/src/configuration/types.ts +60 -100
  146. package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
  147. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  148. package/src/configuration/utils/declarativeSlices.ts +9 -39
  149. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  150. package/src/configuration/utils/index.ts +2 -4
  151. package/src/configuration/utils/serverAuthority.ts +20 -68
  152. package/src/connection/ConnectionIdManager.ts +20 -49
  153. package/src/connection/ConnectionRecoveryManager.ts +51 -178
  154. package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
  155. package/src/connection/networkConnection/reporters.ts +9 -36
  156. package/src/connection/networkConnection/types.ts +12 -27
  157. package/src/connection/wsConnection/StableWSConnection.ts +73 -193
  158. package/src/connection/wsConnection/WSConnection.ts +56 -131
  159. package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
  160. package/src/connection/wsConnection/config.ts +13 -48
  161. package/src/connection/wsConnection/types.ts +17 -70
  162. package/src/constants.ts +4 -4
  163. package/src/entityStore/EntityStore.ts +162 -167
  164. package/src/entityStore/StoreBackedItemIndex.ts +14 -47
  165. package/src/errors.ts +7 -19
  166. package/src/formatMessageMemo.ts +3 -9
  167. package/src/gen/chat/ChannelApi.ts +19 -0
  168. package/src/gen/chat/ChatApi.ts +87 -13
  169. package/src/gen/models/index.ts +793 -71
  170. package/src/gen/moderation/ModerationApi.ts +0 -4
  171. package/src/index.ts +10 -14
  172. package/src/languageNames.ts +9 -24
  173. package/src/logger.ts +1 -3
  174. package/src/messageComposer/LocationComposer.ts +7 -23
  175. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  176. package/src/messageComposer/attachmentIdentity.ts +2 -13
  177. package/src/messageComposer/attachmentManager.ts +17 -63
  178. package/src/messageComposer/attachmentUtils.ts +3 -17
  179. package/src/messageComposer/configuration/configuration.ts +5 -8
  180. package/src/messageComposer/configuration/types.ts +29 -56
  181. package/src/messageComposer/fileUtils.ts +1 -1
  182. package/src/messageComposer/linkPreviewsManager.ts +8 -20
  183. package/src/messageComposer/messageComposer.ts +54 -222
  184. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
  185. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
  186. package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
  187. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
  188. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  189. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
  190. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  191. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  192. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  193. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
  194. package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
  195. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  196. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  197. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  198. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  199. package/src/messageComposer/pollComposer.ts +11 -8
  200. package/src/messageComposer/textComposer.ts +9 -59
  201. package/src/messageComposer/types.ts +9 -12
  202. package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
  203. package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
  204. package/src/messageOperations/FailedSendCache.ts +4 -9
  205. package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
  206. package/src/messageOperations/MessageOperations.ts +33 -62
  207. package/src/messageOperations/applyReactionLocally.ts +9 -28
  208. package/src/messageOperations/createMessageOperations.ts +17 -33
  209. package/src/messageOperations/reflectReactionEvent.ts +5 -13
  210. package/src/messageOperations/sendOrdering.ts +4 -7
  211. package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
  212. package/src/messageOperations/types.ts +15 -30
  213. package/src/middleware.ts +7 -10
  214. package/src/moderation.ts +25 -21
  215. package/src/notifications/NotificationManager.ts +11 -35
  216. package/src/notifications/types.ts +19 -59
  217. package/src/offline-support/offline_support_api.ts +178 -608
  218. package/src/offline-support/offline_sync_manager.ts +25 -69
  219. package/src/offline-support/queueableOperations.ts +31 -84
  220. package/src/offline-support/types.ts +25 -188
  221. package/src/pagination/ItemIndex.ts +4 -12
  222. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  223. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
  224. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  225. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
  226. package/src/pagination/filterCompiler.ts +11 -25
  227. package/src/pagination/paginators/BasePaginator.ts +422 -976
  228. package/src/pagination/paginators/ChannelPaginator.ts +130 -190
  229. package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
  230. package/src/pagination/paginators/MessagePaginator.ts +135 -175
  231. package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
  232. package/src/pagination/paginators/ReminderPaginator.ts +12 -15
  233. package/src/pagination/paginators/ThreadPaginator.ts +16 -26
  234. package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
  235. package/src/pagination/paginators/stateThrottling.ts +5 -10
  236. package/src/pagination/sortCompiler.ts +23 -50
  237. package/src/pagination/utility.normalization.ts +8 -30
  238. package/src/pagination/utility.search.ts +4 -11
  239. package/src/poll.ts +19 -19
  240. package/src/poll_manager.ts +16 -20
  241. package/src/poll_optimistic_votes.ts +17 -22
  242. package/src/reminders/Reminder.ts +5 -6
  243. package/src/reminders/ReminderManager.ts +9 -34
  244. package/src/reminders/ReminderTimer.ts +1 -2
  245. package/src/search/BaseSearchSource.ts +14 -29
  246. package/src/search/ChannelSearchSource.ts +8 -8
  247. package/src/search/MessageSearchSource.ts +19 -25
  248. package/src/search/SearchController.ts +18 -24
  249. package/src/search/types.ts +6 -10
  250. package/src/segment.ts +1 -1
  251. package/src/signing.ts +23 -3
  252. package/src/thread.ts +72 -173
  253. package/src/thread_manager.ts +59 -76
  254. package/src/token_manager.ts +11 -21
  255. package/src/types.ts +78 -126
  256. package/src/types.utility.ts +3 -3
  257. package/src/upload-utils.ts +5 -10
  258. package/src/uploadManager.ts +22 -54
  259. package/src/utils/FixedSizeQueueCache.ts +13 -21
  260. package/src/utils/WithSubscriptions.ts +5 -15
  261. package/src/utils/concurrency.ts +16 -55
  262. package/src/utils/mergeWith/mergeWith.ts +10 -13
  263. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  264. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  265. package/src/utils/objectPath.ts +6 -41
  266. package/src/utils/retryable.ts +10 -14
  267. package/src/utils/throttling/throttle.ts +9 -25
  268. package/src/utils/time.ts +26 -66
  269. package/src/utils.ts +72 -128
package/src/client.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /* eslint no-unused-vars: "off" */
2
2
  /* global process */
3
3
 
4
- import type { AxiosInstance } from 'axios';
4
+ import type { AxiosInstance, AxiosRequestConfig } from 'axios';
5
5
  import axios from 'axios';
6
6
 
7
7
  import type { Channel } from './channel';
@@ -9,6 +9,7 @@ import type { ChannelMuteStatus } from './channel_state';
9
9
  import { ChannelWatchStatus } from './channel_state';
10
10
  import { ClientState } from './client_state';
11
11
  import { UploadManager } from './uploadManager';
12
+ import { DevToken } from './signing';
12
13
  import { TokenManager, type TokenManagerMinimalUser } from './token_manager';
13
14
  import { ApiClient } from './api-client';
14
15
  import {
@@ -43,18 +44,18 @@ import type {
43
44
  LocalMessage,
44
45
  OwnUserResponse,
45
46
  PartializeAllBut,
47
+ PinMessageOptions,
46
48
  QueryChannelsRequest,
47
49
  QueryChannelsResponse,
48
50
  QueryThreadsRequest,
49
51
  ReactionResponse,
50
52
  SdkIdentifier,
51
- StreamChatOptions,
52
53
  StreamRequestOptions,
53
- TimestampNS,
54
54
  TokenOrProvider,
55
55
  UnBanUserOptions,
56
56
  UpdateUserPartialRequest,
57
57
  UserMuteResponse,
58
+ UserRequest,
58
59
  UserResponse,
59
60
  } from './types';
60
61
  import { isWSFailure } from './errors';
@@ -80,7 +81,8 @@ import type { AbstractOfflineDB } from './offline-support';
80
81
  import { FixedSizeQueueCache } from './utils/FixedSizeQueueCache';
81
82
  import { isEqual } from './utils/mergeWith/mergeWithCore';
82
83
  import type { MessageComposer } from './messageComposer';
83
- import type { InstanceSetupState } from './configuration';
84
+ import type { InstanceConfigTree, InstanceSetupState } from './configuration';
85
+ import type { DeepPartial } from './types.utility';
84
86
  import { InstanceConfigurationRegistry } from './configuration/InstanceConfigurationRegistry';
85
87
  import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
86
88
  import { StateStore } from '@stream-io/state-store';
@@ -97,10 +99,6 @@ import type {
97
99
  import { ChatApi } from './gen-imports';
98
100
  import type { StreamResponse } from './types';
99
101
 
100
- function isString(value: unknown): value is string {
101
- return typeof value === 'string' || value instanceof String;
102
- }
103
-
104
102
  const logger = chatLoggerSystem.getLogger('client');
105
103
  const offlineDbLogger = chatLoggerSystem.getLogger('offline-db');
106
104
 
@@ -120,15 +118,8 @@ export type ChannelConfigsState = {
120
118
  export type ClientUser = PartializeAllBut<OwnUserResponse, 'id'> & { anon?: boolean };
121
119
 
122
120
  /**
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.
121
+ * After a thread query with `watch: true` the server watches the thread's channel, as for
122
+ * `channel.watch()` and `queryChannels`.
132
123
  */
133
124
  const markThreadChannelWatched = ({ channel }: Thread) => {
134
125
  channel.watchStatus = ChannelWatchStatus.Watching;
@@ -137,102 +128,70 @@ const markThreadChannelWatched = ({ channel }: Thread) => {
137
128
  export class StreamChat extends ChatApi {
138
129
  private static _instance?: unknown | StreamChat; // type is undefined|StreamChat, unknown is due to TS limitations with statics
139
130
  messageDeliveryReporter: MessageDeliveryReporter;
140
- /**
141
- * @internal
142
- */
131
+ /** @internal */
143
132
  uploadManager: UploadManager;
144
- /**
145
- * @private
146
- */
133
+ /** @private */
147
134
  _user?: ClientUser;
148
135
  appSettingsPromise?: Promise<StreamResponse<Gen_GetApplicationResponse>>;
149
136
  threads: ThreadManager;
150
137
  polls: PollManager;
151
138
  /**
152
- * Channel lists — one or more `ChannelPaginator`s kept in sync with WS events, with ownership
153
- * arbitration between them. Instantiated with the client and living as long as it does; register
154
- * the lists with `client.channelManager.insertPaginator()` and drop them again with
155
- * `removePaginator()`. It only starts handling events once something calls its (ref-counted)
156
- * `registerSubscriptions()`.
157
- *
158
- * It is deliberately not configurable through the client options — everything is set on the
159
- * manager itself (`setOwnershipResolver`, `addEventHandler` / `setEventHandlers` /
160
- * `removeEventHandlers`), which is also the only way to reconfigure it later.
139
+ * Channel lists (`ChannelPaginator`s kept in sync with WS events, with ownership arbitration
140
+ * between them). Register lists with `insertPaginator()` / `removePaginator()`. It handles events
141
+ * only once something calls its ref-counted `registerSubscriptions()`. It is configured on the
142
+ * manager itself (`setOwnershipResolver`, `addEventHandler`, ...), not through the client
143
+ * options.
161
144
  */
162
145
  channelManager: ChannelManager;
163
146
  /**
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 } } })`.
147
+ * On reconnect, re-runs each loaded channel list's first-page query and reloads each active
148
+ * channel and thread, then dispatches `connection.recovered`. Disable it when the app recovers
149
+ * state itself: `client.config.set({ client: { connectionRecovery: { enabled: false } } })`.
170
150
  */
171
151
  connectionRecovery: ConnectionRecoveryManager;
172
152
  /**
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.
153
+ * The device's network status, separate from the WebSocket's ({@link wsConnection}). Platforms
154
+ * report it through `client.config.set({ client: { networkConnection: { statusReporter } } })` or
155
+ * `client.networkConnection.setStatusReporter(...)`. Browsers get a reporter automatically;
156
+ * elsewhere a stand-in mirrors the WebSocket. `isOnline` is `undefined` (unknown, not offline)
157
+ * until something reports.
186
158
  */
187
159
  networkConnection: NetworkConnectionObserver;
188
160
  /**
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`.
161
+ * The connection ID (the WebSocket's, or the long-poll's after an `enableWSFallback` switch). A
162
+ * request with `watch` or `presence` waits here for the handshake (see `requiresConnectionId`).
195
163
  */
196
164
  connectionIdManager: ConnectionIdManager;
197
165
  /**
198
- * Client-global, normalized store holding one canonical copy of each message. The channel main
199
- * list and thread reply paginators read/write message content through it, so a message held in
200
- * more than one of them stays consistent without copy-to-copy fan-out.
166
+ * Client-global store with one canonical copy of each message. The channel and thread paginators
167
+ * read and write messages through it, so a message held in several of them stays consistent.
201
168
  */
202
169
  messageStore: EntityStore<LocalMessage>;
203
170
  offlineDb?: AbstractOfflineDB;
204
171
  notifications: NotificationManager;
205
172
  reminders: ReminderManager;
206
- persistUserOnConnectionFailure?: boolean;
207
173
  axiosInstance: AxiosInstance;
208
174
  baseURL?: string;
209
- browser: boolean;
210
175
  cleaningIntervalRef?: ReturnType<typeof setTimeout>;
211
176
  clientId?: string;
212
177
  key: string;
213
178
  listeners: Map<EventType, Set<EventHandler>>;
214
179
  /**
215
- * If true, we will not clean up threads when channel state is in initializing state.
216
- * The main use case for SDKs who do independent state recovery for channels.
180
+ * When true, threads are not cleaned up while the channel state is initializing (for SDKs that
181
+ * recover channel state themselves).
217
182
  */
218
183
  preventThreadCleanup = false;
219
184
  moderation: Moderation;
220
185
  mutedChannels: ChannelMute[];
221
186
  readonly mutedUsersStore: StateStore<{ mutedUsers: UserMuteResponse[] }>;
222
187
  /**
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}.
188
+ * Reactive store behind {@link channelServerConfigs}: the backend's channel configs, not the ones
189
+ * registered through {@link config}.
229
190
  *
230
191
  * @internal
231
192
  */
232
193
  readonly channelServerConfigsStore: StateStore<ChannelConfigsState>;
233
194
  blockedUsers: StateStore<BlockedUsersState>;
234
- node: boolean;
235
- options: StreamChatOptions;
236
195
  setUserPromise: ConnectAPIResponse | null;
237
196
  state: ClientState;
238
197
  tokenManager: TokenManager;
@@ -246,21 +205,27 @@ export class StreamChat extends ChatApi {
246
205
  private _resolveWsPromise?: (value: Awaited<ConnectAPIResponse>) => void;
247
206
  private _rejectWsPromise?: (reason?: unknown) => void;
248
207
 
208
+ /**
209
+ * Whether the client runs in a browser: the `client.browser` option, else whether `window`
210
+ * exists.
211
+ */
212
+ get browser(): boolean {
213
+ return this.config.getConfig('client')?.browser ?? typeof window !== 'undefined';
214
+ }
215
+ get node(): boolean {
216
+ return !this.browser;
217
+ }
249
218
  get anonymous(): boolean {
250
219
  return this.tokenManager.isAnonymous;
251
220
  }
252
221
  get userId() {
253
222
  return this.user?.id;
254
223
  }
255
- /**
256
- * @deprecated Use `userId` instead.
257
- */
224
+ /** @deprecated Use `userId` instead. */
258
225
  get userID() {
259
226
  return this.user?.id;
260
227
  }
261
- /**
262
- * @deprecated Use `clientId` instead.
263
- */
228
+ /** @deprecated Use `clientId` instead. */
264
229
  get clientID() {
265
230
  return this.clientId;
266
231
  }
@@ -276,11 +241,8 @@ export class StreamChat extends ChatApi {
276
241
  private cachedUserAgent?: string;
277
242
  readonly messageComposerCache: FixedSizeQueueCache<string, MessageComposer>;
278
243
  /**
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.
244
+ * Configuration registered for the instances the SDK creates (channels, threads, composers, the
245
+ * client's own managers). Not the server-provided channel configs ({@link channelServerConfigs}).
284
246
  */
285
247
  readonly config = new InstanceConfigurationRegistry();
286
248
  /** Teardown for the `'client'` setup function, released by {@link disconnectUser}. */
@@ -289,30 +251,31 @@ export class StreamChat extends ChatApi {
289
251
  /**
290
252
  * Initializes a client.
291
253
  *
292
- * **Only use constructor for advanced usages. It is strongly advised to use `StreamChat.getInstance()` instead of `new StreamChat()` to reduce integration issues due to multiple WebSocket connections.**
254
+ * **Prefer `StreamChat.getInstance()`: a second client opens a second WebSocket connection.**
293
255
  *
294
256
  * @example <caption>initialize the client in user mode</caption>
295
257
  * new StreamChat('api_key')
296
- * @example <caption>initialize the client with options</caption>
297
- * new StreamChat('api_key', { axiosRequestConfig: { timeout: 5000 } })
258
+ * @example <caption>initialize the client with configuration</caption>
259
+ * new StreamChat('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
298
260
  *
299
261
  * @param key - The API key.
300
- * @param options - Additional options (optional).
301
- * @param options.browser - Enforce the client to be in browser mode (optional).
302
- * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
303
- * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
262
+ * @param config - Declarative configuration, the tree `client.config.set()` takes (optional).
263
+ * Applied before anything is built, so it reaches the managers and the options read once at
264
+ * construction (`client.baseURL`, `client.axiosRequestConfig`, `client.notificationManager`).
304
265
  */
305
- constructor(key: string, options: StreamChatOptions = {}) {
306
- // generated client requires ApiClient right away
266
+ constructor(key: string, config?: DeepPartial<InstanceConfigTree>) {
267
+ // The generated base class needs the ApiClient before `this` exists, so it is bound afterwards.
307
268
  super(new ApiClient());
308
- // but ApiClient relies on properties defined here so we set it after (can't pass `this` in super call)
309
269
  this.apiClient.client = this;
310
270
 
311
- // set the key
312
271
  this.key = key;
272
+
273
+ // Seeded first: the options read below come from the `client` slice.
274
+ if (config) this.config.set(config);
275
+ const clientConfig = this.config.getConfig('client');
313
276
  this.listeners = new Map();
314
277
  this.state = new ClientState({ client: this });
315
- // a list of channels to hide ws events from
278
+ // channels to hide ws events from
316
279
  this.mutedChannels = [];
317
280
  this.mutedUsersStore = new StateStore<{ mutedUsers: UserMuteResponse[] }>({
318
281
  mutedUsers: [],
@@ -324,22 +287,17 @@ export class StreamChat extends ChatApi {
324
287
 
325
288
  this.moderation = new Moderation(this);
326
289
 
327
- this.notifications = options?.notifications ?? new NotificationManager();
290
+ this.notifications = clientConfig?.notificationManager ?? new NotificationManager();
328
291
  this.uploadManager = new UploadManager(this);
329
292
 
330
- this.browser = options.browser ?? typeof window !== 'undefined';
331
- this.node = !this.browser;
332
-
333
- this.options = { ...options };
334
-
335
293
  this.axiosInstance = axios.create({
336
294
  timeout: 3000,
337
295
  withCredentials: false,
338
- ...this.options.axiosRequestConfig,
296
+ ...(clientConfig?.axiosRequestConfig as AxiosRequestConfig | undefined),
339
297
  paramsSerializer: axiosParamsSerializer,
340
298
  });
341
299
 
342
- this.setBaseURL(this.options.baseURL || 'https://chat.stream-io-api.com');
300
+ this.setBaseURL(clientConfig?.baseURL || 'https://chat.stream-io-api.com');
343
301
 
344
302
  const streamLocalTestRun = getEnv('STREAM_LOCAL_TEST_RUN');
345
303
  const streamLocalTestHost = getEnv('STREAM_LOCAL_TEST_HOST');
@@ -350,26 +308,24 @@ export class StreamChat extends ChatApi {
350
308
  this.setBaseURL(`http://${streamLocalTestHost}`);
351
309
  }
352
310
 
353
- // Both before the WebSocket, which subscribes to the network store and drives the id's lifecycle.
311
+ // Both before the WebSocket, which subscribes to the network store and drives the ID's
312
+ // lifecycle.
354
313
  this.connectionIdManager = new ConnectionIdManager();
355
314
  this.networkConnection = new NetworkConnectionObserver({ client: this });
356
315
  this.networkConnection.registerSubscriptions();
357
316
 
358
- // WS connection is initialized when setUser is called
317
+ // The socket itself opens in `connectUser`.
359
318
  this.wsConnection = new WSConnection({ client: this });
360
319
  this.wsConnection.registerSubscriptions();
361
320
  this.wsPromise = null;
362
321
  this.setUserPromise = null;
363
- // keeps a reference to all the channels that are in use
364
-
365
- this.persistUserOnConnectionFailure = this.options?.persistUserOnConnectionFailure;
366
322
 
367
323
  this.tokenManager = new TokenManager();
368
324
 
369
325
  this.messageStore = new EntityStore<LocalMessage>({
370
326
  getEntityId: (message) => message.id,
371
327
  });
372
- // before the managers that hold channels in its store
328
+ // Before the managers that claim channels in its store.
373
329
  this.channelManager = new ChannelManager({ client: this });
374
330
  this.threads = new ThreadManager({ client: this });
375
331
  this.polls = new PollManager({ client: this });
@@ -385,30 +341,15 @@ export class StreamChat extends ChatApi {
385
341
  name: 'message-composer-cache',
386
342
  });
387
343
 
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.
344
+ // Last: everything a setup function might reach exists now. Subscribing applies the current
345
+ // configuration at once, so deriving it here too would run every `initializeConfig` twice.
397
346
  this.wireClientConfiguration();
398
347
  }
399
348
 
400
349
  /**
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`.
350
+ * Subscribes the client's managers to the `'client'` configuration key. Called by the constructor
351
+ * and by {@link _setUser}, because {@link disconnectUser} releases the subscription (to run the
352
+ * setup function's teardown) while the managers outlive the user. Idempotent.
412
353
  */
413
354
  private wireClientConfiguration() {
414
355
  if (this.unsubscribeClientConfiguration) return;
@@ -422,14 +363,9 @@ export class StreamChat extends ChatApi {
422
363
  }
423
364
 
424
365
  /**
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.
366
+ * Derives each manager's configuration from the package defaults plus the `client` subtree. Every
367
+ * manager is written unconditionally: it is a derivation, not a merge, so `config.reset()` and
368
+ * removed fields take effect.
433
369
  */
434
370
  private initializeManagerConfig() {
435
371
  const config = this.config.getConfig('client');
@@ -453,21 +389,10 @@ export class StreamChat extends ChatApi {
453
389
  }
454
390
 
455
391
  /**
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}.
392
+ * Cache of server-provided channel configuration, keyed by cid (a channel's `config_overrides`
393
+ * can make it differ from other channels of its type). Read it through
394
+ * {@link Channel.serverConfig}. Assigning through the setter notifies subscribers, mutating the
395
+ * record in place does not (prefer {@link _addChannelConfig}).
471
396
  *
472
397
  * @internal
473
398
  */
@@ -481,27 +406,25 @@ export class StreamChat extends ChatApi {
481
406
  }
482
407
 
483
408
  /**
484
- * Returns a client instance.
409
+ * Returns the shared client instance, so there is only one client and WebSocket connection.
485
410
  *
486
- * This function always returns the same client instance to avoid issues raised by multiple client and WS connections.
487
- *
488
- * **After the first call, the client configuration will not change if the key or options parameters change.**
411
+ * **After the first call, the `key` and `config` parameters are ignored.**
489
412
  *
490
413
  * @example <caption>initialize the client in user mode</caption>
491
414
  * StreamChat.getInstance('api_key')
492
- * @example <caption>initialize the client with options</caption>
493
- * StreamChat.getInstance('api_key', { axiosRequestConfig: { timeout: 5000 } })
415
+ * @example <caption>initialize the client with configuration</caption>
416
+ * StreamChat.getInstance('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
494
417
  *
495
418
  * @param key - The API key.
496
- * @param options - Additional options (optional).
497
- * @param options.browser - Enforce the client to be in browser mode (optional).
498
- * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
499
- * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
419
+ * @param config - Declarative configuration, as for the constructor (optional).
500
420
  * @returns The shared client instance.
501
421
  */
502
- public static getInstance(key: string, options?: StreamChatOptions): StreamChat {
422
+ public static getInstance(
423
+ key: string,
424
+ config?: DeepPartial<InstanceConfigTree>,
425
+ ): StreamChat {
503
426
  if (!StreamChat._instance) {
504
- StreamChat._instance = new StreamChat(key, options);
427
+ StreamChat._instance = new StreamChat(key, config);
505
428
  }
506
429
 
507
430
  return StreamChat._instance as StreamChat;
@@ -515,6 +438,17 @@ export class StreamChat extends ChatApi {
515
438
  this.offlineDb = offlineDBInstance;
516
439
  }
517
440
 
441
+ /**
442
+ * Creates a development token for apps with auth checks disabled. Never use one in production.
443
+ * See {@link DevToken}.
444
+ *
445
+ * @param userId - The ID of the user the token is for.
446
+ * @returns The development token.
447
+ */
448
+ devToken(userId: string) {
449
+ return DevToken(userId);
450
+ }
451
+
518
452
  getAuthType() {
519
453
  return this.anonymous ? 'anonymous' : 'jwt';
520
454
  }
@@ -528,9 +462,7 @@ export class StreamChat extends ChatApi {
528
462
 
529
463
  _hasConnectionID = () => Boolean(this._getConnectionID());
530
464
 
531
- /**
532
- * @deprecated Use `client.config.setSetupFunction('messageComposer', fn)`.
533
- */
465
+ /** @deprecated Use `client.config.setSetupFunction('messageComposer', fn)`. */
534
466
  public setMessageComposerSetupFunction = (
535
467
  setupFunction: InstanceSetupState<'messageComposer'>['setupFunction'],
536
468
  ) => {
@@ -538,21 +470,19 @@ export class StreamChat extends ChatApi {
538
470
  };
539
471
 
540
472
  /**
541
- * Sets the current user and opens a WebSocket connection.
473
+ * Sets the current user and opens the WebSocket connection.
542
474
  *
543
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
544
- * @param userTokenOrProvider - A token string or an async provider that returns one.
475
+ * @param user - The user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
476
+ * @param userTokenOrProvider - A token string, or an async provider that resolves to one.
545
477
  * @returns A promise that resolves when the connection is set up.
478
+ * @throws For a different user, unless `disconnectUser()` ran first.
546
479
  */
547
480
  connectUser = async (user: ClientUser, userTokenOrProvider: TokenOrProvider) => {
548
481
  if (!user.id) {
549
482
  throw new Error('The "id" field on the user is missing');
550
483
  }
551
484
 
552
- /**
553
- * Calling connectUser multiple times is potentially the result of a bad integration; however,
554
- * if the user ID remains the same we don't throw an error.
555
- */
485
+ // Repeated calls for the same user warn and return the existing promise.
556
486
  if (this.userId === user.id && this.setUserPromise) {
557
487
  logger
558
488
  .withExtraTags('connectUser')
@@ -568,11 +498,11 @@ export class StreamChat extends ChatApi {
568
498
  );
569
499
  }
570
500
 
571
- if (this.node && !this.options.allowServerSideConnect) {
501
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
572
502
  logger
573
503
  .withExtraTags('connectUser')
574
504
  .warn(
575
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
505
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
576
506
  );
577
507
  }
578
508
 
@@ -582,26 +512,23 @@ export class StreamChat extends ChatApi {
582
512
  const wsPromise = this.openConnection();
583
513
 
584
514
  const setUserPromise = Promise.all([setTokenPromise, wsPromise]).then(
585
- (result) => result[1], // We only return connection promise;
515
+ (result) => result[1], // only the connection promise
586
516
  );
587
517
  this.setUserPromise = setUserPromise;
588
518
 
589
519
  try {
590
520
  return await setUserPromise;
591
521
  } catch (err) {
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.
522
+ // `disconnectUser()` rejects an in-flight handshake, so clean up only if nothing has taken
523
+ // over: a newer `connectUser()` changes `setUserPromise`; `connectAnonymousUser()` (which
524
+ // never sets it) or a bare `disconnectUser()` changes `userId`.
597
525
  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.
526
+ if (!this.config.getConfig('client')?.persistUserOnConnectionFailure) {
527
+ // No user is kept: the app is expected to call `connectUser` again.
601
528
  this.disconnectUser();
602
529
  } 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.
530
+ // A terminal failure (rejected token, bad API key) will not fix itself: close the socket
531
+ // so `StableWSConnection` stops retrying.
605
532
  this.closeConnection();
606
533
  }
607
534
  }
@@ -610,12 +537,12 @@ export class StreamChat extends ChatApi {
610
537
  };
611
538
 
612
539
  /**
613
- * Sets the current user and opens a WebSocket connection.
540
+ * Sets the current user and opens the WebSocket connection.
614
541
  *
615
- * @deprecated Use {@link StreamChat.connectUser} instead. Its naming is more consistent with its functionality.
542
+ * @deprecated Use {@link StreamChat.connectUser} instead.
616
543
  *
617
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
618
- * @param userTokenOrProvider - A token string or an async provider that returns one.
544
+ * @param user - The user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
545
+ * @param userTokenOrProvider - A token string, or an async provider that resolves to one.
619
546
  * @returns A promise that resolves when the connection is set up.
620
547
  */
621
548
  setUser = this.connectUser;
@@ -624,34 +551,23 @@ export class StreamChat extends ChatApi {
624
551
  this.tokenManager.setTokenOrProvider(userTokenOrProvider, user);
625
552
 
626
553
  _setUser(user: TokenManagerMinimalUser) {
627
- /**
628
- * This one is used by the frontend. This is a copy of the current user object stored on backend.
629
- * It contains reserved properties and own user properties which are not present in `this._user`.
630
- */
554
+ // Mirrors the backend's copy of the user, with reserved and own-user properties.
631
555
  this.user = user;
632
- // this one is actually used for requests. This is a copy of current user provided to `connectUser` function.
556
+ // The copy given to `connectUser`, used for requests.
633
557
  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}.
558
+ // Re-arms the `'client'` key if a previous `disconnectUser` released it.
636
559
  this.wireClientConfiguration();
637
560
  }
638
561
 
639
562
  /**
640
- * Disconnects the WebSocket connection, without removing the user set on client.
641
- * client.closeConnection will not trigger default auto-retry mechanism for reconnection. You need
642
- * to call `client.openConnection` to reconnect to the WebSocket.
643
- *
644
- * This is mainly useful on mobile side. You can only receive push notifications
645
- * if you don't have an active WebSocket connection.
646
- * So when your app goes to background, you can call `client.closeConnection`.
647
- * And when app comes back to foreground, call `client.openConnection`.
648
- *
649
- * After an `enableWSFallback` switch it closes the long-poll as well, telling the server to
650
- * close its connection id.
563
+ * Closes the WebSocket without removing the user, and without auto-reconnect: call
564
+ * `openConnection` to reconnect. Mainly for mobile: push notifications arrive only while no
565
+ * WebSocket is active, so close on background and reopen on foreground. After an
566
+ * `enableWSFallback` switch it also closes the long-poll, telling the server to close its
567
+ * connection ID.
651
568
  *
652
- * @param timeout - Max number of milliseconds to wait for the WebSocket close event before forcefully assuming
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).
569
+ * @param timeout - Milliseconds to wait for the WebSocket close event and for the long-poll close
570
+ * request. Defaults to 1s and 2s respectively.
655
571
  */
656
572
  closeConnection = async (timeout?: number) => {
657
573
  this.channelManager.resetAIStateOnChannels();
@@ -680,10 +596,10 @@ export class StreamChat extends ChatApi {
680
596
  };
681
597
 
682
598
  /**
683
- * Creates a new WebSocket connection with the current user. After an `enableWSFallback` switch it
599
+ * Opens a WebSocket connection for the current user. After an `enableWSFallback` switch it
684
600
  * reconnects the long-poll instead: the client never goes back to the WebSocket.
685
601
  *
686
- * @returns The WebSocket connect promise, or an empty resolved promise if a connection is already active.
602
+ * @returns The connect promise, or `undefined` when a healthy connection already exists.
687
603
  */
688
604
  openConnection = () => {
689
605
  if (!this.userId) {
@@ -713,9 +629,7 @@ export class StreamChat extends ChatApi {
713
629
  return wsPromise;
714
630
  };
715
631
 
716
- /**
717
- * Rejects the shared `wsPromise`, invalidates any in-flight connect attempt
718
- */
632
+ /** Rejects the shared `wsPromise` and invalidates any in-flight connect attempt. */
719
633
  private _rejectPendingWsPromise = (reason: Error) => {
720
634
  if (!this._wsPromiseSettled) {
721
635
  // invalidate in-flight attempts so a late settle cannot revive this promise
@@ -730,8 +644,8 @@ export class StreamChat extends ChatApi {
730
644
  };
731
645
 
732
646
  /**
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.
647
+ * Keeps a single pending `wsPromise` across close/reopen, so callers already awaiting it are not
648
+ * stranded when `openConnection` starts a new connect.
735
649
  */
736
650
  private _bindWsPromise = (connectPromise: ConnectAPIResponse): ConnectAPIResponse => {
737
651
  const connectId = ++this._wsConnectId;
@@ -763,10 +677,10 @@ export class StreamChat extends ChatApi {
763
677
  };
764
678
 
765
679
  /**
766
- * Revokes tokens for a connected user issued before the given time.
680
+ * Revokes the connected user's tokens issued before the given time.
767
681
  *
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
682
+ * @param before - Cutoff date; tokens issued before it are revoked (optional). Defaults to now.
683
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
770
684
  * into the request (optional).
771
685
  * @returns The updated users response.
772
686
  */
@@ -791,30 +705,22 @@ export class StreamChat extends ChatApi {
791
705
  /**
792
706
  * Retrieves application settings.
793
707
  *
794
- * @param _request - Unused. Holds the request position so `requestOptions` stays the
795
- * second argument, as on the generated methods; pass `undefined`.
796
708
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
797
709
  * into the request (optional).
798
710
  * @returns The application settings response.
799
711
  */
800
- async getAppSettings(
801
- _request?: Record<string, never>,
802
- requestOptions?: StreamRequestOptions,
803
- ) {
804
- return await (this.appSettingsPromise = this.getApp(undefined, requestOptions));
712
+ async getAppSettings(requestOptions?: StreamRequestOptions) {
713
+ return await (this.appSettingsPromise = this.getApp(requestOptions));
805
714
  }
806
715
 
807
716
  /**
808
- * Disconnects the WebSocket and removes the user from client.
717
+ * Disconnects the WebSocket and removes the user and its state.
809
718
  *
810
- * @param timeout - Max number of milliseconds to wait for the WebSocket close event before forcefully assuming
811
- * successful disconnection. See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent (optional).
812
- * @returns The close-connection promise.
719
+ * @param timeout - Passed to {@link closeConnection} (optional).
813
720
  */
814
721
  disconnectUser = (timeout?: number) => {
815
722
  logger.withExtraTags('disconnectUser').info('Disconnecting the client.');
816
723
 
817
- // remove the user specific fields
818
724
  delete this.user;
819
725
  delete this._user;
820
726
 
@@ -826,18 +732,16 @@ export class StreamChat extends ChatApi {
826
732
  this.wsPromise = null;
827
733
 
828
734
  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.
735
+ // After starting the close, which reads the connection ID synchronously (the long-poll's close
736
+ // request carries it).
831
737
  this.connectionIdManager.rejectConnectionId(teardownReason);
832
738
 
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.
739
+ // Empties the channel lists (they hold the disconnected user's channels) but keeps them
740
+ // registered: which lists exist is app configuration. Reset first so each list empties in one
741
+ // update.
837
742
  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.
743
+ // Disconnects every channel and empties the store, then rethrows the first error a holder
744
+ // threw. Logged, not propagated, so the rest of the logout still runs.
841
745
  try {
842
746
  this.channelManager.clearChannels();
843
747
  } catch (error) {
@@ -845,21 +749,20 @@ export class StreamChat extends ChatApi {
845
749
  .withExtraTags('disconnectUser')
846
750
  .error('Clearing the channels failed during disconnect.', { error });
847
751
  }
848
- // reset client state
849
752
  this.state = new ClientState({ client: this });
850
- // reset thread manager
851
753
  this.threads.resetState();
852
- // channel mutes are per-user; leaving them would let `muted` filters resolve against the
853
- // previous user until the next health check replaces them
754
+ // Channel mutes are per-user: stale ones would resolve `muted` filters against the previous
755
+ // user.
854
756
  this.mutedChannels = [];
855
757
  this.uploadManager.reset();
856
758
  this.messageComposerCache.clear();
857
- // Runs the `'client'` setup function's teardown. Cleared so repeated calls cannot double-run it.
759
+ // Runs the `'client'` setup function's teardown. Cleared so repeated calls cannot double-run
760
+ // it.
858
761
  this.unsubscribeClientConfiguration?.();
859
762
  this.unsubscribeClientConfiguration = undefined;
860
763
 
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.
764
+ // Deferred so the long-poll close can still authenticate; a newer connect may have set the next
765
+ // user and token by then.
863
766
  closePromise
864
767
  .finally(() => {
865
768
  if (!this.userId) this.tokenManager.reset();
@@ -870,29 +773,23 @@ export class StreamChat extends ChatApi {
870
773
  .error('The close promise rejected during disconnect.', { error: err }),
871
774
  );
872
775
 
873
- // close the WS connection
874
776
  return closePromise;
875
777
  };
876
778
 
877
- /**
878
- *
879
- * @deprecated Please use client.disconnectUser instead.
880
- *
881
- * Disconnects the WebSocket and removes the user from client.
882
- */
779
+ /** @deprecated Use `client.disconnectUser` instead. */
883
780
  disconnect = this.disconnectUser;
884
781
 
885
782
  /**
886
- * Sets an anonymous user and opens a WebSocket connection.
783
+ * Sets an anonymous user and opens the WebSocket connection.
887
784
  *
888
785
  * @returns A promise that resolves when the connection is set up.
889
786
  */
890
787
  connectAnonymousUser = () => {
891
- if (this.node && !this.options.allowServerSideConnect) {
788
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
892
789
  logger
893
790
  .withExtraTags('connectAnonymousUser')
894
791
  .warn(
895
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
792
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
896
793
  );
897
794
  }
898
795
 
@@ -908,9 +805,11 @@ export class StreamChat extends ChatApi {
908
805
  };
909
806
 
910
807
  /**
911
- * Creates a guest user and returns its access token.
808
+ * Creates a guest user.
912
809
  *
913
- * @param args - The guest creation request, plus optional per-request options.
810
+ * @param ...args - `[request, requestOptions]`. `request.user` is the guest user to create;
811
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
812
+ * serialized into the request.
914
813
  * @returns The created guest user and its access token.
915
814
  */
916
815
  override async createGuest(...args: Parameters<ChatApi['createGuest']>) {
@@ -932,14 +831,14 @@ export class StreamChat extends ChatApi {
932
831
  }
933
832
 
934
833
  /**
935
- * Sets up a temporary guest user.
834
+ * Creates a temporary guest user and connects as it.
936
835
  *
937
- * @param user - Data about this user, e.g. `{ name: 'john' }`.
938
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
836
+ * @param user - The guest user, with its required `id`, e.g. `{ id: 'john', name: 'John' }`.
837
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
939
838
  * into the request (optional).
940
839
  * @returns A promise that resolves when the connection is set up.
941
840
  */
942
- async setGuestUser(user: UserResponse, requestOptions?: StreamRequestOptions) {
841
+ async setGuestUser(user: UserRequest, requestOptions?: StreamRequestOptions) {
943
842
  const response = await this.createGuest({ user }, requestOptions);
944
843
 
945
844
  const {
@@ -966,17 +865,23 @@ export class StreamChat extends ChatApi {
966
865
  * console.log(event.type);
967
866
  * });
968
867
  *
969
- * @param callbackOrString - The event type to listen for, or the callback when listening to all events.
970
- * @param callbackOrNothing - The callback to call when an event type was provided (optional).
868
+ * @param callback - Called with every event.
971
869
  * @returns An object with an `unsubscribe()` method.
972
870
  */
973
871
  on(callback: EventHandler): { unsubscribe: () => void };
974
- on<T extends EventType | string>(
872
+ /**
873
+ * Listens to one event type on all channels and users you're watching.
874
+ *
875
+ * @param eventType - The event type to listen for.
876
+ * @param callback - Called with each event of that type.
877
+ * @returns An object with an `unsubscribe()` method.
878
+ */
879
+ on<T extends EventType>(
975
880
  eventType: T,
976
881
  callback: EventHandler<T>,
977
882
  ): { unsubscribe: () => void };
978
883
  on(
979
- callbackOrString: EventHandler | string,
884
+ callbackOrString: EventHandler | EventType,
980
885
  callbackOrNothing?: EventHandler,
981
886
  ): { unsubscribe: () => void } {
982
887
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
@@ -1005,14 +910,19 @@ export class StreamChat extends ChatApi {
1005
910
  }
1006
911
 
1007
912
  /**
1008
- * Removes the event handler.
913
+ * Removes a listener for all events.
1009
914
  *
1010
- * @param callbackOrString - The event type, or the callback when removing an all-events listener.
1011
- * @param callbackOrNothing - The callback to remove when an event type was provided (optional).
915
+ * @param callback - The listener to remove.
1012
916
  */
1013
917
  off(callback: EventHandler): void;
1014
- off(eventType: string, callback: EventHandler): void;
1015
- off(callbackOrString: EventHandler | string, callbackOrNothing?: EventHandler) {
918
+ /**
919
+ * Removes a listener for one event type.
920
+ *
921
+ * @param eventType - The event type it listens to.
922
+ * @param callback - The listener to remove.
923
+ */
924
+ off<T extends EventType>(eventType: T, callback: EventHandler<T>): void;
925
+ off(callbackOrString: EventHandler | EventType, callbackOrNothing?: EventHandler) {
1016
926
  const key = callbackOrNothing ? (callbackOrString as EventType) : 'all';
1017
927
  const callback = callbackOrNothing
1018
928
  ? callbackOrNothing
@@ -1032,15 +942,13 @@ export class StreamChat extends ChatApi {
1032
942
  dispatchEvent = (event: Event) => {
1033
943
  if (event.received_at == null) event.received_at = nowNs();
1034
944
 
1035
- // client event handlers
1036
945
  const postListenerCallbacks = this._handleClientEvent(event as WSEvent);
1037
946
 
1038
- // channel event handlers
1039
947
  const cid = (event as Extract<Event, { cid?: any }>).cid;
1040
948
  const channel = cid ? this.channelManager.get(cid) : undefined;
1041
949
  // 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.
950
+ // Its handlers would throw at `getClient()`, so they are skipped (its own listeners below still
951
+ // hear it).
1044
952
  if (channel && !channel.pendingDisposal) {
1045
953
  channel._handleChannelEvent(event as WSEvent);
1046
954
  }
@@ -1051,9 +959,7 @@ export class StreamChat extends ChatApi {
1051
959
  channel._callChannelListeners(event as WSEvent);
1052
960
  }
1053
961
 
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.
962
+ // A failing in-memory cleanup must not skip the other callbacks or the offline DB write below.
1057
963
  for (const callback of postListenerCallbacks) {
1058
964
  try {
1059
965
  callback();
@@ -1071,13 +977,10 @@ export class StreamChat extends ChatApi {
1071
977
 
1072
978
  /**
1073
979
  * 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.
980
+ * read entries of the channels that list them, in one state update per channel.
1076
981
  *
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.
982
+ * @param options.readEntries - Also replace the user in read entries, refreshing read receipts.
983
+ * Off for presence changes: receipts never show online status. Defaults to `true`.
1081
984
  */
1082
985
  _updateMemberWatcherReferences = (
1083
986
  user: UserResponse,
@@ -1094,7 +997,7 @@ export class StreamChat extends ChatApi {
1094
997
  const isOwnMembership = membership?.user?.id === user.id;
1095
998
  if (!member && !hasWatcher && !readState && !isOwnMembership) continue;
1096
999
  // 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.
1000
+ // users.
1098
1001
  if (readState) {
1099
1002
  channel.messageReceiptsTracker.setPendingReadStoreReconcileMeta({
1100
1003
  changedUserIds: [user.id],
@@ -1118,49 +1021,35 @@ export class StreamChat extends ChatApi {
1118
1021
  _updateUserReferences = this._updateMemberWatcherReferences;
1119
1022
 
1120
1023
  /**
1121
- * Updates the messages from the loaded channels that contain this user, with the updated user object.
1024
+ * Replaces the user's object in the messages of the loaded channels.
1122
1025
  *
1123
1026
  * @private
1124
- *
1125
- * @param user - The updated user.
1126
1027
  */
1127
1028
  _updateUserMessageReferences = (user: UserResponse) => {
1128
- // Scan all loaded channels rather than a user->channel reference map. MessageRequest authors are no
1129
- // longer registered as channel references (that registration was removed along with
1130
- // `Channel._trackLatestMessage`); `reflectUserUpdate` filters by author id internally, so it is
1131
- // a no-op on channels without this user's messages.
1132
- // The next step is to have user ItemIndex, where the update would be O(1) complexity
1029
+ // Scans all loaded channels: `reflectUserUpdate` filters by author ID, so it is a no-op for
1030
+ // channels without this user's messages.
1133
1031
  for (const channel of this.channelManager.values()) {
1134
1032
  if (!channel) continue;
1135
1033
 
1136
- /** update the messages from this user. */
1137
1034
  channel.pinnedMessagesPaginator.reflectUserUpdate(user);
1138
1035
  channel.messagePaginator.reflectUserUpdate(user);
1139
1036
  }
1140
1037
  };
1141
1038
 
1142
1039
  /**
1143
- * Deletes the messages from the loaded channels that contain this user.
1144
- *
1145
- * If `hardDelete` is `true`, all the content of the message will be stripped down.
1146
- * Otherwise, only `message.type` will be set as `'deleted'`.
1040
+ * Deletes the user's messages in the loaded channels: stripped of their content with
1041
+ * `hardDelete`, otherwise marked as deleted. `deletedAt` defaults to now.
1147
1042
  *
1148
1043
  * @private
1149
- *
1150
- * @param user - The user whose messages should be deleted.
1151
- * @param hardDelete - Whether to fully strip the message content (optional, defaults to `false`).
1152
- * @param deletedAt - Timestamp to mark messages as deleted at (optional).
1153
1044
  */
1154
1045
  _deleteUserMessageReference = (
1155
1046
  user: UserResponse,
1156
1047
  hardDelete = false,
1157
1048
  deletedAt?: LocalMessage['deleted_at'],
1158
1049
  ) => {
1159
- // Scan all loaded channels rather than a user->channel reference map (see
1160
- // `_updateUserMessageReferences`); `applyMessageDeletionForUser` filters by author id internally.
1050
+ // Scans all loaded channels; `applyMessageDeletionForUser` filters by author ID.
1161
1051
  for (const channel of this.channelManager.values()) {
1162
1052
  if (channel) {
1163
- /** deleted the messages from this user. */
1164
1053
  channel.messagePaginator.applyMessageDeletionForUser({
1165
1054
  userId: user.id,
1166
1055
  hardDelete,
@@ -1175,16 +1064,7 @@ export class StreamChat extends ChatApi {
1175
1064
  }
1176
1065
  };
1177
1066
 
1178
- /**
1179
- * Handle the following user-related events:
1180
- * - `user.presence.changed`
1181
- * - `user.updated`
1182
- * - `user.deleted`
1183
- *
1184
- * @private
1185
- *
1186
- * @param event - The user event.
1187
- */
1067
+ /** @private */
1188
1068
  _handleUserEvent = (
1189
1069
  event: Extract<
1190
1070
  WSEvent,
@@ -1195,13 +1075,12 @@ export class StreamChat extends ChatApi {
1195
1075
  return;
1196
1076
  }
1197
1077
 
1198
- /** update the client.state with any changes to users */
1199
1078
  if (event.type === 'user.presence.changed' || event.type === 'user.updated') {
1200
1079
  if (event.user.id === this.userId) {
1201
1080
  const user = { ...this.user } as NonNullable<StreamChat['user']>;
1202
1081
  const _user = { ...this._user } as NonNullable<StreamChat['_user']>;
1203
1082
 
1204
- // Remove deleted properties from user objects.
1083
+ // Drop properties absent from the event, except own-user-only ones.
1205
1084
  for (const key in this.user) {
1206
1085
  if (key in event.user || isOwnUserBaseProperty(key)) {
1207
1086
  continue;
@@ -1213,7 +1092,7 @@ export class StreamChat extends ChatApi {
1213
1092
  delete _user[deleteKey];
1214
1093
  }
1215
1094
 
1216
- /** Updating only available properties in _user object. */
1095
+ // Update only the properties `_user` already has.
1217
1096
  for (const key in _user) {
1218
1097
  const updateKey = key as keyof typeof _user;
1219
1098
 
@@ -1295,8 +1174,7 @@ export class StreamChat extends ChatApi {
1295
1174
 
1296
1175
  if (event.type === 'notification.mark_read' && event.unread_channels === 0) {
1297
1176
  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.
1177
+ // Resets `read[userId].unread_messages`, which the unread badge reads.
1300
1178
  if (!channel._setOwnUnreadCount(0)) return;
1301
1179
  // the event may name no channel (mark-all-read), but here we know which ones changed
1302
1180
  this.channelManager.dropFromUnmatchedLists(channel);
@@ -1314,18 +1192,17 @@ export class StreamChat extends ChatApi {
1314
1192
  ended?.disconnect();
1315
1193
 
1316
1194
  postListenerCallbacks.push(() => {
1317
- // only the instance disconnected above: a listener that got the channel again keeps its
1318
- // fresh instance (`ensure()` replaces a disposed one)
1195
+ // Only the instance disconnected above: a listener that got the channel again keeps its
1196
+ // fresh instance (`ensure()` replaces a disposed one).
1319
1197
  if (ended && this.channelManager.get(cid) === ended) {
1320
1198
  this.channelManager.removeChannel(cid);
1321
1199
  }
1322
1200
  });
1323
1201
  }
1324
1202
 
1325
- // Current user removed from a channel: evict it like channel.deleted so
1326
- // connection recovery won't re-watch it and no further events reach it (#2599).
1327
- // Type-agnostic. We skip deleteAllChannelReference (unlike deletion) since
1328
- // the channel still exists for its remaining members.
1203
+ // Current user removed from a channel: evict it like channel.deleted so connection recovery
1204
+ // does not re-watch it. `deleteAllChannelReference` is skipped: the channel still
1205
+ // exists for its other members.
1329
1206
  if (event.type === 'notification.removed_from_channel' && event.cid) {
1330
1207
  const { cid } = event;
1331
1208
  const ended = this.channelManager.get(cid);
@@ -1348,8 +1225,7 @@ export class StreamChat extends ChatApi {
1348
1225
  const mute = this.mutedChannels[i];
1349
1226
  if (mute.channel?.cid === cid) {
1350
1227
  muteStatus = {
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.
1228
+ // `expires` is in unix nanoseconds: compare it against `nowNs()`, not `Date.now()`.
1353
1229
  muted: mute.expires != null ? mute.expires > nowNs() : true,
1354
1230
  createdAt: mute.created_at ?? nowNs(),
1355
1231
  expiresAt: mute.expires ?? null,
@@ -1370,9 +1246,7 @@ export class StreamChat extends ChatApi {
1370
1246
  }
1371
1247
 
1372
1248
  _callClientListeners = (event: Event) => {
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.
1249
+ // Snapshot first: a listener subscribed while handling an event must not be invoked for it.
1376
1250
  const listeners = [
1377
1251
  ...(this.listeners.get('all') ?? []),
1378
1252
  ...(this.listeners.get(event.type) ?? []),
@@ -1384,18 +1258,10 @@ export class StreamChat extends ChatApi {
1384
1258
  };
1385
1259
 
1386
1260
  /**
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.
1261
+ * Settles the connect promises after a successful reconnect, so a held `wsPromise` /
1262
+ * `setUserPromise` stops resolving against a superseded (possibly rejected) attempt. Called by
1263
+ * `StableWSConnection._reconnect()` and `WSConnectionFallback.connect(true)`. Recovery itself
1264
+ * belongs to {@link ConnectionRecoveryManager}.
1399
1265
  *
1400
1266
  * @internal
1401
1267
  */
@@ -1406,18 +1272,16 @@ export class StreamChat extends ChatApi {
1406
1272
  `Connection re-established with connection ID ${this.connectionIdManager.connectionId}.`,
1407
1273
  );
1408
1274
 
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
1275
+ // After a failed connect (e.g. `persistUserOnConnectionFailure: true`) recovery must flip
1276
+ // `wsPromise` from rejected to resolved, or calls waiting on it fail. An unsettled promise is
1277
+ // left to the connect sequence.
1412
1278
  if (this._wsPromiseSettled) {
1413
1279
  this.wsPromise = Promise.resolve();
1414
1280
  }
1415
1281
  this.setUserPromise = Promise.resolve();
1416
1282
  };
1417
1283
 
1418
- /**
1419
- * @private
1420
- */
1284
+ /** @private */
1421
1285
  async connect() {
1422
1286
  if (!this.userId || !this._user) {
1423
1287
  throw Error(
@@ -1431,19 +1295,20 @@ export class StreamChat extends ChatApi {
1431
1295
  throw Error('Property clientId is not set');
1432
1296
  }
1433
1297
 
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.
1298
+ // `wsConnection` owns the socket, the long-poll fallback (`enableWSFallback`), reconnection and
1299
+ // the connect timeout.
1437
1300
  return await this.wsConnection.connect();
1438
1301
  }
1439
1302
 
1440
1303
  /**
1441
- * Queries users and watches user presence.
1304
+ * Queries users and stores them in `client.state.users`. Watches presence only when
1305
+ * `request.payload.presence` is set.
1442
1306
  *
1443
1307
  * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts
1444
- * MongoDB-style filter conditions, sort directions (e.g. `[{ field: 'last_active', direction: -1 }]`),
1445
- * and options such as `presence`. `requestOptions` carries per-request options such as an
1446
- * abort `signal` and is never serialized into the request.
1308
+ * MongoDB-style filter conditions, sort directions (e.g.
1309
+ * `[{ field: 'last_active', direction: -1 }]`), and options such as `presence`.
1310
+ * `requestOptions` carries per-request options such as an abort `signal` and is never
1311
+ * serialized into the request.
1447
1312
  * @returns The user query response.
1448
1313
  */
1449
1314
  override async queryUsers(...args: Parameters<ChatApi['queryUsers']>) {
@@ -1455,16 +1320,13 @@ export class StreamChat extends ChatApi {
1455
1320
  }
1456
1321
 
1457
1322
  /**
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
1323
+ * Stops watching a channel on this client's connection. It carries no `watch` flag, but it waits
1324
+ * for the connection ID like a watching request (through a handshake or reconnect, until the
1325
+ * caller's abort signal fires) and throws when there is no connection and none is being
1464
1326
  * established.
1465
1327
  *
1466
1328
  * @param ...args - `[pathParams, request, requestOptions]`. `pathParams` identifies the channel
1467
- * (`{ type, id }`); `request.connection_id` is replaced by this client's connection id.
1329
+ * (`{ type, id }`); `request.connection_id` is replaced by this client's connection ID.
1468
1330
  * @returns The server response.
1469
1331
  */
1470
1332
  override async stopWatchingChannel(
@@ -1473,7 +1335,7 @@ export class StreamChat extends ChatApi {
1473
1335
  const [pathParams, request, requestOptions] = args;
1474
1336
  const signal = requestOptions?.signal;
1475
1337
  const connectionId = await this.connectionIdManager.getConnectionId(
1476
- // Check if signal is still usable - if it is read from offline DB, it has lost `addEventListener`.
1338
+ // A signal revived from the offline DB has lost `addEventListener`.
1477
1339
  typeof signal?.addEventListener === 'function' ? signal : undefined,
1478
1340
  );
1479
1341
 
@@ -1485,19 +1347,15 @@ export class StreamChat extends ChatApi {
1485
1347
  }
1486
1348
 
1487
1349
  /**
1488
- * Queries channels and returns the full API response including top-level metadata such as
1489
- * `predefined_filter`.
1490
- *
1491
- * This exists as a compatibility bridge, as changing `queryChannelsRequest()` to return
1492
- * `QueryChannelsResponse` would be a breaking change because it currently returns
1493
- * only the channel list. In the next major release, the request/response APIs should
1494
- * be consolidated so callers can access the full response through the primary API.
1350
+ * Queries channels and returns the raw API response. See {@link queryChannelsAndHydrate} for
1351
+ * `Channel` instances.
1495
1352
  *
1496
1353
  * @param ...args - `[request, requestOptions]`. The optional `request` accepts MongoDB-style
1497
1354
  * 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.
1500
- * @returns The full query channels response.
1355
+ * options such as `predefined_filter`, `filter_values`, and `sort_values`. `state`, `watch` and
1356
+ * `presence` default to `true`, `true` and `false`. `requestOptions` carries per-request
1357
+ * options such as an abort `signal` and is never serialized into the request.
1358
+ * @returns The full query channels response, including metadata such as `predefined_filter`.
1501
1359
  */
1502
1360
  override async queryChannels(...args: Parameters<ChatApi['queryChannels']>) {
1503
1361
  const [request, requestOptions] = args;
@@ -1515,7 +1373,7 @@ export class StreamChat extends ChatApi {
1515
1373
  ...restOptions
1516
1374
  } = request ?? {};
1517
1375
 
1518
- // Build payload based on whether we're using a predefined filter or traditional filters
1376
+ // With a predefined filter, `filter_conditions` is not sent.
1519
1377
  const payload: QueryChannelsRequest = predefined_filter
1520
1378
  ? {
1521
1379
  predefined_filter,
@@ -1530,37 +1388,30 @@ export class StreamChat extends ChatApi {
1530
1388
  ...restOptions,
1531
1389
  };
1532
1390
 
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.
1391
+ // `ApiClient` waits for a connection ID only when the payload sets `watch` or `presence`.
1535
1392
  return await super.queryChannels(payload, requestOptions);
1536
1393
  }
1537
1394
 
1538
1395
  /**
1539
- * Queries channels and hydrates them into `Channel` instances on this client.
1540
- *
1541
- * Use the inherited `queryChannels()` from `ChatApi` when only the raw API response
1542
- * is needed; this method wraps it with state hydration, `channels.queried` dispatch,
1543
- * and offline-db sync.
1396
+ * Queries channels and hydrates them into `Channel` instances on this client, dispatching
1397
+ * `channels.queried` and syncing the offline DB. Use `queryChannels()` for the raw API response.
1544
1398
  *
1545
1399
  * @param options - The query channels request payload (optional). Accepts MongoDB-style filter
1546
1400
  * conditions, sort directions (e.g. `[{ field: 'created_at', direction: -1 }]`), and options
1547
1401
  * such as `predefined_filter`, `filter_values`, and `sort_values`.
1548
- * @param stateOptions - Options that only affect state management and aren't sent in the request
1549
- * (optional, defaults to `{}`).
1550
- * @param stateOptions.skipInitialization - Skips the initialization of the state for the
1551
- * channels matching the IDs in the list (optional).
1552
- * @param stateOptions.skipHydration - Skips returning the channels as instances of the `Channel`
1553
- * class and instead returns the raw query response (optional).
1554
- * @param stateOptions.withResponse - Returns the full query response with hydrated channels.
1555
- * This is a compatibility bridge for internal callers that need response-level metadata while
1556
- * the default return value remains `Channel[]` (optional).
1557
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1402
+ * @param stateOptions - Options that only affect state management and are not sent in the
1403
+ * request. Defaults to `{}`.
1404
+ * @param stateOptions.skipInitialization - IDs of channels whose state is not initialized.
1405
+ * @param stateOptions.skipHydration - Not read: it has no effect.
1406
+ * @param stateOptions.withResponse - Returns the full query response (with hydrated `channels`)
1407
+ * instead of `Channel[]`.
1408
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1558
1409
  * into the request (optional).
1559
1410
  * @returns The hydrated channel list, or the full response when `withResponse` is `true`.
1560
1411
  */
1561
1412
  async queryChannelsAndHydrate(
1562
- options?: QueryChannelsRequest,
1563
- stateOptions?: ChannelStateOptions & { withResponse: true },
1413
+ options: QueryChannelsRequest | undefined,
1414
+ stateOptions: ChannelStateOptions & { withResponse: true },
1564
1415
  requestOptions?: StreamRequestOptions,
1565
1416
  ): Promise<QueryChannelsResponseWithChannels>;
1566
1417
  async queryChannelsAndHydrate(
@@ -1617,11 +1468,11 @@ export class StreamChat extends ChatApi {
1617
1468
  }
1618
1469
 
1619
1470
  /**
1620
- * Queries reactions for a message and hydrates any cached offline reactions before the network
1621
- * request.
1471
+ * Queries a message's reactions. On the first page, cached offline reactions are dispatched
1472
+ * (`offline_reactions.queried`) before the network request.
1622
1473
  *
1623
- * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the target message ID;
1624
- * `request` carries MongoDB-style filters, sort directions (e.g.
1474
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the target message
1475
+ * ID; `request` carries MongoDB-style filters, sort directions (e.g.
1625
1476
  * `[{ field: 'created_at', direction: -1 }]`) and pagination options; `requestOptions` carries
1626
1477
  * per-request options such as an abort `signal` and is never serialized into the request.
1627
1478
  * @returns The query reactions response.
@@ -1679,11 +1530,9 @@ export class StreamChat extends ChatApi {
1679
1530
  ? { initialized: false, offlineMode: true }
1680
1531
  : { initialized: true, offlineMode: false },
1681
1532
  );
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).
1533
+ // An explicit `watch` choice wins, otherwise watch only on a healthy socket
1534
+ // (`hydrateChannels` is public, so there may be no gated request behind it). Offline
1535
+ // hydration never counts, and a query that did not watch leaves the status untouched.
1687
1536
  if (!offlineMode && (queryChannelsOptions?.watch ?? this.wsConnection.isHealthy)) {
1688
1537
  c.watchStatus = ChannelWatchStatus.Watching;
1689
1538
  }
@@ -1696,19 +1545,11 @@ export class StreamChat extends ChatApi {
1696
1545
  queryChannelsOptions?.message_limit ??
1697
1546
  DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE;
1698
1547
 
1699
- // Seed the paginator BEFORE _initializeState, which hydrates read state and (via
1700
- // MessageReceiptsTracker) resolves read/delivered cursors against this paginator. Seeding
1701
- // first guarantees the tracker sees a populated timeline; a later async seed would run after
1702
- // the reconcile and mislabel delivery status.
1703
- //
1704
- // Skip the re-seed when this (shared) channel's paginator is already loaded AND the user has
1705
- // jumped to an older window (active interval is not the head): a first-page re-seed forces the
1706
- // newest page to merge into that jumped interval across the gap (missing messages in the
1707
- // middle). A cold paginator, or one still at the head (offline/at-latest), re-seeds normally so
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()`.)
1548
+ // Seed the paginator before `_initializeState`, which resolves read/delivered cursors against
1549
+ // it (via `MessageReceiptsTracker`). Skip the re-seed when:
1550
+ // - the paginator is loaded and the user jumped to an older window (active interval not at
1551
+ // the head): a first-page re-seed would merge the newest page across the gap;
1552
+ // - the channel is active: its own `channel.reload()` owns the loaded window.
1712
1553
  if (
1713
1554
  willInitialize &&
1714
1555
  !c.active &&
@@ -1725,7 +1566,7 @@ export class StreamChat extends ChatApi {
1725
1566
  if (skipInitialization === undefined) {
1726
1567
  c._initializeState(channelState);
1727
1568
  } else if (!skipInitialization.includes(channelState.channel.id)) {
1728
- // The paginators are (re)seeded above and via _initializeState → seedFirstPageSync.
1569
+ // The paginators are (re)seeded above and by `_initializeState` (`seedFirstPageSync`).
1729
1570
  c._initializeState(channelState);
1730
1571
  }
1731
1572
 
@@ -1743,17 +1584,17 @@ export class StreamChat extends ChatApi {
1743
1584
 
1744
1585
  /**
1745
1586
  * 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.
1587
+ * {@link ChannelManager.ensure}, so it returns the stored instance for the cid or creates and
1588
+ * stores it.
1748
1589
  *
1749
- * To get a distinct channel between two or more users, leave out the ID and pass the members:
1590
+ * For a distinct channel between users, leave out the ID and pass the members:
1750
1591
  * `client.channel('messaging', { members: [{ user_id: 'tommaso' }, { user_id: 'thierry' }] })`.
1751
1592
  * It has no ID until `channel.watch()`, `query()` or `create()` returns one.
1752
1593
  *
1753
1594
  * @param channelType - The channel type.
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 `{}`).
1595
+ * @param channelId - The channel ID; leave it out for a distinct channel created from members
1596
+ * (optional).
1597
+ * @param custom - Data for a new channel, e.g. `members` or `custom`. Defaults to `{}`.
1757
1598
  * @returns The channel; initialize it with `channel.watch()`.
1758
1599
  */
1759
1600
  channel(channelType: string, channelId?: string | null, custom?: ChannelInput): Channel;
@@ -1775,13 +1616,14 @@ export class StreamChat extends ChatApi {
1775
1616
  }
1776
1617
 
1777
1618
  /**
1778
- * Queries messages.
1619
+ * Searches messages.
1779
1620
  *
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.
1621
+ * @param ...args - `[request, requestOptions]`. The optional `request.payload` accepts channel
1622
+ * `filter_conditions`, `message_filter_conditions`, a `query`, and options such as `limit`,
1623
+ * `offset`, `next` and `sort`. `requestOptions` carries per-request options such as an abort
1624
+ * `signal` and is never serialized into the request.
1784
1625
  * @returns The search messages response.
1626
+ * @throws When both `offset` and `next` are given.
1785
1627
  */
1786
1628
  override async search(...args: Parameters<ChatApi['search']>) {
1787
1629
  const [request, requestOptions] = args;
@@ -1793,15 +1635,10 @@ export class StreamChat extends ChatApi {
1793
1635
  }
1794
1636
 
1795
1637
  /**
1796
- * Caches one channel's server configuration, read through {@link Channel.serverConfig}.
1797
- *
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.
1800
- *
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.
1638
+ * Caches one channel's server configuration, keyed by cid (see {@link Channel.serverConfig}).
1639
+ * Skips the write for a response without `config` (`notification.message_new` omits it) and for a
1640
+ * config deep-equal to the stored one: the API returns a fresh object each time and the store
1641
+ * compares by reference.
1805
1642
  *
1806
1643
  * @internal
1807
1644
  */
@@ -1816,7 +1653,7 @@ export class StreamChat extends ChatApi {
1816
1653
  }
1817
1654
 
1818
1655
  /**
1819
- * Revoke a global ban for a user.
1656
+ * Revokes a global ban.
1820
1657
  *
1821
1658
  * @param targetUserId - The user to unban.
1822
1659
  * @param options - Unban options (optional).
@@ -1864,10 +1701,11 @@ export class StreamChat extends ChatApi {
1864
1701
  }
1865
1702
 
1866
1703
  /**
1867
- * Checks whether a user is muted. Can be used after `connectUser()` is called.
1704
+ * Checks whether a user is muted.
1868
1705
  *
1869
1706
  * @param targetId - The user ID to check.
1870
1707
  * @returns `true` if the user is muted, otherwise `false`.
1708
+ * @throws When no user is connected.
1871
1709
  */
1872
1710
  userMuteStatus(targetId: string) {
1873
1711
  if (!this.user || !this.wsPromise) {
@@ -1880,98 +1718,28 @@ export class StreamChat extends ChatApi {
1880
1718
  return false;
1881
1719
  }
1882
1720
 
1883
- /**
1884
- * Transforms an expiration value into an ISO string.
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
- *
1889
- * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1890
- * in seconds, `string` or `Date` to set the exact expiration date (optional).
1891
- * @returns The expiration as an ISO string, or `null`.
1892
- * @throws If a numeric offset does not resolve to a representable date.
1893
- */
1894
- _normalizeExpiration(timeoutOrExpirationDate?: null | number | string | Date) {
1895
- let pinExpires: null | string = null;
1896
- if (typeof timeoutOrExpirationDate === 'number') {
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();
1905
- } else if (isString(timeoutOrExpirationDate)) {
1906
- pinExpires = timeoutOrExpirationDate;
1907
- } else if (timeoutOrExpirationDate instanceof Date) {
1908
- pinExpires = timeoutOrExpirationDate.toISOString();
1909
- }
1910
- return pinExpires;
1911
- }
1912
-
1913
- /**
1914
- * Extracts a string message ID from either a message object or a message ID.
1915
- *
1916
- * @param messageOrMessageId - MessageRequest object or message ID.
1917
- * @param errorText - Error message to report in case of message ID absence.
1918
- * @returns The extracted message ID.
1919
- */
1920
- _validateAndGetMessageId(
1921
- messageOrMessageId: string | { id: string },
1922
- errorText: string,
1923
- ) {
1924
- let messageId: string;
1925
- if (typeof messageOrMessageId === 'string') {
1926
- messageId = messageOrMessageId;
1927
- } else {
1928
- if (!messageOrMessageId.id) {
1929
- throw Error(errorText);
1930
- }
1931
- messageId = messageOrMessageId.id;
1932
- }
1933
- return messageId;
1934
- }
1935
-
1936
1721
  /**
1937
1722
  * Pins the message.
1938
1723
  *
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
- *
1943
- * @param messageOrMessageId - MessageRequest object or message ID.
1944
- * @param timeoutOrExpirationDate - Expiration date or timeout. Use `number` to set the timeout
1945
- * in seconds, `string` or `Date` to set the exact expiration date (optional).
1946
- * @param pinnedAt - Date when the message should be pinned. It affects the order of pinned
1947
- * messages. Use a negative number to set relative time in the past, `string` or `Date` to
1948
- * set the exact date of pin (optional).
1724
+ * @param message - The message to pin, or just its `{ id }`.
1725
+ * @param options - When the pin expires and where it sorts (optional).
1726
+ * @param options.pin_expires - When the pin expires, as a `Date` or an RFC3339 string; `null` or
1727
+ * leaving it out pins without expiry. Hand a server-sent timestamp back with `nsToDate(timestamp)`.
1728
+ * @param options.pinned_at - The pin time, which orders the pinned messages, as a `Date` or an
1729
+ * RFC3339 string (optional). Defaults to now.
1949
1730
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1950
1731
  * into the request (optional).
1951
1732
  * @returns The updated message response.
1952
1733
  */
1953
- pinMessage<
1954
- Expiration extends null | number | string | Date | undefined = undefined,
1955
- PinnedAt extends number | string | Date | undefined = undefined,
1956
- >(
1957
- messageOrMessageId: string | { id: string },
1958
- timeoutOrExpirationDate?: NotATimestampNS<Expiration>,
1959
- pinnedAt?: NotATimestampNS<PinnedAt>,
1734
+ pinMessage(
1735
+ { id }: { id: string },
1736
+ { pin_expires = null, pinned_at }: PinMessageOptions = {},
1960
1737
  requestOptions?: StreamRequestOptions,
1961
1738
  ) {
1962
- const id = this._validateAndGetMessageId(
1963
- messageOrMessageId,
1964
- 'Please specify the message id when calling pinMessage',
1965
- );
1739
+ if (!id) throw new Error('Please specify the message id when calling pinMessage');
1966
1740
  return this.updateMessagePartial(
1967
1741
  { id },
1968
- {
1969
- set: {
1970
- pinned: true,
1971
- pin_expires: this._normalizeExpiration(timeoutOrExpirationDate),
1972
- pinned_at: this._normalizeExpiration(pinnedAt),
1973
- },
1974
- },
1742
+ { set: { pinned: true, pin_expires, pinned_at: pinned_at ?? null } },
1975
1743
  requestOptions,
1976
1744
  );
1977
1745
  }
@@ -1979,25 +1747,24 @@ export class StreamChat extends ChatApi {
1979
1747
  /**
1980
1748
  * Unpins the message that was previously pinned.
1981
1749
  *
1982
- * @param messageOrMessageId - MessageRequest object or message ID.
1750
+ * @param message - The message to unpin, or just its `{ id }`.
1983
1751
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1984
1752
  * into the request (optional).
1985
1753
  * @returns The updated message response.
1986
1754
  */
1987
- unpinMessage(
1988
- messageOrMessageId: string | { id: string },
1989
- requestOptions?: StreamRequestOptions,
1990
- ) {
1991
- const id = this._validateAndGetMessageId(
1992
- messageOrMessageId,
1993
- 'Please specify the message id when calling unpinMessage',
1994
- );
1755
+ unpinMessage({ id }: { id: string }, requestOptions?: StreamRequestOptions) {
1756
+ if (!id) throw new Error('Please specify the message id when calling unpinMessage');
1995
1757
  return this.updateMessagePartial({ id }, { set: { pinned: false } }, requestOptions);
1996
1758
  }
1997
1759
 
1998
1760
  /**
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.
1761
+ * Updates a message over HTTP only: no offline queueing and no local state.
1762
+ * `messageOperations.update` on a channel or thread is the full edit.
1763
+ *
1764
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the message ID;
1765
+ * `request.message` is the updated message; `requestOptions` carries per-request options such
1766
+ * as an abort `signal` and is never serialized into the request.
1767
+ * @returns The update message response.
2001
1768
  */
2002
1769
  override async updateMessage(...args: Parameters<ChatApi['updateMessage']>) {
2003
1770
  const [pathParams, request, requestOptions] = args;
@@ -2011,14 +1778,20 @@ export class StreamChat extends ChatApi {
2011
1778
  }
2012
1779
 
2013
1780
  /**
2014
- * Deletes a message — the HTTP request and nothing else: no offline queueing and no local state.
1781
+ * Deletes a message over HTTP only: no offline queueing and no local state.
2015
1782
  * `messageOperations.delete` on a channel or thread is the full delete.
1783
+ *
1784
+ * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.id` is the message ID;
1785
+ * `request.hard` deletes it permanently and `request.delete_for_me` deletes it for the current
1786
+ * user only; `requestOptions` carries per-request options such as an abort `signal` and is
1787
+ * never serialized into the request.
1788
+ * @returns The delete message response.
2016
1789
  */
2017
1790
  override async deleteMessage(...args: Parameters<ChatApi['deleteMessage']>) {
2018
1791
  const [, request] = args;
2019
1792
  const result = await super.deleteMessage(...args);
2020
1793
 
2021
- // necessary to populate the below values as the server does not return the message in the response as deleted
1794
+ // The server does not return the message as deleted here.
2022
1795
  if (request?.delete_for_me) {
2023
1796
  result.message.deleted_for_me = true;
2024
1797
  result.message.type = 'deleted';
@@ -2028,19 +1801,18 @@ export class StreamChat extends ChatApi {
2028
1801
  }
2029
1802
 
2030
1803
  /**
2031
- * Returns the list of threads of the current user.
1804
+ * Returns the current user's threads as hydrated `Thread` instances.
2032
1805
  *
2033
- * @param options - Options object for pagination and limiting the participants and replies
2034
- * (optional, defaults to `{}`).
2035
- * @param options.limit - Limits the number of threads to be returned (optional).
2036
- * @param options.watch - Subscribes the user to the channels of the threads (optional).
2037
- * @param options.participant_limit - Limits the number of participants returned per thread (optional).
2038
- * @param options.reply_limit - Limits the number of replies returned per thread (optional).
2039
- * @param options.filter - MongoDB style filters for threads (optional).
2040
- * @param options.sort - MongoDB style sort for threads (optional).
2041
- * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
1806
+ * @param options - Pagination and limits for the participants and replies. Defaults to `{}`.
1807
+ * @param options.limit - Limits the number of threads returned. Defaults to 10.
1808
+ * @param options.watch - Subscribes the user to the channels of the threads. Defaults to `true`.
1809
+ * @param options.participant_limit - Limits the participants returned per thread. Defaults to 10.
1810
+ * @param options.reply_limit - Limits the replies returned per thread. Defaults to 3.
1811
+ * @param options.filter - MongoDB-style filters for threads (optional).
1812
+ * @param options.sort - MongoDB-style sort for threads (optional).
1813
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2042
1814
  * into the request (optional).
2043
- * @returns The list of threads and the next cursor.
1815
+ * @returns The threads and the next cursor.
2044
1816
  */
2045
1817
  async queryThreadsAndHydrate(
2046
1818
  options: QueryThreadsRequest = {},
@@ -2071,13 +1843,12 @@ export class StreamChat extends ChatApi {
2071
1843
 
2072
1844
  const response = await this.queryThreads(requestBody, requestOptions);
2073
1845
 
2074
- // Hydrate the polls for the parent messages of the threads
2075
1846
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2076
1847
  const parentMessages = response.threads.map((thread) => thread.parent_message!);
2077
1848
  this.polls.hydratePollCache(parentMessages);
2078
1849
 
2079
- const threads = response.threads.map(
2080
- (thread) => new Thread({ client: this, threadData: thread }),
1850
+ const threads = response.threads.map((thread) =>
1851
+ this.threads.resolveQueried(new Thread({ client: this, threadData: thread })),
2081
1852
  );
2082
1853
  if (optionsWithDefaults.watch) threads.forEach(markThreadChannelWatched);
2083
1854
 
@@ -2087,18 +1858,19 @@ export class StreamChat extends ChatApi {
2087
1858
  /**
2088
1859
  * Returns the thread of a message by its ID, wrapped in a hydrated `Thread` instance.
2089
1860
  *
2090
- * @param messageId - The message ID.
2091
- * @param options - Options object for pagination and limiting the participants and replies
2092
- * (optional, defaults to `{}`).
2093
- * @param options.watch - Subscribes the user to the channel of the thread (optional).
2094
- * @param options.participant_limit - Limits the number of participants returned per thread (optional).
2095
- * @param options.reply_limit - Limits the number of replies returned per thread (optional).
1861
+ * @param pathParams - The thread's parent message, as for `getThread`.
1862
+ * @param pathParams.message_id - The parent message ID.
1863
+ * @param options - Options object for pagination and limiting the participants and replies.
1864
+ * Defaults to `{}`.
1865
+ * @param options.watch - Subscribes the user to the channel of the thread. Defaults to `true`.
1866
+ * @param options.participant_limit - Limits the participants returned. Defaults to 100.
1867
+ * @param options.reply_limit - Limits the replies returned. Defaults to 3.
2096
1868
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2097
1869
  * into the request (optional).
2098
1870
  * @returns The thread.
2099
1871
  */
2100
1872
  async getThreadAndHydrate(
2101
- messageId: string,
1873
+ { message_id: messageId }: { message_id: string },
2102
1874
  options: GetThreadOptions = {},
2103
1875
  requestOptions?: StreamRequestOptions,
2104
1876
  ) {
@@ -2119,7 +1891,9 @@ export class StreamChat extends ChatApi {
2119
1891
  requestOptions,
2120
1892
  );
2121
1893
 
2122
- const thread = new Thread({ client: this, threadData: response.thread });
1894
+ const thread = this.threads.resolveQueried(
1895
+ new Thread({ client: this, threadData: response.thread }),
1896
+ );
2123
1897
  if (optionsWithDefaults.watch) markThreadChannelWatched(thread);
2124
1898
 
2125
1899
  return thread;
@@ -2131,8 +1905,7 @@ export class StreamChat extends ChatApi {
2131
1905
  return this.userAgent;
2132
1906
  }
2133
1907
 
2134
- // Computed once, then memoized for the client's lifetime - inputs read on
2135
- // the first call (sdk/device identifiers, build-time env) are not re-read.
1908
+ // Memoized on the first call: later changes to the identifiers are not picked up.
2136
1909
  if (!this.cachedUserAgent) {
2137
1910
  const version = process.env.PKG_VERSION;
2138
1911
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
@@ -2145,8 +1918,7 @@ export class StreamChat extends ChatApi {
2145
1918
 
2146
1919
  this.cachedUserAgent = [
2147
1920
  head,
2148
- // reports the host app, the device OS, the device model, and the picked
2149
- // exports bundle, each only when a value is present
1921
+ // Each only when a value is present.
2150
1922
  ...Object.entries({
2151
1923
  app: appName,
2152
1924
  app_version: appVersion,
@@ -2178,11 +1950,11 @@ export class StreamChat extends ChatApi {
2178
1950
  return;
2179
1951
  }
2180
1952
  this.cleaningIntervalRef = setInterval(() => {
2181
- // call clean on the channel, used for calling the stop.typing event etc.
1953
+ // `clean()` sends the stop-typing event, among other things.
2182
1954
  for (const channel of this.channelManager.values()) {
2183
- // a disposed channel has nothing to clean, and `clean()` would throw on it
1955
+ // A disposed channel has nothing to clean, and `clean()` would throw on it.
2184
1956
  if (channel.pendingDisposal) continue;
2185
- // one channel failing to clean must not stop the others (typing indicators would stick)
1957
+ // One channel failing to clean must not stop the others (typing indicators would stick).
2186
1958
  try {
2187
1959
  channel.clean();
2188
1960
  } catch (error) {
@@ -2195,43 +1967,39 @@ export class StreamChat extends ChatApi {
2195
1967
  }
2196
1968
 
2197
1969
  /**
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.
1970
+ * The JSON-encoded WebSocket auth message, sent as the first frame once the socket opens.
2202
1971
  *
2203
1972
  * @private
2204
- *
2205
- * @returns The JSON-encoded auth message.
2206
1973
  */
2207
1974
  _buildWSAuthMessage = () =>
2208
1975
  JSON.stringify(this._buildWSAuthPayload(this.tokenManager.getToken()));
2209
1976
 
2210
1977
  /**
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.
1978
+ * The auth message that {@link _buildWSAuthMessage} encodes for the WebSocket and the long-poll
1979
+ * fallback sends as `longPoll()`'s `json` query param.
2213
1980
  *
2214
1981
  * @private
2215
1982
  *
2216
- * @param token - The token the message carries. The long-poll passes none: it authenticates
2217
- * through the request's `Authorization` header instead.
1983
+ * @param token - The long-poll passes none: it authenticates through the `Authorization` header.
2218
1984
  */
2219
1985
  _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.
1986
+ // The server requires a non-empty token but ignores one that is not JWT-shaped, so anonymous
1987
+ // users and the long-poll send a placeholder.
2223
1988
  token: token || 'anonymous',
2224
1989
  // `connect()` rejects before reaching this when `_user` is unset.
2225
1990
  user_details: this._user as ConnectUserDetailsRequest,
1991
+ // Without 'chat' the server treats the connection as video-only and drops chat events and
1992
+ // unread counts.
2226
1993
  products: ['chat'],
2227
1994
  });
2228
1995
 
2229
1996
  /**
2230
- * Queries poll answers.
1997
+ * Queries poll answers: the votes with `is_answer: true`.
2231
1998
  *
2232
1999
  * @param ...args - `[pathParams, request, requestOptions]`. `pathParams.poll_id` is the poll ID;
2233
2000
  * `request` carries optional vote filter conditions, sort directions, and pagination options
2234
- * (`limit`, `offset`).
2001
+ * (`limit`, `next`, `prev`); `requestOptions` carries per-request options such as an abort
2002
+ * `signal` and is never serialized into the request.
2235
2003
  * @returns The poll answers.
2236
2004
  */
2237
2005
  async queryPollAnswers(...args: Parameters<ChatApi['queryPollVotes']>) {
@@ -2246,11 +2014,12 @@ export class StreamChat extends ChatApi {
2246
2014
  }
2247
2015
 
2248
2016
  /**
2249
- * Uploads a file to the Stream CDN
2017
+ * Uploads a file to the Stream CDN.
2250
2018
  *
2251
2019
  * @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).
2253
- * @returns Response containing the file URL.
2020
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
2021
+ * (optional).
2022
+ * @returns The upload response, with the file URL.
2254
2023
  */
2255
2024
  override async uploadFile(
2256
2025
  request?: Omit<FileUploadRequest, 'file'> & { file?: FileUploadInput },
@@ -2263,11 +2032,12 @@ export class StreamChat extends ChatApi {
2263
2032
  }
2264
2033
 
2265
2034
  /**
2266
- * Uploads an image to Stream CDN
2035
+ * Uploads an image to the Stream CDN.
2267
2036
  *
2268
2037
  * @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).
2270
- * @returns Response containing the image URL.
2038
+ * @param requestOptions - Per-request options, e.g. `onUploadProgress` or an abort `signal`
2039
+ * (optional).
2040
+ * @returns The upload response, with the image URL.
2271
2041
  */
2272
2042
  override async uploadImage(
2273
2043
  request?: Omit<ImageUploadRequest, 'file'> & { file?: FileUploadInput },
@@ -2280,9 +2050,11 @@ export class StreamChat extends ChatApi {
2280
2050
  }
2281
2051
 
2282
2052
  /**
2283
- * Marks the channels as delivered for the given messages and the user.
2053
+ * Marks channels as delivered for the given messages.
2284
2054
  *
2285
2055
  * @param request - Mark delivered options.
2056
+ * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
2057
+ * into the request (optional).
2286
2058
  * @returns The server response, or `undefined` if there are no messages to mark.
2287
2059
  */
2288
2060
  async markChannelsDelivered(