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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
@@ -0,0 +1,5 @@
1
+ // Only the modules that were already public belong here — `src/configuration/index.ts` re-exports this
2
+ // barrel wholesale, so anything added becomes public API. `applyInstanceConfiguration`,
3
+ // `copyConfigPatch`, `deepFreezeConfig` and `declarativeSlices` are `@internal` and are imported by path
4
+ // instead.
5
+ export * from './serverAuthority';
@@ -0,0 +1,146 @@
1
+ import { mergeWith } from '../../utils/mergeWith';
2
+ import type { MergeWithCustomizer } from '../../utils/mergeWith/mergeWithCore';
3
+ import type { DeepPartial } from '../../types.utility';
4
+
5
+ /**
6
+ * The fields a server decides for some configurable object — a partial configuration holding *only* those
7
+ * fields, with the value the server currently reports.
8
+ *
9
+ * Only server-decided fields may appear. The merge below lets any scalar on this side win, so an
10
+ * unrelated field smuggled in here would override the caller's value while looking like a server
11
+ * restriction.
12
+ */
13
+ export type ServerRestrictions<TConfig extends object> = DeepPartial<TConfig>;
14
+
15
+ /**
16
+ * Merges a set of server restrictions over a requested configuration under two rules:
17
+ *
18
+ * 1. **Booleans are ANDed.** A flag the *client* turned off stays off even where the server would allow it —
19
+ * asking for less than you are granted is always legitimate — and a flag the server turned off stays off
20
+ * whatever the client asked. Either side may narrow; neither may widen.
21
+ * 2. **Any other scalar: the server wins.** This is what makes "client configuration can only narrow what
22
+ * the server grants" true rather than aspirational.
23
+ *
24
+ * Objects are left to the normal deep merge, so the rules apply leaf by leaf.
25
+ *
26
+ * A third rule lives in {@link ServerUpperBounds}, passed separately because a ceiling narrows rather than
27
+ * replaces.
28
+ *
29
+ * **Rule 1 is deliberately not keyed on a field name.** It used to read `key === 'enabled'`, which happened
30
+ * to be correct because `location.enabled` was the only boolean restriction — and was a trap for whoever
31
+ * added the next one. A gate named anything else (`text.publishTypingEvents` for `typing_events`, say) would
32
+ * have fallen through to rule 2, and a client's deliberate `false` would have been overwritten by a
33
+ * permissive server: exactly the widening **DV-16** was about, reintroduced one field at a time. Boolean
34
+ * restrictions are gates, and the conjunction of two gates is the rule for all of them.
35
+ */
36
+ const serverRestrictionCustomizer: MergeWithCustomizer<object> = (
37
+ requestedValue,
38
+ restrictionValue,
39
+ ) => {
40
+ // Not a leaf — hand it back to the deep merge and decide further down.
41
+ //
42
+ // `typeof null === 'object'`, so `null` is excluded explicitly: it has no interior to descend into. The
43
+ // upper-bound customizer below has always guarded this and this one did not; the two disagreeing was a
44
+ // latent difference rather than a live bug, since no configuration field is nullable today.
45
+ const isInterior = (value: unknown) => typeof value === 'object' && value !== null;
46
+ if (isInterior(requestedValue)) return undefined;
47
+ // Nothing requested here but the server describes a subtree — descend so it lands, rather than answering
48
+ // with the absent request and dropping it. Deliberately *not* extended to a requested scalar under an
49
+ // object restriction: rule 2 refuses that below, which is the point of its scalar check.
50
+ if (requestedValue == null && isInterior(restrictionValue)) return undefined;
51
+
52
+ // Rule 1: both sides are gates, so the stricter one wins whichever side it is on.
53
+ if (typeof requestedValue === 'boolean' && typeof restrictionValue === 'boolean') {
54
+ return requestedValue && restrictionValue;
55
+ }
56
+
57
+ // Rule 2: the server had the last word.
58
+ if (
59
+ ['string', 'number', 'bigint', 'boolean', 'symbol'].includes(typeof restrictionValue)
60
+ ) {
61
+ return restrictionValue;
62
+ }
63
+
64
+ // The server stated nothing for this field, so the request stands.
65
+ return requestedValue;
66
+ };
67
+
68
+ /**
69
+ * Numeric ceilings the server imposes — a partial configuration holding only fields where the server states
70
+ * a *maximum*, such as a channel type's `max_message_length`.
71
+ *
72
+ * Separate from {@link ServerRestrictions} because the two combine differently, and putting a ceiling in the
73
+ * wrong bucket is a silent bug rather than a type error: a restriction *replaces* the requested value, which
74
+ * for a limit would widen a caller who deliberately asked for something stricter.
75
+ */
76
+ export type ServerUpperBounds<TConfig extends object> = DeepPartial<TConfig>;
77
+
78
+ /**
79
+ * Tightest wins. A ceiling can only lower the requested value, never raise it — and it applies in full when
80
+ * the caller asked for no limit at all, which is the common case and the reason the server's maximum is
81
+ * worth reading: an unlimited composer otherwise lets a message be written that the API will reject.
82
+ */
83
+ const upperBoundCustomizer: MergeWithCustomizer<object> = (
84
+ requestedValue,
85
+ boundValue,
86
+ ) => {
87
+ // Not a leaf — hand it back to the deep merge and decide at the leaves.
88
+ if (typeof requestedValue === 'object' && requestedValue !== null) return undefined;
89
+ // The server states no ceiling for this field, so the request stands.
90
+ if (typeof boundValue !== 'number') return requestedValue;
91
+ // No client limit — the server's is the effective one. For `undefined` the deep merge would reach the
92
+ // same answer on its own; the branch earns its place on a value that is neither, where delegating
93
+ // would keep the nonsense and drop the ceiling.
94
+ if (typeof requestedValue !== 'number') return boundValue;
95
+
96
+ return Math.min(requestedValue, boundValue);
97
+ };
98
+
99
+ /**
100
+ * Applies a server's restrictions to a configuration a caller asked for, so the result never claims more
101
+ * than the server allows.
102
+ *
103
+ * **Why this is a named function rather than an inline merge.** It has to run on *every* route by which a
104
+ * configuration can change — construction, the declarative tree, a setup function, a direct
105
+ * `updateConfig` — because a restriction applied only at construction holds until the first time anything
106
+ * updates the configuration and then silently stops holding. `MessageComposer` learned this the hard way:
107
+ * only its `deriveConfig` applied the restrictions, so registering `location.enabled: true` on a running
108
+ * app widened past a `shared_locations: false` server and produced a composer offering a feature the API
109
+ * rejects (**DV-16**).
110
+ *
111
+ * **What it deliberately does not do.** It knows nothing about *where* restrictions come from. Reading
112
+ * them is the entity's job, because only the entity knows what to ask — a composer reads its channel's
113
+ * `serverConfig`, something else might read capabilities — and the answer depends on an instance that
114
+ * exists. That is also why this does not live in `InstanceConfigurationRegistry`: that service merges
115
+ * declarative layers before any instance exists, and its merges follow the opposite rule (a more specific
116
+ * layer *may* re-enable what a broader one disabled), which rule 1 would break.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * // Inside a configurable class, on every path that resolves configuration:
121
+ * this.configState.partialNext(
122
+ * mergeServerRestrictions(requestedConfig, {
123
+ * location: { enabled: this.channel.serverConfig?.shared_locations },
124
+ * }),
125
+ * );
126
+ * ```
127
+ */
128
+ export const mergeServerRestrictions = <TConfig extends object>(
129
+ requested: TConfig,
130
+ restrictions: ServerRestrictions<TConfig>,
131
+ upperBounds?: ServerUpperBounds<TConfig>,
132
+ ): TConfig => {
133
+ const restricted = mergeWith(
134
+ requested,
135
+ restrictions,
136
+ serverRestrictionCustomizer as MergeWithCustomizer<TConfig>,
137
+ );
138
+
139
+ if (!upperBounds) return restricted;
140
+
141
+ return mergeWith(
142
+ restricted,
143
+ upperBounds,
144
+ upperBoundCustomizer as MergeWithCustomizer<TConfig>,
145
+ );
146
+ };
@@ -0,0 +1,153 @@
1
+ import { chatLoggerSystem } from '../logger';
2
+
3
+ // Part of the connection lifecycle, so it shares the `connection` scope rather than adding another
4
+ // member to the public `ChatLoggerScope` union for a single debug line.
5
+ const logger = chatLoggerSystem.getLogger('connection');
6
+
7
+ /**
8
+ * Holds the connection id — the WebSocket's, or the long-poll's after an `enableWSFallback`
9
+ * switch — and lets callers await one that is still being negotiated.
10
+ *
11
+ * The server keys channel watches and presence subscriptions by connection id, and answers `200`
12
+ * while registering nothing when a request that needs one arrives without it. Requests carrying such
13
+ * a subscription therefore have to wait for the handshake — see `requiresConnectionId` in
14
+ * `api-client.ts` for which those are.
15
+ *
16
+ * The id lives here and nowhere else. A copy kept on the socket outlives the socket it belongs to,
17
+ * and a copy in `client.wsConnection.state` cannot be invalidated by a socket that has already been
18
+ * replaced; either way requests go out keyed to a connection the server has torn down. The long-poll
19
+ * keeps no copy either: `WSConnection.disconnect()` reads the id before the socket's `disconnect()`
20
+ * drops it, and hands it to the long-poll's close.
21
+ *
22
+ * {@link StableWSConnection} drives the lifecycle: {@link arm} before a socket opens,
23
+ * {@link resolveConnectionId} on the hello frame, {@link invalidate} when it drops or is closed
24
+ * deliberately, {@link rejectConnectionId} when a reconnect gives up. After an `enableWSFallback`
25
+ * switch, `WSConnectionFallback` drives it the same way instead.
26
+ */
27
+ export class ConnectionIdManager {
28
+ connectionId?: string;
29
+ loadConnectionIdPromise?: Promise<string>;
30
+ private resolve?: (connectionId: string) => void;
31
+ private reject?: (reason: unknown) => void;
32
+
33
+ /**
34
+ * Arms the deferred a connection attempt will settle, so requests issued while the handshake is in
35
+ * flight have something to await.
36
+ */
37
+ arm = () => {
38
+ if (this.connectionId || this.loadConnectionIdPromise) return;
39
+
40
+ this.loadConnectionIdPromise = new Promise<string>((resolve, reject) => {
41
+ this.resolve = resolve;
42
+ this.reject = reject;
43
+ });
44
+ // A rejected deferred nobody happened to be awaiting is an unhandled rejection in the consumer's
45
+ // application. Real awaiters hold their own reference and still see it; this only keeps the
46
+ // unawaited case quiet.
47
+ this.loadConnectionIdPromise.catch(() => undefined);
48
+ };
49
+
50
+ /**
51
+ * Publishes the id the server answered the handshake with, releasing anything waiting on one.
52
+ *
53
+ * @param connectionId - The connection id carried by the `connection.ok` event.
54
+ */
55
+ resolveConnectionId = (connectionId: string) => {
56
+ this.connectionId = connectionId;
57
+ this.resolve?.(connectionId);
58
+ this.settle();
59
+ };
60
+
61
+ /**
62
+ * Fails anything waiting on an id, for a connection attempt that will not be retried.
63
+ *
64
+ * @param reason - The error to reject pending waiters with.
65
+ */
66
+ rejectConnectionId = (reason: unknown) => {
67
+ this.connectionId = undefined;
68
+ this.reject?.(reason);
69
+ this.settle();
70
+ };
71
+
72
+ /**
73
+ * Drops the id without failing anything waiting on one, for a socket that died but will be
74
+ * retried. Arming a fresh deferred is what makes those requests wait for the reconnect rather than
75
+ * race ahead with a dead id.
76
+ */
77
+ invalidate = () => {
78
+ if (!this.connectionId) return;
79
+
80
+ logger
81
+ .withExtraTags('invalidate')
82
+ .debug('Dropping the connection id; the socket is no longer up.');
83
+
84
+ this.connectionId = undefined;
85
+ this.arm();
86
+ };
87
+
88
+ /**
89
+ * Drops the id and fails any pending waiter, for a socket closed deliberately. The id is dead from
90
+ * that moment, and a request keyed by it would register a subscription on a connection that no
91
+ * longer exists.
92
+ */
93
+ reset = () => {
94
+ logger.withExtraTags('reset').debug('Dropping the connection id.');
95
+
96
+ this.rejectConnectionId(
97
+ new Error(
98
+ 'The WebSocket connection was closed before a connection id could be resolved. Call `client.openConnection()` to open a new one, or `client.connectUser()` if the user was disconnected.',
99
+ ),
100
+ );
101
+ };
102
+
103
+ /**
104
+ * The current id, or a promise for one while the handshake is in flight.
105
+ *
106
+ * Throws when there is neither, because no amount of waiting would produce one: no socket is open
107
+ * and none is being opened.
108
+ *
109
+ * @param signal - Abandons the wait when the caller abandons the request it is waiting to issue.
110
+ * Only the waiting path honours it; an id already in hand is returned either way, and the
111
+ * request layer aborts the call itself.
112
+ */
113
+ getConnectionId = (signal?: AbortSignal): string | Promise<string> => {
114
+ if (this.connectionId) return this.connectionId;
115
+
116
+ const pending = this.loadConnectionIdPromise;
117
+
118
+ if (!pending) {
119
+ throw new Error(
120
+ 'No connection id is available: there is no WebSocket connection, and none is being established. A request that watches a channel or subscribes to presence needs one. Call `client.connectUser()` if no user is connected, or `client.openConnection()` if the socket was closed with `client.closeConnection()`.',
121
+ );
122
+ }
123
+
124
+ if (!signal) return pending;
125
+ if (signal.aborted) return Promise.reject(abortError(signal));
126
+
127
+ return new Promise<string>((resolve, reject) => {
128
+ const onAbort = () => reject(abortError(signal));
129
+ signal.addEventListener('abort', onAbort, { once: true });
130
+ pending
131
+ .then(resolve, reject)
132
+ .finally(() => signal.removeEventListener('abort', onAbort));
133
+ });
134
+ };
135
+
136
+ private settle = () => {
137
+ this.loadConnectionIdPromise = undefined;
138
+ this.resolve = undefined;
139
+ this.reject = undefined;
140
+ };
141
+ }
142
+
143
+ /**
144
+ * The rejection an aborted wait produces, shaped like the one `fetch` and `axios` raise for the same
145
+ * signal so a caller recognises it wherever the abort landed.
146
+ */
147
+ const abortError = (signal: AbortSignal) => {
148
+ const reason: unknown = signal.reason;
149
+ if (reason instanceof Error) return reason;
150
+ const error = new Error('The wait for a connection id was aborted.');
151
+ error.name = 'AbortError';
152
+ return error;
153
+ };
@@ -0,0 +1,371 @@
1
+ import { WithSubscriptions } from '../utils/WithSubscriptions';
2
+ import { chatLoggerSystem } from '../logger';
3
+ import { runDetached } from '../utils';
4
+ import { ConfigController } from '../configuration/ConfigController';
5
+ import { deepFreezeConfig } from '../configuration/utils/deepFreezeConfig';
6
+ import type { StreamChat } from '../client';
7
+ import type { Channel } from '../channel';
8
+ import type { Thread } from '../thread';
9
+ import type { StateStore, Unsubscribe } from '@stream-io/state-store';
10
+
11
+ const logger = chatLoggerSystem.getLogger('client');
12
+
13
+ export type ConnectionRecoveryManagerConfig = {
14
+ /**
15
+ * Whether the client recovers its own state when the connection comes back.
16
+ *
17
+ * Set it to `false` only if the application recovers state itself — nothing is then re-queried or
18
+ * re-watched on reconnect, and refreshing whatever is on screen becomes the consumer's job.
19
+ * Read when a recovery actually runs, so flipping it takes effect from the next reconnect.
20
+ */
21
+ enabled: boolean;
22
+ };
23
+
24
+ export const DEFAULT_CONNECTION_RECOVERY_MANAGER_CONFIG: ConnectionRecoveryManagerConfig =
25
+ deepFreezeConfig({ enabled: true });
26
+
27
+ /**
28
+ * Owns connection recovery: after the socket comes back, brings the surfaces the app is actually
29
+ * consuming back in line with the server.
30
+ *
31
+ * Recovery is deliberately narrow — three things, and nothing else:
32
+ *
33
+ * 1. **Every loaded channel list re-runs its own first-page query** (`ChannelManager.recover`). Since
34
+ * `queryChannels` watches by default, that also re-establishes the watches for the channels on
35
+ * that page.
36
+ * 2. **Every active channel reloads itself** (`Channel.reload`), because a list page carries far fewer
37
+ * messages per channel than an open channel's loaded window, so the open channel cannot be served
38
+ * by the list query.
39
+ * 3. **Every active thread reloads its replies** (`Thread.reload`), because none of the above touches
40
+ * them: a channel reload refreshes the main message list, and `ThreadManager`'s own recovery
41
+ * refreshes the thread *list*, reusing thread instances without rehydrating them unless something
42
+ * separately marked them stale.
43
+ *
44
+ * It is explicitly **not** a sweep over the channel store (`client.channelManager.values()`). Watches
45
+ * are a bounded server resource, and after any scrolling that store holds far more channels than a query returns — so
46
+ * re-watching all of them would be both wasteful and a watch-limit hazard. Channels outside the
47
+ * refreshed pages come back demand-driven, when an event proves them relevant (see
48
+ * `restoreInterruptedWatch` in `ChannelManager`).
49
+ *
50
+ * This replaces the removed `client.recoverState()` bulk query
51
+ * (`cid: { $in: <every loaded channel> }, limit: 30`), which invented its own query shape unrelated to any
52
+ * list's filters and silently dropped everything past the thirtieth channel.
53
+ *
54
+ * ### Triggers, and why there are two
55
+ *
56
+ * One per surface, mirroring what the React Native SDK arrived at:
57
+ *
58
+ * - **Lists** — the socket's status store going online. `ChannelPaginator.executeQuery` carries its
59
+ * own first-page deferral for the unsynced case, so the list query orders itself against the
60
+ * offline sync.
61
+ * - **Active channels** — the offline DB's *sync-status edge* when offline support is enabled, and
62
+ * that same store otherwise. `Channel.reload()` has no deferral of its own, so it has to be
63
+ * triggered by something that is already post-sync.
64
+ *
65
+ * The edge is what guarantees `executePendingTasks()` → `sync()` → query ordering, on every reconnect
66
+ * path: `OfflineDBSyncManager` calls `invokeSyncStatusListeners(true)` **unconditionally** after
67
+ * `syncAndExecutePendingTasks()` on each online transition — it does not require `isSynced` to have
68
+ * been `false` first. That matters because the sync edge, unlike anything derived from a single
69
+ * transition, is guaranteed to land after the replay and the sync rather than alongside them.
70
+ *
71
+ * Recovery deliberately keeps no "did we drop?" flag of its own: `ChannelWatchStatus.WasWatching`
72
+ * already records exactly that, written from the truthful hooks
73
+ * (`StableWSConnection._setHealth(false)` and `closeConnection()`, plus
74
+ * `WSConnectionFallback._setState()` after an `enableWSFallback` switch).
75
+ *
76
+ * The status store it follows is the long-poll's once `enableWSFallback` has switched to it, so a
77
+ * long-poll reconnect recovers the same way a WebSocket reconnect does.
78
+ */
79
+ export class ConnectionRecoveryManager extends WithSubscriptions {
80
+ client: StreamChat;
81
+ /** The shared configuration machinery — see {@link ConfigController}. */
82
+ private readonly configController: ConfigController<ConnectionRecoveryManagerConfig>;
83
+ /** Set while a pass over the active channels and threads is in flight. */
84
+ private isRecovering = false;
85
+ /**
86
+ * A reconnect that arrived while a pass was already running, so the pass re-runs when it finishes.
87
+ *
88
+ * A second pass cannot start alongside the first: they would reload every active channel twice and
89
+ * race on {@link isRecovering}, the earlier one clearing it while the later is still going. Nor can
90
+ * the reconnect simply be dropped — the running pass will withhold its `connection.recovered`
91
+ * precisely because the socket moved under it, so nothing else would bring the newer connection's
92
+ * state back in line.
93
+ *
94
+ * Re-entry is not hypothetical. The trigger is a subscription to the socket's status store, and a
95
+ * reload that moves that status calls straight back into here before the first `await`.
96
+ */
97
+ private recoveryRequestedAgain = false;
98
+ /** Undone by `unregisterSubscriptions`, so re-registering does not stack listeners. */
99
+ private unsubscribeSyncStatus?: Unsubscribe;
100
+
101
+ constructor({ client }: { client: StreamChat }) {
102
+ super();
103
+ this.configController = new ConfigController<ConnectionRecoveryManagerConfig>({
104
+ defaults: DEFAULT_CONNECTION_RECOVERY_MANAGER_CONFIG,
105
+ });
106
+ this.client = client;
107
+ }
108
+
109
+ /**
110
+ * Resolved configuration, as a store — the shape every configurable class exposes
111
+ * (`configState` / `config` / `updateConfig`).
112
+ */
113
+ get configState(): StateStore<ConnectionRecoveryManagerConfig> {
114
+ return this.configController.state;
115
+ }
116
+
117
+ /** The current resolved configuration. `Readonly` — change it through {@link updateConfig}. */
118
+ public get config(): Readonly<ConnectionRecoveryManagerConfig> {
119
+ return this.configState.getLatestValue();
120
+ }
121
+
122
+ /** Merges a partial configuration into the resolved config and notifies subscribers. */
123
+ public updateConfig(config: Partial<ConnectionRecoveryManagerConfig>) {
124
+ this.configController.patch(config);
125
+ }
126
+
127
+ /**
128
+ * Rebuilds the resolved configuration from package defaults plus the declarative slice — the
129
+ * derivation entry point every configurable entity exposes, so the client routes a slice here and
130
+ * knows nothing about this manager's defaults or merge semantics.
131
+ */
132
+ public initializeConfig(config?: Partial<ConnectionRecoveryManagerConfig>) {
133
+ this.configController.initialize(config);
134
+ }
135
+
136
+ public registerSubscriptions = () => {
137
+ if (!this.hasSubscriptions) {
138
+ // Driven by the socket's own status store, and by nothing else. Recovery is about what this
139
+ // client missed while it could not reach the server, which is a fact the socket owns: the store
140
+ // is written on every transition, including the deliberate close and the two error paths that
141
+ // were always silent. The device's network is a separate signal that cannot start a recovery,
142
+ // because a device regaining a network has no reconnected socket and no fresh connection ID yet,
143
+ // so a query fired then would establish no watch.
144
+ let wasHealthy: boolean | undefined;
145
+ this.addUnsubscribeFunction(
146
+ this.client.wsConnection.state.subscribeWithSelector(
147
+ ({ isHealthy, lastUnhealthyAt }) => ({ isHealthy, lastUnhealthyAt }),
148
+ ({ isHealthy, lastUnhealthyAt }) => {
149
+ // The immediate first call is the current status rather than a change. Recovering off it
150
+ // would re-query on nothing more than someone registering subscriptions.
151
+ const previous = wasHealthy;
152
+ wasHealthy = isHealthy;
153
+ if (previous === undefined || !isHealthy) return;
154
+
155
+ // A first connect is not a recovery: nothing was loaded to fall behind, so there is
156
+ // nothing to bring back in line. `lastUnhealthyAt` is written by every drop, including
157
+ // the deliberate `closeConnection()` that mobile backgrounding uses, so every real
158
+ // reconnect still qualifies.
159
+ if (!lastUnhealthyAt) return;
160
+
161
+ // The lists always recover off this edge; their own deferral handles offline ordering.
162
+ runDetached(this.recoverChannelLists(), { context: 'recoverChannelLists' });
163
+
164
+ // Active channels recover off the offline sync-status edge whenever there is one — it is
165
+ // the only signal guaranteed to be post-replay-post-sync. Exactly ONE of these two paths
166
+ // runs per reconnect: binding the subscription is what makes the edge the driver, so the
167
+ // same call reports which path applies. Deliberately not split into a separate predicate
168
+ // — two independent reads of "is there an edge?" could disagree with each other.
169
+ const syncEdgeDrivesActiveChannels = this.ensureSyncStatusSubscription();
170
+ if (!syncEdgeDrivesActiveChannels) {
171
+ runDetached(this.recoverActiveChannels(), {
172
+ context: 'recoverActiveChannels',
173
+ });
174
+ }
175
+ },
176
+ ),
177
+ );
178
+
179
+ this.addUnsubscribeFunction(() => {
180
+ this.unsubscribeSyncStatus?.();
181
+ this.unsubscribeSyncStatus = undefined;
182
+ });
183
+ }
184
+
185
+ this.incrementRefCount();
186
+ return () => this.unregisterSubscriptions();
187
+ };
188
+
189
+ /**
190
+ * Bind to the offline DB's sync-status edge, if there is one to bind to yet.
191
+ *
192
+ * Resolved off `this.client` rather than injected: the DB is already reachable there, it is simply
193
+ * attached after this manager is constructed (and initialized later still), so the binding has to be
194
+ * deferred rather than handed in. Doing it from the status handler is safe even when this manager's
195
+ * subscription runs before the sync manager's: `OfflineDBSyncManager` awaits
196
+ * `syncAndExecutePendingTasks()` before publishing, so the edge cannot land in the same synchronous
197
+ * notification that registers us.
198
+ *
199
+ * An offline DB whose `init()` never succeeded publishes no edge, so it must not be treated as the
200
+ * trigger — hence the `initialized` check, which also means a later successful init is picked up on
201
+ * the next reconnect.
202
+ *
203
+ * @returns whether the sync-status edge is now driving active-channel recovery.
204
+ */
205
+ private ensureSyncStatusSubscription = (): boolean => {
206
+ if (this.unsubscribeSyncStatus) return true;
207
+
208
+ const { offlineDb } = this.client;
209
+ if (!offlineDb?.state.getLatestValue().initialized) return false;
210
+
211
+ const { unsubscribe } = offlineDb.syncManager.onSyncStatusChange((status) => {
212
+ // `false` is only published when going offline; there is nothing to recover then.
213
+ if (!status) return;
214
+ runDetached(this.recoverActiveChannels(), { context: 'recoverActiveChannels' });
215
+ });
216
+ this.unsubscribeSyncStatus = unsubscribe;
217
+ return true;
218
+ };
219
+
220
+ /**
221
+ * The channels this recovery reloads: the ones a consumer has declared it is currently reading.
222
+ *
223
+ * Deliberately NOT filtered on `watchStatus`. A channel opened while offline never reached
224
+ * `Watching` at all (its `watch()` threw, leaving `offlineMode`), so a `WasWatching` filter here
225
+ * would permanently strand the single most important offline case. `Channel.reload()`'s own
226
+ * `initialized || offlineMode` guard is the correct gate, and this is not a "restore a lost watch"
227
+ * decision anyway — it is "the channel being read must show the truth".
228
+ */
229
+ private get recoverableActiveChannels(): Channel[] {
230
+ return this.client.channelManager
231
+ .values()
232
+ .filter((channel) => channel.active && !channel.pendingDisposal);
233
+ }
234
+
235
+ /**
236
+ * The threads this recovery reloads: the ones a consumer has declared it is displaying.
237
+ *
238
+ * Threads need their own pass because nothing else brings an open thread's replies back — a
239
+ * channel reload refreshes the main message list, `ChannelManager.recover()` refreshes the channel
240
+ * lists*, and `ThreadManager`'s own recovery refreshes the thread *list*, reusing existing
241
+ * instances without rehydrating them unless they were separately marked stale.
242
+ *
243
+ * `active` is the filter that matters: the registry also holds every thread the list has paged
244
+ * in, which is not what should be re-fetched on a reconnect — only what someone is actually
245
+ * reading. An active thread is always registered, listed or not (`thread.activate()` registers it).
246
+ * Guarded on the owning channel the same way active channels are: a thread whose channel was
247
+ * disconnected (`disconnect()`) has nothing to recover into.
248
+ */
249
+ private get recoverableActiveThreads(): Thread[] {
250
+ const threads: Thread[] = [];
251
+ for (const thread of this.client.threads.registeredThreads) {
252
+ // Read off state rather than a getter: `Thread` has no `active` accessor the way `Channel`
253
+ // does, and adding one just for this would grow the public surface for a single internal read.
254
+ const { active } = thread.state.getLatestValue();
255
+ if (!active || thread.channel.pendingDisposal) continue;
256
+ threads.push(thread);
257
+ }
258
+ return threads;
259
+ }
260
+
261
+ /**
262
+ * An opened thread stays registered and subscribed after it closes, but a drop loses events it
263
+ * cannot replay. Flag only, no request: a listed one is rehydrated by the thread list's reload,
264
+ * and any other reloads on its next `activate()`.
265
+ */
266
+ private markInactiveThreadsStale() {
267
+ for (const thread of this.client.threads.registeredThreads) {
268
+ const { active, isStateStale } = thread.state.getLatestValue();
269
+ if (!active && !isStateStale) thread.state.partialNext({ isStateStale: true });
270
+ }
271
+ }
272
+
273
+ private recoverChannelLists = async () => {
274
+ if (!this.config.enabled) return;
275
+ await this.client.channelManager.recover();
276
+ };
277
+
278
+ private recoverActiveChannels = async ({ isRetry = false } = {}): Promise<void> => {
279
+ if (!this.config.enabled) return;
280
+
281
+ if (this.isRecovering) {
282
+ this.recoveryRequestedAgain = true;
283
+ return;
284
+ }
285
+
286
+ const channels = this.recoverableActiveChannels;
287
+ const threads = this.recoverableActiveThreads;
288
+ this.markInactiveThreadsStale();
289
+ // Captured before the reloads so a drop *during* them can be detected afterwards. The timestamp
290
+ // rather than the boolean, because a socket that drops and returns inside the recovery window has
291
+ // still failed the reloads while ending up online again.
292
+ //
293
+ // The socket alone. Every reload is a request over it, so it is the connection whose failure
294
+ // invalidates them, and its store records every transition including the deliberate close and the
295
+ // two error paths. A device that loses its network takes the socket with it and is caught here
296
+ // anyway, while a device whose network is merely unknown — every host without a reporter — would
297
+ // otherwise have no protection at all.
298
+ const socketDropBefore =
299
+ this.client.wsConnection.state.getLatestValue().lastUnhealthyAt;
300
+ this.isRecovering = true;
301
+ logger
302
+ .withExtraTags('connectionRecovery')
303
+ .info(
304
+ `Recovering ${channels.length} active channel(s) and ${threads.length} active thread(s).`,
305
+ );
306
+
307
+ // allSettled: one channel or thread failing must not stop the others. A failed refresh is not
308
+ // surfaced anywhere — the loaded window simply stays as it was until the next reconnect, or until
309
+ // a query the consumer itself issues records its own `lastQueryError` on the paginator. Channels
310
+ // and threads are independent requests, so they run together rather than in sequence.
311
+ await Promise.allSettled([
312
+ ...channels.map((channel) => channel.reload()),
313
+ ...threads.map((thread) => thread.reload()),
314
+ ]);
315
+
316
+ this.isRecovering = false;
317
+
318
+ // A reconnect landed while the reloads were in flight, so what they fetched belongs to a
319
+ // connection that is gone. Run once more against the current one: the check below withholds the
320
+ // event for the same reason, and this is what stops that withholding from stranding.
321
+ //
322
+ // Once, not until it settles. A reload that keeps moving the socket would otherwise recur without
323
+ // bound, and a connection still flapping after two passes is not one more query away from being
324
+ // caught up. The next up-edge starts a fresh pass anyway, because this one has finished by then.
325
+ const retryAfterReconnect = this.recoveryRequestedAgain && !isRetry;
326
+ this.recoveryRequestedAgain = false;
327
+ if (retryAfterReconnect) return await this.recoverActiveChannels({ isRetry: true });
328
+
329
+ // `allSettled` above means a drop mid-recovery can fail every single reload while this still
330
+ // reaches the end. Dispatching then would tell consumers that what is on screen is fresh when
331
+ // none of it was refreshed — and the UI SDKs' mark-read-on-catch-up keys off this event, so it
332
+ // would mark messages read that were never fetched.
333
+ //
334
+ // Withholding is safe rather than stranding: a drop guarantees a later reconnect, and that
335
+ // recovery dispatches the event.
336
+ const socket = this.client.wsConnection.state.getLatestValue();
337
+
338
+ if (socket.lastUnhealthyAt !== socketDropBefore || !socket.isHealthy) {
339
+ logger
340
+ .withExtraTags('connectionRecovery')
341
+ .info(
342
+ 'Recovery finished but the socket dropped while it ran; withholding connection.recovered.',
343
+ );
344
+ return;
345
+ }
346
+
347
+ // `connection.recovered` means "recovery finished". Dispatched from here so it fires on EVERY
348
+ // reconnect path — the removed `recoverState()` was only ever called on an automatic
349
+ // reconnect (`StableWSConnection._reconnect()`, or v9's long-poll `connect(true)`), so a
350
+ // `closeConnection()` → `openConnection()` cycle (mobile backgrounding) never produced it.
351
+ // Consumers keying post-recovery work off this event — the UI SDKs' mark-read-on-catch-up
352
+ // among them — need it after the reload above, not before.
353
+ this.client.dispatchEvent({ type: 'connection.recovered' });
354
+ };
355
+
356
+ /**
357
+ * Run a full recovery now, without waiting for a connection event.
358
+ *
359
+ * A no-op while one is already running: {@link recoverActiveChannels} defers the request to the
360
+ * end of the pass in flight rather than stacking a second one alongside it.
361
+ */
362
+ public recover = async () => {
363
+ if (this.isRecovering) {
364
+ logger
365
+ .withExtraTags('connectionRecovery')
366
+ .debug('A recovery is already in flight.');
367
+ return;
368
+ }
369
+ await Promise.allSettled([this.recoverChannelLists(), this.recoverActiveChannels()]);
370
+ };
371
+ }