stream-chat 10.0.0-rc.9 → 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 (361) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +21650 -19790
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +21690 -19798
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +21755 -19895
  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 +13 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +24 -52
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +432 -470
  14. package/dist/types/channel_state.d.ts +68 -112
  15. package/dist/types/client.d.ts +321 -435
  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 +2 -0
  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 +2528 -690
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +33 -14
  52. package/dist/types/index.d.ts +10 -6
  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 +7 -1
  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 -128
  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 +19 -18
  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 +40 -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 -186
  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 -334
  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 +5 -23
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +34 -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 +11 -11
  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 +63 -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 -199
  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 +33 -57
  148. package/dist/types/utils.d.ts +72 -91
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +28 -38
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +37 -76
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1067 -1276
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +73 -168
  159. package/src/client.ts +744 -974
  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 -232
  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 +6 -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 -1540
  195. package/src/gen/models/index.ts +2498 -3383
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +170 -367
  198. package/src/index.ts +22 -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 +19 -23
  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 +223 -174
  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/textComposer.ts +1 -1
  225. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  226. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  227. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  228. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  229. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  230. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  231. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  232. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  233. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  234. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  235. package/src/messageComposer/pollComposer.ts +21 -9
  236. package/src/messageComposer/textComposer.ts +37 -57
  237. package/src/messageComposer/types.ts +39 -11
  238. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -125
  239. package/src/messageDelivery/MessageReceiptsTracker.ts +88 -101
  240. package/src/messageOperations/FailedSendCache.ts +85 -0
  241. package/src/messageOperations/MessageOperationStatePolicy.ts +121 -112
  242. package/src/messageOperations/MessageOperations.ts +297 -175
  243. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +9 -28
  244. package/src/messageOperations/createMessageOperations.ts +176 -0
  245. package/src/messageOperations/index.ts +6 -14
  246. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  247. package/src/messageOperations/sendOrdering.ts +25 -0
  248. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  249. package/src/messageOperations/types.ts +51 -13
  250. package/src/middleware.ts +13 -5
  251. package/src/moderation.ts +25 -21
  252. package/src/notifications/NotificationManager.ts +19 -28
  253. package/src/notifications/types.ts +21 -57
  254. package/src/offline-support/offline_support_api.ts +226 -669
  255. package/src/offline-support/offline_sync_manager.ts +51 -80
  256. package/src/offline-support/queueableOperations.ts +98 -73
  257. package/src/offline-support/types.ts +43 -186
  258. package/src/pagination/FilterBuilder.ts +1 -22
  259. package/src/pagination/ItemIndex.ts +4 -12
  260. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  261. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +15 -63
  262. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  263. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  264. package/src/pagination/filterCompiler.ts +11 -25
  265. package/src/pagination/index.ts +1 -0
  266. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  267. package/src/pagination/paginators/ChannelPaginator.ts +479 -217
  268. package/src/pagination/paginators/MessageIntervalPaginator.ts +1351 -772
  269. package/src/pagination/paginators/MessagePaginator.ts +513 -233
  270. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  271. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  272. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  273. package/src/pagination/paginators/UserGroupPaginator.ts +16 -19
  274. package/src/pagination/paginators/index.ts +1 -0
  275. package/src/pagination/paginators/stateThrottling.ts +5 -10
  276. package/src/pagination/sortCompiler.ts +23 -50
  277. package/src/pagination/utility.normalization.ts +8 -30
  278. package/src/pagination/utility.search.ts +4 -11
  279. package/src/poll.ts +177 -98
  280. package/src/poll_manager.ts +24 -22
  281. package/src/poll_optimistic_votes.ts +335 -0
  282. package/src/reminders/Reminder.ts +16 -12
  283. package/src/reminders/ReminderManager.ts +22 -55
  284. package/src/reminders/ReminderTimer.ts +1 -2
  285. package/src/search/BaseSearchSource.ts +19 -25
  286. package/src/search/ChannelSearchSource.ts +43 -1
  287. package/src/search/MessageSearchSource.ts +77 -13
  288. package/src/search/SearchController.ts +39 -36
  289. package/src/search/types.ts +6 -10
  290. package/src/segment.ts +1 -1
  291. package/src/signing.ts +23 -3
  292. package/src/thread.ts +418 -703
  293. package/src/thread_manager.ts +300 -234
  294. package/src/token_manager.ts +12 -22
  295. package/src/types.ts +102 -216
  296. package/src/types.utility.ts +3 -3
  297. package/src/upload-utils.ts +5 -10
  298. package/src/uploadManager.ts +64 -18
  299. package/src/utils/FixedSizeQueueCache.ts +18 -21
  300. package/src/utils/WithSubscriptions.ts +6 -16
  301. package/src/utils/abort.ts +45 -0
  302. package/src/utils/concurrency.ts +16 -55
  303. package/src/utils/mergeWith/mergeWith.ts +10 -13
  304. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  305. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  306. package/src/utils/objectPath.ts +6 -41
  307. package/src/utils/retryable.ts +10 -14
  308. package/src/utils/throttling/throttle.ts +9 -25
  309. package/src/utils/time.ts +40 -60
  310. package/src/utils.ts +181 -174
  311. package/codegen/i18n/callSites.ts +0 -126
  312. package/codegen/i18n/generate.ts +0 -226
  313. package/codegen/i18n/guards.ts +0 -178
  314. package/codegen/i18n/index.ts +0 -29
  315. package/codegen/i18n/stringMaps.ts +0 -91
  316. package/codegen/i18n/types.ts +0 -100
  317. package/dist/cjs/i18n.browser.js +0 -1131
  318. package/dist/cjs/i18n.browser.js.map +0 -7
  319. package/dist/cjs/i18n.node.js +0 -1160
  320. package/dist/cjs/i18n.node.js.map +0 -7
  321. package/dist/esm/i18n-codegen.mjs +0 -409
  322. package/dist/esm/i18n-codegen.mjs.map +0 -7
  323. package/dist/esm/i18n.mjs +0 -1098
  324. package/dist/esm/i18n.mjs.map +0 -7
  325. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  326. package/dist/types/connection.d.ts +0 -139
  327. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -32
  328. package/dist/types/i18n/Streami18n.d.ts +0 -168
  329. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  330. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  331. package/dist/types/i18n/dayjs.d.ts +0 -104
  332. package/dist/types/i18n/formatters.d.ts +0 -91
  333. package/dist/types/i18n/index.d.ts +0 -15
  334. package/dist/types/i18n/translator.d.ts +0 -29
  335. package/dist/types/i18n/types.d.ts +0 -262
  336. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  337. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  338. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  339. package/dist/types/i18n-codegen/index.d.ts +0 -29
  340. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  341. package/dist/types/i18n-codegen/types.d.ts +0 -94
  342. package/dist/types/insights.d.ts +0 -56
  343. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  344. package/dist/types/messageOperations/persistence.d.ts +0 -21
  345. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  346. package/dist/types/store.d.ts +0 -125
  347. package/src/ConnectionRecoveryManager.ts +0 -293
  348. package/src/i18n/Streami18n.ts +0 -520
  349. package/src/i18n/TranslationBuilder.ts +0 -176
  350. package/src/i18n/TranslationStore.ts +0 -96
  351. package/src/i18n/dayjs.ts +0 -228
  352. package/src/i18n/formatters.ts +0 -461
  353. package/src/i18n/index.ts +0 -15
  354. package/src/i18n/languageNames.ts +0 -103
  355. package/src/i18n/translator.ts +0 -76
  356. package/src/i18n/types.ts +0 -375
  357. package/src/insights.ts +0 -82
  358. package/src/messageOperations/optimistic.ts +0 -257
  359. package/src/messageOperations/persistence.ts +0 -40
  360. package/src/pagination/utility.queryChannel.ts +0 -84
  361. package/src/store.ts +0 -304
package/src/thread.ts CHANGED
@@ -1,44 +1,31 @@
1
- import { StateStore } from './store';
2
- import {
3
- computeOwnReactions,
4
- formatMessage,
5
- localMessageToNewMessagePayload,
6
- } from './utils';
1
+ import { StateStore } from '@stream-io/state-store';
2
+ import { formatMessage } from './utils';
7
3
  import type {
8
4
  DraftResponse,
9
- EventType,
5
+ EventPayload,
10
6
  LocalMessage,
11
7
  MarkReadRequest,
12
8
  MarkReadResponse,
13
9
  MessageResponse,
14
- ReactionRequest,
15
10
  ReadStateResponse,
16
- SendReactionRequest,
17
11
  SortParamRequest,
18
12
  StreamResponse,
19
13
  ThreadStateResponse,
14
+ TimestampNS,
20
15
  UserResponse,
21
16
  } from './types';
22
17
  import { isDoesNotExistError } from './errors';
23
- import type {
24
- Channel,
25
- DeleteMessageWithStateUpdateParams,
26
- SendMessageWithStateUpdateParams,
27
- UpdateMessageWithStateUpdateParams,
28
- } from './channel';
18
+ import type { Channel } from './channel';
19
+ import { ChannelWatchStatus } from './channel_state';
29
20
  import type { StreamChat } from './client';
30
21
  import type { CustomThreadData } from './custom_types';
31
22
  import { MessageComposer } from './messageComposer';
