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
@@ -30,11 +30,8 @@ type EventHandlerContext = ChannelManagerEventHandlerContext;
30
30
  type SupportedEventType = EventType | (string & {});
31
31
 
32
32
  /**
33
- * Resolves which paginators should be the "owners" of a channel
34
- * when the channel matches multiple paginator filters.
35
- *
36
- * Return a set of paginator ids that should keep/own the item.
37
- * Returning an empty set means the channel will be removed everywhere.
33
+ * Picks which paginators own a channel that matches several, by returning their IDs. An empty list
34
+ * means every matching paginator keeps it.
38
35
  */
39
36
  export type PaginatorOwnershipResolver = (args: {
40
37
  channel: Channel;
@@ -42,10 +39,9 @@ export type PaginatorOwnershipResolver = (args: {
42
39
  }) => string[];
43
40
 
44
41
  /**
45
- * Convenience factory for a priority-based ownership resolver.
46
- * - Provide an ordered list of paginator ids from highest to lowest priority.
47
- * - If two or more paginators match a channel, the one with the highest priority wins.
48
- * - If none of the matching paginator ids are in the priority list, all matches are kept (back-compat).
42
+ * Priority-based ownership resolver. `priority` lists paginator IDs from highest to lowest: of the
43
+ * paginators matching a channel, the highest-priority one owns it. If none of them is listed, all
44
+ * keep it.
49
45
  */
50
46
  export const createPriorityOwnershipResolver = (
51
47
  priority?: string[],
@@ -58,7 +54,6 @@ export const createPriorityOwnershipResolver = (
58
54
  if (matchingPaginators.length <= 1) {
59
55
  return matchingPaginators.map((p) => p.id);
60
56
  }
61
- // The winner is the first item in the sorted array of matching paginators
62
57
  const winner = [...matchingPaginators].sort((a, b) => {
63
58
  const rankA = rank.get(a.id);
64
59
  const rankB = rank.get(b.id);
@@ -67,7 +62,7 @@ export const createPriorityOwnershipResolver = (
67
62
  return valueA - valueB;
68
63
  })[0];
69
64
  const winnerValue = rank.get(winner.id);
70
- // If no explicit priority is set for any, keep all (preserve current behavior)
65
+ // None of the matches is listed: keep all.
71
66
  if (winnerValue === undefined) {
72
67
  return matchingPaginators.map((p) => p.id);
73
68
  }
@@ -76,10 +71,8 @@ export const createPriorityOwnershipResolver = (
76
71
  };
77
72
 
78
73
  /**
79
- * The cid the event refers to. Events are inconsistent about how they identify their channel: some carry
80
- * a top-level `cid`, some only `channel_type` + `channel_id`, and some (e.g.
81
- * `notification.added_to_channel`) have all three optional and identify the channel solely through the
82
- * required `event.channel`.
74
+ * The cid the event refers to. Events carry it as `cid`, as `channel_type` + `channel_id`, or only
75
+ * in `event.channel` (e.g. `notification.added_to_channel`).
83
76
  */
84
77
  const getCidFromEvent = (event: PipelineEvent): string | undefined => {
85
78
  if (event.cid) return event.cid;
@@ -90,8 +83,8 @@ const getCidFromEvent = (event: PipelineEvent): string | undefined => {
90
83
  return event.channel?.cid;
91
84
  };
92
85
 
93
- // A channel the app disconnected counts as not stored: it stays in the store only until the next
94
- // `releaseUnusedChannels()`, and an event that makes its cid relevant again gets a live instance.
86
+ // A channel pending disposal counts as not stored, so an event that makes its cid relevant again
87
+ // gets a live instance.
95
88
  const getCachedChannelFromEvent = (
96
89
  event: PipelineEvent,
97
90
  channelManager: ChannelManager,
@@ -105,8 +98,6 @@ const removeItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
105
98
  event,
106
99
  ctx: { channelManager },
107
100
  }) => {
108
- // `getCidFromEvent`, not `event.cid`: on `channel.deleted` the cid can arrive nested in
109
- // `event.channel` only, and the legacy ChannelManager removed by `event.cid || event.channel?.cid`
110
101
  const cid = getCidFromEvent(event);
111
102
  if (!cid) return;
112
103
  const channel = channelManager.get(cid);
@@ -125,22 +116,12 @@ export const ignoreEventsForUnknownChannels: EventHandlerPipelineHandler<
125
116
  };
126
117
 
127
118
  /**
128
- * Restore a watch this client held and lost to a dropped socket.
129
- *
130
- * The server keys watches by connection ID, so a reconnect ends every watch the previous connection
131
- * held. Reconnect recovery re-watches the first page of each list plus the active channel; everything
132
- * else stays `WasWatching` — pages 2+ of a scrolled list, channels visited and navigated away from,
133
- * channels matching no mounted list. Such a channel still receives member-level events (e.g.
134
- * `notification.message_new`), which relocate its row but carry no message body, so its preview would
135
- * sit frozen until the channel was opened. Re-watching it the moment an event proves it relevant is
136
- * what closes that gap, without ever eagerly re-watching the whole cache.
137
- *
138
- * The request is idempotent, so a successful watch flips the status to `Watching`, and
139
- * `ensureWatched()` joins a watch it already has in flight, so a burst of events cannot produce a
140
- * burst of requests.
119
+ * Re-watches a channel whose watch a dropped socket ended (`WasWatching`). Recovery re-watches only
120
+ * the first page of each list and the active channel, so the others re-watch when an event proves
121
+ * them relevant. `ensureWatched()` joins an in-flight watch, so a burst sends one request.
141
122
  */
142
123
  const restoreInterruptedWatch = (channel: Channel) => {
143
- // a disposed channel refuses requests, and its `ensureWatched()` would reject
124
+ // A disposed channel refuses requests.
144
125
  if (channel.pendingDisposal) return;
145
126
  if (channel.watchStatus !== ChannelWatchStatus.WasWatching) return;
146
127
 
@@ -166,9 +147,8 @@ const updateLists: EventHandlerPipelineHandler<EventHandlerContext> = async ({
166
147
 
167
148
  routeToPaginators(channelManager, channel);
168
149
 
169
- // AFTER routing, and not awaited: the row relocates immediately off the event, and the watch (plus
170
- // the state it hydrates) lands whenever it lands. `channel.hidden` is excluded — a channel being
171
- // hidden is the one routed event that must not resurrect a watch.
150
+ // After routing and not awaited, so the row relocates off the event without waiting for the
151
+ // watch. `channel.hidden` must not resurrect a watch.
172
152
  if (event.type !== 'channel.hidden') {
173
153
  restoreInterruptedWatch(channel);
174
154
  }
@@ -176,8 +156,7 @@ const updateLists: EventHandlerPipelineHandler<EventHandlerContext> = async ({
176
156
 
177
157
  /**
178
158
  * Re-inserts a loaded channel whose data changed in place (`channel.updated`, `channel.truncated`), so
179
- * a list sorted or filtered by a changed field moves or drops it. Channels that aren't loaded are
180
- * ignored: these events don't make an unknown channel relevant.
159
+ * lists sorted or filtered by a changed field move or drop it. Unknown channels are ignored.
181
160
  */
182
161
  const reinsertItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
183
162
  event,
@@ -190,10 +169,7 @@ const reinsertItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
190
169
 
191
170
  /** Ingests `channel` into the lists that match and own it, and removes it from the rest. */
192
171
  function routeToPaginators(channelManager: ChannelManager, channel: Channel) {
193
- // The manager never boosts by default on any event — the sort is the single source of truth for
194
- // order, so a channel that just became relevant (new message, added, unhidden) relocates via its
195
- // updated sort key. Boosting remains a public per-paginator primitive (`paginator.boost`) for
196
- // integrators to opt into for specific channels (VIP/mention/deep-link).
172
+ // No boosting: the sort alone decides the order (`paginator.boost` is there for integrators).
197
173
  channelManager.ingestChannel(channel);
198
174
  }
199
175
 
@@ -212,6 +188,12 @@ const channelTruncatedHandler: LabeledEventHandler<EventHandlerContext> = {
212
188
  id: 'ChannelManager:default-handler:channel.truncated',
213
189
  };
214
190
 
191
+ // a hard delete of the last message might move the channel's `last_message_at` back
192
+ const messageDeletedHandler: LabeledEventHandler<EventHandlerContext> = {
193
+ handle: (context) => (context.event.hard_delete ? reinsertItem(context) : undefined),
194
+ id: 'ChannelManager:default-handler:message.deleted',
195
+ };
196
+
215
197
  const channelVisibleHandler: LabeledEventHandler<EventHandlerContext> = {
216
198
  handle: updateLists,
217
199
  id: 'ChannelManager:default-handler:channel.visible',
@@ -222,8 +204,7 @@ const channelHiddenHandler: LabeledEventHandler<EventHandlerContext> = {
222
204
  id: 'ChannelManager:default-handler:channel.hidden',
223
205
  };
224
206
 
225
- // members filter - should not be impacted as id is stable - cannot be updated
226
- // member.user.name - can be impacted
207
+ // Member IDs are stable, but `member.user.name` can affect a list's filter.
227
208
  const memberUpdatedHandler: LabeledEventHandler<EventHandlerContext> = {
228
209
  handle: updateLists,
229
210
  id: 'ChannelManager:default-handler:member.updated',
@@ -234,16 +215,12 @@ const messageNewHandler: LabeledEventHandler<EventHandlerContext> = {
234
215
  id: 'ChannelManager:default-handler:message.new',
235
216
  };
236
217
 
237
- /**
238
- * Sort fields the channel list's sort resolver resolves from read state. `SortParamRequest.field` is an open
239
- * string, so there is no type enumerating them.
240
- */
218
+ /** Sort fields resolved from read state (`SortParamRequest.field` is an open string). */
241
219
  const READ_STATE_SORT_FIELDS: string[] = ['has_unread', 'unread_count'];
242
220
 
243
221
  /**
244
- * Whether a read can change this list at all: its membership (`has_unread` filter) or its order
245
- * (`has_unread` / `unread_count` sort). Unread badges read `channel.state` directly, so nothing else
246
- * about the list depends on it.
222
+ * Whether a read can change this list: its membership (`has_unread` filter) or its order
223
+ * (`has_unread` / `unread_count` sort).
247
224
  */
248
225
  const dependsOnReadState = (paginator: ChannelPaginator) =>
249
226
  paginator.effectiveSort.some(
@@ -252,10 +229,8 @@ const dependsOnReadState = (paginator: ChannelPaginator) =>
252
229
 
253
230
  /**
254
231
  * Re-routes a channel whose read state changed. `message.read` only reaches watchers, so
255
- * `notification.mark_*` is the only signal for channels the user is not watching.
256
- *
257
- * Never fetches, unlike `updateLists`: a read cannot make an unknown channel belong to a list, and
258
- * these events are far too frequent to query on.
232
+ * `notification.mark_*` is the only signal for channels the user is not watching. Never fetches
233
+ * (unlike `updateLists`): these events are too frequent to query on.
259
234
  */
260
235
  const readStateChangedHandler: LabeledEventHandler<EventHandlerContext> = {
261
236
  handle: ({ event, ctx: { channelManager } }) => {
@@ -294,17 +269,15 @@ const notificationRemovedFromChannelHandler: LabeledEventHandler<EventHandlerCon
294
269
  };
295
270
 
296
271
  /**
297
- * `muted` is filterable (resolved from `client.mutedChannels`), but a mute change emits only this
298
- * user-level event — nothing about the channel — so without re-routing here a channel would keep its
299
- * old list until some unrelated event touched it. The client applies `event.me.channel_mutes` before
300
- * its listeners run, so the filters already see the new state.
272
+ * `muted` is filterable but a mute change emits only this user-level event, so channels are
273
+ * re-routed here. The client applies `event.me.channel_mutes` first, so filters see the new state.
301
274
  */
302
275
  const notificationChannelMutesUpdatedHandler: LabeledEventHandler<EventHandlerContext> = {
303
276
  handle: ({ ctx: { channelManager } }) => {
304
277
  const seen = new Set<string>();
305
278
  channelManager.paginators.forEach((paginator) => {
306
279
  (paginator.items ?? []).forEach((channel) => {
307
- if (seen.has(channel.cid)) return; // prevent ingestig -> emitting more than once
280
+ if (seen.has(channel.cid)) return; // ingest once, not once per list
308
281
  seen.add(channel.cid);
309
282
  channelManager.ingestChannel(channel);
310
283
  });
@@ -325,26 +298,24 @@ export type ChannelManagerOptions = {
325
298
  client: StreamChat;
326
299
  paginators?: ChannelPaginator[];
327
300
  /**
328
- * The complete set of event handlers to run, replacing the defaults rather than extending them.
329
- * Start from `ChannelManager.getDefaultHandlers()` (a fresh copy) and enrich it, unless the
330
- * intention really is to route events differently from scratch. Note that the manager the client
331
- * instantiates (`client.channelManager`) is constructed without this option — customize that one
332
- * through `addEventHandler` / `setEventHandlers` / `removeEventHandlers`.
301
+ * The complete set of event handlers, replacing the defaults. Start from
302
+ * `ChannelManager.getDefaultHandlers()` (a copy) and enrich it. `client.channelManager` is built
303
+ * without this option: customize it through `addEventHandler` / `setEventHandlers` /
304
+ * `removeEventHandlers`.
333
305
  */
334
306
  eventHandlers?: ChannelManagerEventHandlers;
335
307
  /**
336
- * Decide which paginator(s) should own a channel when multiple match.
337
- * Defaults to keeping the channel in all matching paginators.
338
- * Channels are kept only in the paginators that are listed in the ownershipResolver array.
339
- * Empty ownershipResolver array means that the channel is kept in all matching paginators.
308
+ * Picks which paginator(s) own a channel that matches several. Defaults to all of them. A function
309
+ * returns the owning paginator IDs; an array is a priority list (highest first), so the
310
+ * highest-priority match owns the channel, and if none of them is listed all keep it.
340
311
  */
341
312
  ownershipResolver?: PaginatorOwnershipResolver | string[];
342
313
  };
343
314
 
344
315
  /**
345
- * A stored channel, the key it is stored under, and what keeps it: its own state (`'watched'`,
346
- * `'active'`, `'querying-channel'`) and the names of its holders. None: a call to
347
- * `releaseUnusedChannels()` would remove it.
316
+ * A stored channel, its store key, and what keeps it: its own state (`'watched'`, `'active'`,
317
+ * `'querying-channel'`) and the names of its holders. If none, `releaseUnusedChannels()` removes
318
+ * it.
348
319
  */
349
320
  export type ChannelUsage = {
350
321
  channel: Channel;
@@ -352,7 +323,6 @@ export type ChannelUsage = {
352
323
  keptBy: string[];
353
324
  };
354
325
 
355
- /** What in the channel's own state keeps it in the channel store. */
356
326
  const keptByOwnState = (channel: Channel) => {
357
327
  const reasons: string[] = [];
358
328
  if (channel.watchStatus !== ChannelWatchStatus.NotWatching) reasons.push('watched');
@@ -365,13 +335,11 @@ export class ChannelManager extends WithSubscriptions {
365
335
  client: StreamChat;
366
336
  state: StateStore<ChannelManagerState>;
367
337
  /**
368
- * Every `Channel` instance, one per cid. A channel created from members, before the server assigns
369
- * its id, is stored under its temporary cid until {@link ChannelManager.changeChannelId} moves it.
370
- * A channel stays until a known end (deleted, or the current user removed from it) or logout removes
371
- * it, or the app calls {@link ChannelManager.releaseUnusedChannels} while it is disconnected, or
372
- * neither watched nor held; each removes it and runs its {@link Channel.disconnect}. A channel
373
- * list holds the channels it shows by linking them, which also tells it about removals and cid
374
- * changes; other users hold theirs through claims.
338
+ * Every `Channel`, one per cid (a channel created from members sits under a temporary cid until
339
+ * {@link ChannelManager.changeChannelId}). A channel stays until it is deleted, the user is
340
+ * removed from it or logs out, or {@link ChannelManager.releaseUnusedChannels} removes it;
341
+ * removal runs {@link Channel.disconnect}. Lists hold the channels they show by linking them,
342
+ * others by claims.
375
343
  *
376
344
  * @internal
377
345
  */
@@ -387,23 +355,13 @@ export class ChannelManager extends WithSubscriptions {
387
355
  >();
388
356
  protected ownershipResolver?: PaginatorOwnershipResolver;
389
357
  /**
390
- * Instances replaced by a stored one ({@link ChannelManager.supersedeChannel}). Not in the store, so
391
- * they are tracked here to be disconnected ({@link Channel.disconnect}) at logout
392
- * ({@link ChannelManager.clearChannels}). Nothing disconnects them earlier, as the app may still hold
393
- * them.
358
+ * Instances replaced by a stored one ({@link ChannelManager.supersedeChannel}). Not in the store,
359
+ * so they are disconnected at logout ({@link ChannelManager.clearChannels}).
394
360
  */
395
361
  private readonly supersededChannels = new Set<Channel>();
396
362
  /**
397
- * The `filterQueryResults` each registered paginator had before this manager wrapped it.
398
- *
399
- * A server query bypasses the manager — the paginator fetches and ingests a page on its own, and
400
- * the backend knows nothing about client-side ownership — so a "Work" (`{ team: 'work' }`) channel
401
- * comes back in a catch-all list's page too and would render in both. `wrapPaginatorFiltering`
402
- * therefore composes the ownership check onto that hook, which every page passes through.
403
- *
404
- * Keys = already wrapped (so re-inserting does not wrap twice); values = what to restore on
405
- * removal, since a detached paginator must stop applying rules resolved against lists it left.
406
- * Weakly keyed so a dropped paginator is not kept alive by this manager.
363
+ * The `filterQueryResults` each registered paginator had before `wrapPaginatorFiltering` wrapped
364
+ * it. Keys mark paginators already wrapped, values are restored on removal. Weakly keyed.
407
365
  */
408
366
  protected filterQueryResultsBeforeWrapping = new WeakMap<
409
367
  ChannelPaginator,
@@ -417,6 +375,7 @@ export class ChannelManager extends WithSubscriptions {
417
375
  'channel.hidden': [channelHiddenHandler],
418
376
  'channel.visible': [channelVisibleHandler],
419
377
  'member.updated': [memberUpdatedHandler],
378
+ 'message.deleted': [messageDeletedHandler],
420
379
  'message.new': [messageNewHandler],
421
380
  'message.read': [readStateChangedHandler],
422
381
  'message.read_locally': [readStateChangedHandler],
@@ -439,13 +398,11 @@ export class ChannelManager extends WithSubscriptions {
439
398
  this.state = new StateStore({ paginators: paginators ?? [] });
440
399
  this.setOwnershipResolver(ownershipResolver);
441
400
 
442
- // A supplied map replaces the defaults wholesale — an event type missing from it is simply not
443
- // handled. `getDefaultHandlers()` returns a copy to enrich when that is what you want.
401
+ // A supplied map replaces the defaults: an event type missing from it is not handled.
444
402
  const finalEventHandlers = eventHandlers ?? ChannelManager.getDefaultHandlers();
445
403
  for (const [type, handlers] of Object.entries(finalEventHandlers)) {
446
404
  if (handlers) this.ensurePipeline(type).replaceAll(handlers);
447
405
  }
448
- // Ensure ownership rules are applied to initial paginators' query results
449
406
  this.paginators.forEach((p) => this.wrapPaginatorFiltering(p));
450
407
  }
451
408
 
@@ -453,17 +410,20 @@ export class ChannelManager extends WithSubscriptions {
453
410
  return this.state.getLatestValue().paginators;
454
411
  }
455
412
 
456
- /** The stored channel for `cid`, if any. */
413
+ /**
414
+ * Returns the stored channel for a cid.
415
+ *
416
+ * @param cid - The channel's cid.
417
+ * @returns The stored channel, or `undefined` when none is stored.
418
+ */
457
419
  get(cid: string): Channel | undefined {
458
420
  return this.channelStore.get(cid);
459
421
  }
460
422
 
461
423
  /**
462
424
  * The instance a channel list should show for `channel`: the one that superseded it, else the one
463
- * stored under its cid, else `channel` itself. A list never puts another instance in place of the
464
- * stored one, which would leave the stored one out of the store, unfinished and without events.
465
- * `undefined` when that instance is disconnected (`pendingDisposal`), stored or not: it receives
466
- * no events, and a list that already shows it drops it at the next `releaseUnusedChannels()`.
425
+ * stored under its cid, else `channel` itself, so a list never displaces the stored instance.
426
+ * `undefined` when that instance is disconnected (`pendingDisposal`): it receives no events.
467
427
  *
468
428
  * @internal
469
429
  */
@@ -482,30 +442,28 @@ export class ChannelManager extends WithSubscriptions {
482
442
  return resolved;
483
443
  }
484
444
 
485
- /** Every stored channel. */
445
+ /**
446
+ * Returns every stored channel.
447
+ *
448
+ * @returns The stored channels.
449
+ */
486
450
  values(): Channel[] {
487
451
  return this.channelStore.values();
488
452
  }
489
453
 
490
454
  /**
491
- * Returns the channel for `type` and `id`, creating it if it isn't stored yet. Use this to get a
492
- * channel instead of calling `new Channel()`; there is one instance per cid. A stored channel
493
- * already disconnected (`pendingDisposal`) is replaced by a fresh one.
455
+ * Returns the channel for `type` and `id`, creating it if it is not stored yet (one instance per
456
+ * cid; a stored `pendingDisposal` channel is replaced by a fresh one). Use it instead of
457
+ * `new Channel()`.
494
458
  *
495
- * Leave out `id` and pass `data.members` for a distinct channel between those members (one channel
496
- * per set of members). It is stored under a temporary cid built from the member IDs until
497
- * `watch()`, `query()` or `create()` returns the real one; a stored distinct channel with the same
498
- * loaded members is returned instead. If another instance holds the real cid by then (its members
499
- * weren't loaded, or an event stored it meanwhile), that instance stays stored and this one is
500
- * left unstored. A group with the same members as another needs its own `id` instead.
459
+ * Leave out `id` and pass `data.members` for a distinct channel between those members. It is
460
+ * stored under a temporary cid until `watch()`, `query()` or `create()` returns the real one; a
461
+ * stored distinct channel with the same loaded members is returned instead. If another instance
462
+ * holds the real cid by then, it stays stored and this one is left unstored. A group with the
463
+ * same members as another needs its own `id`.
501
464
  *
502
465
  * A channel created from members is {@link Channel.isProvisional} until its query is answered: it
503
- * has no id yet, so nothing but that query can be sent for it. A channel with an id is not, even one
504
- * whose id the app generated and the server doesn't have yet: requests for it go to the server.
505
- *
506
- * A channel got this way stays stored until it is deleted, the current user is removed from it, or
507
- * the user logs out. The SDK never releases it on its own; an app freeing memory calls
508
- * {@link ChannelManager.releaseUnusedChannels}, which releases it only while nothing uses it.
466
+ * has no ID yet, so nothing but that query can be sent for it.
509
467
  *
510
468
  * ```ts
511
469
  * const general = client.channelManager.ensure({ type: 'messaging', id: 'general' });
@@ -555,8 +513,8 @@ export class ChannelManager extends WithSubscriptions {
555
513
  cid,
556
514
  () => new Channel(this.client, type, id, data),
557
515
  (channel) => {
558
- // Only `custom` is applied to a stored channel, and only when the caller passed it: other
559
- // fields (e.g. `{ members }`) would otherwise wipe its existing custom data, such as its name.
516
+ // Only `custom`, and only when passed: other fields would wipe the stored custom data (e.g.
517
+ // its name).
560
518
  if (data.custom !== undefined) {
561
519
  channel.data = { ...channel.data, custom: data.custom };
562
520
  channel._data = { ...channel._data, custom: data.custom };
@@ -566,16 +524,15 @@ export class ChannelManager extends WithSubscriptions {
566
524
  }
567
525
 
568
526
  private ensureByMembers(type: string, data: ChannelInput): Channel {
569
- // the id `Channel` gives itself until the server answers, from the same members
527
+ // The ID `Channel` gives itself until the server answers.
570
528
  const tempId = generateChannelTempId((data.members ?? []).map(getMemberUserId));
571
529
  if (!tempId) {
572
530
  throw Error('Please specify atleast one member when creating unique conversation');
573
531
  }
574
532
  const tempCid = `${type}:${tempId}`;
575
533
 
576
- // Stored under the temporary cid until the server returns the real one, then under the real
577
- // cid, whose id for a distinct channel starts with `!members-`. A loaded one with the same
578
- // members is that conversation.
534
+ // The real ID of a distinct channel starts with `!members-`: a loaded one with the same members
535
+ // is this conversation.
579
536
  if (this.get(tempCid)?.pendingDisposal) this.removeChannel(tempCid);
580
537
  if (!this.get(tempCid)) {
581
538
  const existing = this.values().find(
@@ -619,25 +576,15 @@ export class ChannelManager extends WithSubscriptions {
619
576
  }
620
577
 
621
578
  /**
622
- * `previous`, created without an id, was answered with a cid `successor` already holds (stored by an
623
- * event or a channel list while `previous` waited). `successor` stays the one instance for the cid
624
- * and takes over, without losing anything of its own:
625
- *
626
- * - the server's response, as a `queryChannels` result for a stored channel is applied: its data
627
- * and members, and its messages merged into the loaded ones (a local message, such as a failed
628
- * one, is never removed; an open channel's or a scrolled-back one's window isn't re-seeded);
629
- * - `previous`'s local messages (sending or failed), added by id; a message `successor` already has
630
- * keeps `successor`'s copy;
631
- * - `previous`'s composer, when `previous` is open and `successor` isn't: the user is typing in
632
- * `previous`, and nobody in `successor`. When both are open, neither composer is overwritten.
633
- *
634
- * `successor` is marked watched only when the query asked to watch (`watch: true`): the server then
635
- * watches the cid for this connection. A query without a watch leaves its watch status as it was.
579
+ * `previous`, created without an ID, was answered with a cid `successor` already holds (stored by
580
+ * an event or a list meanwhile). `successor` stays the one instance and takes over: the response
581
+ * is applied to it like a `queryChannels` result (local messages are never removed),
582
+ * `previous`'s local messages (sending or failed) are added by ID (`successor`'s copy wins), and
583
+ * `previous`'s composer moves over when `previous` is open and `successor` is not.
636
584
  *
637
- * `previous`'s own entry (`storedUnder`, its temporary cid) is dropped first, without disconnecting
638
- * it: its query is still being applied to it and it may be on screen. It is marked superseded
639
- * (`state.supersededBy`) so its holders switch over, and tracked here until logout, so the SDK
640
- * never loses track of it.
585
+ * `successor` is marked watched only when the query asked to watch. `previous` is dropped from
586
+ * the store (`storedUnder`) without disconnecting, as it may be on screen, marked superseded
587
+ * (`state.supersededBy`) so its holders switch over, and disconnected at logout.
641
588
  *
642
589
  * @internal
643
590
  */
@@ -650,15 +597,15 @@ export class ChannelManager extends WithSubscriptions {
650
597
  if (storedUnder && this.get(storedUnder) === previous) {
651
598
  this.channelStore.detach(storedUnder);
652
599
  }
653
- // `false`, not `undefined`: `hydrateChannels` would take a missing `watch` as "watched if
654
- // connected", and this query may not have asked the server to watch
600
+ // `false`, not `undefined`: a missing `watch` means "watched if connected" to
601
+ // `hydrateChannels`.
655
602
  this.client.hydrateChannels([response], {}, { watch: watch === true });
656
603
  successor.messagePaginator.batch(
657
604
  () => {
658
605
  for (const message of previous.messagePaginator.items ?? []) {
659
606
  if (message.status === 'received') continue;
660
607
  if (successor.messagePaginator.getItem(message.id)) continue;
661
- // composed in `previous`, it carries `previous`'s temporary cid
608
+ // Composed in `previous`, so it carries the temporary cid.
662
609
  successor.messagePaginator.ingestItem({ ...message, cid: successor.cid });
663
610
  }
664
611
  },
@@ -672,28 +619,16 @@ export class ChannelManager extends WithSubscriptions {
672
619
  }
673
620
 
674
621
  /**
675
- * Removes every stored channel the app disconnected ({@link Channel.disconnect}, so
676
- * `pendingDisposal`), whatever still holds or uses it: disconnecting says the app is done with
677
- * it.
678
- * Every list showing it drops it, as the store's removal reaches each list's index. Objects that
679
- * still refer to the instance keep it, finished.
622
+ * Removes every stored channel the app disconnected (`pendingDisposal`), whatever holds it, then
623
+ * every one that is neither watched nor held; lists drop them. Kept: watched channels
624
+ * (`watching`, or `wasWatching` until restored), active ones ({@link Channel.activate}), ones
625
+ * being loaded, and ones held in {@link ChannelManager.channelStore} (lists link theirs; threads,
626
+ * the composer cache and channel search hold theirs through claims,
627
+ * {@link EntityStore.addClaim}).
680
628
  *
681
- * Then removes, and disconnects, every stored channel that is neither watched nor held. A watched
682
- * channel (`watching`,
683
- * or `wasWatching` until its watch is restored) stays, because its events keep it current; so does
684
- * an active one ({@link Channel.activate}), one being loaded (`watch()`, `query()` or `create()` in flight), and
685
- * one a holder holds in {@link ChannelManager.channelStore}: a channel list links each of its
686
- * channels, while threads, the composer cache and an active channel search hold theirs through
687
- * claims ({@link EntityStore.addClaim}).
688
- *
689
- * What remains is an unwatched snapshot nothing shows, which saves no request: using it again
690
- * needs a query, which stores it again.
691
- *
692
- * The SDK never calls this: it can't see the channels an app keeps in its own state, such as a
693
- * stopped watch kept for re-entry or search results held after the search ended. Call it when the
694
- * app is done with what it held, for example after closing a search screen
695
- * (`searchController.dispose()`, then this). A channel your code still uses but that none of the
696
- * above keeps would be released, so keep it with {@link Channel.activate} first.
629
+ * The SDK never calls this, as it cannot see channels an app keeps in its own state. Call it when
630
+ * the app is done with them (e.g. after `searchController.dispose()`), and keep a channel your
631
+ * code still uses with {@link Channel.activate} first.
697
632
  */
698
633
  releaseUnusedChannels() {
699
634
  for (const [key, channel] of this.channelStore.entries()) {
@@ -705,9 +640,8 @@ export class ChannelManager extends WithSubscriptions {
705
640
  }
706
641
 
707
642
  /**
708
- * Every stored channel with what keeps it, by the same rule as
709
- * {@link ChannelManager.releaseUnusedChannels}: a channel kept by nothing would be released by a
710
- * call to it. For debugging tools.
643
+ * Every stored channel with what keeps it, by the rule of
644
+ * {@link ChannelManager.releaseUnusedChannels}. For debugging tools.
711
645
  *
712
646
  * @internal
713
647
  */
@@ -721,8 +655,7 @@ export class ChannelManager extends WithSubscriptions {
721
655
 
722
656
  /**
723
657
  * Removes the channel stored under `cid` whatever uses it, and disconnects it
724
- * ({@link Channel.disconnect}).
725
- * Every list showing it drops it too, as the store's removal reaches each list's index.
658
+ * ({@link Channel.disconnect}). Every list showing it drops it too.
726
659
  *
727
660
  * @internal
728
661
  */
@@ -743,9 +676,8 @@ export class ChannelManager extends WithSubscriptions {
743
676
  }
744
677
 
745
678
  /**
746
- * Fans the client-owned `mutedChannels` out to every stored channel's reactive `state.muteStatus`.
747
- * Each channel republishes only when its own mute status actually changed, so this stays cheap on
748
- * the frequent `health.check` path.
679
+ * Fans the client-owned `mutedChannels` out to every stored channel's `state.muteStatus` (a
680
+ * channel republishes only when its status changed, as this runs on every `health.check`).
749
681
  *
750
682
  * @internal
751
683
  */
@@ -754,8 +686,8 @@ export class ChannelManager extends WithSubscriptions {
754
686
  }
755
687
 
756
688
  /**
757
- * Resets the AI indicator state to `Idle` on every stored channel. Invoked from `closeConnection`
758
- * as it's a deliberate shutdown and will not natively trigger a WS event.
689
+ * Resets the AI indicator state to `Idle` on every stored channel. Invoked from
690
+ * `closeConnection`, a deliberate shutdown that triggers no WS event.
759
691
  *
760
692
  * @internal
761
693
  */
@@ -764,19 +696,11 @@ export class ChannelManager extends WithSubscriptions {
764
696
  }
765
697
 
766
698
  /**
767
- * Demotes every actively-watched channel to `WasWatching`. The server keys watches by connection
768
- * ID, so losing the socket ends every watch this client held — a reconnect issues a NEW id and the
769
- * channels have to be re-queried to watch again. `WasWatching` is what records that they should be.
770
- *
771
- * Only `Watching` is demoted: a channel the consumer stopped on purpose, or one already
772
- * disconnected (`disconnect()`), stays `NotWatching` and must not be resurrected by a reconnect.
773
- *
774
- * Invoked from two places on the WebSocket, because neither covers the other:
775
- * `StableWSConnection._setHealth(false)` for an abnormal close/error, and `closeConnection()` for a
776
- * deliberate shutdown (e.g. mobile backgrounding), whose `disconnect()` writes the status through
777
- * `_applyHealth` and so never reaches `_setHealth`. After an `enableWSFallback` switch the
778
- * long-poll calls it too, from `WSConnectionFallback._setState()` whenever going closed or
779
- * disconnected takes the status offline.
699
+ * Demotes every `Watching` channel to `WasWatching`: the server keys watches by connection ID, so
700
+ * a dropped socket ends them all. Channels stopped on purpose or disconnected stay `NotWatching`.
701
+ * Called when the socket goes unhealthy or offline (`StableWSConnection`, `WSConnectionFallback`)
702
+ * and by `closeConnection()`, whose `disconnect()` writes health through `_applyHealth` and never
703
+ * reaches `_setHealth`.
780
704
  *
781
705
  * @internal
782
706
  */
@@ -796,10 +720,7 @@ export class ChannelManager extends WithSubscriptions {
796
720
  return { channelManager: this };
797
721
  }
798
722
 
799
- /**
800
- * Returns deep copy of default handlers mapping.
801
- * The defaults can be enriched with custom handlers or the custom handlers can be replaced.
802
- */
723
+ /** Returns a copy of the default handler mapping, to enrich or replace. */
803
724
  static getDefaultHandlers(): ChannelManagerEventHandlers {
804
725
  const src = ChannelManager.defaultEventHandlers;
805
726
  const out: ChannelManagerEventHandlers = {};
@@ -811,13 +732,10 @@ export class ChannelManager extends WithSubscriptions {
811
732
  }
812
733
 
813
734
  /**
814
- * Replace the rule deciding which paginator(s) own a channel matched by several of them. Pass an
815
- * ordered array of paginator ids (highest priority first) for the built-in priority resolver, a
816
- * custom resolver function, or `undefined` to go back to the default (a channel is kept in every
817
- * paginator whose filter it matches).
818
- *
819
- * Available as a setter because the manager is constructed by the client, before the app has had
820
- * a chance to create its paginators — their ids are therefore only known later.
735
+ * Sets the rule deciding which paginator(s) own a channel matched by several. Pass paginator IDs
736
+ * (highest priority first) for the built-in priority resolver, a custom resolver, or `undefined`
737
+ * for the default (every matching paginator keeps the channel). A setter because the client
738
+ * builds the manager before the app creates its paginators.
821
739
  */
822
740
  setOwnershipResolver(ownershipResolver?: PaginatorOwnershipResolver | string[]) {
823
741
  if (!ownershipResolver) {
@@ -829,10 +747,7 @@ export class ChannelManager extends WithSubscriptions {
829
747
  : ownershipResolver;
830
748
  }
831
749
 
832
- /**
833
- * Which paginators should own the channel among the ones that matched.
834
- * Default behavior keeps the channel in all matching paginators.
835
- */
750
+ /** Ids of the paginators that own the channel among the matches. Empty: all of them. */
836
751
  resolveOwnership(
837
752
  channel: Channel,
838
753
  matchingPaginators: ChannelPaginator[],
@@ -841,22 +756,15 @@ export class ChannelManager extends WithSubscriptions {
841
756
  }
842
757
 
843
758
  /**
844
- * Route a channel into the paginator(s) that should own it, and remove it from any list it
845
- * no longer belongs to. Ownership is resolved exactly as for live WS updates — the channel is
846
- * ingested into every paginator whose filter it matches (or, when an ownership resolver picks
847
- * winners among several matches, only into the owner(s)).
848
- *
849
- * Use this to surface a channel the app just opened — a search result, a freshly created DM —
850
- * in the list(s) without a full re-query. `ingestItem` dedupes by cid and inserts in sort
851
- * order, so calling this repeatedly is safe. A channel created from members is ignored until its
852
- * first query gives it an id: ingest it once `watch()` (or `ensureWatched()`) resolves.
853
- *
854
- * A channel that matches no paginator is not added anywhere. To have such channels still
855
- * appear, register a catch-all paginator (empty filter) with the lowest ownership priority as
856
- * a local fallback list.
759
+ * Routes a channel into the paginator(s) that own it and removes it from any list it no longer
760
+ * belongs to, as for live WS updates. Use it to surface a channel the app just opened (a search
761
+ * result, a new DM) without a re-query; repeated calls are safe. A channel created from members
762
+ * is ignored until its first query gives it an ID. A channel matching no paginator is added
763
+ * nowhere: register a catch-all paginator (empty filter) with the lowest ownership priority as a
764
+ * fallback.
857
765
  */
858
766
  ingestChannel(input: Channel) {
859
- // not listed until it has its id (see `ChannelPaginator.ingestItem`)
767
+ // Not listed until it has its ID (see `ChannelPaginator.ingestItem`).
860
768
  if (input.isProvisional) return;
861
769
  const channel = this.resolveListedChannel(input);
862
770
  if (!channel) return;
@@ -874,11 +782,10 @@ export class ChannelManager extends WithSubscriptions {
874
782
  }
875
783
 
876
784
  /**
877
- * Drops a channel from the lists whose filters it no longer matches, adding it nowhere.
878
- *
879
- * For state the client changes without an event naming the channel — zeroing every unread count on a
880
- * global read. Removal-only: the backend rejects `has_unread: false`, so becoming read can never make
881
- * a channel belong to a list, and `ingestChannel` would pull unloaded channels into matching ones.
785
+ * Drops a channel from the lists whose filters it no longer matches, adding it nowhere. For state
786
+ * the client changes without an event naming the channel (e.g. zeroing every unread count on a
787
+ * global read). Removal-only: becoming read cannot make a channel belong to a list (the backend
788
+ * rejects `has_unread: false`).
882
789
  */
883
790
  dropFromUnmatchedLists(channel: Channel) {
884
791
  this.paginators.forEach((paginator) => {
@@ -887,10 +794,7 @@ export class ChannelManager extends WithSubscriptions {
887
794
  });
888
795
  }
889
796
 
890
- /**
891
- * Filter a page of query results for a specific paginator according to ownership rules.
892
- * If no owners are specified by the resolver, all matching paginators keep the item.
893
- */
797
+ /** Filters a page of query results for `paginator` by ownership (no owners: all matches keep). */
894
798
  protected filterItemsByOwnership({
895
799
  paginator,
896
800
  items,
@@ -914,26 +818,10 @@ export class ChannelManager extends WithSubscriptions {
914
818
  }
915
819
 
916
820
  /**
917
- * Makes a registered paginator apply this manager's ownership rules to the pages it fetches
918
- * itself, by composing `filterItemsByOwnership` onto its `filterQueryResults`.
919
- *
920
- * A channel can enter a list through two doors, and only one of them goes through the manager:
921
- * - **WS events / `ingestChannel`** — the manager routes the channel and consults
922
- * `resolveOwnership` before ingesting, so exclusivity holds by construction.
923
- * - **A server query** — `paginator.next()` (a `ChannelList` scrolling, `reload()`) queries and
924
- * ingests on its own; the manager is not involved. Without this wrapper a page would land in
925
- * every list whose *server-side* filter matched it, so a channel matching both
926
- * `channels:archived` and `channels:default` would show up in both lists until some later event
927
- * re-routed it — the exact duplication the resolver exists to prevent.
928
- *
929
- * Wrapping (rather than subclassing or a constructor hook) is what lets the manager inject this
930
- * into paginators it does not construct: `filterQueryResults` is an instance property, so the
931
- * original is captured here and handed back by `unwrapPaginatorFiltering` when the paginator is
932
- * detached. The paginator's own filtering runs first and stays authoritative — ownership only ever
933
- * removes further items, never adds any back.
934
- *
935
- * Idempotent: the `WeakMap` guard keeps a re-inserted paginator from being wrapped twice, which
936
- * would filter the same page repeatedly and, worse, lose the reference to the true original.
821
+ * Makes a registered paginator apply the ownership rules to the pages it fetches itself (server
822
+ * queries bypass the manager), by composing `filterItemsByOwnership` onto its
823
+ * `filterQueryResults`. Its own filtering runs first. Idempotent: wrapping twice would lose the
824
+ * true original.
937
825
  */
938
826
  protected wrapPaginatorFiltering(paginator: ChannelPaginator) {
939
827
  if (this.filterQueryResultsBeforeWrapping.has(paginator)) return;
@@ -946,10 +834,8 @@ export class ChannelManager extends WithSubscriptions {
946
834
  }
947
835
 
948
836
  /**
949
- * Undo `wrapPaginatorFiltering` — restore the `filterQueryResults` the paginator had before this
950
- * manager wrapped it. A paginator that has left the manager must not keep applying its ownership
951
- * rules: those are resolved against the paginators the manager still holds, so a detached
952
- * paginator would drop channels owned by lists it is no longer part of.
837
+ * Restores the `filterQueryResults` the paginator had before `wrapPaginatorFiltering`: a detached
838
+ * paginator must not keep applying ownership rules resolved against lists it left.
953
839
  */
954
840
  protected unwrapPaginatorFiltering(paginator: ChannelPaginator) {
955
841
  const original = this.filterQueryResultsBeforeWrapping.get(paginator);
@@ -963,10 +849,9 @@ export class ChannelManager extends WithSubscriptions {
963
849
  }
964
850
 
965
851
  /**
966
- * Replace the whole set of lists in a single state update — the primitive `insertPaginator` and
967
- * `removePaginator` build on, and what to use for a wholesale swap instead of publishing an
968
- * intermediate state per step. Paginators dropped from the set are detached exactly as
969
- * `removePaginator` detaches them; a repeated id keeps only its first occurrence.
852
+ * Replaces the whole set of lists in one state update (the primitive `insertPaginator` and
853
+ * `removePaginator` build on). Dropped paginators are detached as `removePaginator` does; a
854
+ * repeated ID keeps only its first occurrence.
970
855
  *
971
856
  * @param paginators - The lists this manager should hold, in render order.
972
857
  */
@@ -980,8 +865,7 @@ export class ChannelManager extends WithSubscriptions {
980
865
  }
981
866
 
982
867
  const currentPaginators = this.paginators;
983
- // Publishing an equivalent set would hand subscribers a new array for no reason — a
984
- // `state.paginators` selector shallow-compares by reference, so every list would re-render.
868
+ // An equivalent set would hand subscribers a new array and re-render every list.
985
869
  const isUnchanged =
986
870
  currentPaginators.length === nextPaginators.length &&
987
871
  currentPaginators.every((paginator, i) => paginator === nextPaginators[i]);
@@ -997,14 +881,11 @@ export class ChannelManager extends WithSubscriptions {
997
881
  this.unwrapPaginatorFiltering(paginator);
998
882
  paginator.cancelScheduledQuery();
999
883
  });
1000
- // Wrap the current set to enforce ownership on their query results
1001
884
  nextPaginators.forEach((paginator) => this.wrapPaginatorFiltering(paginator));
1002
885
  }
1003
886
 
1004
887
  /**
1005
- * Detach every list at once — the teardown counterpart of `setPaginators`. Each paginator is
1006
- * released exactly as `removePaginator` releases it (ownership-filtering wrapper removed,
1007
- * scheduled query canceled, loaded items kept), in a single state update.
888
+ * Detaches every list as `removePaginator` does, in one update.
1008
889
  *
1009
890
  * @returns The paginators the manager held, in the order it held them.
1010
891
  */
@@ -1015,13 +896,11 @@ export class ChannelManager extends WithSubscriptions {
1015
896
  }
1016
897
 
1017
898
  /**
1018
- * If paginator already exists → remove old, reinsert at new index.
1019
- * If index not provided → append at the end.
1020
- * If index provided → insert (or move) at that index.
899
+ * Inserts a paginator. One already held with the same ID is removed first, so this moves it, or
900
+ * replaces it when it is another instance.
1021
901
  *
1022
- * @param params - The insertion parameters.
1023
902
  * @param params.paginator - The paginator to insert or move.
1024
- * @param params.index - Target index; when omitted the paginator is appended.
903
+ * @param params.index - Target index, clamped to the list. Defaults to appending.
1025
904
  */
1026
905
  insertPaginator({ paginator, index }: { paginator: ChannelPaginator; index?: number }) {
1027
906
  const paginators = [...this.paginators];
@@ -1038,15 +917,11 @@ export class ChannelManager extends WithSubscriptions {
1038
917
  }
1039
918
 
1040
919
  /**
1041
- * Remove a paginator from the manager. The paginator stops receiving WS-driven updates and
1042
- * disappears from `state.paginators` (so UIs rendering one list per paginator drop its list), and
1043
- * gets its own `filterQueryResults` back — from here on it is an independent paginator again.
1044
- *
1045
- * Its loaded items are left untouched: the paginator can be re-inserted later, or kept and
1046
- * queried on its own. Any query scheduled through `nextDebounced` is canceled, so a list that was
1047
- * just removed does not fire one more request.
920
+ * Removes a paginator: it leaves `state.paginators`, stops receiving WS-driven updates and gets
921
+ * its own `filterQueryResults` back. Its loaded items stay, and a query scheduled through
922
+ * `nextDebounced` is cancelled.
1048
923
  *
1049
- * @param paginatorOrId - The paginator to remove, or its id.
924
+ * @param paginatorOrId - The paginator to remove, or its ID.
1050
925
  * @returns The removed paginator, or `undefined` when this manager did not hold it.
1051
926
  */
1052
927
  removePaginator(
@@ -1061,11 +936,8 @@ export class ChannelManager extends WithSubscriptions {
1061
936
  }
1062
937
 
1063
938
  /**
1064
- * Discard the loaded data of every registered list, keeping the registrations themselves: which
1065
- * lists exist is application configuration, while the channels in them belong to the connected
1066
- * user and become invalid on `disconnectUser`. Each paginator returns to "never queried"
1067
- * (`items: undefined`) with its debounced query canceled. Deliberately not named `resetState` —
1068
- * this manager's own `state` *is* the paginator list, which this must not touch.
939
+ * Discards the loaded data of every registered list but keeps the registrations: each paginator
940
+ * returns to "never queried" (`items: undefined`) with its debounced query cancelled.
1069
941
  */
1070
942
  resetPaginatorStates() {
1071
943
  this.paginators.forEach((paginator) => {
@@ -1105,7 +977,7 @@ export class ChannelManager extends WithSubscriptions {
1105
977
  handlers.forEach((params) => pipeline.remove(params));
1106
978
  }
1107
979
 
1108
- /** Subscribe to WS (and more buses via attachBus) */
980
+ /** Subscribes to client events. The returned function releases this registration. */
1109
981
  registerSubscriptions(): Unsubscribe {
1110
982
  if (!this.hasSubscriptions) {
1111
983
  this.addUnsubscribeFunction(
@@ -1144,26 +1016,13 @@ export class ChannelManager extends WithSubscriptions {
1144
1016
  );
1145
1017
 
1146
1018
  /**
1147
- * Re-run every loaded list's own first-page query — the channel-list half of connection recovery,
1148
- * driven by {@link ConnectionRecoveryManager}.
1149
- *
1150
- * Each list re-asserts its *own* `filters` / `sort` / `pageSize` rather than some substitute query,
1151
- * and because `client.queryChannels` watches by default, that page's channels are re-watched as a
1152
- * side effect. Channels below the first page are deliberately not touched — see
1153
- * `restoreInterruptedWatch` for how they come back.
1154
- *
1155
- * `{ keepPreviousItems: true, reset: 'yes' }` is the non-destructive refresh: `reset` restarts the
1156
- * window at page 1, while `keepPreviousItems` merges the fetched page into the loaded list instead
1157
- * of replacing it and keeps the item index populated — the latter is what stops a concurrent
1158
- * offline-replay ingest from rebuilding the list out of a cleared index. Notably NOT `silent`: the
1159
- * `isLoading` transition it would suppress is the in-flight guard that keeps a second overlapping
1160
- * query from being issued.
1161
- *
1162
- * Distinct from {@link ChannelManager.reload}, which is a destructive `reset` that blanks each list
1163
- * to its loading state.
1164
- *
1165
- * Paginators that were never queried are skipped: they run their own first query when they mount,
1166
- * and querying them here would race it.
1019
+ * Re-runs every loaded list's own first-page query, the channel-list half of connection recovery
1020
+ * ({@link ConnectionRecoveryManager}). The page's channels are re-watched (`queryChannels`
1021
+ * watches by default), those below it come back through `restoreInterruptedWatch`.
1022
+ * Never-queried paginators are skipped: they run their own first query on mount, and querying them
1023
+ * here would race it. Unlike {@link ChannelManager.reload}, it merges the page into the loaded
1024
+ * list (`keepPreviousItems`) instead of blanking it, and is not `silent`: the `isLoading`
1025
+ * transition guards against an overlapping query.
1167
1026
  */
1168
1027
  recover = async () =>
1169
1028
  await Promise.allSettled(