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,13 +1,15 @@
1
1
  import type {
2
2
  AnyInterval,
3
3
  BasePaginatorConfig,
4
- CursorDerivator,
4
+ CursorDeriveContext,
5
5
  CursorDeriveResult,
6
+ DoRequestResponse,
7
+ ExecuteQueryReturnValue,
6
8
  Interval,
7
9
  PaginationDirection,
8
10
  PaginationQueryParams,
9
- PaginatorCursor,
10
11
  PaginatorState,
12
+ QueryPagePlacement,
11
13
  } from './BasePaginator';
12
14
  import {
13
15
  BasePaginator,
@@ -18,21 +20,25 @@ import {
18
20
  ZERO_PAGE_CURSOR,
19
21
  } from './BasePaginator';
20
22
  import type {
23
+ ChannelStateResponse,
24
+ GetRepliesResponse,
21
25
  LocalMessage,
22
26
  MessagePaginationParams,
23
- MessageResponse,
24
27
  PinnedMessagePaginationOptions,
25
- ReactionResponse,
26
28
  SortParamRequest,
29
+ StreamResponse,
30
+ TimestampNS,
27
31
  UserResponse,
28
32
  } from '../../types';
29
33
  import type { Channel } from '../../channel';
34
+ import type { Thread } from '../../thread';
35
+ import { ChannelWatchStatus } from '../../channel_state';
30
36
  import { CORE_NOTIFICATION_TYPE } from '../../notifications';
31
- import { StateStore } from '../../store';
37
+ import { StateStore } from '@stream-io/state-store';
32
38
  import {
33
- computeOwnReactions,
34
39
  formatMessage,
35
40
  generateUUIDv4,
41
+ isThreadOnlyReply,
36
42
  toDeletedMessage,
37
43
  } from '../../utils';
38
44
  import { makeComparator } from '../sortCompiler';
@@ -44,7 +50,10 @@ import type { EntityStoreChangeBatch } from '../../entityStore/EntityStore';
44
50
  import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
45
51
  import { deriveCreatedAtAroundPaginationFlags } from '../cursorDerivation';
46
52
  import { deriveIdAroundPaginationFlags } from '../cursorDerivation/idAroundPaginationFlags';
47
- import { deriveLinearPaginationFlags } from '../cursorDerivation/linearPaginationFlags';
53
+ import {
54
+ deriveLinearPaginationFlags,
55
+ getLinearQueryDirection,
56
+ } from '../cursorDerivation/linearPaginationFlags';
48
57
 
49
58
  export type MessageFocusReason =
50
59
  | 'jump-to-message'
@@ -65,20 +74,19 @@ export type MessageFocusSignalState = {
65
74
 
66
75
  export type JumpToMessageOptions = {
67
76
  pageSize?: number;
68
- /**
69
- * Optional reason attached to emitted focus signal.
70
- * Defaults to `jump-to-message`.
71
- */
77
+ /** Reason attached to the emitted focus signal. Defaults to `jump-to-message`. */
72
78
  focusReason?: MessageFocusReason;
73
- /**
74
- * TTL for the emitted focus signal in milliseconds.
75
- * Defaults to `3000`.
76
- */
79
+ /** TTL of the emitted focus signal in milliseconds. Defaults to `3000`. */
77
80
  focusSignalTtlMs?: number;
81
+ /** Suppresses the focus signal after a successful jump. */
82
+ suppressFocusSignal?: boolean;
78
83
  /**
79
- * If true, suppresses focus signal emission after a successful jump.
84
+ * Also watches the channel (so it receives events) when it is not watched yet. The request that
85
+ * loads the interval around the message asks to watch too, so it stays one request, and a message
86
+ * already loaded is loaded again. Ignored for a thread's reply list (its request cannot watch)
87
+ * and when the paginator's `doRequest` loads the messages.
80
88
  */
81
- suppressFocusSignal?: boolean;
89
+ watchChannel?: boolean;
82
90
  };
83
91
 
84
92
  export type MessagePaginatorSort = SortParamRequest[];
@@ -102,11 +110,12 @@ export type MessagePaginatorState = PaginatorState<LocalMessage>;
102
110
  export type MessageQueryShape = MessagePaginationParams | PinnedMessagePaginationOptions;
103
111
 
104
112
  /**
105
- * At the moment all the pagination parameters are just different types of cursors, e.g.
106
- * id_lt, id_gt, ...
107
- * But we always paginate within the same list without changing the sorting params.
108
- * It is currently not possible to change the sorting params.
113
+ * Whether a query asks for no messages (`limit: 0`). Its empty page says nothing about the channel,
114
+ * so it must not be read as an empty one.
109
115
  */
116
+ const isQueryForNoMessages = (limit: number) => limit === 0;
117
+
118
+ /** Query shapes are cursors within one list (the sort cannot change), so a change never resets it. */
110
119
  const hasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
111
120
  MessageQueryShape
112
121
  > = () => false;
@@ -116,10 +125,12 @@ const dataFieldFilterResolver: FieldToDataResolver<LocalMessage> = {
116
125
  resolve: (message, path) => resolveDotPathValue(message, path),
117
126
  };
118
127
 
119
- export const getMessageCreatedAtTimestamp = (message: LocalMessage): number | null => {
120
- if (!(message.created_at instanceof Date)) return null;
121
- const timestamp = message.created_at.getTime();
122
- return Number.isFinite(timestamp) ? timestamp : null;
128
+ /** A message's `created_at` (unix nanoseconds), or `null` when absent or not finite. */
129
+ export const getMessageCreatedAtTimestamp = (
130
+ message: LocalMessage | null | undefined,
131
+ ): TimestampNS | null => {
132
+ const timestamp = message?.created_at;
133
+ return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : null;
123
134
  };
124
135
 
125
136
  export type MessagePaginatorOptions = {
@@ -127,140 +138,189 @@ export type MessagePaginatorOptions = {
127
138
  id?: string;
128
139
  itemIndex?: ItemIndexApi<LocalMessage>;
129
140
  parentMessageId?: string;
130
- /**
131
- * Sort passed to backend message/replies query.
132
- * Does not affect in-memory item ordering.
133
- */
141
+ /** Sort sent to the backend messages/replies query. Does not affect in-memory ordering. */
134
142
  requestSort?: MessagePaginatorSort;
135
143
  /**
136
144
  * @deprecated Use `requestSort` instead.
137
145
  */
138
146
  sort?: MessagePaginatorSort;
139
- /**
140
- * In-memory ordering for items exposed by paginator state.
141
- */
147
+ /** In-memory ordering of the items exposed by paginator state. */
142
148
  itemOrder?: MessagePaginatorSort;
149
+ /** The thread whose replies this paginator lists; without it, it lists the channel's messages. */
150
+ thread?: Thread;
143
151
  paginatorOptions?: PaginatorOptions<LocalMessage, MessageQueryShape>;
144
152
  };
145
153
 
146
154
  /**
147
- * Options for {@link MessageIntervalPaginator.mergeNewestPage} that enable destructive
148
- * reconciliation — removing messages that were hard-deleted (by anyone) while the client was
149
- * offline. A hard delete emits no event to other clients, and the merge is otherwise additive, so
150
- * without this such a message lingers as a ghost after reconnect.
151
- *
152
- * Throughout, `page` is the newest window the server returned for `mergeNewestPage`, and "`page`'s
153
- * newest / oldest message" are its bounds by `created_at`. With NO options, `mergeNewestPage` prunes
154
- * any loaded message that falls WITHIN `page`'s `created_at` span but is absent from it —
155
- * unconditionally safe (a message that arrived live during the caller's fetch is always strictly
156
- * newer than `page`'s newest message, so it can never fall in that span). `candidateIds` widens the
157
- * reconcilable window at the TOP edge; `requestedLimit` only tunes the `hasMoreTail` affordance and
158
- * can never remove a message:
155
+ * Options for {@link MessageIntervalPaginator.reconcileNewestMessages} that enable reconciling
156
+ * messages hard-deleted while the client received no events (no event reaches other clients). With
157
+ * no options it prunes loaded messages inside `page`'s `created_at` span that are absent from it,
158
+ * which is always safe: a live arrival is newer than `page`'s newest message.
159
+ * `headIntervalItemIdsAtRequest` widens reconciliation at the top edge; `requestedLimit` says
160
+ * whether the page reached the channel start.
159
161
  */
160
- export type MergeNewestPageOptions = {
162
+ export type ReconcileNewestMessagesOptions = {
161
163
  /**
162
- * The `limit` the caller passed to the query that produced `page`. Used ONLY to derive
163
- * `hasMoreTail` — whether `page` reached the channel's own oldest message — by comparing it to
164
- * `page.length`. It NEVER removes a message (reconciliation stays window-only regardless), so the
165
- * worst a wrong value can do is show/hide the "load older" affordance for one settle. Trusted only
166
- * when no larger than the paginator's own `pageSize` (see
167
- * {@link MessageIntervalPaginator.pageReachedChannelStart}); a larger over-request — e.g.
168
- * `channel.reload` re-fetching the whole loaded window to reconcile as much as possible — may have
169
- * been silently server-capped, so its short page is ignored rather than mistaken for reaching the
170
- * start.
164
+ * The `limit` the caller passed to the query that produced `page`. Compared to `page.length`, it
165
+ * says whether `page` reached the channel start (see
166
+ * {@link MessageIntervalPaginator.pageReachedChannelStart}, which ignores a limit above
167
+ * `pageSize`), deciding `hasMoreTail`, whether `page` can be separated from the head interval by
168
+ * a gap, and whether a reload asks the server about messages deleted below the page (see
169
+ * {@link MessageIntervalPaginator.removeIdsTailwardOfPageIfNothingOlder}). On its own it never
170
+ * removes a message. Pass the limit actually sent: a larger one makes a short page look like the
171
+ * channel start, welding it to the head interval across a real gap.
171
172
  */
172
173
  requestedLimit?: number;
173
174
  /**
174
- * A snapshot of the loaded message ids taken BEFORE the caller's fetch await. Required to prune
175
- * messages NEWER than `page`'s newest message (a hard-deleted newest message) and to reconcile an
176
- * empty `page` (a fully-emptied channel): at/above that top edge a just-deleted message and a
177
- * message that arrived live during the fetch are indistinguishable by timestamp — only the pre-fetch
178
- * snapshot separates them (a live arrival is not in it). Must be captured before the await; the
179
- * paginator's own items at merge time already include any live arrival.
175
+ * The IDs of the head interval's server-confirmed items when the request for `page` went out,
176
+ * taken with {@link MessageIntervalPaginator.getHeadIntervalItemIdsAtRequest} before the request
177
+ * is awaited. Only these prove what `page` says about the head interval:
178
+ *
179
+ * - deletion: at or above `page`'s newest message, and for an empty `page`, only this snapshot
180
+ * tells a just-deleted message from one that arrived live, or was sent, during the request;
181
+ * - contiguity: `page` starts inside the head interval only if its oldest message the head
182
+ * interval could hold is in this snapshot (see `isSeparatedFromHeadByGap`).
183
+ *
184
+ * Only the head interval receives live messages, so only its IDs are needed.
180
185
  */
181
- candidateIds?: ReadonlySet<string>;
186
+ headIntervalItemIdsAtRequest?: ReadonlySet<string>;
187
+ };
188
+
189
+ /** An external query prepared by {@link MessageIntervalPaginator.prepareExternalQuery}. */
190
+ export type PreparedExternalQuery = {
191
+ messagePaginationParams: MessagePaginationParams;
192
+ isNewestPage: boolean;
193
+ placePage: (page: LocalMessage[]) => boolean;
182
194
  };
183
195
 
184
196
  /**
185
- * Options for {@link MessageIntervalPaginator.seedFirstPageSync}, the synchronous channel-open seed.
197
+ * What one of the message paginator's own queries got back, before its page is extracted (see
198
+ * {@link MessageIntervalPaginator.fetchQueryResponse}), by where it came from.
186
199
  */
187
- export type SeedFirstPageOptions = {
188
- /**
189
- * When true and the paginator has already been seeded once, fold the fresh page via
190
- * {@link MessageIntervalPaginator.mergeNewestPage} — merge in place, reconcile offline hard-deletes,
191
- * re-derive the tail cursor, rebuild on a disjoint window, and skip when jumped away from the head —
192
- * instead of a plain first-page ingest. Lets callers (channel.reload, the channel-list hydrate,
193
- * connection recovery) share one reconciling seed path. Left false for the differently-sorted
194
- * pinned list, and a no-op on a cold open (nothing loaded to fold).
195
- */
196
- reconcile?: boolean;
197
- /**
198
- * Pre-fetch snapshot of loaded message ids (captured before the caller's network await), forwarded
199
- * to {@link MergeNewestPageOptions.candidateIds} so a hard-deleted NEWEST message is reconciled
200
- * without mistaking a message that arrived live during the fetch for a delete. Only consulted when
201
- * {@link reconcile} is set and a window is already loaded.
202
- */
203
- candidateIds?: ReadonlySet<string>;
204
- };
200
+ export type MessageQueryResponse =
201
+ | {
202
+ /** what a custom `doRequest` returned: the page, used as is */
203
+ doRequestResponse: DoRequestResponse<LocalMessage>;
204
+ source: 'doRequest';
205
+ }
206
+ | {
207
+ /** the replies endpoint's response for a thread's reply list */
208
+ repliesResponse: GetRepliesResponse;
209
+ source: 'replies';
210
+ }
211
+ | {
212
+ /** the response of a channel query: its messages, and the rest, applied once they are placed */
213
+ channelResponse: StreamResponse<ChannelStateResponse>;
214
+ source: 'channel';
215
+ /** whether the query watched the channel, which applying the response records */
216
+ watch: boolean;
217
+ };
205
218
 
206
219
  /**
207
- * MessageIntervalPaginator allows configuring backend request sort, while keeping internal item ordering stable.
208
- * Filtering of ingested items is still limited to local predicates (`filterQueryResults`).
220
+ * A message list with a configurable backend request sort and a stable in-memory item order.
221
+ * Ingested items are filtered only by local predicates (`filterQueryResults`).
209
222
  */
210
223
  export class MessageIntervalPaginator extends BasePaginator<
211
224
  LocalMessage,
212
- MessageQueryShape
225
+ MessageQueryShape,
226
+ MessageQueryResponse
213
227
  > {
228
+ /**
229
+ * Holder name of this list's index in the message store. A getter, so a subclass's value is in
230
+ * place while the base constructor builds the index.
231
+ */
232
+ protected get holderName() {
233
+ return 'message-interval-paginator';
234
+ }
235
+
214
236
  declare state: StateStore<MessagePaginatorState>;
215
237
  private readonly _id: string;
216
- protected channel: Channel;
217
- protected parentMessageId?: string;
238
+ /** The channel this list belongs to. A thread's reply list holds its parent channel. */
239
+ readonly channel: Channel;
240
+ /** See {@link MessagePaginatorOptions.thread}. */
241
+ readonly thread?: Thread;
242
+ /** Set when this is a thread's reply list, to the parent message's ID. */
243
+ readonly parentMessageId?: string;
218
244
  readonly messageFocusSignal: StateStore<MessageFocusSignalState>;
219
245
  private clearMessageFocusSignalTimeoutId: ReturnType<typeof setTimeout> | null = null;
220
246
  private messageFocusSignalToken = 0;
221
247
  protected _requestSort = DEFAULT_BACKEND_SORT;
222
248
  protected _itemOrder: MessagePaginatorSort = DEFAULT_BACKEND_SORT;
223
- protected _nextQueryShape: MessageQueryShape | undefined;
224
- /** Pending below-window reached-start probe (exposed for deterministic test awaiting). */
225
- private _belowWindowReconcile?: Promise<void>;
249
+ /** The pending {@link removeIdsTailwardOfPageIfNothingOlder} (kept so tests can await it). */
250
+ private _pendingTailwardOfPageRemoval?: Promise<void>;
251
+ /**
252
+ * The ID of the newest server-confirmed message of the interval whose head mark was cleared last
253
+ * (see {@link unmarkedHeadInterval}). Forgotten once a newest page is reconciled with no head
254
+ * interval loaded, and when the loaded intervals are cleared.
255
+ */
256
+ private unmarkedHeadEdgeId: string | undefined;
226
257
  sortComparator: (a: LocalMessage, b: LocalMessage) => number;
227
258
  /**
228
- * Single source of truth for whether a message should be included in paginator intervals/state.
229
- * Keep this consistent with `filterQueryResults` AND cursor flag derivation.
259
+ * Whether a message belongs in intervals and state. Keep it consistent with `filterQueryResults`
260
+ * and with the page the linear cursor flag derivation reads (see {@link deriveCursorFromPage}).
230
261
  */
231
262
  shouldIncludeMessageInInterval(message: LocalMessage): boolean {
232
263
  return !message.shadowed;
233
264
  }
234
265
 
235
266
  /**
236
- * Entity-store adapter (this paginator is an `EntityStoreSubscriber`): the `EntityStore` calls this
237
- * on each holder with the subset of its watched ids that changed. Unwraps the batch and delegates to
238
- * the base's store-agnostic {@link BasePaginator.reconcileChangedIds}. Lives here, not on the generic
239
- * `BasePaginator`, so the base stays free of `EntityStore` types — only message paginators are
240
- * store-backed.
267
+ * Reconciles the held messages that changed in the entity store.
268
+ *
269
+ * @internal
270
+ * @param batch - The change batch from the store.
271
+ * @param batch.changedIds - IDs of the watched messages that changed.
241
272
  */
242
273
  onEntitiesChanged({ changedIds }: EntityStoreChangeBatch): void {
243
274
  this.reconcileChangedIds(changedIds);
244
275
  }
245
276
 
246
277
  /**
247
- * Entity-store subscriber flush (the optional `EntityStoreSubscriber.flushState`): the `EntityStore`
248
- * calls this after an optimistic (local-user) write so the change renders without throttle delay.
249
- * Delegates to the base's generic {@link BasePaginator.flushPendingPublishes}.
278
+ * Drops a message from this paginator's intervals after the entity store removed it.
279
+ *
280
+ * @internal
281
+ * @param id - ID of the removed message.
282
+ * @param message - The removed message.
250
283
  */
284
+ onEntityRemoved(id: string, message: unknown): void {
285
+ this.removeItem({ id, item: message as LocalMessage });
286
+ }
287
+
288
+ /** Entity-store subscriber flush after an optimistic (local-user) write: skips the throttle. */
251
289
  flushState(): void {
252
290
  this.flushPendingPublishes();
253
291
  }
254
292
 
293
+ /** UI-driven "hold off on pruning" signal ({@link setPruningSuspended}). Off by default. */
294
+ protected get isPruningSuspended(): boolean {
295
+ return this._pruningSuspended;
296
+ }
297
+
298
+ private _pruningSuspended = false;
299
+
300
+ /**
301
+ * Holds off dropping the oldest loaded messages, so pruning does not pull content from under a user
302
+ * reading near them: the interval may grow past `maxLoadedItems` until they scroll back. A plain
303
+ * field, not a `StateStore`: nothing observes it and a scroll-driven signal must not cost a render.
304
+ */
305
+ setPruningSuspended = (suspended: boolean) => {
306
+ this._pruningSuspended = suspended;
307
+ };
308
+
309
+ /**
310
+ * A message anchors pagination once the server has acknowledged it. This keeps an unsent message
311
+ * out of both halves of a prune and stops its ID from becoming the tailward cursor (`id_lt`).
312
+ */
313
+ protected isPaginationAnchorable(item: LocalMessage | undefined): boolean {
314
+ return !!item && this.isServerConfirmedMessage(item);
315
+ }
316
+
255
317
  protected get intervalItemIdsAreHeadFirst(): boolean {
256
- // Messages are stored in chronological order (created_at asc) within an interval.
257
- // Pagination "head" (newest side) is therefore at the END of the `itemIds` array.
318
+ // Intervals hold messages in `created_at` ascending order: the head (newest) is at the END.
258
319
  return false;
259
320
  }
260
321
 
261
322
  protected get intervalSortDirection(): 'asc' | 'desc' {
262
- // Head edge is newest, but sortComparator is created_at asc => newer head edges
263
- // should come first => reverse interval ordering.
323
+ // `itemOrderComparator` is `created_at` ascending but newer head edges must come first.
264
324
  return 'desc';
265
325
  }
266
326
 
@@ -274,6 +334,7 @@ export class MessageIntervalPaginator extends BasePaginator<
274
334
  sort,
275
335
  itemOrder,
276
336
  paginatorOptions,
337
+ thread,
277
338
  }: MessagePaginatorOptions,
278
339
  builtInDefaults: Partial<BasePaginatorConfig<LocalMessage, MessageQueryShape>> = {},
279
340
  ) {
@@ -283,12 +344,9 @@ export class MessageIntervalPaginator extends BasePaginator<
283
344
  {
284
345
  itemIndex,
285
346
  ...paginatorOptions,
286
- // Back every message-interval paginator (channel main list, thread reply list, pinned list)
287
- // with the client-global message store, so a message held in more than one of them has a
288
- // single canonical copy and updates (reactions/edits) fan out to all holders — no copy-to-copy
289
- // sync. When the store is unavailable (e.g. a detached paginator in a test) the index falls
290
- // back to a private store and behaves exactly like a plain per-instance index. Overridable per
291
- // instance via `paginatorOptions.createItemIndex` or an explicit `itemIndex`.
347
+ // Backed by the client's message store: a message held in several lists has one canonical
348
+ // copy and updates fan out to all holders. Without a store (e.g. a detached paginator in a
349
+ // test) the index is private. Overridable via `paginatorOptions.createItemIndex`/`itemIndex`.
292
350
  createItemIndex:
293
351
  paginatorOptions?.createItemIndex ??
294
352
  ((owner) =>
@@ -296,11 +354,10 @@ export class MessageIntervalPaginator extends BasePaginator<
296
354
  store: channel.getClient?.().messageStore,
297
355
  owner: owner as MessageIntervalPaginator,
298
356
  getEntityId: owner.getItemId.bind(owner),
357
+ holderName: (owner as MessageIntervalPaginator).holderName,
299
358
  })),
300
359
  },
301
- // SDK-supplied, so a declarative registration overrides them. `hasPaginationQueryShapeChanged`
302
- // and the zero cursor were previously spread into the caller's options, where they outranked
303
- // every `client.config.set({ messagePaginator: … })`.
360
+ // SDK defaults: a declarative registration (`client.config.set({ messagePaginator })`) wins.
304
361
  {
305
362
  hasPaginationQueryShapeChanged,
306
363
  initialCursor: ZERO_PAGE_CURSOR,
@@ -309,6 +366,7 @@ export class MessageIntervalPaginator extends BasePaginator<
309
366
  },
310
367
  );
311
368
  this.channel = channel;
369
+ this.thread = thread;
312
370
  this.parentMessageId = parentMessageId;
313
371
  this._id = id ?? `message-paginator-${generateUUIDv4()}`;
314
372
  this._requestSort = resolvedRequestSort;
@@ -330,12 +388,8 @@ export class MessageIntervalPaginator extends BasePaginator<
330
388
  }
331
389
 
332
390
  /**
333
- * Memoized so every derivation sees the *same* two functions. `initializeConfig` folds this into the
334
- * config it publishes and skips the publish when nothing moved — which only works if these references
335
- * are stable.
336
- *
337
- * Safe to build once: both close over `this` and read `_itemOrder`, which is assigned in the
338
- * constructor and has no setter.
391
+ * Memoized: `initializeConfig` folds it in and skips the publish when nothing moved, which needs
392
+ * stable references. Safe to build once: `_itemOrder` is set in the constructor, with no setter.
339
393
  */
340
394
  private intervalBehaviour?: Partial<
341
395
  BasePaginatorConfig<LocalMessage, MessageQueryShape>
@@ -346,7 +400,7 @@ export class MessageIntervalPaginator extends BasePaginator<
346
400
  > {
347
401
  if (!this.intervalBehaviour) {
348
402
  this.intervalBehaviour = {
349
- deriveCursor: makeDeriveCursor(this),
403
+ deriveCursor: (ctx) => this.deriveCursorFromPage(ctx),
350
404
  itemOrderComparator: makeComparator<LocalMessage>({
351
405
  sort: this._itemOrder,
352
406
  resolvePathValue: resolveDotPathValue,
@@ -362,12 +416,8 @@ export class MessageIntervalPaginator extends BasePaginator<
362
416
  }
363
417
 
364
418
  /**
365
- * Cursor derivation and in-memory item ordering, which this class installs on `config` rather than
366
- * passing as constructor options.
367
- *
368
- * Contributed to the base derivation rather than written after it — see
369
- * {@link BasePaginator.getBehaviourOverrides}. That is what keeps one re-derivation to one publish,
370
- * and stops the intermediate publish that had these two stripped.
419
+ * Installs cursor derivation and item ordering on `config` through the base derivation
420
+ * ({@link BasePaginator.getBehaviourOverrides}), so one re-derivation is one publish.
371
421
  */
372
422
  protected override getBehaviourOverrides(): Partial<
373
423
  BasePaginatorConfig<LocalMessage, MessageQueryShape>
@@ -376,9 +426,8 @@ export class MessageIntervalPaginator extends BasePaginator<
376
426
  }
377
427
 
378
428
  /**
379
- * The constructor's route to the same overlay. Deliberately calls the private builder rather than the
380
- * overridable hook: this runs inside the constructor, and a subclass override would execute before its
381
- * own fields were initialized.
429
+ * The constructor's route to the same overlay. It calls the private builder, not the overridable
430
+ * hook, which would run a subclass override before its fields are initialized.
382
431
  */
383
432
  protected installIntervalBehaviour(): void {
384
433
  this.updateConfig(this.buildIntervalBehaviour());
@@ -400,25 +449,23 @@ export class MessageIntervalPaginator extends BasePaginator<
400
449
  return this._itemOrder ?? this._requestSort ?? DEFAULT_BACKEND_SORT;
401
450
  }
402
451
 
403
- /**
404
- * Even though we do not send filters object to the server, we need to have filters for client-side item ingestion logic.
405
- */
452
+ /** Not sent to the server: drives client-side item ingestion. */
406
453
  buildMatchFilters = (): MessagePaginatorFilter => ({
407
454
  cid: this.channel.cid,
408
455
  ...(this.parentMessageId ? { parent_id: this.parentMessageId } : {}),
409
456
  });
410
457
 
411
- // invoked inside BasePaginator.executeQuery() to keep it as a query descriptor;
412
458
  protected getNextQueryShape({
413
459
  direction,
414
460
  }: Omit<
415
461
  PaginationQueryParams<MessageQueryShape>,
416
462
  'isFirstPageQuery'
417
463
  >): MessageQueryShape {
464
+ // no server-known message at that edge: no cursor, so the query returns the newest page
465
+ const cursorId = direction ? this.cursor?.[direction] : undefined;
418
466
  return {
419
467
  limit: this.pageSize,
420
- [direction === 'tailward' ? 'id_lt' : 'id_gt']:
421
- direction && this.cursor?.[direction],
468
+ ...(cursorId && { [direction === 'tailward' ? 'id_lt' : 'id_gt']: cursorId }),
422
469
  };
423
470
  }
424
471
 
@@ -429,131 +476,334 @@ export class MessageIntervalPaginator extends BasePaginator<
429
476
  direction?: PaginationDirection;
430
477
  items: LocalMessage[];
431
478
  }) => {
432
- if (!items.length) {
479
+ // Newer side is the pagination head for messages.
480
+ const { head, tail } = this.getPagePaginationEdges(items);
481
+ if (!head || !tail) {
433
482
  return {
434
483
  tailward: undefined,
435
484
  headward: undefined,
436
485
  };
437
486
  }
438
487
 
439
- const start = items[0];
440
- const end = items[items.length - 1];
441
-
442
- // Newer side is the pagination head for messages. Which bound is considered "head"
443
- // is determined by intervalItemIdsAreHeadFirst (see BasePaginator.getIntervalPaginationEdges).
444
- const head = this.intervalItemIdsAreHeadFirst ? start : end;
445
- const tail = this.intervalItemIdsAreHeadFirst ? end : start;
446
-
447
- // if there is no direction, then we are jumping, and we want to set both directions in the cursor
488
+ // Without a direction this is a jump: set both cursors.
448
489
  return {
449
490
  tailward: !direction || direction === 'tailward' ? this.getItemId(tail) : undefined,
450
491
  headward: !direction || direction === 'headward' ? this.getItemId(head) : undefined,
451
492
  };
452
493
  };
453
494
 
454
- query = async ({
495
+ /**
496
+ * Runs the query pipeline (see `BasePaginator.executeQuery`). A query that goes to the channel —
497
+ * not a thread's reply list, not a custom `doRequest` — runs as a tracked query of the channel
498
+ * (`Channel.runTrackedQuery`), so the channel store keeps the channel until the query ends. A
499
+ * disposed channel's query is not tracked: its fetch step is refused, and fails as any failed
500
+ * request does.
501
+ */
502
+ override executeQuery(
503
+ params: PaginationQueryParams<MessageQueryShape> = {},
504
+ ): Promise<ExecuteQueryReturnValue<LocalMessage> | void> {
505
+ const queriesChannel =
506
+ !this.parentMessageId && !this.config.doRequest && !this.channel.pendingDisposal;
507
+ if (!queriesChannel) return super.executeQuery(params);
508
+ return this.channel.runTrackedQuery(() => super.executeQuery(params));
509
+ }
510
+
511
+ /**
512
+ * The fetching step of the query pipeline: requests a page through a custom `doRequest`, the
513
+ * replies endpoint for a thread's reply list, or the channel query otherwise, which takes in what
514
+ * the response says about the channel itself and leaves the rest for the last step (see
515
+ * `Channel.requestChannelState`). Reads `requestOptions.watch`: `true` also watches the channel
516
+ * with the request. Ignored for a thread's reply list and with `doRequest`.
517
+ */
518
+ protected override fetchQueryResponse = async ({
455
519
  direction,
456
- }: PaginationQueryParams<MessageQueryShape>): Promise<
457
- PaginationQueryReturnValue<LocalMessage>
458
- > => {
459
- // get the params only if they were not generated previously
460
- if (!this._nextQueryShape) {
461
- this._nextQueryShape = this.getNextQueryShape({ direction });
462
- }
520
+ queryShape,
521
+ requestOptions,
522
+ }: PaginationQueryParams<MessageQueryShape>): Promise<MessageQueryResponse> => {
523
+ const options = queryShape ?? this.getNextQueryShape({ direction });
463
524
 
464
- const options = this._nextQueryShape;
465
- let items: LocalMessage[];
466
- let tailward: string | undefined;
467
- let headward: string | undefined;
468
525
  if (this.config.doRequest) {
469
- const result = await this.config.doRequest(options);
470
- items = this.getCanonicalQueryItems(result?.items ?? []);
471
- // if there is no direction, then we are jumping, and we want to set both directions in the cursor
472
- tailward =
473
- !direction || direction === 'tailward'
474
- ? (result.cursor?.tailward ?? undefined)
475
- : undefined;
476
- headward =
477
- !direction || direction === 'headward'
478
- ? (result.cursor?.headward ?? undefined)
479
- : undefined;
480
- } else {
481
- const { messages } = this.parentMessageId
482
- ? await this.channel.getClient().getReplies({
483
- parent_id: this.parentMessageId,
484
- ...options,
485
- sort: this.requestSort,
486
- })
487
- : await this.channel.query({
488
- messages: options as MessagePaginationParams,
489
- // todo: why do we query for watchers?
490
- // watchers: { limit: this.pageSize },
491
- });
492
- items = this.getCanonicalQueryItems(messages.map(formatMessage));
493
- const cursor = this.getCursorFromQueryResults({ direction, items });
494
- tailward = cursor.tailward;
495
- headward = cursor.headward;
526
+ return {
527
+ doRequestResponse: await this.config.doRequest(options),
528
+ source: 'doRequest',
529
+ };
496
530
  }
497
-
498
- return { items, headward, tailward };
531
+ if (this.parentMessageId) {
532
+ const repliesResponse = await this.channel
533
+ .getClient()
534
+ .getReplies(
535
+ { parent_id: this.parentMessageId },
536
+ { ...options, sort: this.getRepliesRequestSort(options) },
537
+ );
538
+ return { repliesResponse, source: 'replies' };
539
+ }
540
+ const watch = requestOptions?.watch === true;
541
+ const channelResponse = await this.channel.requestChannelState(
542
+ {
543
+ messages: options as MessagePaginationParams,
544
+ ...(watch && { watch: true }),
545
+ // todo: why do we query for watchers?
546
+ // watchers: { limit: this.pageSize },
547
+ },
548
+ undefined,
549
+ );
550
+ return { channelResponse, source: 'channel', watch };
499
551
  };
500
552
 
501
553
  /**
502
- * Seed the paginator with the page a channel-open query just fetched (`Channel.query` for
503
- * `watch`/`create`, and `client.hydrateActiveChannels`).
554
+ * The extracting step of the query pipeline: the messages in item order and their cursors, which
555
+ * a custom `doRequest` reports and which are derived from the messages otherwise.
556
+ */
557
+ protected override extractQueryPage(
558
+ response: MessageQueryResponse,
559
+ { direction }: PaginationQueryParams<MessageQueryShape>,
560
+ ): PaginationQueryReturnValue<LocalMessage> {
561
+ if (response.source === 'doRequest') {
562
+ const { cursor, items } = response.doRequestResponse;
563
+ // Without a direction this is a jump: set both cursors.
564
+ return {
565
+ headward: !direction || direction === 'headward' ? cursor?.headward : undefined,
566
+ items: this.getCanonicalQueryItems(items),
567
+ tailward: !direction || direction === 'tailward' ? cursor?.tailward : undefined,
568
+ };
569
+ }
570
+ const messages =
571
+ response.source === 'replies'
572
+ ? response.repliesResponse.messages
573
+ : (response.channelResponse.messages ?? []);
574
+ const items = this.getCanonicalQueryItems(messages.map(formatMessage));
575
+ return { items, ...this.getCursorFromQueryResults({ direction, items }) };
576
+ }
577
+
578
+ /**
579
+ * The last step of the query pipeline: the rest of a channel query's response, applied once its
580
+ * page is placed (see `Channel.applyChannelStateFromResponse`). The other sources return nothing
581
+ * else.
582
+ */
583
+ protected override applyQueryResponseRest(
584
+ response: MessageQueryResponse,
585
+ _placeParams: QueryPagePlacement<MessageQueryShape>,
586
+ ) {
587
+ if (response.source === 'channel') {
588
+ // Not the latest message set the offline database stores: `watch()` and the channel list
589
+ // store that.
590
+ this.channel.applyChannelStateFromResponse(response.channelResponse, {
591
+ isLatestMessageSet: false,
592
+ watch: response.watch,
593
+ });
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Whether this paginator is active: the thread it lists is active (see `Thread.activate()`), or,
599
+ * without a thread, its channel is (see `Channel.activate()`). A page from a query an active
600
+ * paginator did not run leaves its active interval active; an inactive paginator shows a fresh
601
+ * newest page instead, also one separated from the loaded messages by a gap (see
602
+ * {@link reconcileNewestMessages}).
603
+ */
604
+ private isActivePaginator(): boolean {
605
+ return (this.thread ?? this.channel).active;
606
+ }
607
+
608
+ /**
609
+ * Places a page from an external query — one this paginator did not run, whose page the caller
610
+ * chose — in the intervals it belongs to, never removing anything loaded. Bringing the loaded
611
+ * newest messages up to date with a fresh newest page, removals included, is
612
+ * {@link reconcileNewestMessages}'s job instead.
613
+ *
614
+ * External queries are a channel query (`watch()`, see {@link prepareExternalQuery}), the
615
+ * channel list's query (`client.hydrateChannels`), and the channel state the pinned list's first
616
+ * page comes with. `messagePaginationParams` are the
617
+ * options the page was queried with; they decide where it goes:
618
+ *
619
+ * - The newest page: when no interval is active yet (nothing loaded, or only live messages), its
620
+ * interval becomes the active one, as the channel's first page. When the active interval is the
621
+ * newest interval, the page lands in it.
622
+ * - Any other page — a page at a cursor or around a message, or the newest page while an older
623
+ * interval is active — is only stored, as a separate interval merged only with an interval it
624
+ * overlaps.
504
625
  *
505
- * These paths hydrate the channel read state in the SAME synchronous tick they add messages
506
- * (`Channel._initializeState`), and the read patch drives `MessageReceiptsTracker`, which resolves
507
- * read/delivered cursors against this paginator (`findItemByTimestamp`) whenever the server omits
508
- * the `last_read_message_id` / `last_delivered_message_id`. `postQueryReconcile` is fully
509
- * synchronous (filtering is a local predicate), so seeding here guarantees the paginator is
510
- * populated before the reconcile runs. First-page reconciliation also takes the unread snapshot.
626
+ * The active interval stays active: changing it is this paginator's own methods' job
627
+ * (`jumpToMessage()` and the like). The exception is an inactive paginator (see
628
+ * {@link isActivePaginator}), where the newest page is shown as when no interval is
629
+ * active. A newest
630
+ * page for loaded messages goes to {@link reconcileNewestMessages} instead
631
+ * (`prepareExternalQuery`, the channel list's query). When a page lands in the active interval,
632
+ * overlaps it, or takes in an active interval of live messages only, that interval is shown again
633
+ * with the page. The paginator's own queries are left alone too: a running one keeps its loading
634
+ * flag, and its last query error and query shape stay.
511
635
  *
512
- * The fetched page is NOT always the latest window: a channel can be opened AROUND a message
513
- * (`messages: { id_around }` / `{ created_at_around }`), so the original pagination options are
514
- * threaded through as the query shape. For an around/jump open this lets `postQueryReconcile`
515
- * apply jump semantics (no forced head/tail; cursor flags derived from the around position)
516
- * instead of wrongly flagging the window as the head (newest) page.
636
+ * It runs synchronously, so a caller can apply the rest of the response right after with the page
637
+ * in place, as it has to: read and delivery positions that come without a message id are looked
638
+ * up among the loaded messages.
639
+ *
640
+ * Returns whether it showed the page as a first page.
517
641
  */
518
- seedFirstPageSync(
519
- messages: LocalMessage[],
642
+ placeExternalQueryPage(
643
+ page: LocalMessage[],
520
644
  requestedPageSize: number,
521
- messagePaginationOptions?: MessagePaginationParams,
522
- options?: SeedFirstPageOptions,
523
- ) {
645
+ messagePaginationParams?: MessagePaginationParams,
646
+ ): boolean {
524
647
  const queryShape: MessageQueryShape = {
525
- ...messagePaginationOptions,
648
+ ...messagePaginationParams,
526
649
  limit: requestedPageSize,
527
650
  };
528
651
  const isJump = this.isJumpQueryShape(queryShape);
652
+ const isNewestPage = this.isHeadPageQueryShape(queryShape);
653
+ // In item order, as `extractQueryPage()` hands its pages over, so the page's edges are its
654
+ // first and last item.
655
+ const items = this.getCanonicalQueryItems(page);
656
+ const { head: headItem, tail: tailItem } = this.getPagePaginationEdges(items);
657
+ // the first page of a list not loaded yet, or the newest page
658
+ const isFirstPage = typeof this.items === 'undefined' || isNewestPage;
659
+ const activeInterval = this.itemIntervals.find((interval) =>
660
+ this.isActiveInterval(interval),
661
+ );
662
+ // only live messages, with no page loaded yet, count as no active interval, as does any
663
+ // interval of an inactive paginator
664
+ const hasActiveInterval =
665
+ !!activeInterval && !isLogicalInterval(activeInterval) && this.isActivePaginator();
666
+ // The newest page lands in the active interval when that is the newest interval; any other page
667
+ // has no known place relative to the active interval, so it is stored as a separate interval.
668
+ const landsInActiveInterval = isNewestPage && this.isActiveIntervalAtHead;
669
+ const showsPage = isNewestPage && (!hasActiveInterval || landsInActiveInterval);
670
+ const placed = this.placePage(
671
+ {
672
+ startsSeparateInterval: !landsInActiveInterval,
673
+ // A jump/around page spans both directions; a page at a cursor pages the way its cursor
674
+ // points, and a plain latest page paginates tailward (older).
675
+ direction: isJump
676
+ ? undefined
677
+ : (getLinearQueryDirection(queryShape) ?? 'tailward'),
678
+ isFirstPage,
679
+ queryShape,
680
+ requestedPageSize,
681
+ results: {
682
+ items,
683
+ headward: isJump ? headItem?.id : undefined,
684
+ tailward: tailItem?.id,
685
+ },
686
+ updateState: showsPage,
687
+ },
688
+ { endsQuery: false },
689
+ );
690
+ // A stored page that took in a live-only active interval (only live messages, no page) carries
691
+ // on as the active interval: its live messages are still shown, with what the page added.
692
+ const tookInActiveInterval =
693
+ !!activeInterval &&
694
+ !this.itemIntervals.some((interval) => this.isActiveInterval(interval));
695
+ const intervalTakingOver = tookInActiveInterval ? placed.targetInterval : null;
696
+ if (intervalTakingOver) {
697
+ this.setActiveInterval(intervalTakingOver, { updateState: false });
698
+ // placing did not publish it: the interval it took in becomes the active one only here
699
+ const { cursor, hasMoreHead, hasMoreTail } = placed.stateCandidate;
700
+ this.publishActiveInterval({ cursor, hasMoreHead, hasMoreTail });
701
+ }
702
+ if (showsPage) {
703
+ // shown without a query of this paginator, so its next query has to continue this interval
704
+ this.recordLoadedIntervalQueryShape();
705
+ }
706
+ return showsPage && isFirstPage;
707
+ }
529
708
 
530
- if (options?.reconcile && !isJump && typeof this.items !== 'undefined') {
531
- // The page came back, so whatever the last query failure was, it is no longer the truth. The
532
- // branch below inherits this from `postQueryReconcile`, which this one deliberately skips —
533
- // without it a failed "load older" would keep a UI's error surface latched through an
534
- // otherwise successful reconnect refresh.
535
- if (this.state.getLatestValue().lastQueryError) {
536
- this.state.partialNext({ lastQueryError: undefined });
537
- }
538
- this.mergeNewestPage(messages, {
539
- candidateIds: options.candidateIds,
540
- requestedLimit: requestedPageSize,
541
- });
542
- return;
709
+ /**
710
+ * Whether messages are loaded for {@link reconcileNewestMessages} to bring up to date. A list
711
+ * loaded empty has none (no interval, not even live messages), so a fresh newest page is placed
712
+ * as a first page instead ({@link placeExternalQueryPage}); reconciling would find nothing to
713
+ * merge it into and drop it.
714
+ */
715
+ get canReconcileNewestMessages(): boolean {
716
+ return typeof this.items !== 'undefined' && this.itemIntervals.length > 0;
717
+ }
718
+
719
+ /**
720
+ * The snapshot a newest page is reconciled against (see
721
+ * {@link ReconcileNewestMessagesOptions.headIntervalItemIdsAtRequest}): the IDs of the head
722
+ * interval's server-confirmed messages. Take it right before the request goes out. Unsent messages
723
+ * are left out: one confirmed during the request proves neither that the page connects to the
724
+ * head interval nor, when the page lacks it, that it was deleted. `undefined` while no head
725
+ * interval is loaded.
726
+ *
727
+ * @internal
728
+ */
729
+ getHeadIntervalItemIdsAtRequest(): ReadonlySet<string> | undefined {
730
+ const head = this.anchoredHeadInterval;
731
+ if (!head) return undefined;
732
+ return new Set(head.itemIds.filter((id) => this.isServerConfirmedItemId(id)));
733
+ }
734
+
735
+ /**
736
+ * Whether the loaded message with this ID is server-confirmed
737
+ * (see {@link isServerConfirmedMessage}).
738
+ */
739
+ private isServerConfirmedItemId(id: string): boolean {
740
+ const message = this.getItem(id);
741
+ return !!message && this.isServerConfirmedMessage(message);
742
+ }
743
+
744
+ /**
745
+ * Prepares an external query for a page of these messages: the watch query the channel sends
746
+ * (`channel.watch()`, `channel.reload()`) with the `messages` options its caller gave. Call it
747
+ * before sending the query, and place the returned page with `placePage` before the response's
748
+ * read state is applied: the read state is resolved against the loaded messages.
749
+ *
750
+ * - `messagePaginationParams`: the options to send as the query's `messages`, with `limit` set to
751
+ * the page size when not given.
752
+ * - `isNewestPage`: whether the query asks for the newest page — no cursor, not around a message,
753
+ * and some messages.
754
+ * - `placePage`: places the returned page. The newest page goes to
755
+ * {@link placeExternalNewestPage}, reconciled against the messages loaded when the query was
756
+ * prepared; any other page is placed by {@link placeExternalQueryPage}. A query for no messages
757
+ * (`limit: 0`) places nothing. Returns whether it showed a first page.
758
+ */
759
+ prepareExternalQuery(messages?: MessagePaginationParams): PreparedExternalQuery {
760
+ const messagePaginationParams: MessagePaginationParams = {
761
+ ...messages,
762
+ limit: messages?.limit ?? this.pageSize,
763
+ };
764
+ const limit = messagePaginationParams.limit ?? this.pageSize;
765
+ if (isQueryForNoMessages(limit)) {
766
+ return { messagePaginationParams, isNewestPage: false, placePage: () => false };
543
767
  }
544
768
 
545
- this.postQueryReconcile({
546
- // A jump/around page spans both directions; a plain latest page paginates tailward (older).
547
- direction: isJump ? undefined : 'tailward',
548
- isFirstPage: true,
549
- queryShape,
550
- requestedPageSize,
551
- results: {
552
- items: messages,
553
- headward: isJump ? messages[messages.length - 1]?.id : undefined,
554
- tailward: messages[0]?.id,
555
- },
556
- });
769
+ const isNewestPage = this.isHeadPageQueryShape(messagePaginationParams);
770
+ const headIntervalItemIdsAtRequest = isNewestPage
771
+ ? this.getHeadIntervalItemIdsAtRequest()
772
+ : undefined;
773
+ return {
774
+ messagePaginationParams,
775
+ isNewestPage,
776
+ placePage: (page) =>
777
+ isNewestPage
778
+ ? this.placeExternalNewestPage(page, {
779
+ headIntervalItemIdsAtRequest,
780
+ requestedLimit: limit,
781
+ })
782
+ : this.placeExternalQueryPage(page, limit, messagePaginationParams),
783
+ };
784
+ }
785
+
786
+ /**
787
+ * Places the newest page of an external query (a channel query, the channel list's query): it
788
+ * reconciles the loaded newest messages ({@link reconcileNewestMessages}), or is placed as a
789
+ * first page when none are loaded ({@link placeExternalQueryPage}). A query for no messages
790
+ * (`requestedLimit: 0`) places nothing. Returns whether it showed a first page.
791
+ *
792
+ * @internal
793
+ */
794
+ placeExternalNewestPage(
795
+ page: LocalMessage[],
796
+ {
797
+ headIntervalItemIdsAtRequest,
798
+ requestedLimit,
799
+ }: ReconcileNewestMessagesOptions & { requestedLimit: number },
800
+ ): boolean {
801
+ if (isQueryForNoMessages(requestedLimit)) return false;
802
+ if (!this.canReconcileNewestMessages) {
803
+ return this.placeExternalQueryPage(page, requestedLimit);
804
+ }
805
+ this.reconcileNewestMessages(page, { headIntervalItemIdsAtRequest, requestedLimit });
806
+ return false;
557
807
  }
558
808
 
559
809
  isJumpQueryShape(queryShape: MessageQueryShape): boolean {
@@ -563,6 +813,30 @@ export class MessageIntervalPaginator extends BasePaginator<
563
813
  );
564
814
  }
565
815
 
816
+ /** Only a query without a cursor and not around a message returns the newest page. */
817
+ protected override isHeadPageQueryShape(
818
+ queryShape: MessageQueryShape | undefined,
819
+ ): boolean {
820
+ return (
821
+ !queryShape ||
822
+ (!this.isJumpQueryShape(queryShape) && !getLinearQueryDirection(queryShape))
823
+ );
824
+ }
825
+
826
+ /** A jump sends its own `limit`: head/tail flags are derived against it, not `pageSize`. */
827
+ protected override getRequestedPageSize(
828
+ queryShape: MessageQueryShape | undefined,
829
+ ): number {
830
+ return queryShape && this.isJumpQueryShape(queryShape)
831
+ ? (queryShape.limit ?? this.pageSize)
832
+ : this.pageSize;
833
+ }
834
+
835
+ /**
836
+ * Makes the interval holding the message the active one, querying the page around it when it is
837
+ * not loaded. Resolves `false` when the message cannot be shown, or when a later claim on the
838
+ * active interval (see `claimActiveInterval`) was made before the page arrived.
839
+ */
566
840
  jumpToMessage = async (
567
841
  messageId: string,
568
842
  {
@@ -570,11 +844,16 @@ export class MessageIntervalPaginator extends BasePaginator<
570
844
  focusSignalTtlMs,
571
845
  pageSize,
572
846
  suppressFocusSignal,
847
+ watchChannel,
573
848
  }: JumpToMessageOptions = {},
574
849
  ): Promise<boolean> => {
850
+ const watch =
851
+ !!watchChannel &&
852
+ !this.parentMessageId &&
853
+ !this.config.doRequest &&
854
+ this.channel.watchStatus !== ChannelWatchStatus.Watching;
575
855
  let localMessage = this.getItem(messageId);
576
856
  let interval: AnyInterval | undefined;
577
- let state: Partial<PaginatorState<LocalMessage>> | undefined;
578
857
  if (localMessage) {
579
858
  interval = this.locateIntervalForItem(localMessage);
580
859
  if (
@@ -582,11 +861,8 @@ export class MessageIntervalPaginator extends BasePaginator<
582
861
  !isLogicalInterval(interval) &&
583
862
  !interval.itemIds.includes(messageId)
584
863
  ) {
585
- // locateIntervalForItem can match by created_at RANGE and return an interval whose range
586
- // spans the target while its loaded itemIds do NOT contain it (e.g. a neighbouring interval
587
- // grew across the target's position without merging). Prefer the interval that actually
588
- // holds the id so the jump activates the window the message really lives in - otherwise, if
589
- // the range-matched interval happens to be active, the jump becomes a no-op.
864
+ // The range match can return an interval that spans the target without holding it (a
865
+ // neighbour grew across its position): use the one that holds the ID, or the jump may no-op.
590
866
  interval = this.itemIntervals.find(
591
867
  (candidate) =>
592
868
  !isLogicalInterval(candidate) && candidate.itemIds.includes(messageId),
@@ -594,18 +870,21 @@ export class MessageIntervalPaginator extends BasePaginator<
594
870
  }
595
871
  }
596
872
 
597
- if (localMessage && interval && !isLogicalInterval(interval)) {
598
- state = {
599
- hasMoreHead: interval.hasMoreHead,
600
- hasMoreTail: interval.hasMoreTail,
601
- cursor: this.getCursorFromInterval(interval),
602
- items: this.intervalToItems(interval),
603
- };
604
- } else if (!localMessage || !interval || isLogicalInterval(interval)) {
873
+ // a loaded message needs no request, unless the jump is also to watch the channel
874
+ if (!watch && localMessage && interval && !isLogicalInterval(interval)) {
875
+ // showing a loaded interval claims the active interval, as a query for one does
876
+ this.claimActiveInterval();
877
+ this.showLoadedInterval(interval);
878
+ } else {
605
879
  const result = await this.executeQuery({
606
- queryShape: { id_around: messageId, limit: pageSize },
880
+ claimsActiveInterval: true,
881
+ // Always send a limit: the replies endpoint ignores `id_around` without one.
882
+ queryShape: { id_around: messageId, limit: pageSize ?? this.pageSize },
883
+ ...(watch && { requestOptions: { watch: true } }),
607
884
  updateState: false,
608
885
  });
886
+ // a later claim decides the active interval, and the page stays stored
887
+ if (result?.isSuperseded) return false;
609
888
  localMessage = this.getItem(messageId);
610
889
  if (!localMessage || !result || !result.targetInterval) {
611
890
  this.channel.getClient().notifications.addError({
@@ -616,24 +895,22 @@ export class MessageIntervalPaginator extends BasePaginator<
616
895
  return false;
617
896
  }
618
897
  interval = result.targetInterval;
619
- state = isLogicalInterval(interval)
620
- ? result.stateCandidate
621
- : {
622
- ...result.stateCandidate,
623
- hasMoreHead: interval.hasMoreHead,
624
- hasMoreTail: interval.hasMoreTail,
625
- // Prefer the cursor derived during postQueryReconcile, but fall back to
626
- // interval-derived cursor to keep jumps consistent if the stateCandidate
627
- // is partial.
628
- cursor: result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
629
- items: this.intervalToItems(interval),
630
- };
898
+ this.showInterval(
899
+ interval,
900
+ isLogicalInterval(interval)
901
+ ? result.stateCandidate
902
+ : {
903
+ ...result.stateCandidate,
904
+ hasMoreHead: interval.hasMoreHead,
905
+ hasMoreTail: interval.hasMoreTail,
906
+ // Falls back to the interval-derived cursor when the stateCandidate is partial.
907
+ cursor:
908
+ result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
909
+ items: this.intervalToItems(interval),
910
+ },
911
+ );
631
912
  }
632
913
 
633
- if (!this.isActiveInterval(interval)) {
634
- this.setActiveInterval(interval, { updateState: false });
635
- }
636
- if (state) this.state.partialNext(state);
637
914
  if (!suppressFocusSignal) {
638
915
  this.emitMessageFocusSignal({
639
916
  messageId,
@@ -644,21 +921,52 @@ export class MessageIntervalPaginator extends BasePaginator<
644
921
  return true;
645
922
  };
646
923
 
647
- jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
648
- let latestMessageId: string | undefined;
649
- if (!(this.itemIntervals[0] as Interval)?.isHead) {
650
- // load the newest page in case pagination is currently on an older window (an empty/partial
651
- // headward response marks the interval as the head)
652
- await this.executeQuery({ direction: 'headward', updateState: false });
924
+ /**
925
+ * Shows a loaded interval as it is: its items, its own pagination flags and the cursor continuing
926
+ * it. Claiming the active interval is the caller's choice (see `claimActiveInterval`).
927
+ */
928
+ protected showLoadedInterval(interval: Interval) {
929
+ this.showInterval(interval, {
930
+ hasMoreHead: interval.hasMoreHead,
931
+ hasMoreTail: interval.hasMoreTail,
932
+ cursor: this.getCursorFromInterval(interval),
933
+ items: this.intervalToItems(interval),
934
+ });
935
+ }
936
+
937
+ /** Makes `interval` the active interval and publishes `state` for it in one update. */
938
+ private showInterval(
939
+ interval: AnyInterval,
940
+ state: Partial<PaginatorState<LocalMessage>>,
941
+ ) {
942
+ if (!this.isActiveInterval(interval)) {
943
+ this.setActiveInterval(interval, { updateState: false });
653
944
  }
945
+ this.state.partialNext(state);
946
+ // shown without a query of this paginator, so its next query has to continue this interval
947
+ this.recordLoadedIntervalQueryShape();
948
+ }
654
949
 
655
- // Re-read itemIntervals AFTER the query: the getter returns a fresh array each call, so a
656
- // reference captured before executeQuery would be stale and miss the head we just loaded.
657
- const headInterval = this.itemIntervals[0] as Interval | undefined;
658
- if (headInterval?.isHead) {
659
- latestMessageId = headInterval.itemIds.slice(-1)[0];
950
+ /**
951
+ * Shows the interval holding the latest message and jumps to that message. Without a loaded head
952
+ * interval (see {@link latestHeadInterval}), the newest page is queried first: no cursor, so it
953
+ * holds the latest message however many pages are missing. The page merges with an interval it
954
+ * overlaps and is an interval of its own otherwise, and is shown either way. Resolves `false` when
955
+ * the latest message cannot be shown, or when a later claim on the active interval (see
956
+ * `claimActiveInterval`) was made before the page arrived: that page is then only stored.
957
+ */
958
+ jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
959
+ if (!this.latestHeadInterval) {
960
+ const result = await this.executeQuery({
961
+ claimsActiveInterval: true,
962
+ queryShape: { limit: this.pageSize },
963
+ updateState: false,
964
+ });
965
+ // a later claim decides the active interval, and the page stays stored
966
+ if (result?.isSuperseded) return false;
660
967
  }
661
968
 
969
+ const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
662
970
  if (!latestMessageId) {
663
971
  this.channel.getClient().notifications.addError({
664
972
  message: 'Jump to latest message unsuccessful',
@@ -676,203 +984,554 @@ export class MessageIntervalPaginator extends BasePaginator<
676
984
  };
677
985
 
678
986
  /**
679
- * Fold an already fetched newest (head) page into the currently loaded items without issuing a
680
- * query. The caller supplies a page it obtained on its own and this reconciles it against what is
681
- * loaded, instead of rerunning the first page query, so the loaded set is updated in place rather
682
- * than blanked and reloaded. Two cases, decided by whether the incoming page overlaps the loaded
683
- * head:
987
+ * The head interval when it is the newest loaded interval, so its newest message is the latest
988
+ * one; `undefined` while no head interval is loaded or live messages newer than it are.
989
+ */
990
+ private get latestHeadInterval(): Interval | undefined {
991
+ const newest = this.itemIntervals[0];
992
+ return newest && !isLogicalInterval(newest) && newest.isHead ? newest : undefined;
993
+ }
994
+
995
+ /**
996
+ * Reconciles the loaded newest messages with a fresh newest page, without issuing a query: they
997
+ * are brought up to date in place — messages added and updated, those the page proves were
998
+ * hard-deleted removed — rather than blanked and reloaded. The page comes from an external query
999
+ * (a reload, a channel-list query, connection recovery). In an active paginator (see
1000
+ * {@link isActivePaginator}) the active interval stays active, the head interval included
1001
+ * (changing it is `jumpToTheLatestMessage()`'s job); in an inactive one, the head interval is
1002
+ * shown.
1003
+ *
1004
+ * Where the page goes depends on the head interval, the loaded interval reaching the newest
1005
+ * message:
684
1006
  *
685
- * 1. OVERLAP - the incoming page shares at least one id with the loaded head (fewer than a full
686
- * page is new). Merge in place: existing items are reconciled by id (edits, soft deletes), new
687
- * items are appended and every already loaded item (including older pages already paged in) is
688
- * kept. The tail boundary (`hasMoreTail`/`cursor.tailward`) is set from whether the page reached
689
- * the channel start ({@link pageReachedChannelStart}): a bounded page that came back short means
690
- * no more older, otherwise "load older" stays enabled and the cursor re-anchors to the true loaded
691
- * oldest (which also clears a stale offline-DB cursor). Then destructive reconciliation
692
- * ({@link reconcileHeadAgainstPage}) removes any loaded message
693
- * that the authoritative page proves was hard-deleted while offline (see that method + the
694
- * {@link MergeNewestPageOptions} for the exact, safe window).
1007
+ * 1. NO HEAD INTERVAL (only live messages, a jumped-to interval, or a cleared head mark, see
1008
+ * {@link unmarkHead}) - the page becomes the head interval, merging with the intervals it
1009
+ * overlaps, live messages included, minus what it proves was hard-deleted. It is shown if the
1010
+ * live messages it absorbed were active; an active interval that it overlaps grows. A
1011
+ * page separated by a gap from the interval whose head mark was cleared is placed as in 2.
695
1012
  *
696
- * 2. DISJOINT - the incoming page shares no id with the loaded head (at least a full page is new).
697
- * Merging would weld the two across the gap (the interval merge treats two head intervals as
698
- * overlapping when one reaches further headward), hiding the items in between with no way to
699
- * reach them. Instead the loaded set is discarded and rebuilt from the incoming page as a fresh
700
- * contiguous head (`hasMoreTail: true`, cursor reanchored to the page's oldest item) so the
701
- * gap and older history load again when paginating older. No separate reconciliation is needed:
702
- * the rebuilt window IS the server truth, so any hard-deleted message is simply absent from it.
1013
+ * 2. SEPARATED BY A GAP (see {@link isSeparatedFromHeadByGap}) - merging would weld the two
1014
+ * across the gap, hiding the messages in between, so the page takes the place of the head
1015
+ * interval (see {@link placeNewestPageAcrossGap}): stored beside the active interval when that
1016
+ * is an older interval, shown in place of the loaded intervals otherwise.
703
1017
  *
704
- * Never blanks the loaded set. Noop unless the newest slice is both loaded AND the interval
705
- * currently in view (the head interval is anchored at the head and active); when the caller has
706
- * jumped to a separate older window the merge is skipped so their position is preserved, and the
707
- * incoming page is picked up on a later load. An empty page never wipes the list on its own, but
708
- * — given a pre-fetch snapshot via `options.candidateIds` — is reconciled as "the channel has no
709
- * messages" (every server-confirmed loaded message removed).
1018
+ * 3. OTHERWISE - the page merges into the head interval, which keeps every loaded message and
1019
+ * drops what the page proves was hard-deleted (see {@link reconcileHeadAgainstPage}). An
1020
+ * active head interval gets its tail boundary from the page (see {@link showHeadInterval});
1021
+ * otherwise the active interval stays active, and grows into the head interval if the page
1022
+ * overlaps it.
710
1023
  *
711
- * @param page - The fetched newest window (may be empty). `created_at` order is normalized on ingest.
712
- * @param options - See {@link MergeNewestPageOptions}. Omit to prune only within the page's own span.
1024
+ * Only a gap drops loaded intervals, never an older active interval, and with nothing loaded it
1025
+ * does nothing: placing a first page is {@link placeQueryPage}'s job. An empty page changes
1026
+ * nothing on its own but, given a pre-fetch snapshot (`options.headIntervalItemIdsAtRequest`), is
1027
+ * reconciled as "the channel has no messages": every server-confirmed message of the head interval
1028
+ * is removed.
1029
+ *
1030
+ * The query shape of the loaded interval is recorded on every exit (see
1031
+ * `recordLoadedIntervalQueryShape`): an interval left without one loses itself on the next
1032
+ * pagination.
1033
+ *
1034
+ * @param page - The fetched newest interval (may be empty). `created_at` order is normalized on
1035
+ * ingest.
1036
+ * @param options - See {@link ReconcileNewestMessagesOptions}. Omit to prune only within the
1037
+ * page's own span.
713
1038
  */
714
- mergeNewestPage = (page: LocalMessage[], options?: MergeNewestPageOptions) => {
1039
+ reconcileNewestMessages = (
1040
+ page: LocalMessage[],
1041
+ options?: ReconcileNewestMessagesOptions,
1042
+ ) => {
1043
+ // The page came back, so whatever the last query failure was, it is no longer the truth: a
1044
+ // failed "load older" would otherwise keep a UI's error surface latched through a successful
1045
+ // refresh. Placing a page clears it in `placeQueryPage`.
1046
+ if (this.state.getLatestValue().lastQueryError) {
1047
+ this.state.partialNext({ lastQueryError: undefined });
1048
+ }
1049
+ this._reconcileNewestMessages(page, options);
1050
+ this.recordLoadedIntervalQueryShape();
1051
+ };
1052
+
1053
+ private _reconcileNewestMessages = (
1054
+ page: LocalMessage[],
1055
+ options?: ReconcileNewestMessagesOptions,
1056
+ ) => {
715
1057
  const headInterval = this.itemIntervals[0] as Interval | undefined;
716
1058
  if (!headInterval?.isHead) {
717
- // Live content no page has anchored yet, the first query came back empty and the reply the
718
- // user then sent went to the logical head (a thread/channel creation for example). Returning would
719
- // discard the fetched page, so the window could never catch up. We anchor it, so `ingestPage` folds
720
- // overlapping logical intervals in, absorbing those items.
721
- //
722
- // It's narrow on purpose, `liveHeadLogical` rather than `itemIntervals[0]`, which is only the head
723
- // by convention and could be a logical tail and no anchored head, whose presence would mean
724
- // this window is anchored with an older island merely in view. Keeps both neighbouring no-op
725
- // contracts, so nothing loaded has no logical head (seeding is `postQueryReconcile`'s job).
1059
+ // The newest messages are not loaded as an interval: only live content arrived (e.g. the first
1060
+ // query came back empty and the user's reply went to the logical head), only a jumped-to
1061
+ // interval is loaded, or the head mark was cleared (see `unmarkHead`). The page becomes the
1062
+ // head interval, and `ingestPage` merges into it the intervals it overlaps, live messages
1063
+ // included, else the newest messages could never be reached. With nothing loaded, placing
1064
+ // a first page is `placeQueryPage`'s job.
726
1065
  const logicalHead = this.liveHeadLogical;
727
1066
  const hasAnchoredHead = this.itemIntervals.some(
728
1067
  (interval) => !isLogicalInterval(interval) && interval.isHead,
729
1068
  );
730
- if (!logicalHead || hasAnchoredHead || !page?.length) return;
1069
+ if (!this.itemIntervals.length || hasAnchoredHead || !page?.length) return;
1070
+
1071
+ // The interval that reached the newest message until its head mark was cleared is judged as
1072
+ // the head interval is, gap included. The page becomes the head interval either way, so that
1073
+ // interval is judged only once.
1074
+ const unmarkedHead = this.unmarkedHeadInterval;
1075
+ this.unmarkedHeadEdgeId = undefined;
1076
+ if (unmarkedHead && this.isSeparatedFromHeadByGap(unmarkedHead, page, options)) {
1077
+ this.placeNewestPageAcrossGap(page, unmarkedHead, options);
1078
+ return;
1079
+ }
731
1080
 
732
- // Take over the view only if the reader is on the live content being absorbed, so if they jumped
733
- // to another interval, anchor for their return and leave them there (the rule the jumped away
734
- // branch below enforces).
735
- const takeOverView = this.isActiveInterval(logicalHead);
1081
+ // Take over the view if the live content being absorbed is active, or the paginator is
1082
+ // inactive. An active interval elsewhere (an interval jumped to) stays active, with the
1083
+ // page anchored as the head interval (the rule the jumped away branch below enforces).
1084
+ const takeOverView =
1085
+ !this.isActivePaginator() ||
1086
+ (!!logicalHead && this.isActiveInterval(logicalHead));
736
1087
 
737
1088
  const anchored = this.ingestPage({ page, isHead: true, setActive: false });
738
- if (!anchored || !takeOverView) return;
739
-
740
- const hasMoreTail = !this.pageReachedChannelStart(page, options);
741
- anchored.hasMoreTail = hasMoreTail;
742
- anchored.isTail = !hasMoreTail;
743
-
744
- this.setActiveInterval(anchored, { updateState: false });
745
- this.state.partialNext({
746
- items: this.intervalToItems(anchored),
747
- hasMoreHead: false,
748
- hasMoreTail,
749
- cursor: {
750
- headward: null,
751
- tailward: hasMoreTail ? (anchored.itemIds[0] ?? null) : null,
752
- },
753
- });
1089
+ if (!anchored) return;
1090
+ // The page may have merged into an interval that stopped reaching the newest message (see
1091
+ // `unmarkHead`); remove from it, as from the head, what the page proves was hard-deleted.
1092
+ this.reconcileHeadAgainstPage(page, options);
1093
+ if (!takeOverView) {
1094
+ // The page merged into the active interval, which now reaches the head: show what it gained.
1095
+ if (this.isActiveInterval(anchored)) {
1096
+ this.publishActiveIntervalGrownIntoHead();
1097
+ }
1098
+ return;
1099
+ }
1100
+ this.showHeadInterval(page, options);
754
1101
  return;
755
1102
  }
756
- // Captured BEFORE the merge overwrites state — inputs for the below-window reached-start probe
757
- // (overlap branch only): did we believe we were at the channel start, and how much was loaded.
1103
+ // Inputs for removeIdsTailwardOfPageIfNothingOlder, captured before the merge overwrites state.
758
1104
  const wasAtChannelStart = !this.state.getLatestValue().hasMoreTail;
759
1105
  const preMergeLoadedCount = headInterval.itemIds.length;
760
- // If the caller jumped to a separate (older) window, that window is active and the head is merely
761
- // still-loaded underneath. Don't MERGE the fresh page or switch the view (that would yank them to
762
- // the newest) — but STILL prune offline hard-deletes out of the hidden head, otherwise returning to
763
- // it later (scroll-to-latest) surfaces ghosts that were deleted while jumped away. Reconciliation
764
- // targets the head interval regardless of which interval is active, and removing a hidden-head ghost
765
- // leaves the active island's items untouched.
766
- if (!this.isActiveInterval(headInterval)) {
767
- this.reconcileHeadAgainstPage(page, options);
768
- return;
769
- }
770
1106
 
771
1107
  if (!page?.length) {
772
- // Empty page: never blanks the list by itself. Only when the caller supplied a pre-fetch
773
- // snapshot do we treat it as authoritative "channel emptied" and remove ghosts (a message that
774
- // arrived live during the fetch is excluded by the snapshot).
1108
+ // An empty page never blanks the list: only with a pre-fetch snapshot is it read as "channel
1109
+ // emptied" (the snapshot excludes messages that arrived live during the fetch).
775
1110
  this.reconcileHeadAgainstPage([], options);
776
1111
  return;
777
1112
  }
778
1113
 
779
- const loadedIds = new Set(headInterval.itemIds);
780
- const overlapsLoadedHead = page.some((item) => loadedIds.has(this.getItemId(item)));
781
-
782
- if (!overlapsLoadedHead) {
783
- // Disjoint window: rebuild from the fetched page as a fresh newest slice. Clearing
784
- // the stale intervals first ensures `ingestPage` builds a single head interval instead of
785
- // merging across the gap so reanchoring the cursor to this page's oldest item keeps the next
786
- // "load older" contiguous.
787
- this.setIntervals([]);
788
- this.setActiveInterval(undefined);
789
- const resetInterval = this.ingestPage({
790
- page,
791
- isHead: true,
792
- // Disjoint means the previously loaded head was entirely OLDER than this newest window, so
793
- // there is always older data to load (the gap + the prior history) - keep hasMoreTail true.
794
- isTail: false,
795
- setActive: false,
796
- });
797
- if (!resetInterval) return;
798
- this.setActiveInterval(resetInterval, { updateState: false });
799
- this.state.partialNext({
800
- items: this.intervalToItems(resetInterval),
801
- cursor: this.getCursorFromInterval(resetInterval),
802
- hasMoreHead: resetInterval.hasMoreHead,
803
- hasMoreTail: resetInterval.hasMoreTail,
804
- });
1114
+ if (this.isSeparatedFromHeadByGap(headInterval, page, options)) {
1115
+ this.placeNewestPageAcrossGap(page, headInterval, options);
805
1116
  return;
806
1117
  }
807
1118
 
808
- // Overlapping window: merge in place, keeping every already-loaded (incl. older) item.
809
- const interval = this.ingestPage({ page, isHead: true, setActive: false });
810
- if (!interval) return;
811
-
812
- // hasMoreTail: does the fetched page prove it reached the channel's own oldest message? Only a
813
- // request bounded by our OWN pageSize gives that proof (a short page); an over-request may have
814
- // been server-capped, so it biases to `true` — never asserting "no more older" from a page that
815
- // may be truncated. See {@link pageReachedChannelStart} (no hardcoded max page size, per-paginator).
816
- // This decides only the "load older" AFFORDANCE — it never removes a message (reconciliation stays
817
- // window-only below). isTail mirrors it: `true` only when we RELIABLY reached the start, which also
818
- // clears a stale offline-DB `isTail:true` and stops `intervalsOverlap` welding a far page across a
819
- // gap. The tail cursor anchors to the oldest loaded id so "load older" stays contiguous.
820
- const hasMoreTail = !this.pageReachedChannelStart(page, options);
821
- interval.hasMoreTail = hasMoreTail;
822
- interval.isTail = !hasMoreTail;
1119
+ // Another interval is shown; the head interval is still reconciled, so returning to it
1120
+ // (scroll-to-latest) shows neither ghosts nor stale newest messages.
1121
+ if (!this.isActiveInterval(headInterval)) {
1122
+ this.reconcileHeadAgainstPage(page, options);
1123
+ this.mergePageIntoInactiveHead(page, options);
1124
+ return;
1125
+ }
823
1126
 
824
- this.setActiveInterval(interval, { updateState: false });
825
- this.state.partialNext({
826
- items: this.intervalToItems(interval),
827
- // The newest slice is loaded (head anchored), so there is nothing newer to load.
828
- hasMoreHead: false,
829
- hasMoreTail,
830
- // Tailward = the oldest loaded id (interval item ids are created_at asc), null once we reached
831
- // the channel start.
832
- cursor: {
833
- headward: null,
834
- tailward: hasMoreTail ? (interval.itemIds[0] ?? null) : null,
835
- },
1127
+ // the head interval is active: merge in place, keeping every loaded message
1128
+ const interval = this.ingestPage({
1129
+ page,
1130
+ isHead: true,
1131
+ setActive: false,
1132
+ targetIntervalId: headInterval.id,
836
1133
  });
1134
+ if (!interval) return;
1135
+ this.showHeadInterval(page, options);
837
1136
 
838
- // With the newest page merged in, drop any loaded message the page proves was hard-deleted, and
839
- // collect the below-window leftovers it cannot decide from the page alone.
840
- const belowWindow = this.reconcileHeadAgainstPage(page, options);
1137
+ const idsTailwardOfPage = this.reconcileHeadAgainstPage(page, options);
841
1138
 
842
- // The leftovers are ambiguous (hard-deleted oldest vs server-capped over-request). Only a
843
- // full-window reload (`requestedLimit >= loaded`, so NOT the small list hydrate) that we believed
844
- // reached the start could have reached it — probe to settle them there; anything else can't, so skip.
1139
+ // Messages tailward of the page may be deleted or just older than the page reached. Only a reload
1140
+ // of the whole head interval (`requestedLimit >= loaded`, not the small list hydrate) that was at
1141
+ // the channel start can settle them, by asking the server; otherwise they are kept.
845
1142
  const requestedLimit = options?.requestedLimit;
846
1143
  if (
847
- belowWindow.length &&
1144
+ idsTailwardOfPage.length &&
848
1145
  wasAtChannelStart &&
849
1146
  typeof requestedLimit === 'number' &&
850
1147
  requestedLimit >= preMergeLoadedCount
851
1148
  ) {
852
- this._belowWindowReconcile = this.pruneBelowWindowIfReachedStart(
853
- belowWindow,
1149
+ this._pendingTailwardOfPageRemoval = this.removeIdsTailwardOfPageIfNothingOlder(
1150
+ idsTailwardOfPage,
854
1151
  this.getItemId(page[0]),
855
1152
  );
856
1153
  }
857
1154
  };
858
1155
 
859
1156
  /**
860
- * Whether `page` proves it reached the channel's own oldest message: the caller's request was
861
- * bounded by this paginator's OWN `pageSize` AND `page` came back shorter than that request.
1157
+ * Shows the head interval a fresh newest page merged into, with no newer messages to load. It has
1158
+ * older ones unless the page reached the channel start (see {@link pageReachedChannelStart});
1159
+ * `isTail` follows, which also clears a stale offline-DB `isTail: true` that would let
1160
+ * `intervalsOverlap` weld a far page across a gap.
1161
+ */
1162
+ private showHeadInterval(
1163
+ page: LocalMessage[],
1164
+ options?: ReconcileNewestMessagesOptions,
1165
+ ) {
1166
+ // read here, as reconciling replaces the interval object a caller holds
1167
+ const interval = this.anchoredHeadInterval;
1168
+ if (!interval) return;
1169
+ const hasMoreTail = !this.pageReachedChannelStart(page, options);
1170
+ interval.hasMoreTail = hasMoreTail;
1171
+ interval.isTail = !hasMoreTail;
1172
+ this.setActiveInterval(interval, { updateState: false });
1173
+ const flags = { hasMoreHead: false, hasMoreTail };
1174
+ this.publishActiveInterval({
1175
+ ...flags,
1176
+ cursor: this.getCursorFromInterval(interval, flags),
1177
+ });
1178
+ }
1179
+
1180
+ /**
1181
+ * Whether a fresh newest page and the head interval (or the interval whose head mark was cleared,
1182
+ * see {@link unmarkedHeadInterval}) are separated by a gap, with messages between them possibly
1183
+ * not loaded. They are not when the two together form one unbroken stretch of the channel:
1184
+ *
1185
+ * - the page starts inside the head interval (see {@link pageStartsInsideHead});
1186
+ * - the page covers the head interval (see {@link pageCoversHead});
1187
+ * - the page reached the channel start (see {@link pageReachedChannelStart}), so nothing older
1188
+ * than it exists to be missing.
1189
+ *
1190
+ * Sharing a message is not enough on its own: a message the user sent while offline is confirmed
1191
+ * by the server before the reconnect's newest page is requested, so it sits at the top of the
1192
+ * head interval and in the page, with the messages missed below it in neither. For example, the
1193
+ * interval holds m1–m100 and the user's queued "hello"; the server got m101–m210 meanwhile. A page
1194
+ * of 25 holds m187–m210 and "hello": it does not start inside the interval (m187 was never loaded)
1195
+ * nor cover it (m1 is not in it), so it is past a gap. When the user wrote the last 10 loaded
1196
+ * messages and others sent 20 since, a page of 25 holds the user's last 5 and the 20 new ones:
1197
+ * its oldest was loaded, so it starts inside the interval.
1198
+ *
1199
+ * A message missed while the socket was down comes with connection recovery's newest page.
1200
+ */
1201
+ private isSeparatedFromHeadByGap(
1202
+ head: Interval,
1203
+ page: LocalMessage[],
1204
+ options?: ReconcileNewestMessagesOptions,
1205
+ ): boolean {
1206
+ if (this.pageStartsInsideHead(head, page, options)) return false;
1207
+ if (this.pageCoversHead(head, page)) return false;
1208
+ if (this.pageReachedChannelStart(page, options)) return false;
1209
+ return true;
1210
+ }
1211
+
1212
+ /**
1213
+ * Whether the page's oldest message the head interval could hold (see
1214
+ * {@link getPageOldestHoldableMessage}) was in the head interval when the request went out. The
1215
+ * page runs unbroken from that message to the newest and the interval is taken to run unbroken
1216
+ * below it, so nothing between them is missing.
1217
+ *
1218
+ * With a snapshot of the request (`options.headIntervalItemIdsAtRequest`), the message must be
1219
+ * in it and held by no interval other than the head interval: a message that reached the interval
1220
+ * during the request, live or as a send confirmed meanwhile, may sit above messages the interval
1221
+ * never loaded. One no longer loaded at all still counts: if the head interval holds messages
1222
+ * older than it, the interval ran unbroken through it and it was removed (e.g. hard-deleted);
1223
+ * if not, the page covers the interval anyway. Without a snapshot, the message must be in the
1224
+ * head interval and server-confirmed now.
1225
+ *
1226
+ * The interval is not unbroken below a send the server confirmed while the channel received no
1227
+ * events, such as one replayed from the offline queue before the reconnect's newest page is
1228
+ * requested. If that send is exactly the page's oldest (as many newer messages as the page has
1229
+ * room for were sent after it), the page is taken to start inside the interval although messages
1230
+ * below the send were missed. The page and the interval cannot tell this apart from a send
1231
+ * confirmed while events were arriving.
1232
+ */
1233
+ private pageStartsInsideHead(
1234
+ head: Interval,
1235
+ page: LocalMessage[],
1236
+ options?: ReconcileNewestMessagesOptions,
1237
+ ): boolean {
1238
+ const pageOldest = this.getPageOldestHoldableMessage(page);
1239
+ if (!pageOldest) return false;
1240
+ const id = this.getItemId(pageOldest);
1241
+ const idsAtRequest = options?.headIntervalItemIdsAtRequest;
1242
+ if (!idsAtRequest) {
1243
+ return head.itemIds.includes(id) && this.isServerConfirmedItemId(id);
1244
+ }
1245
+ const heldByAnotherInterval = !head.itemIds.includes(id) && !!this.getItem(id);
1246
+ return idsAtRequest.has(id) && !heldByAnotherInterval;
1247
+ }
1248
+
1249
+ /**
1250
+ * Whether the page spans the whole head interval: the interval holds no server-confirmed message
1251
+ * older than the page. What the interval holds beyond the page is newer (it arrived as an event
1252
+ * after the page was produced) or unsent (it carries the device's clock).
1253
+ */
1254
+ private pageCoversHead(head: Interval, page: LocalMessage[]): boolean {
1255
+ const pageOldest = this.getPageOldestMessage(page);
1256
+ if (!pageOldest) return true;
1257
+ return !head.itemIds.some((id) => {
1258
+ const message = this.getItem(id);
1259
+ return (
1260
+ !!message &&
1261
+ this.isServerConfirmedMessage(message) &&
1262
+ this.aIsMoreTailwardThanB(message, pageOldest)
1263
+ );
1264
+ });
1265
+ }
1266
+
1267
+ /**
1268
+ * The page's oldest message that the head interval could have loaded: server-confirmed and kept
1269
+ * in intervals (see {@link filterQueryResults}). A message the interval filters out, such as a
1270
+ * shadowed one, would never be found in it. {@link pageCoversHead} compares with the page's
1271
+ * oldest message of any kind instead: it only needs the page's span.
1272
+ */
1273
+ private getPageOldestHoldableMessage(page: LocalMessage[]): LocalMessage | undefined {
1274
+ const holdable = this.filterQueryResults(page).filter((message) =>
1275
+ this.isServerConfirmedMessage(message),
1276
+ );
1277
+ return this.getPageOldestMessage(holdable);
1278
+ }
1279
+
1280
+ /**
1281
+ * The interval whose head mark was cleared last (see {@link unmarkHead}), while it is still
1282
+ * loaded. It reached the newest message until then, so a newest page is judged against it while
1283
+ * no head interval is loaded.
1284
+ */
1285
+ private get unmarkedHeadInterval(): Interval | undefined {
1286
+ const id = this.unmarkedHeadEdgeId;
1287
+ if (!id) return undefined;
1288
+ return this.itemIntervals.find(
1289
+ (interval): interval is Interval =>
1290
+ !isLogicalInterval(interval) && interval.itemIds.includes(id),
1291
+ );
1292
+ }
1293
+
1294
+ /**
1295
+ * Remembers the interval by a message that stays in it: a server-confirmed one, as an unsent one
1296
+ * may be deleted or retried; the raw newest item only when the interval holds none.
1297
+ */
1298
+ protected override unmarkHead(interval: Interval) {
1299
+ const edge =
1300
+ this.getServerKnownEdges(interval).head ??
1301
+ this.getIntervalPaginationEdges(interval)?.head;
1302
+ this.unmarkedHeadEdgeId = edge ? this.getItemId(edge) : undefined;
1303
+ super.unmarkHead(interval);
1304
+ }
1305
+
1306
+ protected override clearItemStorage() {
1307
+ this.unmarkedHeadEdgeId = undefined;
1308
+ super.clearItemStorage();
1309
+ }
1310
+
1311
+ override resetState() {
1312
+ this.unmarkedHeadEdgeId = undefined;
1313
+ super.resetState();
1314
+ }
1315
+
1316
+ private getPageOldestMessage(page: LocalMessage[]): LocalMessage | undefined {
1317
+ return this.getPagePaginationEdges(this.getCanonicalQueryItems(page)).tail;
1318
+ }
1319
+
1320
+ /**
1321
+ * Places a fresh newest page separated by a gap from `headInterval` (the head interval, or the
1322
+ * interval whose head mark was cleared, see {@link isSeparatedFromHeadByGap}). The page becomes
1323
+ * the head interval either way, and the intervals nothing brought up to date are dropped, as a
1324
+ * message deleted meanwhile would come back with them:
1325
+ *
1326
+ * - an active interval other than the head interval (see {@link getActiveIntervalApartFromHead})
1327
+ * stays active, and the page is stored beside it (see
1328
+ * {@link storeNewestPageBesideActiveInterval});
1329
+ * - otherwise the page replaces the loaded intervals and is shown (see
1330
+ * {@link replaceIntervalsWithNewestPage}).
1331
+ */
1332
+ private placeNewestPageAcrossGap(
1333
+ page: LocalMessage[],
1334
+ headInterval: Interval,
1335
+ options?: ReconcileNewestMessagesOptions,
1336
+ ) {
1337
+ const activeInterval = this.getActiveIntervalApartFromHead(headInterval);
1338
+ if (activeInterval) {
1339
+ this.storeNewestPageBesideActiveInterval(page, activeInterval, options);
1340
+ } else {
1341
+ this.replaceIntervalsWithNewestPage(page, options);
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * The active loaded interval when it is not `headInterval`, such as an interval jumped to;
1347
+ * `undefined` when `headInterval` or live messages only are active, and in an inactive paginator
1348
+ * (see {@link isActivePaginator}).
1349
+ */
1350
+ private getActiveIntervalApartFromHead(headInterval: Interval): Interval | undefined {
1351
+ if (!this.isActivePaginator()) return undefined;
1352
+ return this.itemIntervals.find(
1353
+ (interval): interval is Interval =>
1354
+ !isLogicalInterval(interval) &&
1355
+ this.isActiveInterval(interval) &&
1356
+ interval.id !== headInterval.id,
1357
+ );
1358
+ }
1359
+
1360
+ /**
1361
+ * Replaces the loaded intervals with a fresh newest page separated from the head interval by a gap
1362
+ * (see {@link placeNewestPageAcrossGap}) and shows it. The page's interval keeps the loaded
1363
+ * messages that must not be lost (see {@link getMessagesKeptAcrossGap}) and has older messages
1364
+ * to load.
1365
+ */
1366
+ private replaceIntervalsWithNewestPage(
1367
+ page: LocalMessage[],
1368
+ options?: ReconcileNewestMessagesOptions,
1369
+ ) {
1370
+ const keptMessages = this.getMessagesKeptAcrossGap(page, this.itemIntervals);
1371
+ // one publish, once the page's interval is in place and reconciled, so subscribers read it whole
1372
+ this.batch(
1373
+ () => {
1374
+ this.clearItemStorage();
1375
+ this.ingestPageAsHeadInterval(page, keptMessages, options);
1376
+ this.showHeadInterval(page, options);
1377
+ },
1378
+ { coalesce: true },
1379
+ );
1380
+ }
1381
+
1382
+ /**
1383
+ * Stores a fresh newest page separated from the head interval by a gap (see
1384
+ * {@link placeNewestPageAcrossGap}) as the head interval, beside `activeInterval`, which stays
1385
+ * active and shown as it is. Every other loaded interval is dropped and loads again on
1386
+ * demand. The page's interval keeps the messages of the dropped intervals that must not be lost
1387
+ * (see {@link getMessagesKeptAcrossGap}) and has older messages to load.
862
1388
  *
863
- * `pageSize <= the server's max page size` is already the invariant normal pagination
864
- * (`executeQuery`) relies on — `page.length < pageSize` ⟹ reached the end — so a request no larger
865
- * than `pageSize` returns exactly what was asked unless the channel ended. This needs no hardcoded
866
- * max page size and is per-paginator, so a thread reply paginator uses its own `pageSize`.
1389
+ * The active interval keeps all its messages, unsent ones included, so nothing moves in the
1390
+ * shown list, and it is not brought up to date: a message deleted or edited meanwhile stays as it was
1391
+ * loaded. It can load newer messages, up to the head interval it then joins.
1392
+ */
1393
+ private storeNewestPageBesideActiveInterval(
1394
+ page: LocalMessage[],
1395
+ activeInterval: Interval,
1396
+ options?: ReconcileNewestMessagesOptions,
1397
+ ) {
1398
+ const droppedIntervals = this.itemIntervals.filter(
1399
+ (interval) => interval.id !== activeInterval.id,
1400
+ );
1401
+ const keptMessages = this.getMessagesKeptAcrossGap(page, droppedIntervals);
1402
+ const keepingIds = new Set(
1403
+ [...page, ...keptMessages].map((message) => this.getItemId(message)),
1404
+ );
1405
+ // one publish, once the page's interval is in place and reconciled, so subscribers read it whole
1406
+ this.batch(
1407
+ () => {
1408
+ this.dropIntervals(droppedIntervals, { keepingIds });
1409
+ this.unmarkedHeadEdgeId = undefined;
1410
+ // Not the head interval: a head mark would weld the page to it (`intervalsOverlap` joins
1411
+ // anything beyond a head interval's head edge).
1412
+ activeInterval.isHead = false;
1413
+ const pageInterval = this.ingestPageAsHeadInterval(page, keptMessages, options);
1414
+ if (pageInterval && this.isActiveInterval(pageInterval)) {
1415
+ // the page overlapped the active interval, which grew into the head interval
1416
+ this.publishActiveIntervalGrownIntoHead();
1417
+ return;
1418
+ }
1419
+ this.markActiveIntervalBelowHead(activeInterval);
1420
+ },
1421
+ { coalesce: true },
1422
+ );
1423
+ }
1424
+
1425
+ /**
1426
+ * Ingests a fresh newest page placed across a gap, with `keptMessages`, as the head interval,
1427
+ * which has older messages to load, and removes from it what the page proves was hard-deleted (see
1428
+ * {@link reconcileHeadAgainstPage}). Returns the interval the page landed in.
1429
+ */
1430
+ private ingestPageAsHeadInterval(
1431
+ page: LocalMessage[],
1432
+ keptMessages: LocalMessage[],
1433
+ options?: ReconcileNewestMessagesOptions,
1434
+ ): Interval | null {
1435
+ const pageInterval = this.ingestPage({
1436
+ page: [...page, ...keptMessages],
1437
+ isHead: true,
1438
+ isTail: false,
1439
+ setActive: false,
1440
+ });
1441
+ this.reconcileHeadAgainstPage(page, options);
1442
+ return pageInterval;
1443
+ }
1444
+
1445
+ /**
1446
+ * Drops `intervals` from storage and releases their messages, except those with `keepingIds`,
1447
+ * which the caller ingests again.
1448
+ */
1449
+ private dropIntervals(
1450
+ intervals: AnyInterval[],
1451
+ { keepingIds }: { keepingIds: ReadonlySet<string> },
1452
+ ) {
1453
+ for (const interval of intervals) {
1454
+ this.dropInterval(interval.id);
1455
+ for (const id of interval.itemIds) {
1456
+ if (!keepingIds.has(id)) this._itemIndex.remove(id);
1457
+ }
1458
+ }
1459
+ }
1460
+
1461
+ /**
1462
+ * Marks the active interval, which does not reach the newest message, as able to load newer
1463
+ * messages. Publishes the flag and cursor only when they changed, so the interval shown stays as
1464
+ * it is.
1465
+ */
1466
+ private markActiveIntervalBelowHead(interval: Interval) {
1467
+ interval.hasMoreHead = true;
1468
+ const cursor = this.getCursorFromInterval(interval);
1469
+ const shown = this.state.getLatestValue();
1470
+ if (shown.hasMoreHead && shown.cursor?.headward === cursor.headward) return;
1471
+ this.state.partialNext({ hasMoreHead: true, cursor });
1472
+ }
1473
+
1474
+ /**
1475
+ * The messages of `intervals`, missing from a newest page placed across a gap, that the page's
1476
+ * interval keeps:
867
1477
  *
868
- * An OVER-request (larger than `pageSize`, e.g. `channel.reload` re-fetching the whole loaded window
869
- * to reconcile as much as possible) may have been silently capped by the server, so a short page
870
- * there is NOT proof of reaching the start — return `false` and stay conservative. This only ever
871
- * gates the `hasMoreTail` affordance; it never removes a message.
1478
+ * - unsent messages (see {@link isServerConfirmedMessage});
1479
+ * - messages from the page's oldest on: those that arrived during the request stay, and
1480
+ * reconciling removes those the page proves were hard-deleted.
1481
+ */
1482
+ private getMessagesKeptAcrossGap(
1483
+ page: LocalMessage[],
1484
+ intervals: AnyInterval[],
1485
+ ): LocalMessage[] {
1486
+ const pageIds = new Set(page.map((message) => this.getItemId(message)));
1487
+ const pageOldest = this.getPageOldestMessage(page);
1488
+ const isOlderThanPage = (message: LocalMessage) =>
1489
+ !!pageOldest && this.aIsMoreTailwardThanB(message, pageOldest);
1490
+ return intervals
1491
+ .flatMap((interval) => this.intervalToItems(interval))
1492
+ .filter(
1493
+ (message) =>
1494
+ !pageIds.has(this.getItemId(message)) &&
1495
+ (!this.isServerConfirmedMessage(message) || !isOlderThanPage(message)),
1496
+ );
1497
+ }
1498
+
1499
+ /**
1500
+ * Merges a fresh newest page, not separated by a gap, into the head interval while another
1501
+ * interval is shown. That interval stays active and grows into the head interval if the page
1502
+ * overlaps it. In an inactive paginator (see {@link isActivePaginator}), the head interval is
1503
+ * shown instead.
1504
+ */
1505
+ private mergePageIntoInactiveHead(
1506
+ page: LocalMessage[],
1507
+ options?: ReconcileNewestMessagesOptions,
1508
+ ) {
1509
+ const interval = this.ingestPage({ page, isHead: true, setActive: false });
1510
+ if (!interval) return;
1511
+ if (!this.isActivePaginator()) {
1512
+ this.showHeadInterval(page, options);
1513
+ } else if (this.isActiveInterval(interval)) {
1514
+ this.publishActiveIntervalGrownIntoHead();
1515
+ }
1516
+ }
1517
+
1518
+ /** Publishes the active interval once a newest page grew it into the head interval. */
1519
+ private publishActiveIntervalGrownIntoHead() {
1520
+ this.publishActiveInterval({
1521
+ hasMoreHead: false,
1522
+ cursor: { headward: null, tailward: this.cursor?.tailward ?? null },
1523
+ });
1524
+ }
1525
+
1526
+ /**
1527
+ * Whether `page` proves it reached the channel's oldest message: the request was bounded by this
1528
+ * paginator's own `pageSize` and `page` came back shorter. A larger over-request (e.g.
1529
+ * `channel.reload`) may have been server-capped and never proves it. Gates `hasMoreTail` and the
1530
+ * gap rule ({@link isSeparatedFromHeadByGap}), never removing a message.
872
1531
  */
873
1532
  private pageReachedChannelStart(
874
1533
  page: LocalMessage[],
875
- options?: MergeNewestPageOptions,
1534
+ options?: ReconcileNewestMessagesOptions,
876
1535
  ): boolean {
877
1536
  const requestedLimit = options?.requestedLimit;
878
1537
  return (
@@ -883,28 +1542,30 @@ export class MessageIntervalPaginator extends BasePaginator<
883
1542
  }
884
1543
 
885
1544
  /**
886
- * Settle the below-window leftovers {@link reconcileHeadAgainstPage} handed back (loaded messages
887
- * older than `anchorId` — the returned page's oldest — and absent from the page). From the page alone
888
- * they're ambiguous: a hard-deleted oldest vs a server-capped over-request. Ask the server "anything
889
- * older than `anchorId`?" — the only cap-free way to tell. Nothing older ⇒ genuine deletes ⇒ remove
890
- * them and settle the tail. A probe failure or a head change across the await keeps them (never a false
891
- * delete). The caller decides WHEN this runs.
1545
+ * Settles the loaded messages {@link reconcileHeadAgainstPage} found tailward of the page (older
1546
+ * than `pageTailId`, the page's oldest, and absent from it): from the page alone a hard-deleted
1547
+ * oldest message looks like one the page was too short to include. It asks the server whether
1548
+ * anything is older than `pageTailId`. When nothing is, those messages were deleted: they are
1549
+ * removed and the head interval becomes the tail. A failed request, or a head interval replaced
1550
+ * while waiting, keeps them. The caller decides when this runs.
892
1551
  */
893
- private async pruneBelowWindowIfReachedStart(
894
- belowWindow: string[],
895
- anchorId: string,
1552
+ private async removeIdsTailwardOfPageIfNothingOlder(
1553
+ idsTailwardOfPage: string[],
1554
+ pageTailId: string,
896
1555
  ): Promise<void> {
897
- const headId = (this.itemIntervals[0] as Interval | undefined)?.id;
898
- // older exists (or the probe failed), we we're not provably the start, so
899
- // keep the leftovers
900
- if (await this.hasMessagesOlderThan(anchorId).catch(() => true)) return;
901
- // revalidate the head across the await (a jump/reset/newer merge aborts), then remove the leftovers
902
- const head = this.itemIntervals[0] as Interval | undefined;
903
- if (!head?.isHead || head.id !== headId) return;
904
- this.removeReconciledItems(belowWindow);
905
- head.hasMoreTail = false; // we now KNOW we reached the start, so settle the "load older" affordance
906
- head.isTail = true;
907
- if (this.isActiveInterval(head)) {
1556
+ const headIdBeforeRequest = (this.itemIntervals[0] as Interval | undefined)?.id;
1557
+ // A failed request proves nothing, so it counts as "something older exists".
1558
+ const hasMessagesOlderThanPage = await this.hasMessagesOlderThan(pageTailId).catch(
1559
+ () => true,
1560
+ );
1561
+ if (hasMessagesOlderThanPage) return;
1562
+ // A jump, a reset or another newest page may have replaced the head interval meanwhile.
1563
+ const headAfterRequest = this.itemIntervals[0] as Interval | undefined;
1564
+ if (!headAfterRequest?.isHead || headAfterRequest.id !== headIdBeforeRequest) return;
1565
+ this.removeReconciledItems(idsTailwardOfPage);
1566
+ headAfterRequest.hasMoreTail = false;
1567
+ headAfterRequest.isTail = true;
1568
+ if (this.isActiveInterval(headAfterRequest)) {
908
1569
  this.state.partialNext({
909
1570
  hasMoreTail: false,
910
1571
  cursor: { headward: null, tailward: null },
@@ -918,16 +1579,15 @@ export class MessageIntervalPaginator extends BasePaginator<
918
1579
  const { messages } = this.parentMessageId
919
1580
  ? await this.channel
920
1581
  .getClient()
921
- .getReplies({ parent_id: this.parentMessageId, ...pagination })
1582
+ .getReplies({ parent_id: this.parentMessageId }, pagination)
922
1583
  : await this.channel.query({ messages: pagination });
923
1584
  return Array.isArray(messages) && messages.length > 0;
924
1585
  }
925
1586
 
926
1587
  /**
927
- * Whether a loaded message is server-confirmed and therefore eligible to be reconciled away when
928
- * absent from an authoritative page. Excludes local-only messages the server has never
929
- * acknowledged — optimistic (`sending`) and `failed` sends, and client-side `error` placeholders —
930
- * so a legitimately-unsent message is never mistaken for a hard delete.
1588
+ * Whether a loaded message is server-confirmed, so it may be reconciled away when absent from an
1589
+ * authoritative page. Optimistic (`sending`), `failed` and client-side `error` messages are not, so
1590
+ * an unsent message is never mistaken for a hard delete.
931
1591
  */
932
1592
  protected isServerConfirmedMessage(message: LocalMessage): boolean {
933
1593
  return (
@@ -938,56 +1598,87 @@ export class MessageIntervalPaginator extends BasePaginator<
938
1598
  }
939
1599
 
940
1600
  /**
941
- * Destructive half of {@link mergeNewestPage}: remove messages in the loaded head interval that
942
- * `page` proves were hard-deleted while offline (a hard delete emits no event to other clients, and
943
- * the merge is additive, so they would otherwise linger forever).
1601
+ * Whether this list holds `message`: it passes the filter and, in a channel's main list (no
1602
+ * `parentMessageId`), is not a reply only its thread lists (see `isThreadOnlyReply`).
1603
+ */
1604
+ private isListedMessage(message: LocalMessage): boolean {
1605
+ if (!this.matchesFilter(message)) return false;
1606
+ return !!this.parentMessageId || !isThreadOnlyReply(message);
1607
+ }
1608
+
1609
+ /**
1610
+ * The failed messages a reload restores with {@link restoreFailedMessages}: those of the shown
1611
+ * interval and the head interval, and those of `persisted` (e.g. the offline database's rows of
1612
+ * the channel) this list holds (see {@link isListedMessage}). The loaded copy wins, as it is at
1613
+ * least as fresh. Take them before the reload's request.
944
1614
  *
945
- * Here `page` is the freshly-fetched newest window the server returned for the query that produced
946
- * it. Its two bounds are its NEWEST message (`page`'s last item by `created_at`) and its OLDEST
947
- * message (`page`'s first item). Reconciliation removes ONLY messages `page` actually covers — no
948
- * hardcoded page size is involved — in two regions, by a loaded message's `created_at`:
1615
+ * @internal
1616
+ */
1617
+ getFailedMessagesToRestore(persisted: LocalMessage[] = []): LocalMessage[] {
1618
+ const failedById = new Map<string, LocalMessage>();
1619
+ const listed = persisted.filter((message) => this.isListedMessage(message));
1620
+ const loaded = [...(this.items ?? []), ...this.anchoredHeadItems];
1621
+ for (const message of [...listed, ...loaded]) {
1622
+ if (message.status === 'failed') failedById.set(this.getItemId(message), message);
1623
+ }
1624
+ return [...failedById.values()];
1625
+ }
1626
+
1627
+ /**
1628
+ * Ingests again each failed message taken before a reload (see
1629
+ * {@link getFailedMessagesToRestore}) that no interval holds after it, so a reload never loses the
1630
+ * user's unsent work. One an interval holds is left as it is: it may have been resent.
949
1631
  *
950
- * - WITHIN `page` (strictly between `page`'s oldest and newest message): a server-confirmed loaded
951
- * message absent from `page` was hard-deleted. Safe with no snapshot — a message that arrived live
952
- * during the caller's fetch is always strictly newer than `page`'s newest message, so it can never
953
- * fall in this span.
954
- * - AT/ABOVE `page`'s newest message (a hard-deleted newest message), and the empty-`page` case:
955
- * only reconcilable with a pre-fetch `candidateIds` snapshot, which alone tells a just-deleted
956
- * message from one that arrived live during the fetch at that top edge.
1632
+ * @internal
1633
+ */
1634
+ restoreFailedMessages(failedMessages: LocalMessage[]) {
1635
+ const isNoLongerLoaded = (message: LocalMessage) =>
1636
+ !this.findIntervalHoldingItem(message);
1637
+ const toRestore = failedMessages.filter(isNoLongerLoaded);
1638
+ if (!toRestore.length) return;
1639
+ this.batch(
1640
+ () => {
1641
+ for (const message of toRestore) this.ingestItem(message);
1642
+ },
1643
+ { coalesce: true },
1644
+ );
1645
+ }
1646
+
1647
+ /**
1648
+ * Destructive half of {@link reconcileNewestMessages}: removes loaded head-interval messages
1649
+ * that `page` (the fresh newest interval) proves were hard-deleted while the client received no
1650
+ * events, by `created_at`:
957
1651
  *
958
- * A loaded message BELOW `page`'s oldest is NOT removed here (window-only) — from the page alone a
959
- * hard-deleted oldest is indistinguishable from a server-capped over-request. Those messages are
960
- * instead RETURNED (the below-window leftovers) so {@link pruneBelowWindowIfReachedStart} can settle
961
- * them with a `limit: 1` "anything older?" probe — the only cap-free proof — and remove them only if
962
- * the server confirms nothing older exists. Absent that proof they are kept (a later cold/fresh query
963
- * omits any real delete).
1652
+ * - within `page`'s span: a server-confirmed message absent from `page` was deleted (a live
1653
+ * arrival is newer than `page`'s newest, so this needs no snapshot);
1654
+ * - at or above `page`'s newest, and for an empty `page`: only IDs in the pre-fetch
1655
+ * `headIntervalItemIdsAtRequest` snapshot, which tells a just-deleted message from a live
1656
+ * arrival or a send confirmed during the request.
964
1657
  *
965
- * Removal goes through {@link removeItem} (batched) so the item index, intervals, shared message
966
- * store and — via the {@link MessagePaginator} override — the tracked last message all stay correct;
967
- * the active window is then re-emitted once.
1658
+ * Messages below `page`'s oldest are kept (a hard-deleted oldest looks like a server-capped
1659
+ * over-request) and returned for {@link removeIdsTailwardOfPageIfNothingOlder}. Removal goes through
1660
+ * {@link removeItem}, so the index, intervals, message store and any subclass bookkeeping (e.g.
1661
+ * the latest message of {@link MessagePaginator}) stay correct.
968
1662
  *
969
- * @returns the below-window leftover ids (loaded, server-confirmed, older than `page`'s oldest, absent
970
- * from it) for the caller's reached-start probe. Empty for the no-head / empty-page paths.
1663
+ * @returns The below-interval leftover IDs. Empty for the no-head and empty-page paths.
971
1664
  */
972
1665
  protected reconcileHeadAgainstPage(
973
1666
  page: LocalMessage[],
974
- options?: MergeNewestPageOptions,
1667
+ options?: ReconcileNewestMessagesOptions,
975
1668
  ): string[] {
976
1669
  const headInterval = this.itemIntervals[0] as Interval | undefined;
977
1670
  if (!headInterval?.isHead) return [];
978
1671
 
979
1672
  const loadedIds = headInterval.itemIds;
980
- const candidateIds = options?.candidateIds;
1673
+ const headIntervalItemIdsAtRequest = options?.headIntervalItemIdsAtRequest;
981
1674
 
982
- // Empty page → the channel has no messages. Every server-confirmed loaded message is gone, but
983
- // only remove ids from the pre-fetch snapshot so a message that landed during the fetch survives.
1675
+ // Empty page: the channel has no messages. Only IDs from the pre-fetch snapshot are removed, so a
1676
+ // message that landed during the fetch survives.
984
1677
  if (!page.length) {
985
- if (!candidateIds) return [];
986
- const toRemove = loadedIds.filter((id) => {
987
- if (!candidateIds.has(id)) return false;
988
- const message = this.getItem(id);
989
- return !!message && this.isServerConfirmedMessage(message);
990
- });
1678
+ if (!headIntervalItemIdsAtRequest) return [];
1679
+ const toRemove = loadedIds.filter(
1680
+ (id) => headIntervalItemIdsAtRequest.has(id) && this.isServerConfirmedItemId(id),
1681
+ );
991
1682
  this.removeReconciledItems(toRemove);
992
1683
  return [];
993
1684
  }
@@ -996,57 +1687,36 @@ export class MessageIntervalPaginator extends BasePaginator<
996
1687
  const newestReturnedTs = getMessageCreatedAtTimestamp(page[page.length - 1]);
997
1688
  const oldestReturnedTs = getMessageCreatedAtTimestamp(page[0]);
998
1689
 
999
- // Window-only: never remove below the returned page's oldest here, because from the page alone a
1000
- // hard-deleted oldest is indistinguishable from a server-capped over-request. Below-window messages
1001
- // are collected into `belowWindow` and returned instead, for the reached-start probe to settle.
1002
- const windowLowTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
1690
+ // Nothing below the page's oldest is removed here: those go to `idsTailwardOfPage`.
1691
+ const pageTailTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
1003
1692
 
1004
1693
  const toRemove: string[] = [];
1005
- const belowWindow: string[] = [];
1694
+ const idsTailwardOfPage: string[] = [];
1006
1695
  for (const id of loadedIds) {
1007
- if (pageIds.has(id)) continue; // present on the server → keep
1696
+ if (pageIds.has(id)) continue;
1008
1697
  const message = this.getItem(id);
1009
- if (!message || !this.isServerConfirmedMessage(message)) continue; // local-only → keep
1698
+ if (!message || !this.isServerConfirmedMessage(message)) continue;
1010
1699
  const ts = getMessageCreatedAtTimestamp(message);
1011
- if (ts === null) continue; // no server timestamp (optimistic) → keep
1700
+ if (ts === null) continue; // no server timestamp (optimistic)
1012
1701
 
1013
1702
  if (newestReturnedTs !== null && ts >= newestReturnedTs) {
1014
- // At/above the newest returned message: a hard-deleted newest message and a message that
1015
- // arrived live during the fetch are indistinguishable here. Only remove ids present in the
1016
- // pre-fetch snapshot, which excludes live arrivals. (The newest returned message itself is
1017
- // in the page, so it is already skipped above.)
1018
- if (candidateIds?.has(id)) toRemove.push(id);
1703
+ // At or above the page's newest, a hard-deleted newest message, a live arrival and a send
1704
+ // confirmed during the request look the same: remove only IDs from the pre-fetch snapshot,
1705
+ // which holds none of the latter two.
1706
+ if (headIntervalItemIdsAtRequest?.has(id)) toRemove.push(id);
1019
1707
  continue;
1020
1708
  }
1021
- // Below the newest returned message: within the page's span (a live arrival can never be here, so
1022
- // absence = a hard delete) → remove; at/below the page's oldest → a below-window leftover the page
1023
- // cannot decide, returned for the reached-start probe.
1024
- if (ts > windowLowTs) toRemove.push(id);
1025
- else belowWindow.push(id);
1709
+ // Within the page's span a live arrival cannot be here, so absence means a hard delete. At or
1710
+ // below the page's oldest the page cannot decide: return it for the caller to settle.
1711
+ if (ts > pageTailTs) toRemove.push(id);
1712
+ else idsTailwardOfPage.push(id);
1026
1713
  }
1027
1714
 
1028
1715
  this.removeReconciledItems(toRemove);
1029
- return belowWindow;
1716
+ return idsTailwardOfPage;
1030
1717
  }
1031
1718
 
1032
- /**
1033
- * Remove a set of reconciled (hard-deleted) ids from this paginator's loaded state in one coalesced
1034
- * batch. Each id goes through {@link removeItem}, which drops it from THREE places — not a single
1035
- * interval:
1036
- *
1037
- * 1. the item index — unlinks this paginator's membership from the shared entity store (GC'ing the
1038
- * content if this was the last holder);
1039
- * 2. the interval that holds it — located by id, so it is NOT head-specific in general; in practice
1040
- * it is always the head interval, because the sole caller ({@link reconcileHeadAgainstPage})
1041
- * sources these ids from `headInterval.itemIds` and an item has single-interval membership;
1042
- * 3. the active window (`state.items`) if visible — blanking to `[]` when the window empties, per
1043
- * {@link flushWindowPublish}.
1044
- *
1045
- * The coalesced batch collapses all of that into a single `state.items` publish. Then mirror the
1046
- * removal into the offline DB (see {@link purgeReconciledFromOfflineDb}) so a cold start does not
1047
- * re-seed the ghosts from SQLite. No-op for an empty set, so an unaffected merge does not touch
1048
- * state a second time.
1049
- */
1719
+ /** Removes reconciled IDs in one coalesced batch (one publish), then mirrors it offline. */
1050
1720
  private removeReconciledItems(ids: string[]) {
1051
1721
  if (!ids.length) return;
1052
1722
  this.batch(
@@ -1059,26 +1729,15 @@ export class MessageIntervalPaginator extends BasePaginator<
1059
1729
  }
1060
1730
 
1061
1731
  /**
1062
- * Mirror a destructive reconciliation into the offline DB. A hard delete performed while the client
1063
- * was offline reaches it via no event, so the offline store never ran its own hard-delete for these
1064
- * ids; the reconnect query re-hydrates the DB by UPSERT (which never removes what is absent from the
1065
- * page), so without this the ghosts survive in SQLite and a cold start would re-seed them after the
1066
- * in-memory list already dropped them.
1067
- *
1068
- * Owned by the state layer, NOT the SDK: the SDK only supplies the platform `offlineDb`
1069
- * implementation and never orchestrates DB writes for reconciliation. Fire-and-forget and
1070
- * best-effort — the in-memory removal is the source of truth for the live list, so a failed/absent
1071
- * DB write is no worse than before (the ghost merely re-appears on a cold start until the next
1072
- * reconcile). No-op when offline support is off (`client.offlineDb` undefined). The ids are already
1073
- * server-confirmed (the reconcile excludes pending/failed/optimistic), so a plain hard delete —
1074
- * without the pending-task teardown of a local failed message — is correct.
1732
+ * Mirrors a reconciliation into the offline DB: a hard delete done while offline reaches it via no
1733
+ * event and the reconnect query upserts (never removing absent rows), so a cold start would re-seed
1734
+ * the ghosts. Fire-and-forget, no-op without offline support.
1075
1735
  */
1076
1736
  private purgeReconciledFromOfflineDb(ids: string[]) {
1077
1737
  const offlineDb = this.channel.getClient?.()?.offlineDb;
1078
1738
  if (!offlineDb) return;
1079
- // The offline DB owns the batching (single transaction); we just hand it the reconciled ids.
1080
1739
  offlineDb.hardDeleteMessages({ ids }).catch(() => {
1081
- // best-effort persistence cleanup — see doc comment; the live list is already correct.
1740
+ // Best effort: the live list is already correct.
1082
1741
  });
1083
1742
  }
1084
1743
 
@@ -1086,16 +1745,13 @@ export class MessageIntervalPaginator extends BasePaginator<
1086
1745
  lastReadAt,
1087
1746
  messages,
1088
1747
  }: {
1089
- lastReadAt: Date;
1748
+ lastReadAt: TimestampNS;
1090
1749
  messages: LocalMessage[];
1091
1750
  }): { firstUnreadMessageId: string | null; lastReadMessageId: string | null } => {
1092
- // Messages are expected in chronological order. We find:
1093
- // - lastReadMessageId: newest message with created_at <= lastReadAt
1094
- // - firstUnreadMessageId: first message with created_at > lastReadAt
1095
- //
1096
- // If the page starts after lastReadAt, the entire page is unread and the first message is
1097
- // used as unread anchor (legacy "whole channel is unread" behavior for this queried window).
1098
- const lastReadTimestamp = lastReadAt.getTime();
1751
+ // Messages are chronological: `lastReadMessageId` is the newest with `created_at <= lastReadAt`,
1752
+ // `firstUnreadMessageId` the first with `created_at > lastReadAt`. If the page starts after
1753
+ // `lastReadAt`, the whole page is unread and its first message is the unread anchor.
1754
+ const lastReadTimestamp = lastReadAt;
1099
1755
  if (!Number.isFinite(lastReadTimestamp) || !messages.length) {
1100
1756
  return { firstUnreadMessageId: null, lastReadMessageId: null };
1101
1757
  }
@@ -1159,20 +1815,15 @@ export class MessageIntervalPaginator extends BasePaginator<
1159
1815
 
1160
1816
  this.messageFocusSignal.next({ signal });
1161
1817
 
1162
- // NOTE: the auto-dismissal countdown is intentionally NOT started here. A focused message may
1163
- // be emitted while its message list is not yet visible (e.g. the channel is covered by a thread
1164
- // panel when a "view in channel" jump resolves), so measuring the highlight lifetime from the
1165
- // moment the jump resolved would burn it while the message is still off-screen. The consumer
1166
- // starts the countdown via `scheduleMessageFocusSignalClear` once the message is actually
1167
- // viewed.
1818
+ // The auto-dismiss countdown does not start here: the message list may not be visible yet (e.g.
1819
+ // covered by a thread panel), so the consumer starts it via `scheduleMessageFocusSignalClear`.
1168
1820
  return signal;
1169
1821
  };
1170
1822
 
1171
1823
  /**
1172
- * Starts the auto-dismissal countdown for the currently active focus signal. Call this once the
1173
- * focused message has been viewed (rendered and visible), so the highlight's lifetime is measured
1174
- * from when the user could actually see it rather than from when the jump resolved. No-op if the
1175
- * signal has already been cleared or superseded (guarded by `token`).
1824
+ * Starts the auto-dismiss countdown for the active focus signal. Call it once the focused message
1825
+ * is viewed, so the highlight lasts from when the user could see it. No-op if the signal was
1826
+ * cleared or superseded (guarded by `token`).
1176
1827
  */
1177
1828
  scheduleMessageFocusSignalClear = ({
1178
1829
  token,
@@ -1212,25 +1863,20 @@ export class MessageIntervalPaginator extends BasePaginator<
1212
1863
  }
1213
1864
 
1214
1865
  /**
1215
- * Partial truncation for `channel.truncated` carrying a `truncated_at`: drop every loaded
1216
- * message strictly older than the cutoff (keeping newer ones) across all loaded windows,
1217
- * mirroring the legacy per-message-set pruning. For a full truncation (no `truncated_at`) use
1218
- * {@link MessageIntervalPaginator.clearStateAndCache} instead.
1219
- *
1220
- * Batched and edge-classified: because messages are chronological, each interval is classified by
1221
- * its `tail` (oldest) and `head` (newest) edges, so only the single interval that *straddles* the
1222
- * cutoff is scanned member-by-member — the rest are kept or dropped wholesale. The straddling
1223
- * interval becomes the new global tail (nothing older than the cutoff exists anymore), so its
1224
- * `isTail`/`hasMoreTail` are set; intervals entirely newer keep their flags (unloaded older
1225
- * messages may still sit between them and the cutoff). The active window is re-emitted once.
1866
+ * Partial truncation for `channel.truncated` with a `truncated_at`: drops every loaded message
1867
+ * strictly older than the cutoff across all intervals (a full truncation uses
1868
+ * {@link MessageIntervalPaginator.clearStateAndCache}). Only the interval straddling the cutoff is
1869
+ * scanned member by member and becomes the new global tail; intervals entirely newer keep their
1870
+ * flags, since unloaded older messages may sit between them and the cutoff. The active interval is
1871
+ * re-emitted once.
1226
1872
  */
1227
- truncate = ({ truncatedAt }: { truncatedAt: Date }) => {
1228
- const cutoff = truncatedAt.getTime();
1229
- if (Number.isNaN(cutoff)) return;
1873
+ truncate({ truncatedAt }: { truncatedAt: TimestampNS }) {
1874
+ const cutoff = truncatedAt;
1875
+ if (!Number.isFinite(cutoff)) return;
1230
1876
 
1231
1877
  const isOld = (item: LocalMessage | undefined) => {
1232
- const time = item?.created_at ? new Date(item.created_at).getTime() : undefined;
1233
- return typeof time === 'number' && time < cutoff;
1878
+ const time = getMessageCreatedAtTimestamp(item);
1879
+ return time !== null && time < cutoff;
1234
1880
  };
1235
1881
 
1236
1882
  const removedIds: string[] = [];
@@ -1243,8 +1889,7 @@ export class MessageIntervalPaginator extends BasePaginator<
1243
1889
  } else if (isOld(edges.head)) {
1244
1890
  removedIds.push(...interval.itemIds); // newest edge < cutoff → whole interval is older
1245
1891
  } else {
1246
- // determines the cutoff. Items are chronological, so the old ones are at the beginning of the array,
1247
- // binary-search rather than scanning every member.
1892
+ // Items are chronological, so the old ones come first: binary-search the split.
1248
1893
  const ids = interval.itemIds;
1249
1894
  const splitIndex = lowerBound(
1250
1895
  ids.length,
@@ -1263,37 +1908,46 @@ export class MessageIntervalPaginator extends BasePaginator<
1263
1908
  if (!removedIds.length) return;
1264
1909
  for (const id of removedIds) this._itemIndex.remove(id);
1265
1910
 
1266
- // No re-sort needed: `survivingIntervals` preserves the order of the already-sorted
1267
- // `itemIntervals` (we only keep/prune/drop, never reorder), and truncation removes only
1268
- // tailward items — an interval's head edge (the intervalComparator sort key) never changes.
1911
+ // No re-sort: intervals keep their order and truncation only removes tailward items, so the head
1912
+ // edge (the interval sort key) never changes.
1269
1913
  this.setIntervals(survivingIntervals);
1270
1914
 
1271
- // Single re-emit of the active window (setIntervals does not emit).
1915
+ // `setIntervals` does not emit: re-emit the active interval once.
1272
1916
  const active = this._activeIntervalId
1273
1917
  ? this._itemIntervals.get(this._activeIntervalId)
1274
1918
  : undefined;
1275
- if (active && !isLogicalInterval(active)) {
1276
- this.setActiveInterval(active);
1919
+ if (active) {
1920
+ // `setActiveInterval` does not emit for a logical interval, so its survivors are emitted here.
1921
+ if (isLogicalInterval(active)) {
1922
+ this.state.partialNext({ items: this.intervalToItems(active) });
1923
+ } else {
1924
+ this.setActiveInterval(active);
1925
+ }
1277
1926
  return;
1278
1927
  }
1279
1928
 
1280
- // The active window was truncated away entirely. It sat below the cutoff, so it was older
1281
- // than every survivor — activate the nearest surviving window (the tail-most, i.e. oldest,
1282
- // anchored interval) rather than emitting an empty page, which would blank the message list.
1929
+ // The active interval was truncated away: activate the tail-most (oldest) surviving anchored
1930
+ // interval rather than blank the message list.
1283
1931
  const anchoredSurvivors = this.itemIntervals.filter(
1284
1932
  (itv): itv is Interval => !isLogicalInterval(itv),
1285
1933
  );
1286
1934
 
1287
- // If the active interval was truncated, we move to the neareast interval - which is the tail now
1288
1935
  const fallback = this.getTailIntervalFromSortedIntervals(anchoredSurvivors);
1289
1936
  if (fallback) {
1290
1937
  this.setActiveInterval(fallback);
1291
1938
  } else {
1292
- // Nothing loaded survived the truncation.
1293
- this.state.partialNext({ items: [] });
1939
+ // Nothing loaded survived the truncation. Drop the stale active id too: the next ingested
1940
+ // message lands in a logical head interval, which is only activated (and published) when no
1941
+ // interval is active.
1942
+ this.setActiveInterval(undefined);
1943
+ this.state.partialNext({ items: [], hasMoreTail: false });
1294
1944
  }
1295
- };
1945
+ }
1296
1946
 
1947
+ /**
1948
+ * Deletes `userId`'s loaded messages (removes them on a hard delete) and marks the quotes of them
1949
+ * as deleted. Returns the messages it deleted, as they were before.
1950
+ */
1297
1951
  applyMessageDeletionForUser = ({
1298
1952
  userId,
1299
1953
  hardDelete = false,
@@ -1301,58 +1955,56 @@ export class MessageIntervalPaginator extends BasePaginator<
1301
1955
  }: {
1302
1956
  userId: string;
1303
1957
  hardDelete?: boolean;
1304
- deletedAt: Date;
1305
- }) => {
1306
- const loadedMessages = this.items ?? [];
1958
+ deletedAt: TimestampNS;
1959
+ }): LocalMessage[] => {
1960
+ const loadedMessages = this._itemIndex.values();
1961
+ const deletedMessages: LocalMessage[] = [];
1307
1962
 
1308
- // Batch: one logical operation touches many messages; coalesce the shared-store fan-out to a
1309
- // single flush (sibling holders are notified once) instead of once per affected message.
1310
- this.batch(() => {
1311
- for (const message of loadedMessages) {
1312
- if (message.user?.id === userId) {
1313
- if (hardDelete) {
1314
- this.removeItem({ id: message.id });
1315
- } else {
1316
- this.ingestItem(
1317
- toDeletedMessage({
1318
- message,
1963
+ // Coalesce: one emit for this interval and one shared-store flush for the sibling holders.
1964
+ this.batch(
1965
+ () => {
1966
+ for (const message of loadedMessages) {
1967
+ if (message.user?.id === userId) {
1968
+ deletedMessages.push(message);
1969
+ if (hardDelete) {
1970
+ this.removeItem({ id: message.id });
1971
+ } else {
1972
+ this.ingestItem(
1973
+ toDeletedMessage({
1974
+ message,
1975
+ hardDelete,
1976
+ deletedAt,
1977
+ }) as LocalMessage,
1978
+ );
1979
+ }
1980
+ continue;
1981
+ }
1982
+
1983
+ if (
1984
+ message.quoted_message?.user?.id === userId &&
1985
+ message.quoted_message.type !== 'deleted'
1986
+ ) {
1987
+ this.ingestItem({
1988
+ ...message,
1989
+ quoted_message: toDeletedMessage({
1990
+ message: formatMessage(message.quoted_message),
1319
1991
  hardDelete,
1320
1992
  deletedAt,
1321
1993
  }) as LocalMessage,
1322
- );
1994
+ });
1323
1995
  }
1324
- continue;
1325
- }
1326
-
1327
- if (
1328
- message.quoted_message?.user?.id === userId &&
1329
- message.quoted_message.type !== 'deleted'
1330
- ) {
1331
- this.ingestItem({
1332
- ...message,
1333
- quoted_message: toDeletedMessage({
1334
- message: formatMessage(message.quoted_message),
1335
- hardDelete,
1336
- deletedAt,
1337
- }) as LocalMessage,
1338
- });
1339
1996
  }
1340
- }
1341
- });
1997
+ },
1998
+ { coalesce: true },
1999
+ );
2000
+ return deletedMessages;
1342
2001
  };
1343
2002
 
1344
- /**
1345
- * Ensures quoted-message snapshots across loaded paginator cache are in sync
1346
- * with the provided message.
1347
- *
1348
- * Scans cached messages and updates any item where `quoted_message_id`
1349
- * matches `message.id`.
1350
- */
2003
+ /** Updates the quoted-message snapshot of every cached message that quotes `message`. */
1351
2004
  reflectQuotedMessageUpdate = (message: LocalMessage) => {
1352
2005
  const cachedMessages = this._itemIndex.values();
1353
2006
 
1354
- // Batch: several cached messages may quote the updated one; coalesce the shared-store fan-out
1355
- // to a single flush instead of one per re-ingested quoting message.
2007
+ // Several cached messages may quote it: coalesce the shared-store fan-out into one flush.
1356
2008
  this.batch(() => {
1357
2009
  for (const cachedMessage of cachedMessages) {
1358
2010
  if (cachedMessage.quoted_message_id !== message.id) continue;
@@ -1366,22 +2018,18 @@ export class MessageIntervalPaginator extends BasePaginator<
1366
2018
  };
1367
2019
 
1368
2020
  /**
1369
- * Reflect an updated `user` object onto every cached message authored by that user, mirroring
1370
- * the legacy `ChannelState.updateUserMessages` for the main message list (does not touch
1371
- * `quoted_message.user` — that is not part of the legacy behavior).
1372
- *
1373
- * Batched: a user rename can affect many messages, so this patches the shared item index and
1374
- * re-emits the active window a single time (if it held an affected message) rather than one
1375
- * `ingestItem` re-emit per message.
2021
+ * Reflects an updated `user` onto every cached message authored by that user (not
2022
+ * `quoted_message.user`). Patches the shared item index in one batch and re-emits the active
2023
+ * interval once, if it held an affected message.
1376
2024
  */
1377
- reflectUserUpdate = (user: UserResponse) => {
2025
+ reflectUserUpdate(user: UserResponse) {
1378
2026
  const activeIds = new Set((this.items ?? []).map((m) => this.getItemId(m)));
1379
2027
  let activeAffected = false;
1380
- // Batch: a user rename can touch many messages; coalesce the shared-store fan-out to sibling
1381
- // holders into a single flush. This paginator's own active window is re-emitted once below.
2028
+ // A rename can touch many messages: coalesce the shared-store fan-out into one flush.
1382
2029
  this.batch(() => {
1383
2030
  for (const message of this._itemIndex.values()) {
1384
2031
  if (message.user?.id !== user.id) continue;
2032
+ if (message.user === user) continue;
1385
2033
  this._itemIndex.setOne({ ...message, user });
1386
2034
  if (activeIds.has(this.getItemId(message))) activeAffected = true;
1387
2035
  }
@@ -1391,124 +2039,92 @@ export class MessageIntervalPaginator extends BasePaginator<
1391
2039
  items: (this.items ?? []).map((m) => this.getItem(this.getItemId(m)) ?? m),
1392
2040
  });
1393
2041
  }
1394
- };
2042
+ }
1395
2043
 
1396
2044
  /**
1397
- * Apply a reaction WS event (`reaction.new` / `reaction.updated` / `reaction.deleted`) to the
1398
- * cached message. The event's `message` already carries the server-updated
1399
- * `reaction_groups` / `latest_reactions`; only `own_reactions` needs local preservation so a
1400
- * cross-user reaction does not wipe the current user's reactions. This re-homes what
1401
- * `ChannelState.addReaction` / `removeReaction` used to do off the now-removed
1402
- * `channel.state.messages` / `channel.state.threads` caches (the same logic backs the thread
1403
- * paginator via `Thread.messagePaginator`).
1404
- *
1405
- * `own_reactions` is seeded from the currently cached item (so another user's reaction keeps ours),
1406
- * falling back to the event's own_reactions when the message is not loaded — matching the legacy
1407
- * behavior where `_updateMessage` only mutated a message that existed locally.
1408
- *
1409
- * @param params - The reaction event payload.
1410
- * @param params.message - The reaction event's message, carrying the
1411
- * server-computed `reaction_groups` / `latest_reactions`. Ingested as-is except for `own_reactions`.
1412
- * @param params.reaction - The reaction from the event. Only added to/removed from
1413
- * `own_reactions` when its `user_id` is the current user; otherwise the current user's
1414
- * `own_reactions` are left untouched.
1415
- * @param [params.removed=false] - `true` for `reaction.deleted` (remove the reaction from
1416
- * `own_reactions`); `false` for `reaction.new` / `reaction.updated` (add it).
1417
- * @param [params.enforceUnique=false] - When adding, first clear the current user's existing
1418
- * `own_reactions` so only the incoming one remains (used by `reaction.updated`, where a user's
1419
- * reaction replaces their previous one).
1420
- *
1421
- * TODO(reactive-store): reflect reactions ONCE at the store level, not per-paginator. Both the
1422
- * channel handler (channel.ts) and the thread handler (thread.ts) call this on every reaction.*
1423
- * event, so a message held in more than one collection (a show_in_channel reply, or the thread
1424
- * parent) is reflected TWICE: two writes to the same canonical slot, each fanning out to the
1425
- * other holder (double re-projection) and minting a fresh ref that defeats the reconcile
1426
- * ref-equality bail. Idempotent (counts come wholesale from the event) so the result is correct,
1427
- * just wasteful. The store already fans out to every holder, so reflect once (by id, if held) and
1428
- * retire the per-collection reflect calls + parent path + enforce_unique branch.
2045
+ * The last loaded message created at or before `timestamp` (a floor), or `null` when it precedes
2046
+ * every loaded message. With `exactTsMatch`, only a message created exactly at `timestamp` matches.
2047
+ * Searches the loaded intervals from the head down (each already sorted, O(log n) per interval):
2048
+ * the first holding a message at or before `timestamp` holds the answer. Used by the receipts
2049
+ * tracker to resolve read/delivered cursors.
1429
2050
  */
1430
- reflectReaction = ({
1431
- enforceUnique = false,
1432
- message,
1433
- reaction,
1434
- removed = false,
1435
- }: {
1436
- message: MessageResponse | LocalMessage;
1437
- reaction: ReactionResponse;
1438
- enforceUnique?: boolean;
1439
- removed?: boolean;
1440
- }) => {
1441
- const formatted = formatMessage(message);
1442
- const existing = this.getItem(formatted.id);
1443
- const baseOwnReactions = existing?.own_reactions ?? formatted.own_reactions ?? [];
1444
- const own_reactions = computeOwnReactions({
1445
- current: baseOwnReactions,
1446
- enforceUnique,
1447
- reaction,
1448
- removed,
1449
- userId: this.channel.getClient().userId,
1450
- });
1451
- this.ingestItem({ ...formatted, own_reactions });
2051
+ findItemByTimestamp = (
2052
+ timestamp: TimestampNS,
2053
+ exactTsMatch = false,
2054
+ ): LocalMessage | null => {
2055
+ for (const interval of this.sortIntervals(this.itemIntervals)) {
2056
+ const found = this.findItemByTimestampIn(
2057
+ this.intervalToItems(interval),
2058
+ timestamp,
2059
+ exactTsMatch,
2060
+ );
2061
+ if (found !== undefined) return found;
2062
+ }
2063
+ return null;
1452
2064
  };
1453
2065
 
1454
2066
  /**
1455
- * Map a timestamp to a loaded message — the first message in the latest (head) window whose
1456
- * `created_at` is >= `timestampMs` (mirrors the legacy `ChannelState.findMessageByTimestamp`
1457
- * lower-bound search), or the newest loaded message when the timestamp is beyond it. Used by the
1458
- * receipts tracker to resolve read/delivered cursors. Searches the newest loaded window — where
1459
- * read cursors live — which is already sorted, so this is O(log n) with no re-sort.
2067
+ * {@link findItemByTimestamp} within one interval (`items` ascending by `created_at`). `undefined`
2068
+ * when every item is newer than `timestamp`, so an older interval has to be searched.
1460
2069
  */
1461
- findItemByTimestamp = (
1462
- timestampMs: number,
1463
- exactTsMatch = false,
1464
- ): LocalMessage | null => {
1465
- const items = this.headItems; // ascending by created_at
1466
- if (!items.length) return null;
1467
- // Resolve the last message created AT OR BEFORE `timestampMs` (floor). The sole caller is
1468
- // read/delivered cursor resolution (MessageReceiptsTracker): the cursor carries the timestamp of
1469
- // the last message a participant reached, so a message created strictly after the cursor has NOT
1470
- // been reached. A ceil match (first message >= target) would over-count it — e.g. a participant
1471
- // whose read cursor predates every loaded message would be reported as having read the oldest one.
1472
- // `lowerBound` returns the first index whose created_at is strictly greater than the target, so
1473
- // the floor is the item immediately before it.
2070
+ private findItemByTimestampIn(
2071
+ items: LocalMessage[],
2072
+ timestamp: TimestampNS,
2073
+ exactTsMatch: boolean,
2074
+ ): LocalMessage | null | undefined {
2075
+ if (!items.length) return undefined;
2076
+ // A floor, not a ceil: a cursor is the timestamp of the last message a participant reached, so a
2077
+ // ceil would count the oldest loaded message as read by a cursor that predates all of them.
2078
+ // `lowerBound` finds the first index strictly after the target.
1474
2079
  const firstAfter = lowerBound(items.length, (i) => {
1475
2080
  const t = getMessageCreatedAtTimestamp(items[i]);
1476
- return t === null || t > timestampMs;
2081
+ return t === null || t > timestamp;
1477
2082
  });
1478
- if (firstAfter === 0) return null; // target precedes every loaded message
2083
+ if (firstAfter === 0) return undefined; // target precedes every message in this interval
1479
2084
  const found = items[firstAfter - 1];
1480
2085
  const foundTimestamp = getMessageCreatedAtTimestamp(found);
1481
- // A message without a resolvable created_at (e.g. an optimistic message still missing its
1482
- // server timestamp) cannot be located by timestamp.
2086
+ // A message without a server timestamp (e.g. optimistic) cannot be located.
1483
2087
  if (foundTimestamp === null) return null;
1484
2088
  if (!exactTsMatch) return found;
1485
- return foundTimestamp === timestampMs ? found : null;
1486
- };
2089
+ return foundTimestamp === timestamp ? found : null;
2090
+ }
1487
2091
 
1488
- filterQueryResults = (items: LocalMessage[]) =>
1489
- items.filter(this.shouldIncludeMessageInInterval.bind(this));
2092
+ override filterQueryResults(items: LocalMessage[]) {
2093
+ return items.filter(this.shouldIncludeMessageInInterval.bind(this));
2094
+ }
2095
+
2096
+ /**
2097
+ * The sort of a replies request. A page newer than a cursor (`id_gt`, `created_at_after`, ...)
2098
+ * must hold the replies right after the cursor, so it is requested oldest first: newest first
2099
+ * returns the newest replies and skips the ones in between. The page is put in item order
2100
+ * afterwards, so the request sort only decides which replies the page holds.
2101
+ */
2102
+ private getRepliesRequestSort(options: MessageQueryShape): MessagePaginatorSort {
2103
+ if (getLinearQueryDirection(options) !== 'headward') return this.requestSort;
2104
+ return this.requestSort.map((sort) => ({ ...sort, direction: 1 }));
2105
+ }
1490
2106
 
1491
2107
  private getCanonicalQueryItems(items: LocalMessage[]): LocalMessage[] {
1492
2108
  return [...items].sort(this.itemOrderComparator);
1493
2109
  }
1494
- }
1495
2110
 
1496
- const makeDeriveCursor =
1497
- (
1498
- paginator: MessageIntervalPaginator,
1499
- ): CursorDerivator<LocalMessage, MessageQueryShape> =>
1500
- (ctx) => {
1501
- // Not included in the interval (filtered out by MessageIntervalPaginator.filterQueryResults).
1502
- //
1503
- // IMPORTANT: We must keep cursor derivation consistent with the ingested interval.
1504
- // The interval is built from the filtered page, but ctx.page contains the raw response.
1505
- // Around/linear derivators compare page edges and lengths against interval.itemIds. If we
1506
- // pass a page that includes locally filtered messages (e.g. shadowed), those comparisons
1507
- // can incorrectly conclude that the page is not at the dataset bounds.
2111
+ /**
2112
+ * The cursor and more-messages flags after a page is placed (`deriveCursor`). A page around a
2113
+ * point counts the messages the server returned on each side of it. Any other page is compared
2114
+ * with the interval's outermost server-known messages (see {@link getServerKnownEdges}): a page
2115
+ * never holds an unsent message, so one at an edge must not hide that the page reached the edge.
2116
+ */
2117
+ private deriveCursorFromPage(
2118
+ ctx: CursorDeriveContext<LocalMessage, MessageQueryShape>,
2119
+ ): CursorDeriveResult {
2120
+ // The interval is built from the filtered page but `ctx.page` is the raw response. The linear
2121
+ // derivation compares the page's length with the requested size and its edges with the
2122
+ // interval's server-known edges, so the locally filtered messages (e.g. shadowed) are dropped for
2123
+ // it, or it would wrongly conclude the page is not at the bounds.
1508
2124
  const pageWithPermittedMessages: LocalMessage[] = [];
1509
2125
  let filteredLocallyCount = 0;
1510
2126
  for (const message of ctx.page) {
1511
- if (!paginator.shouldIncludeMessageInInterval(message)) {
2127
+ if (!this.shouldIncludeMessageInInterval(message)) {
1512
2128
  filteredLocallyCount++;
1513
2129
  } else {
1514
2130
  pageWithPermittedMessages.push(message);
@@ -1519,11 +2135,7 @@ const makeDeriveCursor =
1519
2135
  0,
1520
2136
  ctx.requestedPageSize - filteredLocallyCount,
1521
2137
  );
1522
-
1523
- if (
1524
- ctx.interval &&
1525
- ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length
1526
- ) {
2138
+ if (ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length) {
1527
2139
  console.error(
1528
2140
  'error',
1529
2141
  'Corrupted message set state: parent set size < returned page size',
@@ -1535,48 +2147,23 @@ const makeDeriveCursor =
1535
2147
  };
1536
2148
  }
1537
2149
 
1538
- const injectCursor = ({
1539
- hasMoreHead,
1540
- hasMoreTail,
1541
- }: {
1542
- hasMoreHead: boolean;
1543
- hasMoreTail: boolean;
1544
- }): CursorDeriveResult => {
1545
- const cursor: PaginatorCursor = {
1546
- headward: !hasMoreHead ? null : (ctx.interval?.itemIds.slice(-1)[0] ?? null),
1547
- tailward: !hasMoreTail ? null : (ctx.interval?.itemIds[0] ?? null),
1548
- };
1549
- return { cursor, hasMoreHead, hasMoreTail };
2150
+ // A page around a point is judged by how many messages the server returned on each side of it,
2151
+ // so it is read as returned: a message filtered locally, the target included, still shows the
2152
+ // server had it, and dropping it would make its side look exhausted.
2153
+ const aroundDerivationCtx = ctx;
2154
+ const linearDerivationCtx = {
2155
+ ...ctx,
2156
+ intervalEdges: this.getServerKnownEdges(ctx.interval),
2157
+ page: pageWithPermittedMessages,
2158
+ requestedPageSize: requestedPageSizeAfterAdjustment,
1550
2159
  };
1551
-
1552
- if ((ctx.queryShape as MessagePaginationParams)?.created_at_around) {
1553
- return injectCursor(
1554
- deriveCreatedAtAroundPaginationFlags<
1555
- LocalMessage,
1556
- MessagePaginationParams,
1557
- MessageIntervalPaginator
1558
- >({
1559
- ...ctx,
1560
- paginator,
1561
- page: pageWithPermittedMessages,
1562
- requestedPageSize: requestedPageSizeAfterAdjustment,
1563
- }),
1564
- );
1565
- } else if (ctx.queryShape?.id_around) {
1566
- return injectCursor(
1567
- deriveIdAroundPaginationFlags({
1568
- ...ctx,
1569
- page: pageWithPermittedMessages,
1570
- requestedPageSize: requestedPageSizeAfterAdjustment,
1571
- }),
1572
- );
1573
- } else {
1574
- return injectCursor(
1575
- deriveLinearPaginationFlags({
1576
- ...ctx,
1577
- page: pageWithPermittedMessages,
1578
- requestedPageSize: requestedPageSizeAfterAdjustment,
1579
- }),
1580
- );
1581
- }
1582
- };
2160
+ const flags = (ctx.queryShape as MessagePaginationParams)?.created_at_around
2161
+ ? deriveCreatedAtAroundPaginationFlags<LocalMessage, MessagePaginationParams>(
2162
+ aroundDerivationCtx,
2163
+ )
2164
+ : ctx.queryShape?.id_around
2165
+ ? deriveIdAroundPaginationFlags(aroundDerivationCtx)
2166
+ : deriveLinearPaginationFlags(linearDerivationCtx);
2167
+ return { ...flags, cursor: this.getCursorFromInterval(ctx.interval, flags) };
2168
+ }
2169
+ }