32
- import {
33
- addReactionOptimistically,
34
- createMessageOperationsPersistence,
35
- deleteReactionOptimistically,
36
- MessageOperations,
37
- } from './messageOperations';
23
+ import { createMessageOperations } from './messageOperations';
24
+ import type { MessageOperations } from './messageOperations';
38
25
  import { nowNs } from './utils/time';
39
26
  import { WithSubscriptions } from './utils/WithSubscriptions';
40
27
  import { MessagePaginator } from './pagination';
41
- import type { MergeNewestPageOptions } from './pagination';
28
+ import type { PaginatorCursor, ReconcileNewestMessagesOptions } from './pagination';
42
29
  import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
43
30
  import { ConfigController } from './configuration/ConfigController';
44
31
  import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
@@ -50,36 +37,41 @@ import {
50
37
  } from './configuration/utils/declarativeSlices';
51
38
  import type { PipelineEvent } from './EventHandlerPipeline';
52
39
 
40
+ const getCursorFromReplies = (
41
+ replies: LocalMessage[],
42
+ reachesTail: boolean,
43
+ ): PaginatorCursor => {
44
+ const oldest = replies.reduce<LocalMessage | undefined>(
45
+ (acc, reply) => (!acc || reply.created_at < acc.created_at ? reply : acc),
46
+ undefined,
47
+ );
48
+ return { headward: null, tailward: reachesTail ? null : (oldest?.id ?? null) };
49
+ };
50
+
53
51
  export type ThreadState = {
54
- /**
55
- * Determines if the thread is currently opened and on-screen. When the thread is active,
56
- * all new messages are immediately marked as read.
57
- */
52
+ /** Whether the thread is open and on-screen. While active, new messages are marked read. */
58
53
  active: boolean;
59
54
  channel: Channel;
60
55
  /** Unix nanoseconds, as the API sends it. */
61
- createdAt: number;
56
+ createdAt: TimestampNS;
62
57
  custom: CustomThreadData;
63
58
  /** Unix nanoseconds, as the API sends it. */
64
- deletedAt: number | null;
59
+ deletedAt: TimestampNS | null;
65
60
  isLoading: boolean;
66
61
  isStateStale: boolean;
67
- /**
68
- * Thread is identified by and has a one-to-one relation with its parent message.
69
- * We use parent message id as a thread id.
70
- */
62
+ /** A thread maps one-to-one to its parent message, whose ID is the thread ID. */
71
63
  parentMessage: LocalMessage;
72
64
  participants: ThreadStateResponse['thread_participants'];
73
65
  read: ThreadReadState;
74
66
  replyCount: number;
75
67
  title: string;
76
68
  /** Unix nanoseconds, as the API sends it. */
77
- updatedAt: number | null;
69
+ updatedAt: TimestampNS | null;
78
70
  };
79
71
 
