stream-chat 10.0.0-rc.8 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +22095 -22290
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +22143 -22298
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +22093 -22288
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +216 -135
  9. package/dist/types/CooldownTimer.d.ts +16 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +25 -47
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +435 -500
  14. package/dist/types/channel_state.d.ts +72 -112
  15. package/dist/types/client.d.ts +323 -440
  16. package/dist/types/client_state.d.ts +1 -3
  17. package/dist/types/configuration/ConfigController.d.ts +31 -125
  18. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
  19. package/dist/types/configuration/keys.d.ts +5 -19
  20. package/dist/types/configuration/shape.d.ts +12 -29
  21. package/dist/types/configuration/types.d.ts +64 -79
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  26. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  27. package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
  28. package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
  29. package/dist/types/connection/index.d.ts +4 -0
  30. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
  31. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  32. package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
  33. package/dist/types/connection/networkConnection/types.d.ts +40 -0
  34. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
  35. package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
  36. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
  37. package/dist/types/connection/wsConnection/config.d.ts +31 -0
  38. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  39. package/dist/types/connection/wsConnection/types.d.ts +46 -0
  40. package/dist/types/constants.d.ts +3 -1
  41. package/dist/types/custom_types.d.ts +0 -2
  42. package/dist/types/entityStore/EntityStore.d.ts +226 -65
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +16 -19
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
  48. package/dist/types/gen/chat/ChatApi.d.ts +149 -105
  49. package/dist/types/gen/models/index.d.ts +2540 -698
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +37 -14
  52. package/dist/types/index.d.ts +10 -5
  53. package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
  54. package/dist/types/logger.d.ts +1 -3
  55. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  56. package/dist/types/messageComposer/LocationComposer.d.ts +8 -2
  57. package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
  58. package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
  59. package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
  60. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  61. package/dist/types/messageComposer/configuration/types.d.ts +38 -50
  62. package/dist/types/messageComposer/index.d.ts +1 -0
  63. package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
  64. package/dist/types/messageComposer/messageComposer.d.ts +60 -123
  65. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
  66. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
  67. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  68. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
  69. package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  71. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  72. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  73. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  74. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
  75. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +20 -19
  76. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  77. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  78. package/dist/types/messageComposer/pollComposer.d.ts +15 -5
  79. package/dist/types/messageComposer/textComposer.d.ts +14 -7
  80. package/dist/types/messageComposer/types.d.ts +27 -7
  81. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
  82. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +43 -73
  83. package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
  84. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
  85. package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
  86. package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
  87. package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
  88. package/dist/types/messageOperations/index.d.ts +6 -4
  89. package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
  90. package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
  91. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
  92. package/dist/types/messageOperations/types.d.ts +43 -14
  93. package/dist/types/middleware.d.ts +10 -0
  94. package/dist/types/moderation.d.ts +21 -14
  95. package/dist/types/notifications/NotificationManager.d.ts +10 -23
  96. package/dist/types/notifications/types.d.ts +21 -57
  97. package/dist/types/offline-support/offline_support_api.d.ts +150 -528
  98. package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
  99. package/dist/types/offline-support/queueableOperations.d.ts +35 -37
  100. package/dist/types/offline-support/types.d.ts +40 -185
  101. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  102. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  103. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  104. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
  105. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
  106. package/dist/types/pagination/index.d.ts +1 -0
  107. package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
  108. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
  109. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -327
  110. package/dist/types/pagination/paginators/MessagePaginator.d.ts +237 -131
  111. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
  112. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
  113. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
  114. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
  115. package/dist/types/pagination/paginators/index.d.ts +1 -0
  116. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  117. package/dist/types/pagination/utility.normalization.d.ts +8 -13
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +35 -8
  120. package/dist/types/poll_manager.d.ts +12 -2
  121. package/dist/types/poll_optimistic_votes.d.ts +57 -0
  122. package/dist/types/reminders/Reminder.d.ts +17 -7
  123. package/dist/types/reminders/ReminderManager.d.ts +13 -25
  124. package/dist/types/search/BaseSearchSource.d.ts +10 -8
  125. package/dist/types/search/ChannelSearchSource.d.ts +16 -0
  126. package/dist/types/search/MessageSearchSource.d.ts +17 -0
  127. package/dist/types/search/SearchController.d.ts +26 -28
  128. package/dist/types/search/types.d.ts +6 -10
  129. package/dist/types/signing.d.ts +12 -3
  130. package/dist/types/thread.d.ts +67 -129
  131. package/dist/types/thread_manager.d.ts +95 -66
  132. package/dist/types/token_manager.d.ts +8 -13
  133. package/dist/types/types.d.ts +81 -197
  134. package/dist/types/types.utility.d.ts +3 -3
  135. package/dist/types/upload-utils.d.ts +5 -10
  136. package/dist/types/uploadManager.d.ts +31 -11
  137. package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
  138. package/dist/types/utils/WithSubscriptions.d.ts +6 -16
  139. package/dist/types/utils/abort.d.ts +17 -0
  140. package/dist/types/utils/concurrency.d.ts +12 -20
  141. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  142. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  143. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  144. package/dist/types/utils/objectPath.d.ts +6 -41
  145. package/dist/types/utils/retryable.d.ts +8 -12
  146. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  147. package/dist/types/utils/time.d.ts +45 -0
  148. package/dist/types/utils.d.ts +74 -93
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +46 -59
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +99 -91
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1098 -1351
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +81 -174
  159. package/src/client.ts +755 -970
  160. package/src/client_state.ts +3 -8
  161. package/src/configuration/ConfigController.ts +42 -158
  162. package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
  163. package/src/configuration/index.ts +1 -1
  164. package/src/configuration/keys.ts +13 -32
  165. package/src/configuration/shape.ts +169 -59
  166. package/src/configuration/types.ts +69 -92
  167. package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
  168. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  169. package/src/configuration/utils/declarativeSlices.ts +9 -39
  170. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  171. package/src/configuration/utils/index.ts +2 -4
  172. package/src/configuration/utils/serverAuthority.ts +20 -68
  173. package/src/connection/ConnectionIdManager.ts +111 -0
  174. package/src/connection/ConnectionRecoveryManager.ts +257 -0
  175. package/src/connection/index.ts +4 -0
  176. package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
  177. package/src/connection/networkConnection/index.ts +3 -0
  178. package/src/connection/networkConnection/reporters.ts +58 -0
  179. package/src/connection/networkConnection/types.ts +45 -0
  180. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -231
  181. package/src/connection/wsConnection/WSConnection.ts +270 -0
  182. package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
  183. package/src/connection/wsConnection/config.ts +73 -0
  184. package/src/connection/wsConnection/index.ts +4 -0
  185. package/src/connection/wsConnection/types.ts +48 -0
  186. package/src/constants.ts +7 -5
  187. package/src/custom_types.ts +0 -1
  188. package/src/entityStore/EntityStore.ts +415 -79
  189. package/src/entityStore/StoreBackedItemIndex.ts +37 -41
  190. package/src/entityStore/index.ts +0 -1
  191. package/src/errors.ts +39 -20
  192. package/src/formatMessageMemo.ts +17 -0
  193. package/src/gen/chat/ChannelApi.ts +122 -36
  194. package/src/gen/chat/ChatApi.ts +578 -1752
  195. package/src/gen/models/index.ts +2566 -3440
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +183 -406
  198. package/src/index.ts +32 -10
  199. package/src/languageNames.ts +88 -0
  200. package/src/logger.ts +1 -3
  201. package/src/messageComposer/CustomDataManager.ts +19 -6
  202. package/src/messageComposer/LocationComposer.ts +49 -9
  203. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  204. package/src/messageComposer/attachmentIdentity.ts +54 -0
  205. package/src/messageComposer/attachmentManager.ts +170 -185
  206. package/src/messageComposer/attachmentUtils.ts +44 -0
  207. package/src/messageComposer/configuration/configuration.ts +15 -8
  208. package/src/messageComposer/configuration/types.ts +38 -50
  209. package/src/messageComposer/fileUtils.ts +1 -1
  210. package/src/messageComposer/index.ts +1 -0
  211. package/src/messageComposer/linkPreviewsManager.ts +18 -21
  212. package/src/messageComposer/messageComposer.ts +234 -179
  213. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  214. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
  215. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
  216. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
  217. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  218. package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
  219. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  220. package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
  221. package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
  222. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
  223. package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
  224. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  225. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  226. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  227. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  228. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  229. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  230. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  231. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  232. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  233. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  234. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  235. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  236. package/src/messageComposer/pollComposer.ts +21 -9
  237. package/src/messageComposer/textComposer.ts +37 -57
  238. package/src/messageComposer/types.ts +39 -11
  239. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -124
  240. package/src/messageDelivery/MessageReceiptsTracker.ts +122 -139
  241. package/src/messageOperations/FailedSendCache.ts +85 -0
  242. package/src/messageOperations/MessageOperationStatePolicy.ts +124 -116
  243. package/src/messageOperations/MessageOperations.ts +297 -175
  244. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +13 -25
  245. package/src/messageOperations/createMessageOperations.ts +176 -0
  246. package/src/messageOperations/index.ts +6 -14
  247. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  248. package/src/messageOperations/sendOrdering.ts +25 -0
  249. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  250. package/src/messageOperations/types.ts +51 -13
  251. package/src/middleware.ts +13 -5
  252. package/src/moderation.ts +25 -21
  253. package/src/notifications/NotificationManager.ts +19 -28
  254. package/src/notifications/types.ts +21 -57
  255. package/src/offline-support/offline_support_api.ts +231 -681
  256. package/src/offline-support/offline_sync_manager.ts +51 -90
  257. package/src/offline-support/queueableOperations.ts +98 -73
  258. package/src/offline-support/types.ts +43 -185
  259. package/src/pagination/FilterBuilder.ts +1 -22
  260. package/src/pagination/ItemIndex.ts +4 -12
  261. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  262. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +17 -62
  263. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  264. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  265. package/src/pagination/filterCompiler.ts +11 -25
  266. package/src/pagination/index.ts +1 -0
  267. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  268. package/src/pagination/paginators/ChannelPaginator.ts +481 -219
  269. package/src/pagination/paginators/MessageIntervalPaginator.ts +1362 -775
  270. package/src/pagination/paginators/MessagePaginator.ts +521 -240
  271. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  272. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  273. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  274. package/src/pagination/paginators/UserGroupPaginator.ts +18 -15
  275. package/src/pagination/paginators/index.ts +1 -0
  276. package/src/pagination/paginators/stateThrottling.ts +5 -10
  277. package/src/pagination/sortCompiler.ts +23 -50
  278. package/src/pagination/utility.normalization.ts +17 -24
  279. package/src/pagination/utility.search.ts +4 -11
  280. package/src/poll.ts +183 -102
  281. package/src/poll_manager.ts +24 -22
  282. package/src/poll_optimistic_votes.ts +335 -0
  283. package/src/reminders/Reminder.ts +33 -16
  284. package/src/reminders/ReminderManager.ts +23 -56
  285. package/src/reminders/ReminderTimer.ts +6 -6
  286. package/src/search/BaseSearchSource.ts +19 -25
  287. package/src/search/ChannelSearchSource.ts +43 -1
  288. package/src/search/MessageSearchSource.ts +77 -13
  289. package/src/search/SearchController.ts +39 -36
  290. package/src/search/types.ts +6 -10
  291. package/src/segment.ts +1 -1
  292. package/src/signing.ts +23 -3
  293. package/src/thread.ts +430 -712
  294. package/src/thread_manager.ts +300 -234
  295. package/src/token_manager.ts +12 -22
  296. package/src/types.ts +102 -214
  297. package/src/types.utility.ts +3 -3
  298. package/src/upload-utils.ts +5 -10
  299. package/src/uploadManager.ts +64 -18
  300. package/src/utils/FixedSizeQueueCache.ts +18 -21
  301. package/src/utils/WithSubscriptions.ts +6 -16
  302. package/src/utils/abort.ts +45 -0
  303. package/src/utils/concurrency.ts +16 -55
  304. package/src/utils/mergeWith/mergeWith.ts +10 -13
  305. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  306. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  307. package/src/utils/objectPath.ts +6 -41
  308. package/src/utils/retryable.ts +10 -14
  309. package/src/utils/throttling/throttle.ts +9 -25
  310. package/src/utils/time.ts +64 -0
  311. package/src/utils.ts +227 -174
  312. package/codegen/i18n/callSites.ts +0 -126
  313. package/codegen/i18n/generate.ts +0 -226
  314. package/codegen/i18n/guards.ts +0 -178
  315. package/codegen/i18n/index.ts +0 -29
  316. package/codegen/i18n/stringMaps.ts +0 -91
  317. package/codegen/i18n/types.ts +0 -100
  318. package/dist/cjs/i18n.browser.js +0 -1131
  319. package/dist/cjs/i18n.browser.js.map +0 -7
  320. package/dist/cjs/i18n.node.js +0 -1160
  321. package/dist/cjs/i18n.node.js.map +0 -7
  322. package/dist/esm/i18n-codegen.mjs +0 -409
  323. package/dist/esm/i18n-codegen.mjs.map +0 -7
  324. package/dist/esm/i18n.mjs +0 -1098
  325. package/dist/esm/i18n.mjs.map +0 -7
  326. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  327. package/dist/types/connection.d.ts +0 -139
  328. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -26
  329. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  330. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  331. package/dist/types/i18n/Streami18n.d.ts +0 -168
  332. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  333. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  334. package/dist/types/i18n/dayjs.d.ts +0 -104
  335. package/dist/types/i18n/formatters.d.ts +0 -91
  336. package/dist/types/i18n/index.d.ts +0 -15
  337. package/dist/types/i18n/translator.d.ts +0 -29
  338. package/dist/types/i18n/types.d.ts +0 -262
  339. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  340. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  341. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  342. package/dist/types/i18n-codegen/index.d.ts +0 -29
  343. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  344. package/dist/types/i18n-codegen/types.d.ts +0 -94
  345. package/dist/types/insights.d.ts +0 -56
  346. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  347. package/dist/types/messageOperations/persistence.d.ts +0 -21
  348. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  349. package/dist/types/store.d.ts +0 -125
  350. package/src/ConnectionRecoveryManager.ts +0 -293
  351. package/src/gen/model-decoders/decoders.ts +0 -2710
  352. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  353. package/src/i18n/Streami18n.ts +0 -520
  354. package/src/i18n/TranslationBuilder.ts +0 -176
  355. package/src/i18n/TranslationStore.ts +0 -96
  356. package/src/i18n/dayjs.ts +0 -228
  357. package/src/i18n/formatters.ts +0 -461
  358. package/src/i18n/index.ts +0 -15
  359. package/src/i18n/languageNames.ts +0 -103
  360. package/src/i18n/translator.ts +0 -76
  361. package/src/i18n/types.ts +0 -375
  362. package/src/insights.ts +0 -82
  363. package/src/messageOperations/optimistic.ts +0 -249
  364. package/src/messageOperations/persistence.ts +0 -40
  365. package/src/pagination/utility.queryChannel.ts +0 -84
  366. package/src/store.ts +0 -304