80
72
  export type ThreadUserReadState = {
81
73
  /** Unix nanoseconds, as the API sends it. */
82
- lastReadAt: number;
74
+ lastReadAt: TimestampNS;
83
75
  unreadMessageCount: number;
84
76
  user: UserResponse;
85
77
  lastReadMessageId?: string;
@@ -88,7 +80,10 @@ export type ThreadUserReadState = {
88
80
 
89
81
  export type ThreadReadState = Record<string, ThreadUserReadState | undefined>;
90
82
 
91
- const timestampOr = (value: number | undefined, fallback: number): number =>
83
+ const timestampOr = (
84
+ value: TimestampNS | undefined,
85
+ fallback: TimestampNS,
86
+ ): TimestampNS =>
92
87
  typeof value === 'number' && Number.isFinite(value) ? value : fallback;
93
88
 
94
89
  const DEFAULT_PAGE_LIMIT = 50;
@@ -106,27 +101,21 @@ export type ThreadConfig = {
106
101
  };
107
102
  };
108
103
 
109
- /**
110
- * Empty because every field of `ThreadConfig` is optional — a thread's own configuration is one handler
111
- * wide. Declared and frozen anyway, so the entity carries the same defaults layer as every other
112
- * configurable class rather than a special case.
113
- */
104
+ /** Empty: every field of `ThreadConfig` is optional. */
114
105
  export const DEFAULT_THREAD_CONFIG: ThreadConfig = deepFreezeConfig({});
115
106
 
116
107
  export class Thread extends WithSubscriptions {
117
- /** The shared configuration machinery — see {@link ConfigController}. */
118
108
  private readonly configController = new ConfigController<ThreadConfig>({
119
109
  defaults: DEFAULT_THREAD_CONFIG,
120
110
  });
121
111
  public readonly state: StateStore<ThreadState>;
122
112
  public readonly id: string;
123
113
  public readonly messageComposer: MessageComposer;
124
- public readonly messagePaginator: MessagePaginator;
125
114
  public readonly messageOperations: MessageOperations;
115
+ public readonly messagePaginator: MessagePaginator;
126
116
 
127
117
  private client: StreamChat;
128
118
  private failedRepliesMap: Map<string, LocalMessage> = new Map();
129
- /** How many consumers have called `activate()` without a matching `deactivate()`. */
130
119
  private _activeRefCount = 0;
131
120
 
132
121
  constructor({
@@ -144,48 +133,12 @@ export class Thread extends WithSubscriptions {
144
133
  }) {
145
134
  super();
146
135
  if (threadData) {
147
- if (!threadData.channel) {
148
- throw new Error('Thread channel is required when threadData is provided');
149
- }
150
- if (!threadData.parent_message) {
151
- throw new Error('Thread parent_message is required when threadData is provided');
152
- }
153
- const threadChannel = client.channel(
154
- threadData.channel.type,
155
- threadData.channel.id,
156
- { custom: threadData.channel.custom },
157
- );
158
- threadChannel._hydrateMembers({
159
- members: threadData.channel.members ?? [],
160
- overrideCurrentState: false,
161
- });
162
-
163
136
  this.state = new StateStore<ThreadState>({
164
- // local only
165
137
  active: false,
166
138
  isLoading: false,
167
139
  isStateStale: false,
168
- // 99.9% should never change
169
- channel: threadChannel,
170
- createdAt: threadData.created_at,
171
- // rest
172
- deletedAt: threadData.deleted_at ?? null,
173
- parentMessage: formatMessage(threadData.parent_message),
174
- participants: threadData.thread_participants,
175
- read: formatReadState(
176
- !threadData.read || threadData.read.length === 0
177
- ? getPlaceholderReadResponse(client.userId)
178
- : threadData.read,
179
- ),
180
- // Use the parent message's reply_count, not the top-level threadData.reply_count. The
181
- // thread endpoints (getThread/queryThreads) return a top level reply_count that EXCLUDES
182
- // soft-deleted replies, while parent_message.reply_count (and the channel's own copy)
183
- // INCLUDE them so the top level value renders fewer replies than the channel badge shows.
184
- // parent_message.reply_count is the authoritative, channel consistent count.
185
- replyCount: threadData.parent_message.reply_count ?? 0,
186
- updatedAt: threadData.updated_at ?? null,
187
- title: threadData.title,
188
- custom: threadData.custom ?? {},
140
+ ...formatThreadState(threadData, client.userId),
141
+ channel: ensureThreadChannel(client, threadData),
189
142
  });
190
143
 
191
144
  this.id = threadData.parent_message_id;
@@ -202,6 +155,7 @@ export class Thread extends WithSubscriptions {
202
155
 
203
156
  const formattedParentMessage = formatMessage(parentMessage);
204
157
  const createdAt = timestampOr(parentMessage.created_at, nowNs());
158
+ const replyCount = parentMessage.reply_count ?? 0;
205
159
 
206
160
  this.state = new StateStore<ThreadState>({
207
161
  active: false,
@@ -210,11 +164,15 @@ export class Thread extends WithSubscriptions {
210
164
  custom: {},
211
165
  deletedAt: formattedParentMessage.deleted_at ?? null,
212
166
  isLoading: false,
213
- isStateStale: false,
167
+ // Loads its data once when opened. A parent without replies in a watched channel has nothing
168
+ // on the server yet (`getThread` would answer 404); in an unwatched channel `reply_count` may
169
+ // miss newer replies, so it loads.
170
+ isStateStale:
171
+ replyCount > 0 || channel.watchStatus !== ChannelWatchStatus.Watching,
214
172
  parentMessage: formattedParentMessage,
215
173
  participants: [],
216
174
  read: formatReadState(getPlaceholderReadResponse(client.userId)),
217
- replyCount: parentMessage.reply_count ?? 0,
175
+ replyCount,
218
176
  title: '',
219
177
  updatedAt: parentMessage.updated_at ?? null,
220
178
  });
@@ -224,11 +182,9 @@ export class Thread extends WithSubscriptions {
224
182
 
225
183
  this.client = client;
226
184
 
227
- // Read the declarative configuration before the sub-objects exist, so it can go in as constructor
228
- // options — the reply paginator's `unreadReferencePolicy` and initial cursor are read once.
185
+ // Read up front: the reply paginator takes `unreadReferencePolicy` as a constructor argument.
229
186
  const declarativeConfig = client.config.getConfig('thread') ?? undefined;
230
- // Thread replies are backed by a MessagePaginator too, so the general key applies here as well;
231
- // the per-parent slice overrides it (thread replies default to a smaller page than a channel).
187
+ // The general `messagePaginator` key applies to replies; the thread's own slice overrides it.
232
188
  const messagePaginatorConfig = mergeDeclarativePaginatorConfig(
233
189
  client.config.getConfig('messagePaginator') ?? undefined,
234
190
  declarativeConfig?.messagePaginator,
@@ -237,39 +193,36 @@ export class Thread extends WithSubscriptions {
237
193
  this.messagePaginator = new MessagePaginator(
238
194
  {
239
195
  channel: this.channel,
196
+ thread: this,
240
197
  parentMessageId: this.id,
241
198
  requestSort: DEFAULT_SORT,
242
199
  itemOrder: DEFAULT_ITEM_ORDER,
243
- // Split as in `Channel`: the policy is a constructor argument, not paginator configuration.
200
+ // A constructor argument, not paginator configuration.
244
201
  unreadReferencePolicy: messagePaginatorConfig?.unreadReferencePolicy,
245
202
  paginatorOptions: {
246
203
  declarativeConfig: toDeclarativePaginatorConfig(messagePaginatorConfig),
247
204
  },
248
205
  },
249
- // Thread replies default to a smaller page than a channel list. Supplied by the SDK, not by the
250
- // integrator, so it sits at stage 1 — `client.config.set({ messagePaginator: { pageSize } })`
251
- // overrides it, which would not be true of a construction argument.
206
+ // SDK default page size. Overridable through `client.config.set`
207
+ // (`messagePaginator.pageSize`).
252
208
  { pageSize: DEFAULT_PAGE_LIMIT },
253
209
  );
254
210
 
255
- // Seed the reply paginator from the thread's `latest_replies` so a thread we already hold
256
- // data for (queried via the ThreadManager or hydrated from a ThreadResponse) renders its
257
- // first reply page instantly, without a network fetch on open. `latest_replies` is the most
258
- // recent window of replies, so it reaches the head (nothing newer to load); it reaches the
259
- // tail only when it already contains every reply. Threads built from a bare parent message
260
- // carry no replies to seed and fall back to a paginator fetch on first open.
211
+ // Seeds the first reply page without a fetch. `latest_replies` is the newest interval: it
212
+ // reaches the head, and the tail only if it holds every reply.
261
213
  if (threadData?.latest_replies?.length) {
214
+ const replies = threadData.latest_replies.map(formatMessage);
215
+ const isLastPage = holdsEveryReply(replies, threadData);
262
216
  this.messagePaginator.setItems({
263
- valueOrFactory: threadData.latest_replies.map(formatMessage),
217
+ valueOrFactory: replies,
218
+ cursor: getCursorFromReplies(replies, isLastPage),
264
219
  isFirstPage: true,
265
- isLastPage: threadData.latest_replies.length === (threadData.reply_count ?? 0),
220
+ isLastPage,
266
221
  });
267
222
  }
268
223
 
269
- // Seed the reply paginator's lastMessageAt floor from the thread's server-provided
270
- // `last_message_at` (analogous to the channel seed in Channel._initializeState), so a thread whose
271
- // newest reply is not among `latest_replies` still reports the correct latest-activity timestamp.
272
- this.messagePaginator.seedLastMessageAt(threadData?.last_message_at);
224
+ // Floor for `latestMessageAt`, for when the newest reply is not among `latest_replies`.
225
+ this.messagePaginator.setQueriedLatestMessageAt(threadData?.last_message_at);
273
226
 
274
227
  this.messageComposer = new MessageComposer({
275
228
  client,
@@ -277,119 +230,19 @@ export class Thread extends WithSubscriptions {
277
230
  compositionContext: this,
278
231
  });
279
232
 
280
- this.messageOperations = new MessageOperations({
281
- ...createMessageOperationsPersistence({ channel: this.channel }),
282
- ingest: (m) => {
283
- const store = this.channel.getClient().messageStore;
284
- // See the matching comment in `Channel`: the reply paginator's filter demands
285
- // `parent_id === this.id`, so an operation on this thread's PARENT message — edited or deleted
286
- // from inside the open thread, which is how the UI SDKs route it — is not something the reply
287
- // paginator can hold. The store reaches it (a subscribed thread seeds its parent there) and
288
- // fans the change out to the channel list too.
289
- if (this.messagePaginator.matchesFilter(m)) {
290
- this.messagePaginator.ingestItem(m);
291
- } else if (store.has(m.id)) {
292
- store.upsert(m);
293
- }
294
- store.flushSubscribers(m.id);
295
- },
296
- // Mirrors `ingest`'s routing: a message this paginator does not hold can still be held by the
297
- // client-global store (a thread parent, a message displayed by another collection), and the
298
- // policy uses this both for its freshness comparison and to decide whether there is anything to
299
- // update optimistically at all. Reading only the paginator would make those two disagree.
300
- get: (id) =>
301
- this.messagePaginator.getItem(id) ??
302
- this.channel.getClient().messageStore.get(id),
303
- remove: (id) => {
304
- this.messagePaginator.removeItem({ id });
305
- // A reply with `show_in_channel` is held by the channel list as well, so removing it from the
306
- // reply paginator alone leaves a ghost there until the `message.deleted` event arrives. Both
307
- // calls are no-ops when the paginator does not hold the id, which is the same reason the SDK's
308
- // own `removeMessage` removes from the channel unconditionally.
309
- this.channel.messagePaginator.removeItem({ id });
310
- this.channel.pinnedMessagesPaginator.removeItem({ id });
311
- },
312
- normalizeOutgoingMessage: (m) => ({
313
- ...m,
314
- parent_id: this.id,
315
- }),
316
- handlers: () => {
317
- const { requestHandlers } = this.channel.configState.getLatestValue();
318
- const deleteMessageRequest = requestHandlers?.deleteMessageRequest;
319
- const sendMessageRequest = requestHandlers?.sendMessageRequest;
320
- const retrySendMessageRequest = requestHandlers?.retrySendMessageRequest;
321
- const updateMessageRequest = requestHandlers?.updateMessageRequest;
322
- return {
323
- delete: deleteMessageRequest
324
- ? (p) =>
325
- deleteMessageRequest({
326
- localMessage: p.localMessage,
327
- options: p.options,
328
- })
329
- : undefined,
330
- send: sendMessageRequest
331
- ? (p) =>
332
- sendMessageRequest({
333
- localMessage: p.localMessage,
334
- message: p.message,
335
- options: p.options,
336
- })
337
- : undefined,
338
- retry: retrySendMessageRequest
339
- ? (p) =>
340
- retrySendMessageRequest({
341
- localMessage: p.localMessage,
342
- message: p.message,
343
- options: p.options,
344
- })
345
- : undefined,
346
- update: updateMessageRequest
347
- ? (p) =>
348
- updateMessageRequest({
349
- localMessage: p.localMessage,
350
- options: p.options,
351
- })
352
- : undefined,
353
- };
354
- },
355
- defaults: {
356
- delete: async (id, o) => {
357
- const result = await this.channel.getClient().deleteMessage({ id, ...o });
358
- return { message: result.message };
359
- },
360
- send: async (m, o) => {
361
- const result = await this.channel.sendMessage({ message: m, ...o });
362
- return { message: result.message };
363
- },
364
- update: async (m, o) => {
365
- const result = await this.channel.getClient().updateMessage({
366
- id: m.id,
367
- message: localMessageToNewMessagePayload(m),
368
- ...o,
369
- });
370
- return { message: result.message };
371
- },
372
- },
373
- });
233
+ this.messageOperations = createMessageOperations(this);
374
234
 
375
- // Share one derivation path with `config.reset()`. Idempotent — the paginator was already
376
- // configured through its constructor above; this re-applies the mutable half the way a reset does.
235
+ // Same derivation path as `config.reset()`. Idempotent: re-applies what the constructors set.
377
236
  this.initializeConfig(declarativeConfig);
378
237
  }
379
238
 
380
239
  /**
381
- * Derives this thread's configuration — and its reply paginator's — from the declarative slice.
382
- *
383
- * Called by the constructor and by `client.config.reset()`. The thread owns only its own
384
- * `requestHandlers`; the paginator derives its own configuration.
240
+ * Derives this thread's configuration, and its reply paginator's, from the declarative slice.
241
+ * Called by the constructor and by `client.config.reset()`.
385
242
  */
386
243
  initializeConfig(declarativeConfig?: ThreadDeclarativeConfig): void {
387
- // Only the thread's own slice goes in. The paginator and the operations keys are handed to those
388
- // objects below, so putting them here too would publish them on `thread.config` as well.
389
- //
390
- // Replaces rather than merges: a handler dropped from the declarative tree must disappear. The
391
- // controller skips a write that changes nothing, which matters because `alsoWatch` re-runs this for
392
- // any of three keys and `useThreadRequestHandlers` subscribes to the store.
244
+ // Only the thread's own slice: the paginator and operations keys go to those objects below.
245
+ // Replaces rather than merges, so a handler dropped from the declarative tree disappears.
393
246
  this.configController.initialize({
394
247
  requestHandlers: declarativeConfig?.requestHandlers,
395
248
  });
@@ -403,8 +256,7 @@ export class Thread extends WithSubscriptions {
403
256
  ),
404
257
  );
405
258
 
406
- // A thread sends messages too, so it owns a `MessageOperations` of its own and takes the same shared
407
- // key the channel does, with its own per-parent override.
259
+ // Takes the shared `messageOperations` key like the channel does, with its own override.
408
260
  this.messageOperations.initializeConfig(
409
261
  mergeDeclarativeMessageOperationsConfig(
410
262
  this.client.config.getConfig('messageOperations') ?? undefined,
@@ -413,23 +265,19 @@ export class Thread extends WithSubscriptions {
413
265
  );
414
266
  }
415
267
 
416
- /**
417
- * Resolved configuration as a store, so consumers can react to it — the shape every configurable class
418
- * exposes.
419
- */
420
268
  get configState(): StateStore<ThreadConfig> {
421
269
  return this.configController.state;
422
270
  }
423
271
 
424
- /**
425
- * This thread's resolved configuration. `Readonly` because the value is the store's live object —
426
- * assigning to a field of it would change state without notifying anyone. Use {@link updateConfig}.
427
- */
428
272
  get config(): Readonly<ThreadConfig> {
429
273
  return this.configController.value;
430
274
  }
431
275
 
432
- /** Merges a partial configuration into the resolved config and notifies subscribers. */
276
+ /**
277
+ * Merges a partial configuration into the resolved config.
278
+ *
279
+ * @param config - The fields to change.
280
+ */
433
281
  updateConfig(config: Partial<ThreadConfig>): void {
434
282
  this.configController.patch(config);
435
283
  }
@@ -446,48 +294,45 @@ export class Thread extends WithSubscriptions {
446
294
  return ownUnreadCountSelector(this.client.userId)(this.state.getLatestValue());
447
295
  }
448
296
 
297
+ /** See {@link Thread.activate}. */
298
+ get active() {
299
+ return this.state.getLatestValue().active;
300
+ }
301
+
449
302
  /**
450
- * Declares that a consumer is displaying this thread (mirrors `channel.activate()`).
303
+ * Declares that a consumer is displaying this thread and returns the function that ends it (as
304
+ * `channel.activate()`). Refcounted: the thread stays active until the last release, and each
305
+ * release is idempotent. `active` selects the threads reloaded on reconnect, so release it.
451
306
  *
452
- * `active` is also what {@link ConnectionRecoveryManager} filters on to decide which threads to
453
- * reload on reconnect, so an unbalanced `deactivate()` now costs more than a missed auto-read —
454
- * hence the refcount, matching `channel.activate()`. A thread held by more than one mount stays
455
- * active until the last holder releases it.
307
+ * The first activation keeps the thread in `client.threads` for the session, subscribed and
308
+ * resolvable through `client.threads.get(id)` after release.
456
309
  */
457
- public activate = () => {
310
+ public activate = (): (() => void) => {
458
311
  this._activeRefCount += 1;
459
312
  if (this._activeRefCount === 1) {
313
+ this.client.threads.register(this);
460
314
  this.state.partialNext({ active: true });
461
315
  }
462
- };
463
316
 
464
- /**
465
- * Declares that a consumer has stopped displaying this thread (mirrors `channel.deactivate()`).
466
- * Only flips `active` back to `false` once the last holder deactivates.
467
- */
468
- public deactivate = () => {
469
- if (this._activeRefCount === 0) return;
470
- this._activeRefCount -= 1;
471
- if (this._activeRefCount === 0) {
472
- this.state.partialNext({ active: false });
473
- }
317
+ let released = false;
318
+ return () => {
319
+ if (released) return;
320
+ released = true;
321
+ this._activeRefCount -= 1;
322
+ if (this._activeRefCount === 0) {
323
+ this.state.partialNext({ active: false });
324
+ }
325
+ };
474
326
  };
475
327
 
476
328
  /**
477
- * Re-queries this thread's replies, sized to the loaded window, and reconciles them in place — the
478
- * thread analogue of {@link Channel.reload}, and what connection recovery calls for every active
479
- * thread.
480
- *
481
- * Preserves failed (unsent) replies. They are read out of the reply paginator rather than out of
482
- * `failedRepliesMap`, because that map is only written by `upsertReplyLocally`, whose callers are
483
- * this thread's own subscriptions and the offline-DB path keyed on `ThreadManager.threadsById` —
484
- * neither of which covers a thread constructed directly and never registered (the common path in
485
- * the React Native SDK, which resolves `threadsById[id] ?? new Thread(...)`). Reading the paginator
486
- * is true for managed and unmanaged threads alike. An overlap merge keeps them anyway (the
487
- * reconcile's provenance guard never prunes a non-server message); only a disjoint rebuild can drop
488
- * them, so any that actually fell out are re-ingested below.
489
- *
490
- * Rethrows, except for a not-found answer on a thread that never had replies (see the catch).
329
+ * Re-queries the replies, sized to the loaded interval, and reconciles them in place (the thread
330
+ * analogue of {@link Channel.reload}; recovery calls it for active threads). The thread applies
331
+ * the response to itself ({@link Thread.hydrateState}), whether or not it is registered in
332
+ * `client.threads`. Failed replies are kept: those loaded in the reply paginator or in the
333
+ * offline DB before the request that are no longer loaded after it are ingested again (the
334
+ * offline DB read is best effort). Rethrows, except for a not-found answer on a thread that never
335
+ * had replies.
491
336
  */
492
337
  public reload = async () => {
493
338
  if (this.state.getLatestValue().isLoading) {
@@ -497,45 +342,40 @@ export class Thread extends WithSubscriptions {
497
342
  this.state.partialNext({ isLoading: true });
498
343
 
499
344
  try {
500
- const loadedReplies = this.messagePaginator.items ?? [];
501
- const loadedReplyCount = loadedReplies.length;
345
+ const loadedReplyCount = this.messagePaginator.items?.length ?? 0;
502
346
  const requestedReplyLimit =
503
347
  Math.max(loadedReplyCount, this.messagePaginator.pageSize ?? 0) || undefined;
504
- const reconcileCandidateIds = new Set(loadedReplies.map((reply) => reply.id));
505
- const failedBefore = loadedReplies.filter((reply) => reply.status === 'failed');
506
- const thread = await this.client.getThreadAndHydrate(this.id, {
507
- watch: true,
508
- reply_limit: requestedReplyLimit,
509
- });
510
- this.hydrateState(thread, {
348
+ const offlineDb = this.client.offlineDb;
349
+ // best effort: a failing read must not fail the reload
350
+ const failedInDb = offlineDb
351
+ ? await offlineDb.getFailedMessages({ cid: this.channel.cid }).catch(() => [])
352
+ : [];
353
+ // after the read: a reply that fails meanwhile is loaded by then
354
+ const failedBefore = this.messagePaginator.getFailedMessagesToRestore(failedInDb);
355
+ const headIntervalItemIdsAtRequest =
356
+ this.messagePaginator.getHeadIntervalItemIdsAtRequest();
357
+ const { thread: threadData } = await this.client.getThread(
358
+ { message_id: this.id },
359
+ {
360
+ participant_limit: DEFAULT_THREAD_PARTICIPANT_LIMIT,
361
+ watch: true,
362
+ reply_limit: requestedReplyLimit,
363
+ },
364
+ );
365
+ this.channel.watchStatus = ChannelWatchStatus.Watching;
366
+ this.hydrateState(threadData, {
511
367
  reconcile: {
512
368
  requestedLimit: requestedReplyLimit,
513
- candidateIds: reconcileCandidateIds,
369
+ headIntervalItemIdsAtRequest,
514
370
  },
515
371
  });
516
-
517
- if (failedBefore.length) {
518
- // Membership is checked against the visible window, NOT `getItem`: that reads the item
519
- // index, which can still hold a message the rebuild dropped from the loaded window — so an
520
- // index-based guard skips the re-ingest on exactly the path that needs it.
521
- const visible = new Set((this.messagePaginator.items ?? []).map((r) => r.id));
522
- this.messagePaginator.batch(
523
- () => {
524
- for (const failed of failedBefore) {
525
- if (!visible.has(failed.id)) this.messagePaginator.ingestItem(failed);
526
- }
527
- },
528
- { coalesce: true },
529
- );
530
- }
372
+ this.messagePaginator.restoreFailedMessages(failedBefore);
531
373
  } catch (error) {
532
374
  const notFound =
533
375
  isDoesNotExistError(error as Error) ||
534
376
  (error as { status?: number })?.status === 404;
535
377
  const neverExisted = notFound && this.state.getLatestValue().replyCount === 0;
536
- // Do not throw an error if we haven't created the thread yet, the tiebreaker
537
- // being whether the parent message has any replies or not. A thread with all hard
538
- // deleted replies will simply not throw.
378
+ // Not found while the parent has no replies: the thread was never created, not an error.
539
379
  if (neverExisted) return;
540
380
 
541
381
  throw error;
@@ -544,107 +384,71 @@ export class Thread extends WithSubscriptions {
544
384
  }
545
385
  };
546
386
 
387
+ /**
388
+ * Updates the thread's state and its channel's members and custom data, and merges the replies
389
+ * into the loaded interval (with `reconcile`) or replaces it (without).
390
+ */
547
391
  public hydrateState = (
548
- thread: Thread,
549
- options?: { reconcile?: MergeNewestPageOptions },
392
+ threadData: ThreadStateResponse,
393
+ options?: { reconcile?: ReconcileNewestMessagesOptions },
550
394
  ) => {
551
- if (thread === this) {
552
- // skip if the instances are the same
553
- return;
395
+ if (threadData.parent_message_id !== this.id) {
396
+ throw new Error("Cannot hydrate thread's state from another thread's response");
554
397
  }
555
398
 
556
- if (thread.id !== this.id) {
557
- throw new Error(
558
- "Cannot hydrate thread's state using thread with different threadId",
559
- );
560
- }
399
+ const serverState = formatThreadState(threadData, this.client.userId);
400
+ const reconcile = options?.reconcile;
561
401
 
562
- const {
563
- createdAt,
564
- custom,
565
- title,
566
- deletedAt,
567
- parentMessage,
568
- participants,
569
- read,
570
- replyCount,
571
- updatedAt,
572
- } = thread.state.getLatestValue();
573
-
574
- // Preserve pending (failed) replies so they survive the hydrate. The messagePaginator is now
575
- // the sole reply source, so we merge the incoming newest page into it and re-ingest the
576
- // pending replies (mirrors the previous state.replies concat behavior).
402
+ // Failed replies survive the hydrate: they are re-ingested after the incoming page is merged.
577
403
  const pendingReplies = Array.from(this.failedRepliesMap.values());
578
404
 
579
- this.state.partialNext({
580
- title,
581
- createdAt,
582
- custom,
583
- deletedAt,
584
- parentMessage,
585
- participants,
586
- read,
587
- replyCount,
588
- updatedAt,
589
- isStateStale: false,
590
- });
405
+ ensureThreadChannel(this.client, threadData);
406
+ this.state.partialNext({ ...serverState, isStateStale: false });
591
407
 
592
- if (parentMessage && this.hasSubscriptions) {
593
- this.client.messageStore.upsert(parentMessage);
408
+ if (this.hasSubscriptions) {
409
+ this.client.messageStore.upsert(serverState.parentMessage);
594
410
  }
595
411
 
596
- this.messagePaginator.mergeNewestPage(
597
- thread.messagePaginator.state.getLatestValue().items ?? [],
598
- options?.reconcile,
599
- );
412
+ const incomingReplies = (threadData.latest_replies ?? []).map(formatMessage);
413
+ if (!reconcile) this.messagePaginator.clearStateAndCache();
414
+ // The response's newest reply time replaces what was known, so latestMessageAt is right even
415
+ // when the merged page lacks the newest reply, or that reply was hard-deleted.
416
+ this.messagePaginator.setQueriedLatestMessageAt(threadData.last_message_at);
417
+ if (typeof this.messagePaginator.items === 'undefined') {
418
+ // Nothing loaded yet (e.g. a thread opened from a message): `reconcileNewestMessages` no-ops
419
+ // without a loaded interval and would drop the fetched replies, so set them as the constructor
420
+ // does.
421
+ const isLastPage = holdsEveryReply(incomingReplies, threadData);
422
+ this.messagePaginator.setItems({
423
+ valueOrFactory: incomingReplies,
424
+ cursor: getCursorFromReplies(incomingReplies, isLastPage),
425
+ isFirstPage: true,
426
+ isLastPage,
427
+ });
428
+ } else {
429
+ this.messagePaginator.reconcileNewestMessages(incomingReplies, reconcile);
430
+ }
600
431
  pendingReplies.forEach((reply) => this.messagePaginator.ingestItem(reply));
601
- // Carry the re-queried thread's last-activity floor so lastMessageAt stays fresh even when the
602
- // merged page does not include the newest reply. Monotonic, so an older value is a no-op.
603
- this.messagePaginator.seedLastMessageAt(thread.messagePaginator.lastMessageAt);
604
432
  };
605
433
 
606
434
  public registerSubscriptions = () => {
607
435
  if (this.hasSubscriptions) {
608
- // Thread is already listening for events and changes
609
436
  return;
610
437
  }
611
438
 
612
439
  this.addUnsubscribeFunction(this.subscribeThreadSetupStateChange());
613
440
  this.addUnsubscribeFunction(this.subscribeParentMessageFromStore());
614
- this.addUnsubscribeFunction(this.subscribeThreadUpdated());
615
441
  this.addUnsubscribeFunction(this.subscribeMarkActiveThreadRead());
616
442
  this.addUnsubscribeFunction(this.subscribeReloadActiveStaleThread());
617
- this.addUnsubscribeFunction(this.subscribeMarkThreadStale());
618
- this.addUnsubscribeFunction(this.subscribeNewReplies());
619
- this.addUnsubscribeFunction(this.subscribeRepliesRead());
620
- this.addUnsubscribeFunction(this.subscribeRepliesUnread());
621
- this.addUnsubscribeFunction(this.subscribeMessageDeleted());
622
- this.addUnsubscribeFunction(this.subscribeMessageUpdated());
623
- this.addUnsubscribeFunction(this.subscribeUserMessagesDeleted());
443
+ this.addUnsubscribeFunction(this.subscribeMarkStaleOnStopWatching());
624
444
  };
625
445
 
626
446
  /**
627
- * Subscribes this thread to the `'thread'` configuration key. Registered through
628
- * `WithSubscriptions`, so `unregisterSubscriptions()` runs the setup function's teardown.
629
- *
630
- * **This is where `Thread` differs from `Channel`,** which subscribes from its constructor. Everything
631
- * below follows from that, and applies to a thread that never calls `registerSubscriptions()`:
632
- *
633
- * - no *setup function* runs for it — matching how `MessageComposer` already behaves;
634
- * - it sees the declarative slice **as it stood when the thread was constructed**, because the
635
- * constructor applies it directly, but no *later* `client.config.set({ thread: … })` or
636
- * `set({ messagePaginator: … })` reaches it;
637
- * - it is absent from the registry's `liveInstances`, so `client.config.reset()` skips it, and
638
- * `hasLiveInstances('thread')` does not count it when deciding whether to warn about a
639
- * construction-only path registered too late.
640
- *
641
- * So read "declarative configuration is unaffected" as *at construction only*. A thread held by a
642
- * `ThreadManager` that has itself registered is covered — `subscribeManageThreadSubscriptions` calls
643
- * `registerSubscriptions()` on every thread entering its state — so the common path is fine. A thread
644
- * constructed directly, or held by an unregistered manager, is not.
645
- *
646
- * The alternative — applying the setup function at construction — would break the teardown symmetry
647
- * `WithSubscriptions` provides, which is why the asymmetry stands.
447
+ * Subscribes to the `'thread'` configuration key. Unlike `Channel`, which subscribes in its
448
+ * constructor, a thread that never registers sees the declarative slice only as of construction:
449
+ * no setup function runs, later `client.config.set` calls miss it and `client.config.reset()`
450
+ * skips it. `ThreadManager` registers the threads it holds (listed, `ensure()`d or active) while
451
+ * its own subscriptions are registered.
648
452
  */
649
453
  private subscribeThreadSetupStateChange = () =>
650
454
  applyInstanceConfiguration({
@@ -655,26 +459,25 @@ export class Thread extends WithSubscriptions {
655
459
  // Read fresh: by the time reset calls this, the declarative store has been cleared.
656
460
  reinitializeConfig: () =>
657
461
  this.initializeConfig(this.client.config.getConfig('thread') ?? undefined),
658
- // The reply paginator also derives from the shared `messagePaginator` key — run the full cycle
659
- // on a change there, so the setup function's overrides survive.
462
+ // Also rerun on the shared keys the reply paginator and operations derive from, so the setup
463
+ // function's overrides survive.
660
464
  alsoWatch: ['messagePaginator', 'messageOperations'],
661
465
  });
662
466
 
663
- private subscribeThreadUpdated = () =>
664
- this.client.on('thread.updated', (event) => {
665
- if (!event.thread || event.thread.parent_message_id !== this.id) {
666
- return;
667
- }
467
+ public handleThreadUpdated = (event: EventPayload<'thread.updated'>) => {
468
+ if (!event.thread || event.thread.parent_message_id !== this.id) {
469
+ return;
470
+ }
668
471
 
669
- const threadData = event.thread;
472
+ const threadData = event.thread;
670
473
 
671
- this.state.partialNext({
672
- title: threadData.title,
673
- updatedAt: threadData.updated_at,
674
- deletedAt: threadData.deleted_at ?? null,
675
- custom: threadData.custom ?? {},
676
- });
677
- }).unsubscribe;
474
+ this.state.partialNext({
475
+ title: threadData.title,
476
+ updatedAt: threadData.updated_at,
477
+ deletedAt: threadData.deleted_at ?? null,
478
+ custom: threadData.custom ?? {},
479
+ });
480
+ };
678
481
 
679
482
  private subscribeMarkActiveThreadRead = () =>
680
483
  this.state.subscribeWithSelector(
@@ -698,251 +501,194 @@ export class Thread extends WithSubscriptions {
698
501
  },
699
502
  );
700
503
 
701
- private subscribeMarkThreadStale = () =>
702
- this.client.on('user.watching.stop', (event: PipelineEvent) => {
703
- const { channel } = this.state.getLatestValue();
704
-
705
- if (
706
- !this.client.userId ||
707
- this.client.userId !== event.user?.id ||
708
- event.channel?.cid !== channel.cid
709
- ) {
710
- return;
711
- }
712
-
713
- this.state.partialNext({ isStateStale: true });
714
- }).unsubscribe;
504
+ /**
505
+ * A watch stopped while the connection stays up (`NotWatching`) ends the channel's events with no
506
+ * reconnect to catch it. A dropped connection (`WasWatching`) is left to recovery.
507
+ */
508
+ private subscribeMarkStaleOnStopWatching = () =>
509
+ this.channel.state.subscribeWithSelector(
510
+ ({ watchStatus }) => ({ watchStatus }),
511
+ ({ watchStatus }, previous) => {
512
+ if (
513
+ previous?.watchStatus === ChannelWatchStatus.Watching &&
514
+ watchStatus === ChannelWatchStatus.NotWatching
515
+ ) {
516
+ this.state.partialNext({ isStateStale: true });
517
+ }
518
+ },
519
+ );
715
520
 
716
- private subscribeRepliesUnread = () =>
717
- this.client.on('notification.mark_unread', (event) => {
718
- if (!event.user || event.created_at == null || !event.thread_id) return;
719
- if (event.thread_id !== this.id) return;
521
+ public handleRepliesUnread = (event: EventPayload<'notification.mark_unread'>) => {
522
+ if (!event.user || event.created_at == null || !event.thread_id) return;
523
+ if (event.thread_id !== this.id) return;
524
+
525
+ const userId = event.user.id;
526
+ const createdAt = event.created_at;
527
+ const user = event.user;
528
+
529
+ this.state.next((current) => ({
530
+ ...current,
531
+ read: {
532
+ ...current.read,
533
+ [userId]: {
534
+ ...current.read[userId],
535
+ lastReadAt: timestampOr(event.last_read_at, createdAt),
536
+ user,
537
+ firstUnreadMessageId: event.first_unread_message_id,
538
+ unreadMessageCount: event.unread_messages ?? 0,
539
+ },
540
+ },
541
+ }));
542
+ };
720
543
 
721
- const userId = event.user.id;
722
- const createdAt = event.created_at;
723
- const user = event.user;
544
+ public handleNewReply = (event: EventPayload<'message.new'>) => {
545
+ if (!this.client.userId || event.message?.parent_id !== this.id) {
546
+ return;
547
+ }
724
548
 
725
- this.state.next((current) => ({
726
- ...current,
727
- read: {
728
- ...current.read,
729
- [userId]: {
730
- ...current.read[userId],
731
- lastReadAt: timestampOr(event.last_read_at, createdAt),
732
- user,
733
- firstUnreadMessageId: event.first_unread_message_id,
734
- unreadMessageCount: event.unread_messages ?? 0,
735
- },
736
- },
737
- }));
738
- }).unsubscribe;
549
+ const isOwnMessage = event.message.user?.id === this.client.userId;
550
+ const { active, read } = this.state.getLatestValue();
739
551
 
740
- private subscribeNewReplies = () =>
741
- this.client.on('message.new', (event) => {
742
- if (!this.client.userId || event.message?.parent_id !== this.id) {
743
- return;
744
- }
552
+ this.upsertReplyLocally({
553
+ message: event.message,
554
+ timestampChanged: isOwnMessage,
555
+ });
745
556
 
746
- const isOwnMessage = event.message.user?.id === this.client.userId;
747
- const { active, read } = this.state.getLatestValue();
557
+ if (active) {
558
+ this.throttledMarkRead();
559
+ }
748
560
 
749
- this.upsertReplyLocally({
750
- message: event.message,
751
- // MessageRequest from current user could have been added optimistically,
752
- // so the actual timestamp might differ in the event
753
- timestampChanged: isOwnMessage,
754
- });
561
+ const nextRead: ThreadReadState = {};
755
562
 
756
- if (active) {
757
- this.throttledMarkRead();
758
- }
563
+ for (const userId of Object.keys(read)) {
564
+ const userRead = read[userId];
759
565
 
760
- const nextRead: ThreadReadState = {};
761
-
762
- for (const userId of Object.keys(read)) {
763
- const userRead = read[userId];
764
-
765
- if (userRead) {
766
- let nextUserRead: ThreadUserReadState = userRead;
767
-
768
- if (userId === event.user?.id) {
769
- // The user who just sent a message to the thread has no unread messages
770
- // in that thread
771
- nextUserRead = {
772
- ...nextUserRead,
773
- lastReadAt: timestampOr(event.created_at, nowNs()),
774
- user: event.user,
775
- unreadMessageCount: 0,
776
- };
777
- } else if (active && userId === this.client.userId) {
778
- // Do not increment unread count for the current user in an active thread
779
- } else {
780
- // Increment unread count for all users except the author of the new message
781
- nextUserRead = {
782
- ...nextUserRead,
783
- unreadMessageCount: userRead.unreadMessageCount + 1,
784
- };
785
- }
566
+ if (userRead) {
567
+ let nextUserRead: ThreadUserReadState = userRead;
786
568
 
787
- nextRead[userId] = nextUserRead;
569
+ if (userId === event.user?.id) {
570
+ // The sender has no unread messages.
571
+ nextUserRead = {
572
+ ...nextUserRead,
573
+ lastReadAt: timestampOr(event.created_at, nowNs()),
574
+ user: event.user,
575
+ unreadMessageCount: 0,
576
+ };
577
+ } else if (active && userId === this.client.userId) {
578
+ // Do not increment unread count for the current user in an active thread
579
+ } else {
580
+ nextUserRead = {
581
+ ...nextUserRead,
582
+ unreadMessageCount: userRead.unreadMessageCount + 1,
583
+ };
788
584
  }
789
- }
790
585
 
791
- this.state.partialNext({ read: nextRead });
792
- }).unsubscribe;
793
-
794
- private subscribeRepliesRead = () =>
795
- this.client.on('message.read', (event) => {
796
- if (!event.user || event.created_at == null || !event.thread) return;
797
- if (event.thread.parent_message_id !== this.id) return;
586
+ nextRead[userId] = nextUserRead;
587
+ }
588
+ }
798
589
 
799
- const userId = event.user.id;
800
- const createdAt = event.created_at;
801
- const user = event.user;
590
+ this.state.partialNext({ read: nextRead });
591
+ };
802
592
 
803
- this.state.next((current) => ({
804
- ...current,
805
- read: {
806
- ...current.read,
807
- [userId]: {
808
- lastReadAt: createdAt,
809
- user,
810
- lastReadMessageId: event.last_read_message_id,
811
- unreadMessageCount: 0,
812
- },
593
+ public handleRepliesRead = (event: EventPayload<'message.read'>) => {
594
+ if (!event.user || event.created_at == null || !event.thread) return;
595
+ if (event.thread.parent_message_id !== this.id) return;
596
+
597
+ const userId = event.user.id;
598
+ const createdAt = event.created_at;
599
+ const user = event.user;
600
+
601
+ this.state.next((current) => ({
602
+ ...current,
603
+ read: {
604
+ ...current.read,
605
+ [userId]: {
606
+ lastReadAt: createdAt,
607
+ user,
608
+ lastReadMessageId: event.last_read_message_id,
609
+ unreadMessageCount: 0,
813
610
  },
814
- }));
815
- }).unsubscribe;
611
+ },
612
+ }));
613
+ };
816
614
 
817
- private subscribeMessageDeleted = () =>
818
- this.client.on('message.deleted', (event) => {
819
- if (!event.message) return;
820
- const formattedMessage = formatMessage(event.message);
615
+ public handleMessageDeleted = (event: EventPayload<'message.deleted'>) => {
616
+ if (!event.message) return;
617
+ const formattedMessage = formatMessage(event.message);
821
618
 
822
- // Deleted message is a reply of this thread
823
- if (event.message.parent_id === this.id) {
824
- if (event.hard_delete) {
825
- this.deleteReplyLocally({ message: event.message });
826
- } else {
827
- // Handle soft delete (updates deleted_at timestamp)
828
- this.upsertReplyLocally({ message: event.message });
829
- }
619
+ if (event.message.parent_id === this.id) {
620
+ if (event.hard_delete) {
621
+ this.deleteReplyLocally({ message: event.message });
622
+ } else {
623
+ this.upsertReplyLocally({ message: event.message });
830
624
  }
625
+ }
831
626
 
832
- // Deleted message is parent message of this thread
833
- if (event.message.id === this.id) {
834
- this.updateParentMessageLocally({ message: event.message });
835
- }
627
+ if (event.message.id === this.id) {
628
+ this.updateParentMessageLocally({ message: event.message });
629
+ }
836
630
 
837
- this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
838
- }).unsubscribe;
839
-
840
- private subscribeMessageUpdated = () => {
841
- const messageUpdateTypes: EventType[] = ['message.updated', 'message.undeleted'];
842
- const reactionTypes: EventType[] = [
843
- 'reaction.new',
844
- 'reaction.deleted',
845
- 'reaction.updated',
846
- ];
847
-
848
- const unsubscribeMessageUpdated = messageUpdateTypes.map(
849
- (eventType) =>
850
- this.client.on(eventType, (event: PipelineEvent) => {
851
- if (!event.message) return;
852
- // A `message.updated` WS event carries `own_reactions: []`; upserting it verbatim would
853
- // wipe the current user's reactions on an edit. Preserve them off the copy we already hold
854
- // — the reply paginator for a reply, `state.parentMessage` for the parent (the parent is
855
- // not held in any paginator, so it needs the same treatment directly).
856
- const message =
857
- event.message.parent_id === this.id
858
- ? {
859
- ...event.message,
860
- own_reactions:
861
- this.messagePaginator.getItem(event.message.id)?.own_reactions ??
862
- event.message.own_reactions,
863
- }
864
- : !event.message.parent_id && event.message.id === this.id
865
- ? {
866
- ...event.message,
867
- own_reactions:
868
- this.state.getLatestValue().parentMessage?.own_reactions ??
869
- event.message.own_reactions,
870
- }
871
- : event.message;
872
- this.updateParentMessageOrReplyLocally(message);
873
- this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
874
- }).unsubscribe,
875
- );
631
+ this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
632
+ };
876
633
 
877
- const unsubscribeReactions = reactionTypes.map(
878
- (eventType) =>
879
- this.client.on(eventType, (event: PipelineEvent) => {
880
- if (!event.message || !event.reaction) return;
881
- const { message, reaction } = event;
882
- if (message.parent_id === this.id) {
883
- // Preserve/apply the current user's `own_reactions` off the reply paginator itself,
884
- // independently of the channel (mirrors the channel's main-list reflectReaction).
885
- this.messagePaginator.reflectReaction({
886
- enforceUnique: eventType === 'reaction.updated',
887
- message,
888
- reaction,
889
- removed: eventType === 'reaction.deleted',
890
- });
891
- } else if (!message.parent_id && message.id === this.id) {
892
- // Reaction on the PARENT. The parent isn't in a paginator, so apply the current user's
893
- // own_reactions delta here (mirroring the reply path's reflectReaction) rather than
894
- // copying the WS event verbatim — which would drop own_reactions the event omits.
895
- const own_reactions = computeOwnReactions({
896
- current:
897
- this.state.getLatestValue().parentMessage?.own_reactions ??
898
- message.own_reactions ??
899
- [],
900
- enforceUnique: eventType === 'reaction.updated',
901
- reaction,
902
- removed: eventType === 'reaction.deleted',
903
- userId: this.client.userId,
904
- });
905
- this.updateParentMessageLocally({ message: { ...message, own_reactions } });
634
+ public handleMessageUpdated = (event: PipelineEvent) => {
635
+ if (!event.message) return;
636
+ // A `message.updated` event carries `own_reactions: []`, which would wipe the current user's
637
+ // reactions: keep them from the held copy (the reply paginator, or `state.parentMessage`).
638
+ const message =
639
+ event.message.parent_id === this.id
640
+ ? {
641
+ ...event.message,
642
+ own_reactions:
643
+ this.messagePaginator.getItem(event.message.id)?.own_reactions ??
644
+ event.message.own_reactions,
906
645
  }
907
- this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(message));
908
- }).unsubscribe,
909
- );
910
-
911
- const unsubscribeFunctions = [...unsubscribeMessageUpdated, ...unsubscribeReactions];
646
+ : !event.message.parent_id && event.message.id === this.id
647
+ ? {
648
+ ...event.message,
649
+ own_reactions:
650
+ this.state.getLatestValue().parentMessage?.own_reactions ??
651
+ event.message.own_reactions,
652
+ }
653
+ : event.message;
654
+ this.updateParentMessageOrReplyLocally(message);
655
+ this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
656
+ };
912
657
 
913
- return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
658
+ public handleReactionChanged = (event: PipelineEvent) => {
659
+ if (!event.message || !event.reaction) return;
660
+ const { message } = event;
661
+ this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(message));
914
662
  };
915
663
 
916
- private subscribeUserMessagesDeleted = () => {
917
- // Apply a user ban / deletion to this thread's own reply list. Previously
918
- // channel.state.deleteUserMessages marked banned-user replies deleted in the (now removed)
919
- // channel.state.threads shadow; the reply paginator is the thread's source of truth now.
920
- const eventTypes: EventType[] = ['user.messages.deleted', 'user.deleted'];
921
-
922
- const unsubscribeFunctions = eventTypes.map(
923
- (eventType) =>
924
- this.client.on(eventType, (event: PipelineEvent) => {
925
- if (!event.user) return;
926
- // user.deleted carries the deletion time on the user; user.messages.deleted on the event.
927
- const deletedAtSource =
928
- eventType === 'user.deleted' ? event.user.deleted_at : event.created_at;
929
- this.messagePaginator.applyMessageDeletionForUser({
930
- userId: event.user.id,
931
- hardDelete: !!event.hard_delete,
932
- deletedAt: deletedAtSource ?? nowNs(),
933
- });
934
- }).unsubscribe,
935
- );
664
+ public handleUserUpdated = (event: PipelineEvent) => {
665
+ const { user } = event;
666
+ if (!user) return;
667
+ this.messagePaginator.reflectUserUpdate(user);
668
+
669
+ // the parent message might not yet be loaded in channel.messagePaginator
670
+ const parent = this.client.messageStore.get(this.id);
671
+ if (parent?.user?.id === user.id && parent.user !== user) {
672
+ this.client.messageStore.upsert({ ...parent, user });
673
+ }
674
+ };
936
675
 
937
- return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
676
+ // Applies a user ban or deletion to this thread's replies.
677
+ public handleUserMessagesDeleted = (event: PipelineEvent) => {
678
+ if (!event.user) return;
679
+ // user.deleted carries the deletion time on the user; user.messages.deleted on the event.
680
+ const deletedAtSource =
681
+ event.type === 'user.deleted' ? event.user.deleted_at : event.created_at;
682
+ this.messagePaginator.applyMessageDeletionForUser({
683
+ userId: event.user.id,
684
+ hardDelete: !!event.hard_delete,
685
+ deletedAt: deletedAtSource ?? nowNs(),
686
+ });
938
687
  };
939
688
 
940
- // The parent message lives in the client-global message store (one canonical POJO per id);
941
- // `state.parentMessage` and the fields derived from it are a projection of that copy. Every update
942
- // to the parent — optimistic reaction, WS reaction/edit/delete, reply-count bump — writes the
943
- // store, which reflects it here through this single subscription (one per thread, not one per
944
- // message). Seeds the store on first subscribe when no other collection holds the parent yet
945
- // (e.g. a thread opened from a notification, its parent not in the channel window).
689
+ // `state.parentMessage` and its derived fields project the parent in the client-global message
690
+ // store, so every update to the parent reaches them through this one subscription. Seeds the
691
+ // store when no other collection holds the parent yet (e.g. a thread opened from a notification).
946
692
  private subscribeParentMessageFromStore = () => {
947
693
  const store = this.client.messageStore;
948
694
  const parent = this.state.getLatestValue().parentMessage;
@@ -954,9 +700,10 @@ export class Thread extends WithSubscriptions {
954
700
  ...current,
955
701
  deletedAt: message.deleted_at ?? null,
956
702
  parentMessage: message,
957
- participants:
958
- normalizeThreadParticipants(message.thread_participants, current.channel.cid) ??
703
+ participants: mergeThreadParticipants(
959
704
  current.participants,
705
+ normalizeThreadParticipants(message.thread_participants, current.channel.cid),
706
+ ),
960
707
  replyCount: message.reply_count ?? current.replyCount,
961
708
  }));
962
709
  });
@@ -964,11 +711,9 @@ export class Thread extends WithSubscriptions {
964
711
 
965
712
  public unregisterSubscriptions = () => {
966
713
  const symbol = super.unregisterSubscriptions();
967
- // Release the reply paginator's hold on the shared message store. The parent subscription is
968
- // torn down by `super.unregisterSubscriptions()` (it was added as an unsubscribe function), but
969
- // the reply paginator's per-id links live in its item index, not in the subscription list — so a
970
- // removed thread would otherwise stay pinned by `messageStore.subscribers` and keep its replies
971
- // alive. `getThread` builds a fresh instance if this thread is re-opened, so this is a discard.
714
+ // Releases the reply paginator's per-ID links on the shared message store (they are not in the
715
+ // subscription list), which would otherwise pin a removed thread and its replies. `getThread`
716
+ // builds a fresh instance if the thread is re-opened.
972
717
  this.messagePaginator.dispose();
973
718
  this.state.partialNext({ isStateStale: true });
974
719
  return symbol;
@@ -976,8 +721,7 @@ export class Thread extends WithSubscriptions {
976
721
 
977
722
  // todo: can be removed with the next breaking change and use MessagePaginator only
978
723
  public deleteReplyLocally = ({ message }: { message: MessageResponse }) => {
979
- // The reply messagePaginator is the reply list source. removeItem is a no-op when the reply
980
- // isn't loaded, so it's safe to run unconditionally.
724
+ // A no-op when the reply is not loaded.
981
725
  this.messagePaginator.removeItem({ id: message.id });
982
726
  };
983
727
 
@@ -986,8 +730,7 @@ export class Thread extends WithSubscriptions {
986
730
  message,
987
731
  }: {
988
732
  message: MessageResponse | LocalMessage;
989
- // Accepted for backward compatibility but no longer used — the messagePaginator repositions
990
- // by created_at on ingest, so a changed timestamp is handled without an explicit flag.
733
+ // Unused: the reply paginator repositions by `created_at` on ingest.
991
734
  timestampChanged?: boolean;
992
735
  }) => {
993
736
  if (message.parent_id !== this.id) {
@@ -998,13 +741,18 @@ export class Thread extends WithSubscriptions {
998
741
 
999
742
  // todo: do we really need to keep the failedRepliesMap?
1000
743
  if (formattedMessage.status === 'failed') {
1001
- // store failed reply so that it's not lost when reloading or hydrating
744
+ // Kept so a failed reply survives a reload or hydrate.
1002
745
  this.failedRepliesMap.set(formattedMessage.id, formattedMessage);
1003
746
  } else if (this.failedRepliesMap.has(message.id)) {
1004
747
  this.failedRepliesMap.delete(message.id);
1005
748
  }
1006
749
 
1007
- // The reply messagePaginator is the reply list source.
750
+ // Already showing this snapshot (a holder sharing the store wrote it first): skip the ingest.
751
+ // TODO: This can probably be generalized as a safeguard up in ingestItem or maybe even EntityStore
752
+ // (so if a collection exists that holds this referential entity already, just use that or maybe
753
+ // even skip ingestion sometimes when it makes sense). But leaving that for a separate change.
754
+ if (this.messagePaginator.getItem(formattedMessage.id) === formattedMessage) return;
755
+
1008
756
  this.messagePaginator.ingestItem(formattedMessage);
1009
757
  };
1010
758
 
@@ -1014,9 +762,7 @@ export class Thread extends WithSubscriptions {
1014
762
  throw new Error('Message does not belong to this thread');
1015
763
  }
1016
764
 
1017
- // The parent's content lives in the client-global message store; `state.parentMessage` (and the
1018
- // fields derived from it) is a projection kept in sync by `subscribeParentMessageFromStore`.
1019
- // Writing the store fans the change out to every collection holding this id and reflects it here.
765
+ // Written to the message store; `subscribeParentMessageFromStore` projects it into the state.
1020
766
  if (this.client.messageStore.has(message.id)) {
1021
767
  this.client.messageStore.upsert(formatMessage(message));
1022
768
  }
@@ -1033,105 +779,6 @@ export class Thread extends WithSubscriptions {
1033
779
  }
1034
780
  };
1035
781
 
1036
- /**
1037
- * Sends a message with optimistic local state update.
1038
- */
1039
- async sendMessageWithLocalUpdate({
1040
- localMessage,
1041
- message,
1042
- options,
1043
- sendMessageRequestFn,
1044
- }: SendMessageWithStateUpdateParams): Promise<void> {
1045
- await this.messageOperations.send(
1046
- {
1047
- localMessage,
1048
- message,
1049
- options,
1050
- },
1051
- sendMessageRequestFn,
1052
- );
1053
- }
1054
-
1055
- /**
1056
- * Retry sending a failed message.
1057
- */
1058
- async retrySendMessageWithLocalUpdate(
1059
- params: Omit<SendMessageWithStateUpdateParams, 'message'>,
1060
- ) {
1061
- await this.messageOperations.retry(
1062
- {
1063
- localMessage: { ...params.localMessage, type: 'regular' },
1064
- options: params.options,
1065
- },
1066
- params.sendMessageRequestFn,
1067
- );
1068
- }
1069
-
1070
- /**
1071
- * Updates a message with optimistic local state update.
1072
- *
1073
- * The update flows through `messagePaginator`, which is the sole reply source.
1074
- */
1075
- async updateMessageWithLocalUpdate(params: UpdateMessageWithStateUpdateParams) {
1076
- await this.messageOperations.update(
1077
- {
1078
- localMessage: params.localMessage,
1079
- options: params.options,
1080
- },
1081
- params.updateMessageRequestFn,
1082
- );
1083
- }
1084
-
1085
- /**
1086
- * Deletes a message with local state update.
1087
- */
1088
- async deleteMessageWithLocalUpdate(params: DeleteMessageWithStateUpdateParams) {
1089
- await this.messageOperations.delete(
1090
- {
1091
- localMessage: params.localMessage,
1092
- options: params.options,
1093
- },
1094
- params.deleteMessageRequestFn,
1095
- );
1096
- }
1097
-
1098
- /**
1099
- * Adds a reaction to a reply with an optimistic local state update — see
1100
- * {@link addReactionOptimistically}, which `Channel` shares. The request routes through the parent
1101
- * channel because reactions are channel-level, while the local write is addressed by message id and
1102
- * so reaches a pure reply no channel collection holds.
1103
- */
1104
- async addReactionWithLocalUpdate({
1105
- messageId,
1106
- reaction,
1107
- options,
1108
- }: {
1109
- messageId: string;
1110
- reaction: ReactionRequest;
1111
- options?: Pick<SendReactionRequest, 'enforce_unique' | 'skip_push'>;
1112
- }) {
1113
- await addReactionOptimistically({
1114
- channel: this.channel,
1115
- messageId,
1116
- options,
1117
- reaction,
1118
- });
1119
- }
1120
-
1121
- /**
1122
- * Removes the current user's reaction from a reply with an optimistic local state update — see
1123
- * {@link deleteReactionOptimistically}, which `Channel` shares.
1124
- */
1125
- async deleteReactionWithLocalUpdate({
1126
- messageId,
1127
- type,
1128
- }: {
1129
- messageId: string;
1130
- type: string;
1131
- }) {
1132
- await deleteReactionOptimistically({ channel: this.channel, messageId, type });
1133
- }
1134
-
1135
782
  public markRead = async ({ force = false }: { force?: boolean } = {}) => {
1136
783
  if (this.ownUnreadCount === 0 && !force) {
1137
784
  return null;
@@ -1176,6 +823,74 @@ const normalizeThreadParticipants = (
1176
823
  );
1177
824
  };
1178
825
 
826
+ /**
827
+ * Adds the participants a parent message lists to the thread's. The message lists only the users who
828
+ * replied, while a thread response also counts the parent's author, so replacing the thread's list
829
+ * with the message's would drop that author.
830
+ */
831
+ const mergeThreadParticipants = (
832
+ current: ThreadStateResponse['thread_participants'],
833
+ fromMessage: ThreadStateResponse['thread_participants'],
834
+ ): ThreadStateResponse['thread_participants'] => {
835
+ if (!fromMessage) return current;
836
+ if (!current?.length) return fromMessage;
837
+ const known = new Set(current.map((participant) => participant.user_id));
838
+ const added = fromMessage.filter((participant) => !known.has(participant.user_id));
839
+ return added.length ? [...current, ...added] : current;
840
+ };
841
+
842
+ /** `participant_limit` of the single-thread requests (`getThreadAndHydrate`, `reload()`). */
843
+ export const DEFAULT_THREAD_PARTICIPANT_LIMIT = 100;
844
+
845
+ /** The thread's channel, with the members and custom data of `threadData` applied. */
846
+ export const ensureThreadChannel = (
847
+ client: StreamChat,
848
+ threadData: ThreadStateResponse,
849
+ ) => {
850
+ if (!threadData.channel) {
851
+ throw new Error('Thread channel is required when threadData is provided');
852
+ }
853
+ const channel = client.channelManager.ensure({
854
+ type: threadData.channel.type,
855
+ id: threadData.channel.id,
856
+ data: { custom: threadData.channel.custom },
857
+ });
858
+ channel._hydrateMembers({
859
+ members: threadData.channel.members ?? [],
860
+ overrideCurrentState: false,
861
+ });
862
+ return channel;
863
+ };
864
+
865
+ /** Against the top-level `reply_count`: unlike the parent's, it excludes soft-deleted replies. */
866
+ const holdsEveryReply = (replies: LocalMessage[], threadData: ThreadStateResponse) =>
867
+ replies.length === (threadData.reply_count ?? 0);
868
+
869
+ const formatThreadState = (threadData: ThreadStateResponse, currentUserId?: string) => {
870
+ const parentMessage = threadData.parent_message;
871
+ if (!parentMessage) {
872
+ throw new Error('Thread parent_message is required when threadData is provided');
873
+ }
874
+
875
+ return {
876
+ createdAt: threadData.created_at,
877
+ custom: threadData.custom ?? {},
878
+ deletedAt: threadData.deleted_at ?? null,
879
+ parentMessage: formatMessage(parentMessage),
880
+ participants: threadData.thread_participants,
881
+ read: formatReadState(
882
+ !threadData.read || threadData.read.length === 0
883
+ ? getPlaceholderReadResponse(currentUserId)
884
+ : threadData.read,
885
+ ),
886
+ // From the parent message: the top-level `threadData.reply_count` excludes soft-deleted
887
+ // replies, the parent's (like the channel's) includes them.
888
+ replyCount: parentMessage.reply_count ?? 0,
889
+ title: threadData.title,
890
+ updatedAt: threadData.updated_at ?? null,
891
+ };
892
+ };
893
+
1179
894
  const formatReadState = (read: ReadStateResponse[]): ThreadReadState =>
1180
895
  read.reduce<ThreadReadState>((state, userRead) => {
1181
896
  state[userRead.user.id] = {