@@ -1,17 +1,22 @@
1
1
  import { chatLoggerSystem } from './logger';
2
2
  import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
3
- import { StateStore } from './store';
3
+ import { StateStore, type Unsubscribe } from '@stream-io/state-store';
4
4
  import { ConfigController } from './configuration/ConfigController';
5
5
  import { throttle } from './utils';
6
+ import { EntityStore, type EntityStoreSubscriber } from './entityStore/EntityStore';
7
+ import { ThreadPaginator } from './pagination/paginators/ThreadPaginator';
6
8
 
9
+ import type { Channel } from './channel';
7
10
  import type { StreamChat } from './client';
8
- import type { Thread } from './thread';
11
+ import { ensureThreadChannel, Thread } from './thread';
9
12
  import type {
10
13
  Event,
11
14
  EventPayload,
12
15
  EventType,
16
+ LocalMessage,
17
+ MessageResponse,
13
18
  OwnUserResponse,
14
- QueryThreadsRequest,
19
+ ThreadStateResponse,
15
20
  } from './types';
16
21
  import { WithSubscriptions } from './utils/WithSubscriptions';
17
22
 
@@ -22,10 +27,8 @@ const eventCarriesOwnUser = (
22
27
 
23
28
  export type ThreadManagerConfig = {
24
29
  /**
25
- * Minimum gap between thread-list reloads triggered by connection recovery (defaults to 1000ms).
26
- *
27
- * Read when subscriptions are registered, since the throttle captures the interval in a closure — a
28
- * change applies from the next `registerSubscriptions()`, not retroactively.
30
+ * Minimum gap between thread-list reloads triggered by connection recovery, in milliseconds.
31
+ * Defaults to 1000. Read in `registerSubscriptions()`, so a change applies from the next call.
29
32
  */
30
33
  connectionRecoveryThrottleMs: number;
31
34
  };
@@ -33,69 +36,54 @@ export type ThreadManagerConfig = {
33
36
  export const DEFAULT_THREAD_MANAGER_CONFIG: ThreadManagerConfig = deepFreezeConfig({
34
37
  connectionRecoveryThrottleMs: 1000,
35
38
  });
36
- const MAX_QUERY_THREADS_LIMIT = 25;
37
- export const THREAD_MANAGER_INITIAL_STATE = {
38
- active: false,
39
- wasActivatedAtLeastOnce: false,
40
- isThreadOrderStale: false,
41
- threads: [],
42
- unreadThreadCount: 0,
43
- unseenThreadIds: [],
44
- lastConnectionDropAt: null,
45
- pagination: {
46
- isLoading: false,
47
- isLoadingNext: false,
48
- nextCursor: null,
49
- },
50
- ready: false,
51
- };
52
39
 
40
+ /** Manager-level state. The list itself lives on {@link ThreadManager.paginator}. */
53
41
  export type ThreadManagerState = {
54
42
  active: boolean;
55
- /**
56
- * Whether the thread manager has been activated at least once in the current
57
- * session (i.e. `activate()` was called). Used to avoid requerying threads
58
- * on connection recovery for consumers that never actually activate the manager.
59
- */
43
+ /** Whether `activate()` was called this session. Recovery skips the reload when it never was. */
60
44
  wasActivatedAtLeastOnce: boolean;
45
+ /** A listed thread got a reply since the latest reload, so the list order may be out of date. */
61
46
  isThreadOrderStale: boolean;
62
- lastConnectionDropAt: Date | null;
63
- pagination: ThreadManagerPagination;
64
- ready: boolean;
65
- threads: Thread[];
66
47
  unreadThreadCount: number;
67
- /**
68
- * List of threads that haven't been loaded in the list, but have received new messages
69
- * since the latest reload. Useful to display a banner prompting to reload the thread list.
70
- */
48
+ /** Threads not in the list that got new messages since the latest reload (for a banner). */
71
49
  unseenThreadIds: string[];
72
50
  };
73
51
 
74
- export type ThreadManagerPagination = {
75
- isLoading: boolean;
76
- isLoadingNext: boolean;
77
- nextCursor: string | null;
52
+ export const THREAD_MANAGER_INITIAL_STATE: ThreadManagerState = {
53
+ active: false,
54
+ isThreadOrderStale: false,
55
+ unreadThreadCount: 0,
56
+ unseenThreadIds: [],
57
+ wasActivatedAtLeastOnce: false,
78
58
  };
79
59
 
80
60
  const logger = chatLoggerSystem.getLogger('thread-manager');
81
61
 
62
+ const getThreadId = (thread: Thread) => thread.id;
63
+
64
+ /** `threadStore` holder for a thread opened this session (`register()`, from `thread.activate()`). */
65
+ const REGISTERED_HOLDER: EntityStoreSubscriber = { onEntitiesChanged: () => undefined };
66
+
82
67
  export class ThreadManager extends WithSubscriptions {
83
68
  public readonly state: StateStore<ThreadManagerState>;
69
+ /** The thread list, in server order. */
70
+ public readonly paginator: ThreadPaginator;
84
71
  private client: StreamChat;
85
- private threadsByIdGetterCache: {
86
- threads: ThreadManagerState['threads'];
87
- threadsById: Record<string, Thread | undefined>;
88
- };
89
- // cache used in combination with threadsById
90
- // used for threads which are not stored in the list
91
- // private threadCache: Record<string, Thread | undefined> = {};
92
-
93
- /** The shared configuration machinery — see {@link ConfigController}. */
94
- private readonly configController: ConfigController<ThreadManagerConfig>;
95
72
  /**
96
- * Resolved configuration, as a store — the shape every configurable class exposes
97
- * (`configState` / `config` / `updateConfig`).
73
+ * Every live thread, held by the list and/or `REGISTERED_HOLDER` (opened this session). A thread
74
+ * leaves once neither holds it.
98
75
  */
76
+ private readonly threadStore = new EntityStore<Thread>({ getEntityId: getThreadId });
77
+ /** A reload is in flight; a second one is dropped. */
78
+ private isReloadInFlight = false;
79
+ /**
80
+ * A local `pendingDisposal` listener per channel with a listed or opened thread, removed when the
81
+ * channel is disposed or on reset.
82
+ */
83
+ private readonly disposalListeners = new Map<Channel, Unsubscribe>();
84
+
85
+ private readonly configController: ConfigController<ThreadManagerConfig>;
86
+
99
87
  get configState(): StateStore<ThreadManagerConfig> {
100
88
  return this.configController.state;
101
89
  }
@@ -108,60 +96,175 @@ export class ThreadManager extends WithSubscriptions {
108
96
  });
109
97
  this.client = client;
110
98
  this.state = new StateStore<ThreadManagerState>(THREAD_MANAGER_INITIAL_STATE);
111
-
112
- this.threadsByIdGetterCache = { threads: [], threadsById: {} };
99
+ this.paginator = new ThreadPaginator({ client, store: this.threadStore });
100
+ // A listed or opened thread keeps its channel.
101
+ client.channelManager.channelStore.addClaim({
102
+ heldBy: () => this.registeredThreads.map((thread) => thread.channel),
103
+ name: 'threads',
104
+ });
105
+ // Every listed thread gets its channel's disposal listener, independent of
106
+ // `registerSubscriptions()`.
107
+ this.paginator.state.subscribeWithSelector(
108
+ ({ items }) => ({ items }),
109
+ ({ items }) => items?.forEach(this.listenForDisposal),
110
+ );
113
111
  }
114
112
 
115
- /** The current resolved configuration. `Readonly` — change it through {@link updateConfig}. */
116
113
  public get config(): Readonly<ThreadManagerConfig> {
117
114
  return this.configState.getLatestValue();
118
115
  }
119
116
 
120
- /** Merges a partial configuration into the resolved config and notifies subscribers. */
117
+ /**
118
+ * Merges a partial configuration into the resolved config.
119
+ *
120
+ * @param config - The fields to change.
121
+ */
121
122
  public updateConfig(config: Partial<ThreadManagerConfig>) {
122
123
  this.configController.patch(config);
123
124
  }
124
125
 
125
126
  /**
126
- * Rebuilds the resolved configuration from package defaults plus the declarative slice.
127
- *
128
- * The derivation entry point every configurable entity exposes, so the owner routes a slice here and
129
- * knows nothing about ThreadManager's defaults or merge semantics. This logic used to live in the owner,
130
- * which is how `reset()` became a no-op for the client key (F4) and how a registered
131
- * `notifications.sortComparator` became unremovable (G8) — an owner writing another object's
132
- * derivation gets that object's rules wrong sooner or later.
127
+ * Re-derives the configuration from the declarative slice.
133
128
  *
134
- * Routed through {@link updateConfig} rather than replacing the store, which is exact here because
135
- * every field of `ThreadManagerConfig` is required and present in the defaults, so a patch naming all of
136
- * them amounts to a replacement. `NotificationManager` cannot do this — its `sortComparator` is
137
- * optional with no default, so a patch can never remove one — which is why it replaces outright.
129
+ * @param config - The declarative slice (optional).
138
130
  */
139
131
  public initializeConfig(config?: Partial<ThreadManagerConfig>) {
140
132
  this.configController.initialize(config);
141
133
  }
142
134
 
143
- public get threadsById() {
144
- const { threads } = this.state.getLatestValue();
135
+ /**
136
+ * The live thread for `id`: one in the list, or one opened this session. `paginator.items` holds
137
+ * the list only; list membership is `paginator.getItem(id)`.
138
+ */
139
+ public get = (id: string): Thread | undefined => this.threadStore.get(id);
145
140
 
146
- if (threads === this.threadsByIdGetterCache.threads) {
147
- return this.threadsByIdGetterCache.threadsById;
141
+ /**
142
+ * Returns the thread for `parentMessage`, creating and registering it if needed. Use it instead
143
+ * of `new Thread()`: the thread list reuses this instance if it later loads the same thread. A
144
+ * created thread starts stale and loads its data when first opened, unless the parent has no
145
+ * replies in a watched channel (nothing to load: `getThread` would 404, the first reply arrives
146
+ * as an event). In an unwatched channel the parent's `reply_count` may miss newer replies, so it
147
+ * always loads.
148
+ *
149
+ * @param params.channel - The channel of the parent message.
150
+ * @param params.parentMessage - The thread's parent message.
151
+ * @returns The registered thread.
152
+ */
153
+ public ensure = ({
154
+ channel,
155
+ parentMessage,
156
+ }: {
157
+ channel: Channel;
158
+ parentMessage: LocalMessage | MessageResponse;
159
+ }): Thread => {
160
+ let thread = this.threadStore.get(parentMessage.id);
161
+ if (!thread) {
162
+ thread = new Thread({ channel, client: this.client, parentMessage });
148
163
  }
164
+ this.register(thread);
165
+ return thread;
166
+ };
149
167
 
150
- const threadsById = threads.reduce<Record<string, Thread>>(
151
- (newThreadsById, thread) => {
152
- newThreadsById[thread.id] = thread;
153
- return newThreadsById;
154
- },
155
- {},
156
- );
157
-
158
- this.threadsByIdGetterCache.threads = threads;
159
- this.threadsByIdGetterCache.threadsById = threadsById;
168
+ /**
169
+ * The registered thread, or a new one when none is registered. Only a stale thread nobody has
170
+ * open is hydrated from `threadData`: an open one reloads itself, and events keep any other
171
+ * current (an answer that was in flight would roll them back). The channel's members and custom
172
+ * data are applied either way, as the constructor does for a new thread.
173
+ *
174
+ * @internal
175
+ */
176
+ public resolveQueried = (threadData: ThreadStateResponse): Thread => {
177
+ const registered = this.threadStore.get(threadData.parent_message_id);
178
+ if (!registered) return new Thread({ client: this.client, threadData });
179
+
180
+ const { active, isStateStale } = registered.state.getLatestValue();
181
+ if (isStateStale && !active) registered.hydrateState(threadData);
182
+ else ensureThreadChannel(this.client, threadData);
183
+ return registered;
184
+ };
160
185
 
161
- return threadsById;
186
+ /**
187
+ * Every registered thread: the list's plus the opened ones.
188
+ *
189
+ * @internal
190
+ */
191
+ public get registeredThreads(): Thread[] {
192
+ return this.threadStore.values();
162
193
  }
163
194
 
195
+ /**
196
+ * Keeps `thread` for the session: resolvable through {@link ThreadManager.get} and subscribed
197
+ * whether or not the list holds it, until its channel is disposed or the user disconnects.
198
+ *
199
+ * @internal
200
+ */
201
+ public register = (thread: Thread) => {
202
+ const { id } = thread;
203
+ const registered = this.threadStore.get(id);
204
+ if (registered && registered !== thread) {
205
+ logger
206
+ .withExtraTags('register')
207
+ .warn(
208
+ 'Another instance of this thread is registered; this one stays unmanaged.',
209
+ {
210
+ threadId: id,
211
+ },
212
+ );
213
+ return;
214
+ }
215
+
216
+ this.threadStore.link(id, REGISTERED_HOLDER);
217
+ this.threadStore.upsert(thread, REGISTERED_HOLDER);
218
+ if (this.hasSubscriptions) thread.registerSubscriptions();
219
+ this.listenForDisposal(thread);
220
+ };
221
+
222
+ /** Releases the `REGISTERED_HOLDER` hold, and unsubscribes the thread unless listed. */
223
+ private release = (thread: Thread) => {
224
+ this.threadStore.unlink(thread.id, REGISTERED_HOLDER);
225
+ if (this.hasSubscriptions && !this.paginator.items?.includes(thread)) {
226
+ thread.unregisterSubscriptions();
227
+ }
228
+ };
229
+
230
+ /** Listens for its channel's disposal the first time a thread on that channel is seen. */
231
+ private listenForDisposal = (thread: Thread) => {
232
+ const { channel } = thread;
233
+ if (this.disposalListeners.has(channel)) return;
234
+ if (channel.pendingDisposal) {
235
+ this.releaseThreadsOfChannel(channel);
236
+ return;
237
+ }
238
+ this.disposalListeners.set(
239
+ channel,
240
+ channel.state.subscribeWithSelector(
241
+ ({ pendingDisposal }) => ({ pendingDisposal }),
242
+ ({ pendingDisposal }) => {
243
+ if (pendingDisposal) this.releaseThreadsOfChannel(channel);
244
+ },
245
+ ),
246
+ );
247
+ };
248
+
249
+ /** The channel was disposed, so its threads are unusable: release every one of them. */
250
+ private releaseThreadsOfChannel = (channel: Channel) => {
251
+ this.disposalListeners.get(channel)?.();
252
+ this.disposalListeners.delete(channel);
253
+ const onChannel = (thread: Thread) => thread.channel === channel;
254
+ this.threadStore.values().filter(onChannel).forEach(this.release);
255
+ const listed = (this.paginator.items ?? []).filter(onChannel);
256
+ if (!listed.length) return;
257
+ this.paginator.batch(
258
+ () => listed.forEach(({ id }) => this.paginator.removeItem({ id })),
259
+ { coalesce: true },
260
+ );
261
+ };
262
+
164
263
  public resetState = () => {
264
+ this.threadStore.values().forEach(this.release);
265
+ this.paginator.resetState();
266
+ this.disposalListeners.forEach((unsubscribe) => unsubscribe());
267
+ this.disposalListeners.clear();
165
268
  this.state.next(THREAD_MANAGER_INITIAL_STATE);
166
269
  };
167
270
 
@@ -180,12 +283,78 @@ export class ThreadManager extends WithSubscriptions {
180
283
  this.addUnsubscribeFunction(this.subscribeManageThreadSubscriptions());
181
284
  this.addUnsubscribeFunction(this.subscribeReloadOnActivation());
182
285
  this.addUnsubscribeFunction(this.subscribeNewReplies());
183
- this.addUnsubscribeFunction(this.subscribeRecoverAfterConnectionDrop());
184
- this.addUnsubscribeFunction(this.subscribeChannelDeleted());
286
+ this.addUnsubscribeFunction(this.subscribeReloadOnConnectionRecovered());
287
+ this.addUnsubscribeFunction(this.subscribeThreadEvents());
288
+ // The list's threads are registered by `subscribeManageThreadSubscriptions`; this covers the
289
+ // opened ones it does not hold.
290
+ this.threadStore.values().forEach((thread) => thread.registerSubscriptions());
291
+ };
292
+
293
+ /**
294
+ * Routes client events to the threads in the store by ID. A message event reaches the thread the
295
+ * message replies in and the thread it starts; quoted-message updates stay within the reply's own
296
+ * thread. A thread follows its channel's `watchStatus` itself.
297
+ */
298
+ private subscribeThreadEvents = () => {
299
+ const threadsOf = (message?: { id: string; parent_id?: string }) =>
300
+ message
301
+ ? [
302
+ message.parent_id ? this.get(message.parent_id) : undefined,
303
+ this.get(message.id),
304
+ ]
305
+ : [];
306
+
307
+ const unsubscribeFunctions = [
308
+ this.client.on('message.new', (event) => {
309
+ if (event.message?.parent_id)
310
+ this.get(event.message.parent_id)?.handleNewReply(event);
311
+ }),
312
+ this.client.on('message.read', (event) => {
313
+ if (event.thread)
314
+ this.get(event.thread.parent_message_id)?.handleRepliesRead(event);
315
+ }),
316
+ this.client.on('notification.mark_unread', (event) => {
317
+ if (event.thread_id) this.get(event.thread_id)?.handleRepliesUnread(event);
318
+ }),
319
+ this.client.on('thread.updated', (event) => {
320
+ if (event.thread)
321
+ this.get(event.thread.parent_message_id)?.handleThreadUpdated(event);
322
+ }),
323
+ this.client.on('message.deleted', (event) =>
324
+ threadsOf(event.message).forEach((thread) => thread?.handleMessageDeleted(event)),
325
+ ),
326
+ ...(['message.updated', 'message.undeleted'] as const).map((eventType) =>
327
+ this.client.on(eventType, (event) =>
328
+ threadsOf(event.message).forEach((thread) =>
329
+ thread?.handleMessageUpdated(event),
330
+ ),
331
+ ),
332
+ ),
333
+ ...(['reaction.new', 'reaction.deleted', 'reaction.updated'] as const).map(
334
+ (eventType) =>
335
+ this.client.on(eventType, (event) =>
336
+ threadsOf(event.message).forEach((thread) =>
337
+ thread?.handleReactionChanged(event),
338
+ ),
339
+ ),
340
+ ),
341
+ // A user's replies can be in any thread, so the user events are the exception.
342
+ ...(['user.messages.deleted', 'user.deleted'] as const).map((eventType) =>
343
+ this.client.on(eventType, (event) =>
344
+ this.threadStore
345
+ .values()
346
+ .forEach((thread) => thread.handleUserMessagesDeleted(event)),
347
+ ),
348
+ ),
349
+ this.client.on('user.updated', (event) =>
350
+ this.threadStore.values().forEach((thread) => thread.handleUserUpdated(event)),
351
+ ),
352
+ ].map(({ unsubscribe }) => unsubscribe);
353
+
354
+ return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
185
355
  };
186
356
 
187
357
  private subscribeUnreadThreadsCountChange = () => {
188
- // initiate
189
358
  const { unread_threads: unreadThreadCount = 0 } =
190
359
  (this.client.user as OwnUserResponse) ?? {};
191
360
  this.state.partialNext({ unreadThreadCount });
@@ -215,24 +384,18 @@ export class ThreadManager extends WithSubscriptions {
215
384
  return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
216
385
  };
217
386
 
218
- private subscribeChannelDeleted = () =>
219
- this.client.on('notification.channel_deleted', (event) => {
220
- const { cid } = event;
221
- const { threads } = this.state.getLatestValue();
222
-
223
- const newThreads = threads.filter((thread) => thread.channel.cid !== cid);
224
- this.state.partialNext({ threads: newThreads });
225
- }).unsubscribe;
226
-
227
387
  private subscribeManageThreadSubscriptions = () =>
228
- this.state.subscribeWithSelector(
229
- (nextValue) => ({ threads: nextValue.threads }),
388
+ this.paginator.state.subscribeWithSelector(
389
+ (nextValue) => ({ threads: nextValue.items ?? [] }),
230
390
  ({ threads: nextThreads }, prev) => {
231
391
  const { threads: prevThreads = [] } = prev ?? {};
232
- // Thread instance was removed if there's no thread with the given id at all,
233
- // or it was replaced with a new instance
392
+ // Left the list and not opened. Checks `REGISTERED_HOLDER`, not `threadStore.get`:
393
+ // `removeItem` publishes before it unlinks the list's hold.
394
+ const listed = new Set(nextThreads);
234
395
  const removedThreads = prevThreads.filter(
235
- (thread) => thread !== this.threadsById[thread.id],
396
+ (thread) =>
397
+ !listed.has(thread) &&
398
+ !this.threadStore.isHeldBy(thread.id, REGISTERED_HOLDER),
236
399
  );
237
400
 
238
401
  nextThreads.forEach((thread) => thread.registerSubscriptions());
@@ -253,165 +416,68 @@ export class ThreadManager extends WithSubscriptions {
253
416
  const parentId = event.message?.parent_id;
254
417
  if (!parentId) return;
255
418
 
256
- const { unseenThreadIds, ready } = this.state.getLatestValue();
257
- if (!ready) return;
419
+ if (!this.paginator.hasResults) return;
420
+ const { unseenThreadIds } = this.state.getLatestValue();
258
421
 
259
- if (this.threadsById[parentId]) {
422
+ if (this.paginator.getItem(parentId)) {
260
423
  this.state.partialNext({ isThreadOrderStale: true });
261
424
  } else if (!unseenThreadIds.includes(parentId)) {
262
425
  this.state.partialNext({ unseenThreadIds: unseenThreadIds.concat(parentId) });
263
426
  }
264
427
  }).unsubscribe;
265
428
 
266
- private subscribeRecoverAfterConnectionDrop = () => {
267
- const unsubscribeConnectionDropped = this.client.on('connection.changed', (event) => {
268
- if (event.online === false) {
269
- this.state.next((current) =>
270
- current.lastConnectionDropAt
271
- ? current
272
- : {
273
- ...current,
274
- lastConnectionDropAt: new Date(),
275
- },
276
- );
277
- }
278
- }).unsubscribe;
279
-
429
+ /** Reloads the thread list once recovery after a reconnect finished (`connection.recovered`). */
430
+ private subscribeReloadOnConnectionRecovered = () => {
280
431
  const throttledHandleConnectionRecovered = throttle(
281
432
  () => {
282
- const { lastConnectionDropAt, wasActivatedAtLeastOnce } =
283
- this.state.getLatestValue();
284
- if (!lastConnectionDropAt || !wasActivatedAtLeastOnce) return;
433
+ if (!this.state.getLatestValue().wasActivatedAtLeastOnce) return;
285
434
  this.reload({ force: true });
286
435
  },
287
436
  this.config.connectionRecoveryThrottleMs,
288
437
  { trailing: true },
289
438
  ).throttledFn;
290
439
 
291
- const unsubscribeConnectionRecovered = this.client.on(
292
- 'connection.recovered',
293
- throttledHandleConnectionRecovered,
294
- ).unsubscribe;
295
-
296
- return () => {
297
- unsubscribeConnectionDropped();
298
- unsubscribeConnectionRecovered();
299
- };
440
+ return this.client.on('connection.recovered', throttledHandleConnectionRecovered)
441
+ .unsubscribe;
300
442
  };
301
443
 
302
444
  public unregisterSubscriptions = () => {
303
- this.state
304
- .getLatestValue()
305
- .threads.forEach((thread) => thread.unregisterSubscriptions());
445
+ this.threadStore.values().forEach((thread) => thread.unregisterSubscriptions());
306
446
  return super.unregisterSubscriptions();
307
447
  };
308
448
 
449
+ /**
450
+ * Loads the first page, or re-queries a loaded list in place, sized to what is loaded plus the
451
+ * unseen threads. Skipped once loaded unless forced or something changed; the list survives a
452
+ * failure. Dropped while another reload is in flight. Only the first load shows
453
+ * `paginator.isLoading`.
454
+ */
309
455
  public reload = async ({ force = false } = {}) => {
310
- const { threads, unseenThreadIds, isThreadOrderStale, pagination, ready } =
311
- this.state.getLatestValue();
312
- if (pagination.isLoading) return;
313
- if (!force && ready && !unseenThreadIds.length && !isThreadOrderStale) return;
314
- const limit = threads.length + unseenThreadIds.length;
315
-
456
+ if (this.isReloadInFlight) return;
457
+ const { isThreadOrderStale, unseenThreadIds } = this.state.getLatestValue();
458
+ if (
459
+ !force &&
460
+ this.paginator.hasResults &&
461
+ !unseenThreadIds.length &&
462
+ !isThreadOrderStale
463
+ )
464
+ return;
465
+ const { items, pageSize } = this.paginator;
466
+ const limit = (items?.length ?? 0) + unseenThreadIds.length;
467
+
468
+ this.isReloadInFlight = true;
316
469
  try {
317
- this.state.next((current) => ({
318
- ...current,
319
- pagination: {
320
- ...current.pagination,
321
- isLoading: true,
322
- },
323
- }));
324
-
325
- const response = await this.queryThreads({
326
- limit: Math.min(limit, MAX_QUERY_THREADS_LIMIT) || MAX_QUERY_THREADS_LIMIT,
327
- });
328
-
329
- const nextThreads: Thread[] = [];
330
-
331
- for (const incomingThread of response.threads) {
332
- const existingThread = this.threadsById[incomingThread.id];
333
-
334
- if (existingThread) {
335
- // Reuse thread instances if possible
336
- nextThreads.push(existingThread);
337
- if (existingThread.hasStaleState) {
338
- existingThread.hydrateState(incomingThread);
339
- }
340
- } else {
341
- nextThreads.push(incomingThread);
342
- }
470
+ await this.paginator.reload({ limit: Math.min(limit, pageSize) || pageSize });
471
+ } finally {
472
+ this.isReloadInFlight = false;
473
+ const error = this.paginator.lastQueryError;
474
+ if (error) {
475
+ logger
476
+ .withExtraTags('reload')
477
+ .error('Failed to reload the thread list.', { error });
478
+ } else {
479
+ this.state.partialNext({ isThreadOrderStale: false, unseenThreadIds: [] });
343
480
  }
344
-
345
- this.state.next((current) => ({
346
- ...current,
347
- threads: nextThreads,
348
- unseenThreadIds: [],
349
- isThreadOrderStale: false,
350
- pagination: {
351
- ...current.pagination,
352
- isLoading: false,
353
- nextCursor: response.next ?? null,
354
- },
355
- ready: true,
356
- }));
357
- } catch (error) {
358
- logger
359
- .withExtraTags('reload')
360
- .error('Failed to reload the thread list.', { error });
361
- this.state.next((current) => ({
362
- ...current,
363
- pagination: {
364
- ...current.pagination,
365
- isLoading: false,
366
- },
367
- }));
368
- }
369
- };
370
-
371
- public queryThreads = (options: QueryThreadsRequest = {}) =>
372
- this.client.queryThreadsAndHydrate({
373
- limit: 25,
374
- participant_limit: 10,
375
- reply_limit: 10,
376
- watch: true,
377
- ...options,
378
- });
379
-
380
- public loadNextPage = async (options: Omit<QueryThreadsRequest, 'next'> = {}) => {
381
- const { pagination } = this.state.getLatestValue();
382
-
383
- if (pagination.isLoadingNext || !pagination.nextCursor) return;
384
-
385
- try {
386
- this.state.partialNext({ pagination: { ...pagination, isLoadingNext: true } });
387
-
388
- const response = await this.queryThreads({
389
- ...options,
390
- next: pagination.nextCursor,
391
- });
392
-
393
- this.state.next((current) => ({
394
- ...current,
395
- threads: response.threads.length
396
- ? current.threads.concat(response.threads)
397
- : current.threads,
398
- pagination: {
399
- ...current.pagination,
400
- nextCursor: response.next ?? null,
401
- isLoadingNext: false,
402
- },
403
- }));
404
- } catch (error) {
405
- logger
406
- .withExtraTags('loadNextPage')
407
- .error('Failed to load the next page of threads.', { error });
408
- this.state.next((current) => ({
409
- ...current,
410
- pagination: {
411
- ...current.pagination,
412
- isLoadingNext: false,
413
- },
414
- }));
415
481
  }
416
482
  };
417
483
  }