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
@@ -2,7 +2,7 @@ import type { ItemLocation } from '../sortCompiler';
2
2
  import { deepFreezeConfig } from '../../configuration/utils/deepFreezeConfig';
3
3
  import { binarySearch } from '../sortCompiler';
4
4
  import { itemMatchesFilter } from '../filterCompiler';
5
- import { isPatch, StateStore, type ValueOrPatch } from '../../store';
5
+ import { isPatch, StateStore, type ValueOrPatch } from '@stream-io/state-store';
6
6
  import { debounce, type DebouncedFunc, generateUUIDv4, sleep } from '../../utils';
7
7
  import { throttle, type Throttled } from '../../utils/throttling/throttle';
8
8
  import { isStateThrottlingEnabled } from './stateThrottling';
@@ -32,27 +32,9 @@ export type Interval = {
32
32
  hasMoreTail: boolean;
33
33
  itemIds: string[];
34
34
  id: string;
35
- /**
36
- * True if this interval represents the global head of the dataset
37
- * under the current sortComparator.
38
- *
39
- * Cursor pagination:
40
- * headward === null
41
- *
42
- * Offset pagination:
43
- * offset === 0
44
- */
35
+ /** Reaches the dataset head (cursor: `headward === null`, offset: `offset === 0`). */
45
36
  isHead: boolean;
46
- /**
47
- * True if this interval represents the global tail of the dataset
48
- * under the current sortComparator.
49
- *
50
- * Cursor pagination:
51
- * tailward === null
52
- *
53
- * Offset pagination:
54
- * returnedItems.length < pageSize
55
- */
37
+ /** Reaches the dataset tail (cursor: `tailward === null`, offset: a short page). */
56
38
  isTail: boolean;
57
39
  };
58
40
 
@@ -96,17 +78,9 @@ export type MakeIntervalParams<T> = {
96
78
  export type SetPaginatorItemsParams<T> = {
97
79
  valueOrFactory: ValueOrPatch<T[]>;
98
80
  cursor?: PaginatorCursor;
99
- /**
100
- * Relevant only is using item interval storage in the paginator.
101
- * Indicates that the page would be the head of pagination intervals array.
102
- * Items falling outside this intervals head bound will be merged into this interval.
103
- */
81
+ /** The page is the head interval: items beyond its head bound merge into it. */
104
82
  isFirstPage?: boolean;
105
- /**
106
- * Relevant only is using item interval storage in the paginator.
107
- * Indicates that the page would be the tail of pagination intervals array
108
- * Items falling outside this intervals tail bound will be merged into this interval.
109
- */
83
+ /** The page is the tail interval: items beyond its tail bound merge into it. */
110
84
  isLastPage?: boolean;
111
85
  };
112
86
 
@@ -117,35 +91,22 @@ type MergeIntervalsResult = {
117
91
  };
118
92
 
119
93
  /**
120
- * headward - going from page X -> X-Y -> 0
121
- * tailward - goring from page 0 -> X -> X + Y ...
122
- *
123
- * Head is the place where new items are added - same as git.
124
- * Tail is the place where retrieved pages are appended.
94
+ * `headward` moves toward page 0, `tailward` away from it. New items are added at the head,
95
+ * retrieved pages are appended at the tail.
125
96
  */
126
97
  export type PaginationDirection = 'headward' | 'tailward';
127
98
 
128
99
  export type CursorDeriveContext<T, Q> = {
129
- /**
130
- * Current cursor to be merged with the newly derived cursor.
131
- * Allows to preserve the direction we have not paginated with the given request.
132
- */
100
+ /** Current cursor, merged with the derived one to keep the direction not paginated. */
133
101
  cursor: PaginatorCursor | undefined;
134
- /**
135
- * Direction we just paginated in.
136
- *
137
- * May be undefined for non-directional queries (e.g. jump-to / *_around).
138
- */
102
+ /** Direction just paginated in. Undefined for non-directional queries (jump-to, `*_around`). */
139
103
  direction: PaginationDirection | undefined;
140
104
  hasMoreTail: boolean;
141
105
  hasMoreHead: boolean;
142
- /** The parent interval the page was ingested into (if any) */
143
106
  interval: Interval;
144
- /** The page we just received after filtering */
107
+ /** The page received, after filtering. */
145
108
  page: T[];
146
- /** Last query shape (sometimes useful for bespoke logic) */
147
109
  queryShape: Q | undefined;
148
- /** Number we asked for */
149
110
  requestedPageSize: number;
150
111
  };
151
112
 
@@ -183,62 +144,126 @@ export type PaginationQueryShapeChangeIdentifier<S> = (
183
144
  ) => boolean;
184
145
 
185
146
  export type PaginationQueryParams<Q> = {
147
+ /**
148
+ * Whether the query claims the active interval (see `BasePaginator.claimActiveInterval`): after
149
+ * a later claim, its page is only stored and the result reports `isSuperseded`. Default: see
150
+ * `BasePaginator.decidesActiveInterval`.
151
+ */
152
+ claimsActiveInterval?: boolean;
186
153
  direction?: PaginationDirection;
187
154
  /**
188
- * Keep the currently loaded items (and cursor/flags) visible while a first-page query runs
189
- * instead of blanking to the empty initial state. The freshly fetched page is merged into the
190
- * active interval by `postQueryReconcile` (upserting changed items, appending new ones), so the
191
- * list is refreshed in place with no loading-screen flash. Used by the non-destructive refresh.
155
+ * Keeps loaded items (and cursor/flags) visible during a first-page query instead of resetting;
156
+ * `placeQueryPage` merges the fetched page into the active interval.
192
157
  */
193
158
  keepPreviousItems?: boolean;
194
159
  /** Data that define the query (filters, sort, ...) */
195
160
  queryShape?: Q;
196
- /** Per-call override of the reset behavior. */
161
+ /** Per-call override: 'yes' forces a first page, 'no' continues, else the query shape decides. */
197
162
  reset?: StateResetPolicy;
198
163
  /**
199
- * How many times to **retry** a failed request, i.e. `retryCount + 1` attempts in total. Per-call
200
- * override of `PaginatorOptions.retryCount`, which defaults to 0 (no retry).
164
+ * Request options outside the query shape, so they never make the query a new first page. Each
165
+ * paginator reads the ones it documents. Resent on retries.
201
166
  */
167
+ requestOptions?: Record<string, unknown>;
168
+ /** Number of retries after a failure. Overrides `PaginatorOptions.retryCount`. */
202
169
  retryCount?: number;
203
170
  /**
204
- * Suppress `isLoading` transitions for this query (a silent, background refresh). When falsy
205
- * (default) the usual loading state is surfaced so the UI can show a spinner.
171
+ * Skips the `isLoading: true` publish for a non-first-page or `keepPreviousItems` query
172
+ * (background refresh). A first page without `keepPreviousItems` still surfaces loading.
206
173
  */
207
174
  silent?: boolean;
208
- /** Determines, whether the page loaded with the query will be committed to the paginator state. Default: true. */
175
+ /**
176
+ * Whether the page's interval becomes the active one and the state is published. Default: true.
177
+ * Otherwise the page is only stored; one landing in the active interval is still published. Even
178
+ * with it, the paginator's own page can be only stored (see `BasePaginator.isPageOnlyStored`).
179
+ */
209
180
  updateState?: boolean;
210
181
  };
211
182
 
212
- export type PostQueryReconcileParams<T, Q> = Pick<
183
+ /**
184
+ * How a query's page is placed: what `BasePaginator.placeQueryPage` takes besides the page itself.
185
+ * The last step of the query pipeline gets it too (see `BasePaginator.applyQueryResponseRest`).
186
+ */
187
+ export type QueryPagePlacement<Q> = Pick<
213
188
  PaginationQueryParams<Q>,
214
189
  'direction' | 'queryShape' | 'updateState' | 'keepPreviousItems'
215
190
  > & {
191
+ /**
192
+ * The query's claim on the active interval, for a query that claims it (see
193
+ * `PaginationQueryParams.claimsActiveInterval`). After a later claim, the page is only stored.
194
+ */
195
+ activeIntervalClaim?: number;
196
+ /**
197
+ * Whether the page starts a separate interval, merged only with intervals it overlaps, as its
198
+ * place relative to the active interval is unknown (queried elsewhere, or at a caller's shape).
199
+ * Otherwise it continues the active interval. Default: `false`, except for jump queries.
200
+ */
201
+ startsSeparateInterval?: boolean;
202
+ /**
203
+ * The interval active when a query from the paginator's own cursor was prepared. The page
204
+ * continues it only while it is still active (see `BasePaginator.isPageOnlyStored`).
205
+ */
206
+ continuesIntervalId?: string;
216
207
  isFirstPage: boolean;
208
+ /** The position a refresh keeping the items reset, restored when it places no page. */
209
+ positionBeforeReset?: Pick<PaginatorState<unknown>, 'cursor' | 'offset'>;
217
210
  requestedPageSize: number;
211
+ };
212
+
213
+ export type PlaceQueryPageParams<T, Q> = QueryPagePlacement<Q> & {
214
+ /** The page to place; `null` only ends the query. */
218
215
  results: PaginationQueryReturnValue<T> | null;
219
216
  };
220
217
 
218
+ /**
219
+ * What the preparing step of the query pipeline hands to the next ones (see
220
+ * `BasePaginator.executeQuery`): the parameters for fetching and for placing the page, and the
221
+ * offline preload a first page waits for before it is fetched, when there is one.
222
+ */
223
+ type PreparedQuery<Q> = {
224
+ fetchParams: PaginationQueryParams<Q>;
225
+ offlinePreloadPromise?: Promise<void>;
226
+ placeParams: QueryPagePlacement<Q>;
227
+ };
228
+
221
229
  export type ExecuteQueryReturnValue<T> = {
222
230
  /**
223
- * State object resulting from the post query processing.
224
- * The object is committed to the state if PaginationQueryParams<Q>['updateState'] === true.
231
+ * State from the placing step (see `BasePaginator.placeQueryPage`), committed when `updateState`
232
+ * is true.
225
233
  */
226
234
  stateCandidate: Partial<PaginatorState<T>>;
227
- /** In case the items are kept in intervals, the interval into which the page has been merged, will be returned. */
235
+ /** The interval the page was merged into, when items are kept in intervals. */
228
236
  targetInterval: AnyInterval | null;
237
+ /**
238
+ * Set by `BasePaginator.executeQuery`: whether a later claim on the active interval overtook the
239
+ * query's own (see `PaginationQueryParams.claimsActiveInterval`).
240
+ */
241
+ isSuperseded?: boolean;
229
242
  };
230
243
 
244
+ /**
245
+ * What a paginator's custom `doRequest` resolves to: a page of items, and its cursor with cursor
246
+ * pagination (see `BasePaginatorConfig.doRequest`).
247
+ */
248
+ export type DoRequestResponse<T> = { items: T[]; cursor?: PaginatorCursor };
249
+
231
250
  export type PaginationQueryReturnValue<T> = { items: T[] } & {
232
- headward?: string;
233
- tailward?: string;
234
251
  /**
235
- * @deprecated Use `tailward` instead.
252
+ * The cursor to the next page towards the head.
253
+ *
254
+ * - `null`: the page reaches the head of the dataset, so there is none. This holds for every
255
+ * paginator, including one that derives its cursors (`deriveCursor`).
256
+ * - `undefined` depends on where the paginator takes its cursors from. One that derives them reads it
257
+ * as not reported (a page queried towards the tail says nothing about the head side) and derives
258
+ * the cursor itself. One that takes them from the query reads it as no next page, as an API leaves
259
+ * out the cursor at the end.
236
260
  */
237
- next?: string;
261
+ headward?: string | null;
238
262
  /**
239
- * @deprecated Use `headward` instead.
263
+ * The cursor to the next page towards the tail; `null` and `undefined` as for {@link headward}, with
264
+ * `null` meaning the page reaches the tail of the dataset.
240
265
  */
241
- prev?: string;
266
+ tailward?: string | null;
242
267
  };
243
268
  export type PaginatorDebounceOptions = {
244
269
  debounceMs: number;
@@ -258,23 +283,21 @@ export type PaginatorState<T> = {
258
283
  };
259
284
 
260
285
  /**
261
- * Reactive projections of specific (fixed-identity) intervals, published independently of the
262
- * paginated `state` (which tracks only the *active* interval). See {@link BasePaginator.intervalViews}.
263
- * A field is rewritten only when its own interval changes, so a `useStateStore`/`subscribeWithSelector`
264
- * consumer selecting one field only wakes when *that* interval changes. (The head-most window that can
265
- * be either a logical or an anchored interval is a derived *role*, not a fixed interval, so it is not
266
- * published here — read it one-shot via {@link BasePaginator.headItems} / {@link BasePaginator.headmostItem}.)
286
+ * Projections of fixed-identity intervals, published independently of `state` (which tracks only
287
+ * the active interval; see {@link BasePaginator.intervalViews}). A field is rewritten only when its
288
+ * own interval changes. One-shot reads: {@link BasePaginator.anchoredHeadItems},
289
+ * {@link BasePaginator.logicalHeadItems}, {@link BasePaginator.logicalTailItems}.
267
290
  */
268
291
  export type PaginatorIntervalViews<T> = {
269
- /** Live logical-head interval — out-of-order items above the loaded window. */
270
- logicalHead: T[];
271
- /** Live logical-tail interval — out-of-order items below the loaded window. */
272
- logicalTail: T[];
273
292
  /**
274
- * Anchored head interval — the loaded page bounded at the dataset head (`isHead`), i.e. the newest
275
- * loaded page; empty when the head is not loaded. Its content updates when that page ingests/removes
276
- * an item, and its identity updates when a page's `isHead` flag flips during query reconciliation.
293
+ * Out-of-order items above the loaded interval. With no page loaded (before the first one, or after
294
+ * every loaded item left the list) the logical head can itself be the active interval, and then
295
+ * `state.items` lists the same items: a UI rendering both shows them twice.
277
296
  */
297
+ logicalHead: T[];
298
+ /** Out-of-order items below the loaded interval; can be the active interval too, as above. */
299
+ logicalTail: T[];
300
+ /** The loaded page bounded at the dataset head (`isHead`); empty when the head is not loaded. */
278
301
  anchoredHead: T[];
279
302
  };
280
303
 
@@ -287,19 +310,8 @@ export type PaginatorItemsChangeProcessor<T> = (params: {
287
310
 
288
311
  export interface PaginatorPlugin<T> {
289
312
  /**
290
- * Optional plugin hook invoked immediately before the paginator emits a new
291
- * `items` value to subscribers, but only when the `items` array has actually
292
- * changed by reference.
293
- *
294
- * This hook allows plugins to post-process the visible items—such as
295
- * deduplicating, normalizing, sorting, enriching, or otherwise transforming
296
- * the array—at the final stage of state emission. The processed value becomes
297
- * the `items` value delivered to subscribers.
298
- *
299
- * Return a new array to replace `nextState.items`, or return `undefined`
300
- * to leave the items unchanged.
301
- *
302
- * Executed in the order plugins are registered.
313
+ * Runs before `items` are emitted, only when the array changed by reference. Return a new array
314
+ * to replace `nextState.items`, or `undefined` to keep it. Runs in registration order.
303
315
  */
304
316
  onBeforeItemsEmitted?: PaginatorItemsChangeProcessor<T>;
305
317
 
@@ -309,25 +321,14 @@ export interface PaginatorPlugin<T> {
309
321
  // onQueryError?(ctx: { error: unknown; paginator: BasePaginator<T, Q> }): void | Promise<void>;
310
322
  }
311
323
 
312
- /**
313
- * Optional list of plugins that can hook into paginator lifecycle events.
314
- *
315
- * Plugins allow you to encapsulate cross-cutting behavior (such as items
316
- * post-processing, analytics, offline caching, etc.) without modifying
317
- * the core paginator logic. Each plugin can register handlers like
318
- * `onItemsChange` that are invoked when relevant events occur.
319
- *
320
- * All registered plugins are executed in the order they appear in this array.
321
- */
324
+ // Plugins hook into the paginator lifecycle and run in array order.
322
325
  // plugins?: PaginatorPlugin<T, Q>[];
323
326
 
324
327
  /**
325
- * The value-level subset of paginator configuration that can be supplied declaratively through
326
- * `client.config`. Structural inputs (`itemIndex`, `createItemIndex`) and subclass behaviour overrides
327
- * (`doRequest`, `itemOrderComparator`, `deriveCursor`) are deliberately absent — see
328
- * {@link BasePaginator.initializeConfig}.
329
- *
330
- * Declared standalone rather than derived from {@link PaginatorOptions} to avoid a circular type.
328
+ * The value-level subset of paginator options that `client.config` can supply declaratively.
329
+ * Structural inputs (`itemIndex`, `createItemIndex`) and subclass overrides (`doRequest`,
330
+ * `itemOrderComparator`, `deriveCursor`) are excluded. Declared standalone to avoid a circular type
331
+ * with `PaginatorOptions`.
331
332
  */
332
333
  export type DeclarativePaginatorConfig = {
333
334
  debounceMs?: number;
@@ -335,6 +336,7 @@ export type DeclarativePaginatorConfig = {
335
336
  initialCursor?: PaginatorCursor;
336
337
  initialOffset?: number;
337
338
  lockItemOrder?: boolean;
339
+ maxLoadedItems?: number;
338
340
  pageSize?: number;
339
341
  retryCount?: number;
340
342
  stateThrottleMs?: number;
@@ -343,77 +345,75 @@ export type DeclarativePaginatorConfig = {
343
345
 
344
346
  export type PaginatorOptions<T, Q> = {
345
347
  /**
346
- * Declarative configuration for this paginator, supplied by whoever constructs it from
347
- * `client.config`. Kept separate from the other options so {@link BasePaginator.initializeConfig}
348
- * can re-derive with a *fresh* slice — a reset then drops declarative values while preserving
349
- * constructor-injected ones. Excluded from {@link BasePaginatorConfig}: it is an input, not part of
350
- * the resolved configuration.
348
+ * Declarative values from `client.config`, kept apart so a reset (`initializeConfig` with a fresh
349
+ * slice) drops them but keeps injected options. Not part of {@link BasePaginatorConfig}.
351
350
  */
352
351
  declarativeConfig?: DeclarativePaginatorConfig;
353
- /** The number of milliseconds to debounce the search query. The default interval is 300ms. */
352
+ /** Debounce of the search query in milliseconds. Defaults to 300. */
354
353
  debounceMs?: number;
355
354
  /**
356
- * When set (and not disabled for tests — see `stateThrottling.ts`), coalesces the paginator's own
357
- * live `state.items` publishes to at most once per `stateThrottleMs` (leading + trailing edge): a
358
- * burst of live mutations (WS `message.new`, reactions, reads) re-projects the active window and
359
- * publishes it ~2×/sec instead of once per event. Only the paginator's OWN writes to `state.items`
360
- * are batched — `state.getLatestValue()` is untouched (no `StateStore` change), pagination / jump /
361
- * query publishes stay immediate, and an immediate flush past it is available via
362
- * {@link flushPendingPublishes}. Unset ⇒ no throttle (default). Enabled at
363
- * 500ms for the message list — see {@link MessagePaginator}.
355
+ * Coalesces the paginator's own live `state.items` publishes to one per `stateThrottleMs`
356
+ * (leading and trailing edge). Pagination, jump and query publishes stay immediate. Disabled
357
+ * under test runners. Unset: no throttle.
364
358
  */
365
359
  stateThrottleMs?: number;
366
360
  /**
367
- * Function containing custom logic that decides, whether the next pagination query to be executed should be considered the first page query.
368
- * It makes sense to consider the next query as the first page query if filters, sort, options etc. (query params) excluding the page size have changed.
361
+ * Decides whether the next query is a first-page query. It should be when filters, sort or
362
+ * options (the query params except page size) changed.
369
363
  */
370
-
371
364
  hasPaginationQueryShapeChanged?: PaginationQueryShapeChangeIdentifier<any>;
372
365
  /**
373
- * Optional hook to fully control cursor + hasMore logic in 'derived' mode.
374
- * If not provided, BasePaginator uses its own default implementation.
366
+ * Derives the cursor and `hasMore` flags from the ingested interval. Without it, the cursor comes
367
+ * from the query response (`headward`/`tailward`, falsy meaning exhausted).
375
368
  */
376
369
  deriveCursor?: CursorDerivator<T, Q>;
377
- /** Custom function to retrieve items pages and optionally return a cursor in case of cursor pagination. */
378
- doRequest?: (queryParams: Q) => Promise<{ items: T[]; cursor?: PaginatorCursor }>;
379
- /** In case of cursor pagination, specify the initial cursor value. */
370
+ /**
371
+ * Custom function to retrieve items pages and optionally return a cursor in case of cursor
372
+ * pagination. A `null` cursor side tells that the page reaches that end of the dataset; an
373
+ * `undefined` side is read as {@link PaginationQueryReturnValue.headward} describes for this
374
+ * paginator.
375
+ */
376
+ doRequest?: (queryParams: Q) => Promise<DoRequestResponse<T>>;
380
377
  initialCursor?: PaginatorCursor;
381
- /** In case of offset pagination, specify the initial offset value. */
382
378
  initialOffset?: number;
383
- /** If item index is provided, this index ensures updates in a single place and all consumers have access to a single source of data. */
379
+ /** Shared item index: a single source of data for all consumers. */
384
380
  itemIndex?: ItemIndexApi<T>;
385
381
  /**
386
- * Factory for the item index, invoked with the fully-constructed paginator as `owner`.
387
- * Lets a subclass back the paginator with an adapter that needs a reference to the
388
- * owner (e.g. a shared, client-global store) without the `this`-before-`super` problem.
389
- * Ignored when an explicit `itemIndex` is supplied.
382
+ * Builds the item index from the paginator (`owner`), for adapters that need it (e.g. a
383
+ * client-global store). Runs in the base constructor, before subclass fields are initialized.
384
+ * Ignored when `itemIndex` is supplied.
390
385
  */
391
- createItemIndex?: (owner: BasePaginator<T, Q>) => ItemIndexApi<T>;
386
+ createItemIndex?: (owner: BasePaginator<T, Q, unknown>) => ItemIndexApi<T>;
392
387
  /**
393
- * Comparator defining in-memory item ordering for interval math and visible list rendering.
394
- * Defaults to `sortComparator` to preserve existing paginator behavior.
388
+ * Orders items in memory for interval math and the visible list. Defaults to `sortComparator`.
395
389
  */
396
390
  itemOrderComparator?: (a: T, b: T) => number;
397
391
  /**
398
- * Will prevent changing the index of existing items in state.
399
- * If true, an item that is already visible keeps its relative position in the current items array when updated.
400
- * It does not guarantee global stability across interval changes or page jumps.
392
+ * An already visible item keeps its relative position in the current items array when updated.
393
+ * Does not hold across interval changes or page jumps.
401
394
  */
402
395
  lockItemOrder?: boolean;
403
- /** The item page size to be requested from the server. */
396
+ /**
397
+ * Caps the loaded items: when the head interval exceeds it, the oldest are released as new ones
398
+ * arrive and the tailward edge re-opens, so scrolling back re-fetches. Unset: unbounded. Values
399
+ * below `pageSize` are clamped up to it. See {@link BasePaginator.pruneTailToLimit}.
400
+ */
401
+ maxLoadedItems?: number;
402
+ /** Items requested per page. Defaults to 10. */
404
403
  pageSize?: number;
405
404
  /**
406
- * How many times to **retry** a failed request before giving up, i.e. `retryCount + 1` attempts in
407
- * total, with `DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES` between them. Defaults to 0 (no retry);
405
+ * Retries after a failed request (`retryCount + 1` attempts),
406
+ * `DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES` apart. Defaults to 0.
408
407
  * `PaginationQueryParams.retryCount` overrides it per call.
409
408
  */
410
409
  retryCount?: number;
411
- /** Prevent silencing the errors thrown during the pagination execution. Default is false. */
410
+ /** Rethrows errors from pagination execution instead of swallowing them. Defaults to false. */
412
411
  throwErrors?: boolean;
413
412
  };
414
413
 
415
414
  type OptionalPaginatorConfigFields =
416
415
  | 'stateThrottleMs'
416
+ | 'maxLoadedItems'
417
417
  | 'deriveCursor'
418
418
  | 'doRequest'
419
419
  | 'initialCursor'
@@ -422,12 +422,8 @@ type OptionalPaginatorConfigFields =
422
422
  | 'throwErrors';
423
423
 
424
424
  /**
425
- * Construction-only inputs that are not part of the resolved configuration.
426
- *
427
- * `itemIndex` and `createItemIndex` are here rather than in {@link BasePaginatorConfig} because the
428
- * constructor destructures them out before building the config and resolves them once into
429
- * {@link BasePaginator._itemIndex}. They were typed as config members and never written, so
430
- * `paginator.config.itemIndex` compiled and returned `undefined` for every paginator ever built.
425
+ * Options minus the construction-only inputs: the constructor resolves `itemIndex` and
426
+ * `createItemIndex` once into {@link BasePaginator._itemIndex}, so they are not config.
431
427
  */
432
428
  type ResolvedPaginatorOptions<T, Q> = Omit<
433
429
  PaginatorOptions<T, Q>,
@@ -455,103 +451,91 @@ export const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any> = deepFre
455
451
  } as const,
456
452
  );
457
453
 
458
- export abstract class BasePaginator<T, Q> {
454
+ /**
455
+ * Loads a sorted dataset page by page and keeps what it loaded as intervals.
456
+ *
457
+ * Terms used across the paginators, their names and their docs:
458
+ * - **interval**: a contiguous run of loaded items, with nothing missing between them
459
+ * ({@link Interval}). A page that connects to a loaded interval merges into it
460
+ * ({@link IntervalMergePolicy}); one that does not is kept as an interval of its own, so several
461
+ * intervals can be loaded at once.
462
+ * - **head / tail**: the two ends of the dataset in its sort order, and the matching ends of an
463
+ * interval. "Headward" and "tailward" are the directions toward them.
464
+ * - **active interval**: the interval whose items `state.items` exposes. The paginator's own
465
+ * navigation (loading toward the head or tail, jumping to an item) moves it; a page placed from
466
+ * outside moves it only where a subclass's placement rules say so.
467
+ * - **anchored head interval**: the loaded interval that reaches the head of the dataset
468
+ * (`isHead`); see {@link BasePaginator.anchoredHeadItems}. An interval reached by a jump is not
469
+ * anchored until it loads up to the head.
470
+ * - **logical head / tail interval**: items that arrived beyond the loaded head or tail and wait
471
+ * there until a page covers them ({@link LogicalInterval}).
472
+ *
473
+ * Say "interval", never "window": "window" is kept for the browser global and for time spans.
474
+ */
475
+ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
459
476
  state: StateStore<PaginatorState<T>>;
460
477
  /**
461
- * Reactive projections of specific intervals — see {@link PaginatorIntervalViews}. Unlike `state`
462
- * (which only re-emits when the *active* interval is impacted), a field here is rewritten whenever
463
- * its own interval changes, regardless of which interval is active — so consumers can reactively
464
- * render off-window "sideloaded" content (`logicalHead`/`logicalTail`) and the newest loaded page
465
- * (`anchoredHead`). Kept separate from `state` so the paginated-list contract stays focused on the
466
- * active window + pagination status.
478
+ * Projections of specific intervals ({@link PaginatorIntervalViews}). Unlike `state`, a field is
479
+ * rewritten whenever its own interval changes, active or not.
467
480
  */
468
481
  intervalViews: StateStore<PaginatorIntervalViews<T>>;
469
482
 
470
- /** The shared configuration machinery — see {@link ConfigController}. */
471
483
  private readonly configController: ConfigController<BasePaginatorConfig<T, Q>>;
472
- /**
473
- * The paginator's resolved configuration, as a store so consumers can react to it.
474
- *
475
- * Every configurable class exposes its resolved configuration this way — `configState` for the store,
476
- * {@link config} for the current value. Before this, paginators held a plain object that changed
477
- * silently, so anything displaying a paginator's settings had to poll to notice a
478
- * `client.config.set()` or `reset()`.
479
- *
480
- * This is *resolved* configuration, distinct from `client.config`, which holds the configuration you
481
- * registered. The registered tree is an input to {@link initializeConfig}; this is its output.
482
- */
483
484
  get configState(): StateStore<BasePaginatorConfig<T, Q>> {
484
485
  return this.configController.state;
485
486
  }
486
487
 
487
- /**
488
- * Options this paginator was constructed with, kept so {@link initializeConfig} can rebuild the
489
- * config from its real inputs instead of restoring a snapshot of the result. Excludes the
490
- * declarative slice, which is supplied fresh on every call — that is what lets a reset drop
491
- * declarative configuration while keeping constructor-injected options.
492
- */
488
+ /** Constructor options minus the declarative slice, for `initializeConfig` to rebuild from. */
493
489
  private readonly explicitOptions: Omit<
494
490
  PaginatorOptions<T, Q>,
495
491
  'createItemIndex' | 'declarativeConfig' | 'itemIndex'
496
492
  >;
497
493
 
498
- /**
499
- * Throttle for the active-window `state.items` publish (message list). Created only when
500
- * `config.stateThrottleMs` is set; drives {@link scheduleWindowPublish} / {@link flushPendingPublishes}. See
501
- * `stateThrottleMs` in {@link PaginatorOptions}.
502
- */
503
- private _windowPublishThrottle?: Throttled<[]>;
494
+ /** Throttle for the active-interval `state.items` publish. Set only with `stateThrottleMs`. */
495
+ private _activeIntervalPublishThrottle?: Throttled<[]>;
504
496
 
505
497
  /**
506
- * Throttle for the interval-view publishes (`anchoredHead` / `logicalHead` / `logicalTail`) driven
507
- * by sibling store updates. Independent of {@link _windowPublishThrottle} so a view refresh lands on
508
- * its own trailing edge even when `state.items` stays quiet. Created alongside it (only when
509
- * `config.stateThrottleMs` is set); buffers changed ids in {@link _pendingViewChangedIds}.
498
+ * Throttle for interval-view publishes. Independent of {@link _activeIntervalPublishThrottle} so
499
+ * a view refresh lands on its own trailing edge even when `state.items` is quiet. Created with it.
510
500
  */
511
501
  private _viewPublishThrottle?: Throttled<[]>;
512
502
 
513
- /** Changed ids buffered since the last {@link flushIntervalViewPublish} (throttled paginators only). */
503
+ /** Changed IDs buffered since the last {@link flushIntervalViewPublish} (throttled only). */
514
504
  private _pendingViewChangedIds = new Set<string>();
515
505
 
516
506
  /**
517
- * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem` / `removeItem` record
518
- * that the active window changed (see {@link _suspendedWindowDirty}) instead of publishing it, so
519
- * the whole batch produces a single `state.items` emit — independent of state throttling.
507
+ * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`/`removeItem` record
508
+ * the changed interval ({@link _staleActiveIntervalState}) instead of publishing.
520
509
  */
521
- private _windowPublishSuspendDepth = 0;
522
- /** Set by a suspended op that changed the active window, so {@link batch} publishes once on exit. */
523
- private _suspendedWindowDirty = false;
524
-
510
+ private _activeIntervalPublishSuspendDepth = 0;
525
511
  /**
526
- * Intervals keep items in disconnected ranges.
527
- * That is a scenario of jumping to non-sequential pages.
528
- * Intervals are populated only if itemIndex is provided.
512
+ * The interval a prune just shortened. Its `hasMoreTail` and `cursor` ride on the next
513
+ * `state.items` publish, which can be a throttle interval late, so
514
+ * {@link consumePendingPrunePaginationState} rereads them from the interval by ID when it fires.
529
515
  */
516
+ private _prunedIntervalId?: string;
517
+ /** The state shown when a suspended op last changed the active interval (see {@link batch}). */
518
+ private _staleActiveIntervalState?: PaginatorState<T>;
519
+
520
+ /** Disconnected ranges of items, e.g. after jumping to non-sequential pages. */
530
521
  protected _itemIntervals: Map<string, AnyInterval> = new Map();
531
522
  protected _activeIntervalId: string | undefined;
523
+ /** How many claims on the active interval were made; the latest one decides it. */
524
+ private _activeIntervalClaimCount = 0;
532
525
 
533
- /**
534
- * ItemIndex is a canonical, ID-addressable storage layer for domain items.
535
- * It serves as a single source of truth for all those that need to access the items
536
- * outside the paginator.
537
- */
526
+ /** Canonical, ID-addressable item storage: the single source of truth outside the paginator. */
538
527
  protected _itemIndex: ItemIndexApi<T>;
539
528
 
540
529
  protected _executeQueryDebounced!: DebouncedExecQueryFunction<Q>;
541
- /** Last effective query shape produced by subclass for the most recent request. */
530
+ /** Last effective query shape produced by the subclass for the most recent request. */
542
531
  protected _lastQueryShape?: Q;
543
- protected _nextQueryShape?: Q;
532
+ /** Set by `setItems`, which loads a page (even an empty one) without a query. */
533
+ private _pageSetWithoutQuery = false;
544
534
 
545
535
  /**
546
- * Stable, performs purely item data-driven (age, last_message_at, etc.) comparison.
547
- * Used under the hood
548
- * 1. as a fallback by effectiveComparator / boostComparator if boost comparison is not conclusive
549
- * 2. interval comparator
550
- *
551
- * Intervals cannot be sorted using boostComparator, because boosting the interval boundary (top item)
552
- * would lead to the boosting of the entire interval when sorting the intervals.
553
- *
554
- * Sorting within a single interval should be done using effectiveComparator, which by default uses boostComparator.
536
+ * Stable, purely data-driven comparison (age, timestamps, ...). Default for
537
+ * `itemOrderComparator`, which orders items and intervals and breaks `boostComparator` ties.
538
+ * Intervals never use the boost order: boosting a boundary item would boost its whole interval.
555
539
  */
556
540
  sortComparator: (a: T, b: T) => number;
557
541
  protected _filterFieldToDataResolvers: FieldToDataResolver<T>[];
@@ -560,37 +544,25 @@ export abstract class BasePaginator<T, Q> {
560
544
  protected _maxBoostSeq = 0;
561
545
 
562
546
  /**
563
- * Describes how `interval.itemIds` are oriented relative to pagination semantics.
564
- *
565
- * - `true` => `itemIds[0]` is the pagination head edge (default)
566
- * - `false` => `itemIds[itemIds.length - 1]` is the pagination head edge
567
- *
568
- * NOTE: This does not affect the *sorting* of `itemIds` (they are always kept
569
- * in `sortComparator` order). It only affects which side is considered
570
- * "head" for interval ordering and live ingestion decisions.
547
+ * Whether `itemIds[0]` (true) or the last ID (false) is the pagination head edge. Defaults to
548
+ * true. `itemIds` stay in `itemOrderComparator` order either way.
571
549
  */
572
550
  protected get intervalItemIdsAreHeadFirst(): boolean {
573
551
  return true;
574
552
  }
575
553
 
576
554
  /**
577
- * Determines the ordering of intervals in the internal interval list.
578
- *
579
- * This controls only the ordering of intervals relative to each other (by comparing
580
- * their head edges using `sortComparator`). It is intentionally decoupled from:
581
- * - the ordering of itemIds inside an interval
582
- * - the meaning of the head edge (controlled by `intervalItemIdsAreHeadFirst`)
555
+ * Order of intervals relative to each other, comparing head edges under `itemOrderComparator`.
556
+ * Independent of the `itemIds` order and of `intervalItemIdsAreHeadFirst`.
583
557
  */
584
558
  protected get intervalSortDirection(): 'asc' | 'desc' {
585
559
  return 'asc';
586
560
  }
587
561
 
588
562
  /**
589
- * @param options - what the **integrator** passed. Stage 3, so it outranks the declarative tree.
590
- * @param builtInDefaults - what the SDK supplies on this instance's behalf — a subclass's defaults, or
591
- * an owner's for the object it builds. Stage 1, so a `client.config.set()` overrides it. Keeping the
592
- * two apart is what lets the documented layer order apply here at all: they arrive through the same
593
- * object otherwise, and a paginator built with no configuration already carries four of them.
563
+ * @param options - What the integrator passed. Outranks the declarative `client.config` tree.
564
+ * @param builtInDefaults - What the SDK supplies on the instance's behalf (a subclass's or an
565
+ * owner's defaults). A `client.config.set()` overrides these.
594
566
  */
595
567
  protected constructor(
596
568
  {
@@ -610,10 +582,7 @@ export abstract class BasePaginator<T, Q> {
610
582
  constructorOptions: this.explicitOptions as Partial<BasePaginatorConfig<T, Q>>,
611
583
  initialSlice: declarativeConfig as Partial<BasePaginatorConfig<T, Q>> | undefined,
612
584
  getBehaviourOverrides: () => this.getBehaviourOverrides(),
613
- // Both of these are read once into a closure, so storing a new value achieves nothing on its own.
614
- // Pairing the write with the rebuild here rather than in `initializeConfig` is what finally makes
615
- // `updateConfig({ debounceMs })` work: it used to store 900 and leave the debounce running at 300,
616
- // so `config.debounceMs` reported a value the paginator was not using.
585
+ // Both values are captured in closures, so a change must rebuild them.
617
586
  onChanged: (next, previous) => {
618
587
  if (next.debounceMs !== previous.debounceMs) {
619
588
  this.setDebounceOptions({ debounceMs: next.debounceMs });
@@ -626,14 +595,12 @@ export abstract class BasePaginator<T, Q> {
626
595
  const { debounceMs } = this.config;
627
596
  this.state = new StateStore<PaginatorState<T>>({
628
597
  ...this.initialState,
629
- // Seeded from the *resolved* config, not the raw constructor argument. These two are the reason
630
- // `initialCursor`/`initialOffset` are construction-only: they prime state, not just configuration.
631
- // Reading the argument directly missed a subclass's own default once those moved to stage 1 — and
632
- // it also meant a declaratively registered cursor configured the paginator without seeding it.
598
+ // Seeded from the resolved config (subclass defaults, declarative values), not the raw
599
+ // argument.
633
600
  cursor: this.config.initialCursor,
634
601
  offset: this.config.initialOffset ?? 0,
635
602
  });
636
- // Direct, not through the setter: `onChanged` fires on *changes*, and this is the initial build.
603
+ // Called directly: `onChanged` fires on changes, not on the initial build.
637
604
  this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
638
605
  this.intervalViews = new StateStore<PaginatorIntervalViews<T>>({
639
606
  logicalHead: [],
@@ -646,13 +613,12 @@ export abstract class BasePaginator<T, Q> {
646
613
  this._itemIndex =
647
614
  itemIndex ??
648
615
  createItemIndex?.(this) ??
649
- new StoreBackedItemIndex({ getEntityId: this.getItemId.bind(this) });
616
+ new StoreBackedItemIndex({
617
+ getEntityId: this.getItemId.bind(this),
618
+ holderName: 'base-paginator',
619
+ });
650
620
  }
651
621
 
652
- // ---------------------------------------------------------------------------
653
- // Basic getters
654
- // ---------------------------------------------------------------------------
655
-
656
622
  get lastQueryError() {
657
623
  return this.state.getLatestValue().lastQueryError;
658
624
  }
@@ -665,20 +631,6 @@ export abstract class BasePaginator<T, Q> {
665
631
  return this.state.getLatestValue().hasMoreHead;
666
632
  }
667
633
 
668
- /**
669
- * @deprecated Use `hasMoreTail` instead.
670
- */
671
- get hasNext() {
672
- return this.hasMoreTail;
673
- }
674
-
675
- /**
676
- * @deprecated Use `hasMoreHead` instead.
677
- */
678
- get hasPrev() {
679
- return this.hasMoreHead;
680
- }
681
-
682
634
  get hasResults() {
683
635
  return Array.isArray(this.state.getLatestValue().items);
684
636
  }
@@ -687,11 +639,26 @@ export abstract class BasePaginator<T, Q> {
687
639
  return this.state.getLatestValue().isLoading;
688
640
  }
689
641
 
690
- /** Signals that the paginator has not performed any query so far */
642
+ /**
643
+ * True once a query has run or a non-empty interval was loaded without one (`setItems`, or a
644
+ * subclass calling `recordLoadedIntervalQueryShape`). Cleared by `resetState`.
645
+ */
691
646
  get isInitialized() {
692
647
  return typeof this._lastQueryShape !== 'undefined';
693
648
  }
694
649
 
650
+ /**
651
+ * True once a page was loaded: by a query, or by `setItems`, including an empty page (e.g. a
652
+ * catch-all list seeded so it never runs its own query). Items that live events ingested into a
653
+ * never-queried list are not a loaded page, although they make `items` defined: a UI deciding
654
+ * whether to run the first query reads this, not `items === undefined`. Unlike `isInitialized`,
655
+ * an empty `setItems` page counts, so connection recovery (which re-runs initialized lists'
656
+ * queries) still skips such a list. Cleared by `resetState`.
657
+ */
658
+ get hasLoadedPage() {
659
+ return this._pageSetWithoutQuery || this.isInitialized;
660
+ }
661
+
695
662
  get isOfflineSupportEnabled() {
696
663
  return false;
697
664
  }
@@ -716,33 +683,6 @@ export abstract class BasePaginator<T, Q> {
716
683
  return this.state.getLatestValue().items;
717
684
  }
718
685
 
719
- /**
720
- * The newest loaded window of items, independent of which window is currently *active*
721
- * (`items` follows the active interval, which may point at a jumped-to / searched window). This is
722
- * the head-most loaded interval under the paginator's ordering (anchored or the live-head logical
723
- * interval).
724
- *
725
- * NOTE: this deliberately uses the head-*most loaded* interval rather than requiring the
726
- * `isHead` flag — the query/hydration seed does not reliably mark a freshly loaded latest page
727
- * as `isHead`, so an isHead-only check would miss channel-list channels entirely. The trade-off
728
- * is that after jumping to an older window with the latest window not loaded, this reports that
729
- * older window as "latest" (best effort). Use for "latest"-derived reads: last message, unread
730
- * counting, delivery candidates, channel-list previews.
731
- */
732
- get headItems(): T[] {
733
- const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
734
- return head ? this.intervalToItems(head) : [];
735
- }
736
-
737
- /**
738
- * The item on the head edge of the head pagination interval (of {@link BasePaginator.headItems}).
739
- * `undefined` when nothing is loaded.
740
- */
741
- get headmostItem(): T | undefined {
742
- const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
743
- return head ? (this.getIntervalPaginationEdges(head)?.head ?? undefined) : undefined;
744
- }
745
-
746
686
  get cursor() {
747
687
  return this.state.getLatestValue().cursor;
748
688
  }
@@ -751,21 +691,15 @@ export abstract class BasePaginator<T, Q> {
751
691
  return this.state.getLatestValue().offset;
752
692
  }
753
693
 
754
- /**
755
- * The current resolved configuration.
756
- *
757
- * `Readonly` on purpose: the value is the store's live object, so assigning to a field of it would
758
- * mutate state without notifying anyone. That used to be the only way to change these values, so the
759
- * type is what turns those call sites into compile errors rather than silent non-reactive writes —
760
- * use {@link updateConfig}.
761
- */
762
694
  get config(): Readonly<BasePaginatorConfig<T, Q>> {
763
695
  return this.configState.getLatestValue();
764
696
  }
765
697
 
766
698
  /**
767
- * Merges a partial configuration into the resolved config and notifies subscribers, unless every
768
- * field in the patch already holds an equal value.
699
+ * Merges a partial configuration into the resolved config. The next `initializeConfig` discards
700
+ * it.
701
+ *
702
+ * @param config - The fields to merge.
769
703
  */
770
704
  updateConfig(config: Partial<BasePaginatorConfig<T, Q>>) {
771
705
  this.configController.patch(config);
@@ -787,7 +721,7 @@ export abstract class BasePaginator<T, Q> {
787
721
  this.updateConfig({ initialOffset: offset });
788
722
  }
789
723
 
790
- /** Single point of truth: always use the effective comparator */
724
+ /** The boost-aware comparator to use for ordering items. */
791
725
  get effectiveComparator() {
792
726
  return this.boostComparator;
793
727
  }
@@ -800,9 +734,9 @@ export abstract class BasePaginator<T, Q> {
800
734
  return (a: AnyInterval, b: AnyInterval) => {
801
735
  const aEdges = this.getIntervalPaginationEdges(a);
802
736
  const bEdges = this.getIntervalPaginationEdges(b);
803
- if (!aEdges || !bEdges) return 0;
804
- if (!aEdges) return 1; // move interval without bounds to the end
805
- if (!bEdges) return -1; // keep interval a preceding b
737
+ if (!aEdges && !bEdges) return 0;
738
+ if (!aEdges) return 1;
739
+ if (!bEdges) return -1;
806
740
  return this.compareIntervalHeadEdges(aEdges.head, bEdges.head);
807
741
  };
808
742
  }
@@ -825,43 +759,58 @@ export abstract class BasePaginator<T, Q> {
825
759
  return itv && isLiveTailInterval(itv) ? itv : undefined;
826
760
  }
827
761
 
828
- /**
829
- * The current contents of the live logical-head interval (items ingested out of pagination order).
830
- * Reads the same value published to {@link BasePaginator.intervalViews}.`logicalHead`.
831
- */
762
+ /** `intervalViews.logicalHead`: out-of-order items above the loaded interval. */
832
763
  get logicalHeadItems(): T[] {
833
764
  return this.intervalViews.getLatestValue().logicalHead;
834
765
  }
835
766
 
836
- /**
837
- * The current contents of the live logical-tail interval (out-of-order items below the loaded
838
- * window). Reads the same value published to {@link BasePaginator.intervalViews}.`logicalTail`.
839
- */
767
+ /** `intervalViews.logicalTail`: out-of-order items below the loaded interval. */
840
768
  get logicalTailItems(): T[] {
841
769
  return this.intervalViews.getLatestValue().logicalTail;
842
770
  }
843
771
 
844
772
  /**
845
- * The current contents of the anchored head interval (the loaded page bounded at the dataset head,
846
- * `isHead`). Reads the same value published to {@link BasePaginator.intervalViews}.`anchoredHead`.
773
+ * The anchored head interval: the loaded interval that reaches the head of the dataset (`isHead`).
774
+ * `undefined` while that interval is not loaded, for example when only an interval reached by a
775
+ * jump is.
776
+ */
777
+ protected get anchoredHeadInterval(): Interval | undefined {
778
+ for (const interval of this._itemIntervals.values()) {
779
+ if (!isLogicalInterval(interval) && interval.isHead) return interval;
780
+ }
781
+ return undefined;
782
+ }
783
+
784
+ /**
785
+ * The items of the anchored head interval; empty while it is not loaded (an interval reached by a
786
+ * jump never counts). Reactive counterpart: `intervalViews.anchoredHead`.
847
787
  */
848
788
  get anchoredHeadItems(): T[] {
849
- return this.intervalViews.getLatestValue().anchoredHead;
789
+ const head = this.anchoredHeadInterval;
790
+ return head ? this.intervalToItems(head) : [];
791
+ }
792
+
793
+ /**
794
+ * The item at the head edge of the anchored head interval (see {@link anchoredHeadItems}).
795
+ * `undefined` while that interval is not loaded, including once an interval is known to lack items
796
+ * toward the head (see {@link unmarkHead}). A loaded interval always holds an item, so this also
797
+ * tells whether it is loaded.
798
+ */
799
+ get anchoredHeadItem(): T | undefined {
800
+ const head = this.anchoredHeadInterval;
801
+ return head ? (this.getIntervalPaginationEdges(head)?.head ?? undefined) : undefined;
850
802
  }
851
803
 
852
804
  /**
853
- * Commit an interval into storage. Single choke point for adding/updating an interval, so it also
854
- * republishes the matching {@link intervalViews} field when the committed interval is a tracked one
855
- * (logical head / logical tail / anchored head). Use this instead of writing `_itemIntervals`
856
- * directly — bulk re-sorting (which does not change any interval's membership) goes through
857
- * {@link setIntervals}.
805
+ * Commits an interval to storage and republishes its {@link intervalViews} field when tracked.
806
+ * Use it instead of writing `_itemIntervals` (bulk re-sorting goes through {@link setIntervals}).
858
807
  */
859
808
  protected commitInterval(interval: AnyInterval) {
860
809
  this._itemIntervals.set(interval.id, interval);
861
810
  this.publishIntervalViewFor(interval);
862
811
  }
863
812
 
864
- /** Drop an interval from storage, republishing the matching {@link intervalViews} field if tracked. */
813
+ /** Drops an interval from storage, republishing its {@link intervalViews} field if tracked. */
865
814
  protected dropInterval(id: string) {
866
815
  const removed = this._itemIntervals.get(id);
867
816
  this._itemIntervals.delete(id);
@@ -869,11 +818,9 @@ export abstract class BasePaginator<T, Q> {
869
818
  }
870
819
 
871
820
  /**
872
- * Republish the {@link intervalViews} field backed by the given interval — called from
873
- * {@link commitInterval} / {@link dropInterval} (i.e. when that interval ingests or removes an item).
874
- * A write to an untracked interval touches nothing here. (The anchored head is also published
875
- * directly via {@link publishAsAnchoredHead} from the reconciliation points that flip `isHead` —
876
- * see {@link postQueryReconcile}.)
821
+ * Republishes the {@link intervalViews} field backed by the interval (untracked ones change
822
+ * nothing). Placing a page also publishes the anchored head when `isHead` flips (see
823
+ * {@link publishAsAnchoredHead}).
877
824
  */
878
825
  private publishIntervalViewFor(interval: AnyInterval, { removed = false } = {}) {
879
826
  if (interval.id === LOGICAL_HEAD_INTERVAL_ID) {
@@ -885,51 +832,120 @@ export abstract class BasePaginator<T, Q> {
885
832
  logicalTail: this.intervalItemsOrEmpty(this.liveTailLogical),
886
833
  });
887
834
  } else if ((interval as Interval).isHead) {
888
- // On removal the head page is gone (no other interval is `isHead`) → clear; otherwise the
889
- // committed page IS the head.
835
+ // On removal the head page is gone (no other interval is `isHead`): clear it.
890
836
  this.publishAsAnchoredHead(removed ? undefined : interval);
891
837
  }
892
838
  }
893
839
 
894
- /**
895
- * Publish `interval` as the anchored head — the loaded page bounded at the dataset head (`isHead`),
896
- * or `undefined` to clear it (the head page was removed or a page stopped being the head). Callers
897
- * pass the interval they already have, so this does not re-scan storage for the head. Its content
898
- * changes via ingest/remove (routed through {@link commitInterval}/{@link dropInterval}) and its
899
- * identity changes when a page's `isHead` flag flips during query reconciliation — both call here.
900
- */
840
+ /** Publishes `interval` as the anchored head, or `undefined` to clear it. */
901
841
  protected publishAsAnchoredHead(interval: AnyInterval | undefined) {
902
842
  this.intervalViews.partialNext({ anchoredHead: this.intervalItemsOrEmpty(interval) });
903
843
  }
904
844
 
905
845
  /**
906
- * Keep `anchoredHead` in sync after a page's `isHead` flag was (re)computed during query
907
- * reconciliation, given its value `wasHead` beforehand. Acts only on an actual transition:
908
- * - became the head page → publish it as the anchored head;
909
- * - stopped being the head page → clear the anchored head;
910
- * - unchanged → nothing (a content change, if any, was already published when the interval was
911
- * committed — see {@link commitInterval}).
846
+ * Keeps `anchoredHead` in sync after `isHead` was recomputed while a page was placed (`wasHead`
847
+ * is the previous value): publishes the page on becoming the head, clears it on losing that.
912
848
  */
913
849
  protected syncAnchoredHeadAfterHeadFlip(interval: Interval, wasHead: boolean) {
914
850
  if (interval.isHead === wasHead) return;
915
851
  this.publishAsAnchoredHead(interval.isHead ? interval : undefined);
916
852
  }
917
853
 
854
+ /**
855
+ * Clears the head mark of `interval`: it no longer reaches the head of the dataset, which holds
856
+ * more items toward the head. It stops being the anchored head ({@link anchoredHeadItem} is then
857
+ * `undefined`) and can load toward the head, which the paginator state reflects when it is the
858
+ * active interval.
859
+ */
860
+ protected unmarkHead(interval: Interval) {
861
+ this.clearHeadMark(interval);
862
+ this.syncAnchoredHeadAfterHeadFlip(interval, true);
863
+ }
864
+
865
+ /** {@link unmarkHead} without touching the anchored head view. */
866
+ private clearHeadMark(interval: Interval) {
867
+ interval.isHead = false;
868
+ interval.hasMoreHead = true;
869
+ if (this.isActiveInterval(interval)) {
870
+ this.state.partialNext({
871
+ hasMoreHead: true,
872
+ cursor: this.getCursorFromInterval(interval),
873
+ });
874
+ }
875
+ }
876
+
877
+ /**
878
+ * Makes `interval`, marked as the head and proven to reach it, the only head: two separate
879
+ * intervals cannot both reach it. Other heads lose the mark and can load toward the head, up to
880
+ * `interval`, except one reaching further headward, which contradicts the proof: it keeps the
881
+ * mark and is published as the anchored head (see {@link anchoredHeadInterval}).
882
+ */
883
+ protected makeOnlyHead(interval: Interval) {
884
+ let keptOtherHead = false;
885
+ for (const other of this.itemIntervals) {
886
+ if (other.id === interval.id || isLogicalInterval(other) || !other.isHead) continue;
887
+ if (this.reachesFurtherHeadwardThan(other, interval)) keptOtherHead = true;
888
+ else this.clearHeadMark(other);
889
+ }
890
+ if (keptOtherHead) this.publishAsAnchoredHead(this.anchoredHeadInterval);
891
+ }
892
+
893
+ /** The ids of the anchored intervals marked as reaching the head of the dataset. */
894
+ private getHeadIntervalIds(): string[] {
895
+ const ids: string[] = [];
896
+ for (const interval of this._itemIntervals.values()) {
897
+ if (!isLogicalInterval(interval) && interval.isHead) ids.push(interval.id);
898
+ }
899
+ return ids;
900
+ }
901
+
902
+ /**
903
+ * Whether `interval` reaches the head because a headward page joined it to the head interval:
904
+ * it is, or merged, one of `headIntervalIds` (the intervals marked as the head before the page
905
+ * was placed). Only where cursors are derived from the interval (`config.deriveCursor`): a
906
+ * cursor a response returned stays as sent.
907
+ */
908
+ private inheritsHeadMark(
909
+ interval: Interval,
910
+ direction: PaginationDirection | undefined,
911
+ headIntervalIds: string[],
912
+ ): boolean {
913
+ if (!this.config.deriveCursor || direction !== 'headward') return false;
914
+ // an interval merged into another one is dropped
915
+ return headIntervalIds.some(
916
+ (id) => id === interval.id || !this._itemIntervals.has(id),
917
+ );
918
+ }
919
+
920
+ /** Whether `a`'s head edge (see {@link getServerKnownEdges}) is further headward than `b`'s. */
921
+ private reachesFurtherHeadwardThan(a: Interval, b: Interval): boolean {
922
+ const aHeadEdge = this.getServerKnownEdges(a).head;
923
+ const bHeadEdge = this.getServerKnownEdges(b).head;
924
+ return !!aHeadEdge && !!bHeadEdge && this.aIsMoreHeadwardThanB(aHeadEdge, bHeadEdge);
925
+ }
926
+
918
927
  private intervalItemsOrEmpty(interval: AnyInterval | undefined): T[] {
919
928
  return interval ? this.intervalToItems(interval) : [];
920
929
  }
921
930
 
922
931
  /**
923
- * Empty every {@link intervalViews} field. Used by reset paths that clear intervals in bulk (via
924
- * {@link setIntervals}), which bypasses the per-interval {@link commitInterval}/{@link dropInterval}
925
- * publishing. No-ops when the views are already empty so a reset does not emit needlessly.
932
+ * Drops every loaded interval and item without publishing `state`, so the next ingest starts from
933
+ * empty storage while `state.items` keeps showing the previous interval until the caller
934
+ * publishes.
926
935
  */
936
+ protected clearItemStorage() {
937
+ this.setIntervals([]);
938
+ this.setActiveInterval(undefined);
939
+ this._itemIndex.clear();
940
+ this.clearIntervalViews();
941
+ }
942
+
943
+ /** Empties every {@link intervalViews} field, bypassing `commitInterval`/`dropInterval`. */
927
944
  protected clearIntervalViews() {
928
945
  this._pendingViewChangedIds.clear();
929
946
  const { logicalHead, logicalTail, anchoredHead } =
930
947
  this.intervalViews.getLatestValue();
931
- // Clear whenever any view holds items; skip only when all are already empty, so a reset on an
932
- // empty paginator does not emit a redundant empty→empty change (new `[]` refs would wake selectors).
948
+ // Skip when all views are already empty: fresh `[]` refs would wake selectors for nothing.
933
949
  const alreadyEmpty =
934
950
  logicalHead.length === 0 && logicalTail.length === 0 && anchoredHead.length === 0;
935
951
  if (alreadyEmpty) return;
@@ -940,33 +956,56 @@ export abstract class BasePaginator<T, Q> {
940
956
  });
941
957
  }
942
958
 
943
- // ---------------------------------------------------------------------------
944
- // Abstracts
945
- // ---------------------------------------------------------------------------
959
+ /**
960
+ * The fetching step of the query pipeline (see {@link executeQuery}): requests the page that
961
+ * `params.queryShape` describes (`executeQuery` always prepares it, and a retry sends it again)
962
+ * and returns the response. What the response carries besides the page is applied in the last
963
+ * step ({@link applyQueryResponseRest}).
964
+ */
965
+ protected abstract fetchQueryResponse(params: PaginationQueryParams<Q>): Promise<R>;
946
966
 
947
- abstract query(
967
+ /**
968
+ * The extracting step of the query pipeline (see {@link executeQuery}): the page in a response,
969
+ * its items and cursors. A paginator whose response is the page returns it as it is.
970
+ */
971
+ protected abstract extractQueryPage(
972
+ response: R,
948
973
  params: PaginationQueryParams<Q>,
949
- ): Promise<PaginationQueryReturnValue<T>>;
974
+ ): PaginationQueryReturnValue<T>;
950
975
 
951
- abstract filterQueryResults(items: T[]): T[];
976
+ /**
977
+ * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
978
+ * besides its page, once the page is placed with `placeParams`. Runs once for every response that
979
+ * arrived, also when extracting or placing its page failed. Does nothing by default.
980
+ */
981
+ protected applyQueryResponseRest(
982
+ _response: R,
983
+ _placeParams: QueryPagePlacement<Q>,
984
+ ): void {
985
+ // a response is its page by default, with nothing else to apply
986
+ }
952
987
 
953
988
  /**
954
- * Subclasses must return the query shape.
989
+ * Filters a fetched page's items before the page is placed, synchronously, as placing runs in a
990
+ * single tick. Keeps every item by default; a paginator that drops some overrides it.
955
991
  */
992
+ filterQueryResults(items: T[]): T[] {
993
+ return items;
994
+ }
995
+
996
+ /** Subclasses must override it and return the query shape. */
956
997
  protected getNextQueryShape(
957
- _params: Pick<PaginationQueryParams<Q>, 'direction'> = {},
998
+ _params: Pick<PaginationQueryParams<Q>, 'direction'> & { pageSize?: number } = {},
958
999
  ): Q {
959
1000
  throw new Error('Paginator.getNextQueryShape() is not implemented');
960
1001
  }
961
1002
 
962
1003
  /**
963
- * Filters an item is matched against locally (`matchesFilter`) — NOT the filters sent to the server.
964
- * A paginator whose backend query is filtered has to build the request filters separately (see
965
- * `ChannelPaginator.buildQueryFilters`), because the two can differ: the backend may resolve a
966
- * server-side stored filter of its own, and some paginators filter locally without sending anything.
1004
+ * Filters that `matchesFilter` applies locally, not the ones sent to the server; a subclass whose
1005
+ * backend query is filtered builds those separately. `null`: no filters.
967
1006
  */
968
1007
  protected buildMatchFilters(): object | null {
969
- return null; // === no filters
1008
+ return null;
970
1009
  }
971
1010
 
972
1011
  matchesFilter(item: T): boolean {
@@ -981,13 +1020,17 @@ export abstract class BasePaginator<T, Q> {
981
1020
  this._filterFieldToDataResolvers = resolvers;
982
1021
  }
983
1022
 
1023
+ /**
1024
+ * Adds rules ahead of the existing ones. The first rule that matches a field resolves it, so an
1025
+ * added rule takes precedence over a built-in one, including a catch-all.
1026
+ */
984
1027
  addFilterResolvers(resolvers: FieldToDataResolver<T>[]) {
985
- this._filterFieldToDataResolvers.push(...resolvers);
1028
+ this._filterFieldToDataResolvers = [
1029
+ ...resolvers,
1030
+ ...this._filterFieldToDataResolvers,
1031
+ ];
986
1032
  }
987
1033
 
988
- // ---------------------------------------------------------------------------
989
- // Item accessors
990
- // ---------------------------------------------------------------------------
991
1034
  getItemId(item: T): string {
992
1035
  return (item as { id: string }).id;
993
1036
  }
@@ -997,72 +1040,250 @@ export abstract class BasePaginator<T, Q> {
997
1040
  }
998
1041
 
999
1042
  /**
1000
- * Whether this paginator's live `state.items` publishes are currently throttled — `stateThrottleMs`
1001
- * is set, throttling is not globally disabled (tests), and item order is not locked (a locked-order
1002
- * list must emit the caller-computed, order-preserved array, not a re-projection). When false, every
1003
- * live mutation publishes immediately, exactly as before this feature.
1043
+ * Whether live `state.items` publishes are throttled: `stateThrottleMs` is set, throttling is not
1044
+ * disabled (tests) and item order is not locked (its emit is not a re-projection).
1004
1045
  */
1005
1046
  protected get isStateThrottled(): boolean {
1006
1047
  return (
1007
1048
  isStateThrottlingEnabled() &&
1008
- !!this._windowPublishThrottle &&
1049
+ !!this._activeIntervalPublishThrottle &&
1009
1050
  !this.config.lockItemOrder
1010
1051
  );
1011
1052
  }
1012
1053
 
1013
- /** True while a coalescing {@link batch} scope is suspending this paginator's own window publishes. */
1014
- protected get isWindowPublishSuspended(): boolean {
1015
- return this._windowPublishSuspendDepth > 0;
1054
+ protected get isActiveIntervalPublishSuspended(): boolean {
1055
+ return this._activeIntervalPublishSuspendDepth > 0;
1016
1056
  }
1017
1057
 
1018
- /** Re-project the active window from its (live, source-of-truth) interval. `undefined` when inactive. */
1019
- private projectActiveWindow(): T[] | undefined {
1058
+ /** Re-projects the items of the active interval; `undefined` when none is active. */
1059
+ private projectActiveInterval(): T[] | undefined {
1020
1060
  if (!this._activeIntervalId) return undefined;
1021
1061
  const active = this._itemIntervals.get(this._activeIntervalId);
1022
1062
  return active ? this.intervalToItems(active) : undefined;
1023
1063
  }
1024
1064
 
1025
1065
  /**
1026
- * Publish the active window to `state`, re-projecting it fresh from the active interval at call time
1027
- * (the throttle boundary / flush). Because the intervals are mutated synchronously by every live op,
1028
- * this always reflects the latest settled state, so intermediate values within a window coalesce
1029
- * away. Clears the visible window when the active interval is gone (e.g. the last item was removed).
1066
+ * Publishes the active interval to `state`, re-projected at call time. Clears the shown interval
1067
+ * when the active interval is gone.
1030
1068
  */
1031
- private flushWindowPublish(): void {
1032
- const items = this.projectActiveWindow();
1069
+ private flushActiveIntervalPublish(): void {
1070
+ const items = this.projectActiveInterval();
1033
1071
  if (items) {
1034
- this.state.partialNext({ items });
1072
+ this.state.partialNext({ items, ...this.consumePendingPrunePaginationState() });
1035
1073
  return;
1036
1074
  }
1037
1075
  if ((this.state.getLatestValue().items?.length ?? 0) > 0) {
1038
- this.state.partialNext({ items: [] });
1076
+ this.state.partialNext({ items: [], ...this.consumePendingPrunePaginationState() });
1039
1077
  }
1040
1078
  }
1041
1079
 
1042
1080
  /**
1043
- * Schedule a throttled active-window publish (leading + trailing). Called from live mutations
1044
- * (ingest / content-change / remove) INSTEAD of an inline `state.partialNext({ items })` when
1045
- * {@link isStateThrottled}. Safe to call many times within one op — they coalesce to a single emit.
1081
+ * Publishes the active interval's items with `state` and any pending prune changes, at once.
1082
+ * Inside a coalescing {@link batch}, call it after the batch's last interval change: the batch
1083
+ * then publishes nothing more.
1046
1084
  */
1047
- protected scheduleWindowPublish(): void {
1048
- this._windowPublishThrottle?.throttledFn();
1085
+ protected publishActiveInterval(state: Partial<PaginatorState<T>> = {}) {
1086
+ this.state.partialNext({
1087
+ items: this.projectActiveInterval(),
1088
+ ...this.consumePendingPrunePaginationState(),
1089
+ ...state,
1090
+ });
1049
1091
  }
1050
1092
 
1051
1093
  /**
1052
- * Flush any pending throttled window + interval-view publishes immediately. No-op when nothing
1053
- * is pending or throttling is off.
1094
+ * Schedules a throttled (leading and trailing) active-interval publish. Live mutations call it
1095
+ * instead of publishing inline when {@link isStateThrottled}. Repeated calls coalesce.
1054
1096
  */
1097
+ protected scheduleActiveIntervalPublish(): void {
1098
+ this._activeIntervalPublishThrottle?.throttledFn();
1099
+ }
1100
+
1101
+ /**
1102
+ * Runs `fn` with active-interval publishes suspended and emits once on exit (a replace is
1103
+ * remove-then-insert, which would emit twice), unless the interval was published after its last
1104
+ * change. Only the outermost scope emits. `exit: 'auto'` rides the throttle when there is one,
1105
+ * `'sync'` always flushes ({@link batch}). Skipped for `lockItemOrder` lists, whose emit
1106
+ * republishes the last array and must not be re-derived from the interval.
1107
+ */
1108
+ protected withSingleActiveIntervalPublish(
1109
+ fn: () => void,
1110
+ { exit = 'auto' }: { exit?: 'auto' | 'sync' } = {},
1111
+ ): void {
1112
+ if (this.config.lockItemOrder) {
1113
+ fn();
1114
+ return;
1115
+ }
1116
+ const isOutermost = this._activeIntervalPublishSuspendDepth === 0;
1117
+ this._activeIntervalPublishSuspendDepth += 1;
1118
+ try {
1119
+ fn();
1120
+ } finally {
1121
+ this._activeIntervalPublishSuspendDepth -= 1;
1122
+ }
1123
+ const staleState = this._staleActiveIntervalState;
1124
+ if (!isOutermost || !staleState) return;
1125
+ this._staleActiveIntervalState = undefined;
1126
+ // the interval was published after its last change
1127
+ if (this.items !== staleState.items) return;
1128
+ if (exit === 'auto' && this.isStateThrottled) this.scheduleActiveIntervalPublish();
1129
+ else this.flushActiveIntervalPublish();
1130
+ }
1131
+
1132
+ /** Immediately flushes the pending throttled active-interval and interval-view publishes. */
1055
1133
  protected flushPendingPublishes(): void {
1056
- this._windowPublishThrottle?.flush();
1134
+ this._activeIntervalPublishThrottle?.flush();
1057
1135
  this._viewPublishThrottle?.flush();
1058
1136
  }
1059
1137
 
1060
1138
  /**
1061
- * {@link _viewPublishThrottle} boundary: apply every interval-view change buffered since the last
1062
- * flush, then clear the buffer. Independent of the `state.items` window publish, so a view update
1063
- * lands within one throttle interval even when the active window stays quiet (e.g. a reaction on a
1064
- * head message while a non-head window is active). No-op when nothing was buffered.
1139
+ * Whether pruning is on hold, e.g. while the user reads near the tail edge, where a prune drops
1140
+ * items. False: the configured cap always applies.
1141
+ */
1142
+ protected get isPruningSuspended(): boolean {
1143
+ return false;
1144
+ }
1145
+
1146
+ /**
1147
+ * Whether the server knows `item`, so its ID is safe as a cursor. Prunes drop and anchor on such
1148
+ * items only. Subclasses holding locally-created items narrow it.
1149
+ */
1150
+ protected isPaginationAnchorable(item: T | undefined): boolean {
1151
+ return !!item;
1152
+ }
1153
+
1154
+ /**
1155
+ * The interval cap, or `undefined` when unbounded. Clamped up to `pageSize`: a smaller cap would
1156
+ * prune each tailward page as it lands and `onEndReached` would refetch it in a loop.
1157
+ */
1158
+ protected get effectiveMaxLoadedItems(): number | undefined {
1159
+ const { maxLoadedItems, pageSize } = this.config;
1160
+ if (typeof maxLoadedItems !== 'number' || maxLoadedItems <= 0) return undefined;
1161
+ return Math.max(maxLoadedItems, pageSize);
1162
+ }
1163
+
1164
+ /**
1165
+ * Drops the oldest items from `interval` until at most `maxLoadedItems` remain, releasing them
1166
+ * from the item index. Returns whether anything was pruned.
1167
+ *
1168
+ * Runs from `ingestItem` on the uncommitted interval copy, so the following `commitInterval` and
1169
+ * publish carry it (see {@link _prunedIntervalId}). No-op unless a cap is set, pruning is not
1170
+ * suspended ({@link isPruningSuspended}) and the interval is the anchored, active head interval
1171
+ * and over the cap. Assumes cursor pagination (`removeItem` is bypassed, so
1172
+ * {@link shrinkOffsetAfterRemoval} never runs). Items the server does not know
1173
+ * ({@link isPaginationAnchorable}) are skipped, so the interval may sit a few items above the cap.
1174
+ */
1175
+ protected pruneTailToLimit(interval: AnyInterval): boolean {
1176
+ const limit = this.effectiveMaxLoadedItems;
1177
+ if (typeof limit === 'undefined' || this.isPruningSuspended) return false;
1178
+
1179
+ // Anchored intervals only: a logical interval has no pagination provenance, so pruned items
1180
+ // could not be refetched. Also narrows the type for the field reads below.
1181
+ if (isLogicalInterval(interval)) return false;
1182
+
1183
+ if (
1184
+ !interval.isHead ||
1185
+ this._activeIntervalId !== interval.id ||
1186
+ interval.itemIds.length <= limit
1187
+ )
1188
+ return false;
1189
+
1190
+ const ids = interval.itemIds;
1191
+ // The tail (oldest) edge is index 0 unless the interval stores IDs head-first.
1192
+ const tailEdgeIsFirst = !this.intervalItemIdsAreHeadFirst;
1193
+ const step = tailEdgeIsFirst ? 1 : -1;
1194
+ const dropped = new Set<string>();
1195
+
1196
+ let remaining = ids.length - limit;
1197
+ for (
1198
+ let i = tailEdgeIsFirst ? 0 : ids.length - 1;
1199
+ remaining > 0 && i >= 0 && i < ids.length;
1200
+ i += step
1201
+ ) {
1202
+ const id = ids[i];
1203
+ const item = this._itemIndex.get(id);
1204
+ if (item && !this.isPaginationAnchorable(item)) continue;
1205
+ dropped.add(id);
1206
+ remaining -= 1;
1207
+ }
1208
+
1209
+ if (!dropped.size) return false;
1210
+
1211
+ // Rebuild rather than splice: skipped local items leave the dropped IDs non-contiguous.
1212
+ interval.itemIds = ids.filter((id) => !dropped.has(id));
1213
+
1214
+ // One transaction so sibling holders re-project once. `remove` releases only this paginator's
1215
+ // reference: content still held elsewhere survives.
1216
+ this._itemIndex.batch(() => {
1217
+ for (const id of dropped) this._itemIndex.remove(id);
1218
+ });
1219
+
1220
+ // Older items exist on the server again: re-open the tail edge, even if the interval had reached
1221
+ // it (a stale `isTail` would also mislead interval merging).
1222
+ interval.isTail = false;
1223
+ interval.hasMoreTail = true;
1224
+
1225
+ // Only the ID is recorded: the `state` fields are derived at publish time.
1226
+ this._prunedIntervalId = interval.id;
1227
+
1228
+ return true;
1229
+ }
1230
+
1231
+ /**
1232
+ * The interval's outermost items the server knows about (see {@link isPaginationAnchorable}), at
1233
+ * its head and tail; `undefined` where it holds none. Items the server never saw do not count:
1234
+ * they cannot continue its pagination as a cursor, nor be reached by a page the server returns.
1235
+ */
1236
+ protected getServerKnownEdges(interval: AnyInterval): {
1237
+ head: T | undefined;
1238
+ tail: T | undefined;
1239
+ } {
1240
+ const items = interval.itemIds.map((id) => this._itemIndex.get(id));
1241
+ const known = items.filter((item): item is T => this.isPaginationAnchorable(item));
1242
+ return this.getPagePaginationEdges(known);
1243
+ }
1244
+
1245
+ /** Keeps the `items` that are members of `interval`, in order. */
1246
+ private retainIntervalMembers(items: T[], interval: AnyInterval): T[] {
1247
+ const members = new Set(interval.itemIds);
1248
+ return items.filter((item) => members.has(this.getItemId(item)));
1249
+ }
1250
+
1251
+ /**
1252
+ * Returns the `state` pagination fields a prune moved, derived from the committed active interval
1253
+ * at call time, and clears the pending prune. Publishes of the active interval spread it in. Only
1254
+ * changed fields are returned, so an unchanged `cursor` keeps its identity. Left alone: another
1255
+ * interval than the pruned one, `cursor.headward` (a `deriveCursor` verdict survives), and a null
1256
+ * tail edge (every item is locally created: `null` would read as exhausted, so the cursor stays).
1065
1257
  */
1258
+ private consumePendingPrunePaginationState(): Partial<PaginatorState<T>> {
1259
+ const prunedIntervalId = this._prunedIntervalId;
1260
+ if (!prunedIntervalId) return {};
1261
+ this._prunedIntervalId = undefined;
1262
+
1263
+ if (this._activeIntervalId !== prunedIntervalId) return {};
1264
+
1265
+ const active = this._itemIntervals.get(prunedIntervalId);
1266
+ if (!active || isLogicalInterval(active)) return {};
1267
+
1268
+ const current = this.state.getLatestValue();
1269
+ const next: Partial<PaginatorState<T>> = {};
1270
+
1271
+ // Read from the interval, not the prune's `true`: this publish can be a throttle interval late
1272
+ // and a `toTail()` in between may have loaded the rest of the history.
1273
+ if (current.hasMoreTail !== active.hasMoreTail) next.hasMoreTail = active.hasMoreTail;
1274
+
1275
+ if (this.isCursorPagination) {
1276
+ const { tail } = this.getServerKnownEdges(active);
1277
+ const tailward = tail ? this.getItemId(tail) : null;
1278
+ if (tailward !== null && current.cursor?.tailward !== tailward) {
1279
+ next.cursor = { headward: current.cursor?.headward, tailward };
1280
+ }
1281
+ }
1282
+
1283
+ return next;
1284
+ }
1285
+
1286
+ /** {@link _viewPublishThrottle} boundary: applies the buffered interval-view changes. */
1066
1287
  private flushIntervalViewPublish(): void {
1067
1288
  if (!this._pendingViewChangedIds.size) return;
1068
1289
  this.refreshIntervalViewsForChangedIds(this._pendingViewChangedIds);
@@ -1070,18 +1291,10 @@ export abstract class BasePaginator<T, Q> {
1070
1291
  }
1071
1292
 
1072
1293
  /**
1073
- * Refresh any tracked {@link intervalViews} field (logical head, logical tail, anchored head) that
1074
- * holds one of `changedIds`. A sibling holder writing new content through the shared item store
1075
- * swaps the item object those views reference, but only this paginator's own ingest/remove
1076
- * ({@link commitInterval}/{@link dropInterval}) republish them — so a reaction/edit made elsewhere
1077
- * would otherwise leave stale references in `anchoredHead`/`logicalHead`/`logicalTail` even though
1078
- * the active window (`state.items`, see {@link reconcileChangedIds}) was refreshed.
1079
- *
1080
- * Called immediately for un-throttled paginators, or from {@link flushIntervalViewPublish} at the
1081
- * view-publish throttle boundary when throttled — see {@link reconcileChangedIds}. Handled
1082
- * independently of `state.items`. When the anchored head is also the active interval its content is
1083
- * projected here as well as into `state.items`; deduping that double projection is a separate,
1084
- * deferred perf follow-up.
1294
+ * Refreshes the tracked {@link intervalViews} fields holding one of `changedIds`. A sibling
1295
+ * holder writing through the shared item store swaps the item objects the views reference, and
1296
+ * only this paginator's own ingest/remove republishes them. Immediate unless throttled, then from
1297
+ * {@link flushIntervalViewPublish}.
1085
1298
  */
1086
1299
  private refreshIntervalViewsForChangedIds(changedIds: ReadonlySet<string>): void {
1087
1300
  const head = this.liveHeadLogical;
@@ -1113,17 +1326,13 @@ export abstract class BasePaginator<T, Q> {
1113
1326
  }
1114
1327
 
1115
1328
  /**
1116
- * Reconcile the projected window + interval views against a set of changed ids: another holder
1117
- * swapped the shared item object those views reference. Refreshes any tracked interval view that
1118
- * holds a changed id and re-projects (or slot-swaps) the active window — coalesced through the
1119
- * publish throttles when throttling is on.
1329
+ * Reconciles the active interval and interval views after another holder swapped the shared item
1330
+ * objects they reference: refreshes views holding a changed ID and re-projects (or slot-swaps) the
1331
+ * active interval, coalesced through the publish throttles when throttling is on.
1120
1332
  */
1121
1333
  protected reconcileChangedIds(changedIds: ReadonlySet<string>): void {
1122
- // A sibling holder changed shared content: refresh any tracked interval view (logical head/tail,
1123
- // anchored head) holding a changed id — independent of the active window below, since a view can
1124
- // hold a changed id the active window does not. When throttled, buffer the ids and tick the
1125
- // view-publish throttle so refreshes coalesce (once per interval) yet still land on their own
1126
- // trailing edge even if `state.items` never publishes again; otherwise publish immediately.
1334
+ // Views refresh independently of the active interval (they can hold IDs it does not). Throttled:
1335
+ // buffer the IDs so refreshes coalesce.
1127
1336
  if (this.isStateThrottled) {
1128
1337
  for (const id of changedIds) this._pendingViewChangedIds.add(id);
1129
1338
  this._viewPublishThrottle?.throttledFn();
@@ -1135,26 +1344,32 @@ export abstract class BasePaginator<T, Q> {
1135
1344
  const activeInterval = this._itemIntervals.get(this._activeIntervalId);
1136
1345
  if (!activeInterval) return;
1137
1346
 
1138
- // Throttled (message list): the slot-swap fast path below reads the last-published `items`, which
1139
- // lags the live intervals while throttled — so skip it. Gate on membership only and schedule a
1140
- // single coalesced re-projection; the boundary re-derives the window fresh from the interval.
1347
+ // Throttled: `this.items` lags the intervals, so no slot swap. Schedule a re-projection, but
1348
+ // only if something changed (a sibling may have written the object the interval already shows).
1141
1349
  if (this.isStateThrottled) {
1142
- for (const id of activeInterval.itemIds) {
1143
- if (changedIds.has(id)) {
1144
- this.scheduleWindowPublish();
1350
+ const currentItems = this.items;
1351
+ if (!currentItems || currentItems.length !== activeInterval.itemIds.length) {
1352
+ // Positions only line up when the lengths match: gate on membership alone.
1353
+ if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
1354
+ this.scheduleActiveIntervalPublish();
1355
+ }
1356
+ return;
1357
+ }
1358
+ for (let i = 0; i < currentItems.length; i++) {
1359
+ const id = this.getItemId(currentItems[i]);
1360
+ if (!changedIds.has(id)) continue;
1361
+ const updated = this._itemIndex.get(id);
1362
+ if (!updated || updated !== currentItems[i]) {
1363
+ this.scheduleActiveIntervalPublish();
1145
1364
  return;
1146
1365
  }
1147
1366
  }
1148
1367
  return;
1149
1368
  }
1150
1369
 
1151
- // Fast path: a content update (an in-place edit written through a sibling holder) changes
1152
- // items in place without changing membership or order. When the current window still lines
1153
- // up with the interval one-to-one, shallow-copy it and swap only the changed slots — this
1154
- // preserves every unchanged item reference (so memoized rows bail) and avoids re-mapping and
1155
- // re-sorting the whole active window on every event. Skipped when a boost is active (a boost
1156
- // can reorder the visible window, which a slot-swap would not reflect) — then we fall through
1157
- // to the full projection below, which applies the boost order.
1370
+ // Fast path: an in-place update keeps membership and order, so when the interval lines up with
1371
+ // the interval, swap only the changed slots (unchanged item references survive). Skipped when a
1372
+ // boost is active: it can reorder the interval, which the full projection below applies.
1158
1373
  const currentItems = this.items;
1159
1374
  this.clearExpiredBoosts();
1160
1375
  if (
@@ -1169,7 +1384,7 @@ export abstract class BasePaginator<T, Q> {
1169
1384
  if (!changedIds.has(id)) continue;
1170
1385
  const updated = this._itemIndex.get(id);
1171
1386
  if (!updated) {
1172
- // The id left the store (a removal, not an in-place update) — resync via a full projection.
1387
+ // The ID left the store (a removal): resync via a full projection.
1173
1388
  needsFullProjection = true;
1174
1389
  break;
1175
1390
  }
@@ -1183,20 +1398,13 @@ export abstract class BasePaginator<T, Q> {
1183
1398
  }
1184
1399
  }
1185
1400
 
1186
- // Fallback: membership/order drifted (or no window to patch, or a boost is active). Re-project,
1187
- // but only if a changed id is actually in the active interval.
1188
- for (const id of activeInterval.itemIds) {
1189
- if (changedIds.has(id)) {
1190
- this.state.partialNext({ items: this.intervalToItems(activeInterval) });
1191
- return;
1192
- }
1401
+ // Fallback (membership or order drifted, no interval to patch, or a boost is active): re-project
1402
+ // only if a changed ID is in the active interval.
1403
+ if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
1404
+ this.state.partialNext({ items: this.intervalToItems(activeInterval) });
1193
1405
  }
1194
1406
  }
1195
1407
 
1196
- // ---------------------------------------------------------------------------
1197
- // Boosts
1198
- // ---------------------------------------------------------------------------
1199
-
1200
1408
  protected clearExpiredBoosts(now = Date.now()) {
1201
1409
  for (const [id, b] of this.boosts) if (now > b.until) this.boosts.delete(id);
1202
1410
  this._maxBoostSeq = Math.max(
@@ -1205,12 +1413,7 @@ export abstract class BasePaginator<T, Q> {
1205
1413
  );
1206
1414
  }
1207
1415
 
1208
- /**
1209
- * Applied by the effectiveComparator to take into consideration item boosts when sorting items.
1210
- *
1211
- * @param a - The first item to compare.
1212
- * @param b - The second item to compare.
1213
- */
1416
+ /** Boosted items first (higher `seq` first), then `itemOrderComparator`. */
1214
1417
  protected boostComparator = (a: T, b: T): number => {
1215
1418
  const now = Date.now();
1216
1419
  this.clearExpiredBoosts(now);
@@ -1234,11 +1437,12 @@ export abstract class BasePaginator<T, Q> {
1234
1437
  };
1235
1438
 
1236
1439
  /**
1237
- * Increases the item's importance when sorting.
1238
- * Boost affects position inside an item interval (if used), but should not redefine interval boundaries.
1440
+ * Raises the item's priority in `effectiveComparator`. Affects position inside an interval, not
1441
+ * interval boundaries.
1239
1442
  *
1240
- * @param itemId - Id of the item to boost.
1241
- * @param opts - Boost options: `ttlMs` / `until` control expiry and `seq` orders concurrent boosts.
1443
+ * @param itemId - ID of the item to boost.
1444
+ * @param opts - Boost options: `until` (or `ttlMs` from now) sets the expiry and `seq` orders
1445
+ * concurrent boosts. Expiry defaults to 15s from now; `seq` defaults to 0.
1242
1446
  */
1243
1447
  boost(itemId: string, opts?: { ttlMs?: number; until?: number; seq?: number }) {
1244
1448
  const now = Date.now();
@@ -1269,10 +1473,6 @@ export abstract class BasePaginator<T, Q> {
1269
1473
  return !!(boost && Date.now() <= boost.until);
1270
1474
  }
1271
1475
 
1272
- // ---------------------------------------------------------------------------
1273
- // Interval manipulation
1274
- // ---------------------------------------------------------------------------
1275
-
1276
1476
  generateIntervalId(_page: (T | string)[]): string {
1277
1477
  return `interval-${generateUUIDv4()}`;
1278
1478
  }
@@ -1282,20 +1482,18 @@ export abstract class BasePaginator<T, Q> {
1282
1482
  .map((id) => this._itemIndex?.get(id))
1283
1483
  .filter((item): item is T => !!item);
1284
1484
 
1285
- // When lockItemOrder is true, we must *not* reflect boosts in state.items.
1485
+ // A locked order ignores boosts.
1286
1486
  if (this.config.lockItemOrder) {
1287
1487
  return items;
1288
1488
  }
1289
1489
 
1290
- // itemIds are maintained in itemOrder, so the mapped items are already ordered; only an active
1291
- // boost can reorder the visible window. Skip the otherwise-redundant full re-sort when none are
1292
- // active (the common case), so a page ingest / full projection is a map, not a map + sort.
1490
+ // `itemIds` are already in item order: only an active boost can reorder, so skip the re-sort
1491
+ // otherwise.
1293
1492
  this.clearExpiredBoosts();
1294
1493
  if (this.boosts.size === 0) {
1295
1494
  return items;
1296
1495
  }
1297
1496
 
1298
- // Visible ordering uses boost-aware comparator
1299
1497
  return items.sort(this.effectiveComparator.bind(this));
1300
1498
  }
1301
1499
 
@@ -1303,9 +1501,8 @@ export abstract class BasePaginator<T, Q> {
1303
1501
  const sorted = [...page].sort((a, b) => this.itemOrderComparator(a, b));
1304
1502
  return {
1305
1503
  id: this.generateIntervalId(page),
1306
- // Default semantics:
1307
- // - if interval is known global head/tail, there is no more data in that direction
1308
- // - otherwise treat it as unknown => "has more" (until proven otherwise by a query)
1504
+ // A known global head/tail has no more data that way, otherwise assume more until a query
1505
+ // proves not.
1309
1506
  hasMoreHead: isHead ? false : true,
1310
1507
  hasMoreTail: isTail ? false : true,
1311
1508
  itemIds: sorted.map(this.getItemId.bind(this)),
@@ -1314,29 +1511,18 @@ export abstract class BasePaginator<T, Q> {
1314
1511
  };
1315
1512
  }
1316
1513
 
1317
- protected getCursorFromInterval(interval: Interval): PaginatorCursor {
1318
- // Prefer resolving edge items via sort bounds, because:
1319
- // - interval ordering can differ from interval sorting (intervalSortDirection)
1320
- // - "head" is a semantic concept (where new items appear), not necessarily `itemIds[0]`
1321
- // - itemIds are stored in sortComparator order, but we want the *pagination* edges
1322
- const edges = this.getIntervalPaginationEdges(interval);
1323
-
1324
- const fallbackFirstId = interval.itemIds[0] ?? null;
1325
- const fallbackLastId = interval.itemIds.slice(-1)[0] ?? null;
1326
-
1327
- const fallbackHeadId = this.intervalItemIdsAreHeadFirst
1328
- ? fallbackFirstId
1329
- : fallbackLastId;
1330
- const fallbackTailId = this.intervalItemIdsAreHeadFirst
1331
- ? fallbackLastId
1332
- : fallbackFirstId;
1333
-
1334
- const headId = edges?.head ? this.getItemId(edges.head) : fallbackHeadId;
1335
- const tailId = edges?.tail ? this.getItemId(edges.tail) : fallbackTailId;
1336
-
1514
+ /**
1515
+ * The cursor continuing `interval` where it has more items (by default, per its own flags), at
1516
+ * its outermost items the server knows about (see {@link getServerKnownEdges}).
1517
+ */
1518
+ protected getCursorFromInterval(
1519
+ interval: Interval,
1520
+ { hasMoreHead, hasMoreTail }: PaginationFlags = interval,
1521
+ ): PaginatorCursor {
1522
+ const { head, tail } = this.getServerKnownEdges(interval);
1337
1523
  return {
1338
- headward: interval.hasMoreHead ? headId : null,
1339
- tailward: interval.hasMoreTail ? tailId : null,
1524
+ headward: hasMoreHead && head ? this.getItemId(head) : null,
1525
+ tailward: hasMoreTail && tail ? this.getItemId(tail) : null,
1340
1526
  };
1341
1527
  }
1342
1528
 
@@ -1344,13 +1530,7 @@ export abstract class BasePaginator<T, Q> {
1344
1530
  return this._activeIntervalId === interval.id;
1345
1531
  }
1346
1532
 
1347
- /**
1348
- * Whether the currently active (viewed) interval is the anchored head. Used to decide if it is
1349
- * safe to re-seed an already-loaded paginator with a fresh newest page: only when at the head
1350
- * (the newest page overlaps it, so the re-seed reconciles + re-derives cursors in place). When the
1351
- * caller has jumped to an older window (active interval is NOT the head), a first-page re-seed
1352
- * would force-merge the newest page into that window across the gap - so the re-seed is skipped.
1353
- */
1533
+ /** Whether the active (shown) interval is the loaded one reaching the head of the dataset. */
1354
1534
  get isActiveIntervalAtHead(): boolean {
1355
1535
  const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
1356
1536
  return (
@@ -1361,15 +1541,27 @@ export abstract class BasePaginator<T, Q> {
1361
1541
  );
1362
1542
  }
1363
1543
 
1544
+ /**
1545
+ * Claims the active interval for a call that decides it, and returns the claim; a query claims
1546
+ * it as `claimsActiveInterval` says (see {@link decidesActiveInterval}). The latest claim wins: a
1547
+ * page arriving after a later claim is only stored.
1548
+ */
1549
+ protected claimActiveInterval(): number {
1550
+ this._activeIntervalClaimCount += 1;
1551
+ return this._activeIntervalClaimCount;
1552
+ }
1553
+
1554
+ /** Whether no claim on the active interval followed `claim` (see {@link claimActiveInterval}). */
1555
+ protected isLatestActiveIntervalClaim(claim: number): boolean {
1556
+ return claim === this._activeIntervalClaimCount;
1557
+ }
1558
+
1364
1559
  setActiveInterval(interval: AnyInterval | undefined, opts?: { updateState?: boolean }) {
1365
1560
  this._activeIntervalId = interval?.id;
1366
1561
 
1367
- // Public API expectation: activating an anchored interval should immediately
1368
- // reflect its pagination ability in paginator state.
1369
- //
1370
- // Internal callers that are in the middle of a transactional `state.next()`
1371
- // update must pass `{ updateState: false }` and project these flags into the
1372
- // state object directly.
1562
+ // Activating an anchored interval immediately reflects its pagination flags in `state`. Callers
1563
+ // inside a transactional `state.next()` pass `{ updateState: false }` and project the flags
1564
+ // themselves.
1373
1565
  if (opts?.updateState === false) return;
1374
1566
  if (!interval || isLogicalInterval(interval)) return;
1375
1567
 
@@ -1391,14 +1583,23 @@ export abstract class BasePaginator<T, Q> {
1391
1583
  }
1392
1584
 
1393
1585
  /**
1394
- * Returns pagination head/tail edges of an interval.
1395
- *
1396
- * IMPORTANT:
1397
- * - Edges are derived from the *sort bounds* of the interval (min/max under `sortComparator`).
1398
- * - Which bound is treated as the pagination "head" is controlled by `intervalItemIdsAreHeadFirst`.
1399
- * - This is a semantic notion of head/tail (where new items are expected to appear),
1400
- * not necessarily "min/max under sortComparator".
1401
- * New items are always expected to appear at the head of the interval.
1586
+ * The items at the head and tail edges of a page given in item order (`sortComparator` order), as
1587
+ * {@link getIntervalPaginationEdges} gives them for an interval. Both `undefined` for an empty page.
1588
+ */
1589
+ protected getPagePaginationEdges(page: T[]): {
1590
+ head: T | undefined;
1591
+ tail: T | undefined;
1592
+ } {
1593
+ const [first, last] = [page[0], page[page.length - 1]];
1594
+ return this.intervalItemIdsAreHeadFirst
1595
+ ? { head: first, tail: last }
1596
+ : { head: last, tail: first };
1597
+ }
1598
+
1599
+ /**
1600
+ * Pagination head/tail edges of an interval, taken from its sort bounds.
1601
+ * `intervalItemIdsAreHeadFirst` decides which bound is the head: where new items appear, not
1602
+ * necessarily the min under `itemOrderComparator`.
1402
1603
  */
1403
1604
  protected getIntervalPaginationEdges(
1404
1605
  interval: Interval | LogicalInterval,
@@ -1465,9 +1666,37 @@ export abstract class BasePaginator<T, Q> {
1465
1666
  this._itemIntervals = new Map(intervals.map((i) => [i.id, i]));
1466
1667
  }
1467
1668
 
1669
+ /**
1670
+ * The span pages and items are matched against: from the interval's outermost items the server
1671
+ * knows about (see {@link isPaginationAnchorable}), or its sort bounds when it holds none. An
1672
+ * item the server never saw does not stretch it, as its sort key may come from the client.
1673
+ */
1674
+ protected getIntervalSpan(interval: AnyInterval): IntervalSortBounds<T> | null {
1675
+ const ids = interval.itemIds;
1676
+ const knownItemAt = (index: number) => {
1677
+ const item = this._itemIndex.get(ids[index]);
1678
+ return this.isPaginationAnchorable(item) ? item : undefined;
1679
+ };
1680
+ let start: T | undefined;
1681
+ let end: T | undefined;
1682
+ for (let index = 0; index < ids.length && !start; index++) start = knownItemAt(index);
1683
+ for (let index = ids.length - 1; index >= 0 && !end; index--)
1684
+ end = knownItemAt(index);
1685
+ return start && end ? { start, end } : this.getIntervalSortBounds(interval);
1686
+ }
1687
+
1688
+ /** The head and tail edges of the interval's span (see {@link getIntervalSpan}). */
1689
+ private getIntervalSpanEdges(interval: AnyInterval): IntervalPaginationEdges<T> | null {
1690
+ const span = this.getIntervalSpan(interval);
1691
+ if (!span) return null;
1692
+ return this.intervalItemIdsAreHeadFirst
1693
+ ? { head: span.start, tail: span.end }
1694
+ : { head: span.end, tail: span.start };
1695
+ }
1696
+
1468
1697
  protected intervalsStrictlyOverlap(a: AnyInterval, b: AnyInterval): boolean {
1469
- const aBounds = this.getIntervalSortBounds(a);
1470
- const bBounds = this.getIntervalSortBounds(b);
1698
+ const aBounds = this.getIntervalSpan(a);
1699
+ const bBounds = this.getIntervalSpan(b);
1471
1700
  if (!aBounds || !bBounds) return false;
1472
1701
  return (
1473
1702
  this.itemOrderComparator(aBounds.start, bBounds.end) <= 0 &&
@@ -1476,36 +1705,25 @@ export abstract class BasePaginator<T, Q> {
1476
1705
  }
1477
1706
 
1478
1707
  /**
1479
- * Returns true if intervals A and B should be merged.
1480
- *
1481
- * 1) Strict overlap (range overlap in `sortComparator` order):
1482
- * A.min ≤ B.max AND B.min ≤ A.max
1483
- *
1484
- * 2) Forced merge (policy: 'auto' only):
1485
- * If one interval is marked as `isHead`/`isTail`, treat the other as mergeable
1486
- * when it extends beyond that interval's pagination head/tail edge
1487
- * (computed via `getIntervalPaginationEdges` + headward/tailward helpers).
1488
- *
1489
- * In 'strict-overlap-only' policy, only (1) applies.
1708
+ * Whether intervals A and B should be merged: they strictly overlap in `itemOrderComparator` order
1709
+ * (`A.min <= B.max && B.min <= A.max`) or, under policy 'auto' only, one is marked
1710
+ * `isHead`/`isTail` and the other extends beyond its pagination head/tail edge.
1490
1711
  */
1491
1712
  protected intervalsOverlap(
1492
1713
  a: AnyInterval,
1493
1714
  b: AnyInterval,
1494
1715
  policy: IntervalMergePolicy = 'auto',
1495
1716
  ): boolean {
1496
- const aBounds = this.getIntervalSortBounds(a);
1497
- const bBounds = this.getIntervalSortBounds(b);
1717
+ const aBounds = this.getIntervalSpan(a);
1718
+ const bBounds = this.getIntervalSpan(b);
1498
1719
  if (!aBounds || !bBounds) return false;
1499
1720
 
1500
- // Strict overlap if:
1501
- // a.first <= b.last && b.first <= a.last
1502
1721
  if (
1503
1722
  this.itemOrderComparator(aBounds.start, bBounds.end) <= 0 &&
1504
1723
  this.itemOrderComparator(bBounds.start, aBounds.end) <= 0
1505
1724
  )
1506
1725
  return true;
1507
1726
 
1508
- // If policy is strict-overlap-only, return false if the intervals do not strictly overlap.
1509
1727
  if (policy === 'strict-overlap-only') return false;
1510
1728
 
1511
1729
  const aIsHead = (a as Interval).isHead;
@@ -1513,8 +1731,8 @@ export abstract class BasePaginator<T, Q> {
1513
1731
  const aIsTail = (a as Interval).isTail;
1514
1732
  const bIsTail = (b as Interval).isTail;
1515
1733
 
1516
- const aEdges = this.getIntervalPaginationEdges(a);
1517
- const bEdges = this.getIntervalPaginationEdges(b);
1734
+ const aEdges = this.getIntervalSpanEdges(a);
1735
+ const bEdges = this.getIntervalSpanEdges(b);
1518
1736
  if (!aEdges || !bEdges) return false;
1519
1737
 
1520
1738
  if (bIsHead && this.aIsMoreHeadwardThanB(aEdges.head, bEdges.head)) return true;
@@ -1526,22 +1744,29 @@ export abstract class BasePaginator<T, Q> {
1526
1744
  }
1527
1745
 
1528
1746
  /**
1529
- * Whether an item belongs to an anchored interval.
1747
+ * Whether `item` belongs in `interval`: within its span (see {@link getIntervalSpan}), or beyond
1748
+ * the edge of a head or tail interval. An item the server never saw stays in the interval holding
1749
+ * it, so updating it does not move it.
1530
1750
  */
1531
1751
  protected belongsToInterval(item: T, interval: AnyInterval): boolean {
1532
- const sortBounds = this.getIntervalSortBounds(interval);
1533
- if (!sortBounds) return false;
1534
- const { start, end } = sortBounds;
1752
+ if (
1753
+ !this.isPaginationAnchorable(item) &&
1754
+ interval.itemIds.includes(this.getItemId(item))
1755
+ )
1756
+ return true;
1757
+ const span = this.getIntervalSpan(interval);
1758
+ if (!span) return false;
1759
+ const { start, end } = span;
1535
1760
  if (
1536
1761
  this.itemOrderComparator(start, item) <= 0 &&
1537
1762
  this.itemOrderComparator(item, end) <= 0
1538
1763
  )
1539
1764
  return true;
1540
1765
 
1541
- const edges = this.getIntervalPaginationEdges(interval);
1766
+ const edges = this.getIntervalSpanEdges(interval);
1542
1767
  if (!edges) return false;
1543
1768
 
1544
- // Items beyond head/tail edges are considered belonging to the head/tail pages.
1769
+ // Items beyond the edge of a head/tail page belong to it.
1545
1770
  if ((interval as Interval).isHead && this.aIsMoreHeadwardThanB(item, edges.head))
1546
1771
  return true;
1547
1772
 
@@ -1571,7 +1796,7 @@ export abstract class BasePaginator<T, Q> {
1571
1796
  getItemAt: (index: number) => merged[index],
1572
1797
  itemIdentityEquals: (item1, item2) =>
1573
1798
  this.getItemId(item1) === this.getItemId(item2),
1574
- // inter-interval operation sorts using the base comparator
1799
+ // Inter-interval operations use the base comparator.
1575
1800
  compare: this.itemOrderComparator.bind(this),
1576
1801
  });
1577
1802
  if (insertionIndex > -1) {
@@ -1594,8 +1819,7 @@ export abstract class BasePaginator<T, Q> {
1594
1819
  const isHead = preceding.isHead || following.isHead;
1595
1820
  const isTail = preceding.isTail || following.isTail;
1596
1821
 
1597
- // Default conservative merge:
1598
- // - if any contributor already concluded "no more" in a direction, keep that
1822
+ // Conservative default: "no more" in either interval stays "no more".
1599
1823
  let hasMoreHead = preceding.hasMoreHead && following.hasMoreHead;
1600
1824
  let hasMoreTail = preceding.hasMoreTail && following.hasMoreTail;
1601
1825
 
@@ -1614,7 +1838,7 @@ export abstract class BasePaginator<T, Q> {
1614
1838
  return {
1615
1839
  ...preceding,
1616
1840
  itemIds: mergedItemIds,
1617
- // Boundary intervals stay boundaries even if their edge shifts due to forced merges.
1841
+ // Boundary intervals stay boundaries even when forced merges shift their edge.
1618
1842
  hasMoreHead: isHead ? false : hasMoreHead,
1619
1843
  hasMoreTail: isTail ? false : hasMoreTail,
1620
1844
  isHead,
@@ -1622,9 +1846,7 @@ export abstract class BasePaginator<T, Q> {
1622
1846
  };
1623
1847
  }
1624
1848
 
1625
- /**
1626
- * Merges anchored intervals. Returns null if there are no intervals to merge.
1627
- */
1849
+ /** Merges anchored intervals; `null` when there are none. */
1628
1850
  protected mergeAnchoredIntervals(
1629
1851
  intervals: Interval[],
1630
1852
  baseInterval?: Interval,
@@ -1642,10 +1864,6 @@ export abstract class BasePaginator<T, Q> {
1642
1864
  return acc;
1643
1865
  }
1644
1866
 
1645
- // ---------------------------------------------------------------------------
1646
- // Locate items and intervals
1647
- // ---------------------------------------------------------------------------
1648
-
1649
1867
  protected locateIntervalIndex(interval: Interval): number {
1650
1868
  const intervals = this.itemIntervals.filter(
1651
1869
  (i) => !isLogicalInterval(i),
@@ -1665,16 +1883,15 @@ export abstract class BasePaginator<T, Q> {
1665
1883
  plateauScan: true,
1666
1884
  }).currentIndex;
1667
1885
  }
1668
- /**
1669
- * Locate item inside a specific interval using the same logic as locateByItem,
1670
- * but scoped to interval items.
1671
- */
1672
1886
  protected locateByItemInInterval({
1673
1887
  item,
1674
1888
  interval,
1889
+ plateauScan = true,
1675
1890
  }: {
1676
1891
  item: T;
1677
1892
  interval: Interval | LogicalInterval;
1893
+ /** Walk the interval for an item the binary search missed. Off when it cannot be there. */
1894
+ plateauScan?: boolean;
1678
1895
  }): ItemLocation | null {
1679
1896
  const ids = interval.itemIds;
1680
1897
 
@@ -1684,9 +1901,9 @@ export abstract class BasePaginator<T, Q> {
1684
1901
  getItemAt: (index: number) => this.getItem(ids[index]),
1685
1902
  itemIdentityEquals: (item1, item2) =>
1686
1903
  this.getItemId(item1) === this.getItemId(item2),
1687
- // items in intervals are not sorted by effectiveComparator
1904
+ // Interval items are not sorted by `effectiveComparator`.
1688
1905
  compare: this.itemOrderComparator.bind(this),
1689
- plateauScan: true,
1906
+ plateauScan,
1690
1907
  });
1691
1908
  }
1692
1909
 
@@ -1700,9 +1917,7 @@ export abstract class BasePaginator<T, Q> {
1700
1917
  }
1701
1918
  }
1702
1919
 
1703
- /**
1704
- * The interval whose `itemIds` lists this id, regardless of where the item now sorts.
1705
- */
1920
+ /** The interval whose `itemIds` lists this ID, regardless of where the item sorts. */
1706
1921
  protected findIntervalHoldingItem(item: T): AnyInterval | undefined {
1707
1922
  const id = this.getItemId(item);
1708
1923
  for (const interval of this.itemIntervals) {
@@ -1712,30 +1927,24 @@ export abstract class BasePaginator<T, Q> {
1712
1927
  }
1713
1928
 
1714
1929
  protected locateByItemInIntervals(item: T): ItemCoordinates['interval'] | undefined {
1715
- // Two different questions, asked in this order:
1716
- // 1. which interval's sort bounds does this item fall into (`locateIntervalForItem`)? The only
1717
- // one that can answer for an item this paginator has never stored.
1718
- // 2. which interval actually lists this id (`findIntervalHoldingItem`)?
1719
- //
1720
- // They disagree when an item is updated in place: the interval holds the very object being
1721
- // ingested, so it already carries the item's NEW sort value, and an item that moved outside its
1722
- // own window's bounds is no longer found by (1) — even though (2) still lists it. The fallback
1723
- // is what lets `ingestItem` take the old entry out before re-inserting; without it the id stays
1724
- // behind in that interval and ends up stored in two places at once.
1725
- const interval =
1726
- this.locateIntervalForItem(item) ?? this.findIntervalHoldingItem(item);
1727
- if (!interval) return undefined;
1728
- const itemLocation = this.locateByItemInInterval({ item, interval });
1729
- if (!itemLocation) return undefined;
1730
- return { interval, ...itemLocation };
1731
- }
1732
-
1733
- /**
1734
- * Locates the current position of the item and the index at which the item should be inserted
1735
- * according to effectiveComparator.
1736
- *
1737
- * @param item - The item to locate within the current state.
1738
- */
1930
+ const locateIn = (interval: AnyInterval | undefined, plateauScan?: boolean) => {
1931
+ const location =
1932
+ interval && this.locateByItemInInterval({ item, interval, plateauScan });
1933
+ return interval && location ? { interval, ...location } : undefined;
1934
+ };
1935
+ const boundsInterval = this.locateIntervalForItem(item);
1936
+ // Not held by this list, so in no interval: locate where it would go.
1937
+ if (!this._itemIndex.has(this.getItemId(item)))
1938
+ return locateIn(boundsInterval, false);
1939
+ // Held and unmoved: its sort value points at the interval, no scan needed.
1940
+ const inBounds = locateIn(boundsInterval);
1941
+ if (inBounds && inBounds.currentIndex > -1) return inBounds;
1942
+ // Held but moved: scan all intervals for it.
1943
+ const holdingInterval = this.findIntervalHoldingItem(item);
1944
+ return holdingInterval ? locateIn(holdingInterval) : inBounds;
1945
+ }
1946
+
1947
+ /** Position of the item in `state.items` and its insertion index under `effectiveComparator`. */
1739
1948
  protected locateItemInState(item: T): ItemLocation | null {
1740
1949
  const items = [...(this.items ?? [])];
1741
1950
 
@@ -1753,13 +1962,11 @@ export abstract class BasePaginator<T, Q> {
1753
1962
  locateByItem = (item: T): ItemCoordinates => {
1754
1963
  const result: ItemCoordinates = {};
1755
1964
 
1756
- // 1. Search in visible state.items
1757
1965
  const stateLoc = this.locateItemInState(item);
1758
1966
  if (stateLoc) {
1759
1967
  result.state = stateLoc;
1760
1968
  }
1761
1969
 
1762
- // 2. Search in intervals if interval-mode is active
1763
1970
  const intervalLoc = this.locateByItemInIntervals(item);
1764
1971
  if (intervalLoc) {
1765
1972
  result.interval = intervalLoc;
@@ -1768,16 +1975,11 @@ export abstract class BasePaginator<T, Q> {
1768
1975
  return result;
1769
1976
  };
1770
1977
 
1771
- // ---------------------------------------------------------------------------
1772
- // Item ingestion
1773
- // ---------------------------------------------------------------------------
1774
-
1775
1978
  protected removeItemIdFromInterval({
1776
1979
  interval,
1777
1980
  ...itemLocation
1778
1981
  }: ItemIntervalCoordinates): ItemIntervalCoordinates {
1779
1982
  if (
1780
- // If already at the correct position, nothing to change
1781
1983
  itemLocation.currentIndex >= 0 &&
1782
1984
  itemLocation.currentIndex === itemLocation.insertionIndex
1783
1985
  )
@@ -1785,8 +1987,8 @@ export abstract class BasePaginator<T, Q> {
1785
1987
 
1786
1988
  const itemIds = [...interval.itemIds];
1787
1989
 
1788
- // Adjust insertion index if we are removing the item before reinserting index.
1789
- // locateByItemInInterval() computed insertionIndex with the item still in the array.
1990
+ // `insertionIndex` was computed with the item still in the array: shift it when removing before
1991
+ // it.
1790
1992
  let insertionIndex = itemLocation.insertionIndex;
1791
1993
  if (
1792
1994
  itemLocation.currentIndex >= 0 &&
@@ -1795,7 +1997,6 @@ export abstract class BasePaginator<T, Q> {
1795
1997
  insertionIndex--;
1796
1998
  }
1797
1999
 
1798
- // Remove existing occurrence if present
1799
2000
  if (itemLocation.currentIndex >= 0) {
1800
2001
  itemIds.splice(itemLocation.currentIndex, 1);
1801
2002
  }
@@ -1806,10 +2007,7 @@ export abstract class BasePaginator<T, Q> {
1806
2007
  };
1807
2008
  }
1808
2009
 
1809
- /**
1810
- * Inserts an item ID into the interval in the correct sorted position.
1811
- * Returns unchanged interval if the correct insertion position could not be determined.
1812
- */
2010
+ /** Inserts the item ID at its sorted position; no-op when none can be determined. */
1813
2011
  protected insertItemIdIntoInterval<I extends Interval | LogicalInterval>(
1814
2012
  interval: I,
1815
2013
  item: T,
@@ -1826,7 +2024,6 @@ export abstract class BasePaginator<T, Q> {
1826
2024
 
1827
2025
  const id = this.getItemId(item);
1828
2026
 
1829
- // Insert at the new position
1830
2027
  if (typeof insertionIndex !== 'undefined' && insertionIndex > -1) {
1831
2028
  itemIds.splice(insertionIndex, 0, id);
1832
2029
  }
@@ -1838,12 +2035,11 @@ export abstract class BasePaginator<T, Q> {
1838
2035
  }
1839
2036
 
1840
2037
  /**
1841
- * Re-evaluates what the logical (live head / tail) intervals still hold against a freshly ingested
1842
- * page, returning the resulting anchored interval. Live updates park items there before any page
1843
- * exists — a channel archived while the archived list is untouched lands in the live head — and
1844
- * once a page covers such an item, leaving it gives the same id two homes, which is what renders
1845
- * as a duplicated row. The merge in `ingestPage` only folds logical intervals in when its
1846
- * `isHead`/overlap heuristics fire; this pass is unconditional and idempotent.
2038
+ * Re-evaluates what the logical (live head/tail) intervals hold against a freshly ingested page
2039
+ * and returns the resulting anchored interval. Live updates park items there before any page
2040
+ * exists; once a page covers one, leaving it gives the same ID two homes (a duplicated row).
2041
+ * Unlike the `ingestPage` merge, whose heuristics fire only sometimes, this pass is unconditional
2042
+ * and idempotent.
1847
2043
  */
1848
2044
  protected reconcileLogicalIntervalsAgainst(anchored: Interval): Interval {
1849
2045
  let merged = anchored;
@@ -1871,14 +2067,10 @@ export abstract class BasePaginator<T, Q> {
1871
2067
  }
1872
2068
 
1873
2069
  /**
1874
- * Moves items the loaded window proves are parked on the wrong side: an item sitting in the live
1875
- * head that actually sorts past the tail edge of everything loaded belongs to the live tail (the
1876
- * unloaded region on that side), and vice versa. Leaving it claims the wrong end of the list —
1877
- * the archived channel would render above a page it sorts below.
1878
- *
1879
- * Compared against the outermost anchored interval, not the page just ingested: an item that
1880
- * lands between two loaded pages is not "beyond" either side, it is a gap item, and those stay
1881
- * where they are (`ingestPage` turns them into their own island once the merge reaches the edge).
2070
+ * Moves items the loaded interval proves are parked on the wrong side: an item in the live head
2071
+ * that sorts past the tail edge of everything loaded belongs to the live tail, and vice versa.
2072
+ * Compared against the outermost anchored interval, not the page just ingested: an item between
2073
+ * two loaded pages is a gap item and stays.
1882
2074
  */
1883
2075
  protected moveMisfiledItemsToOppositeSide(
1884
2076
  logical: LogicalInterval,
@@ -1926,11 +2118,7 @@ export abstract class BasePaginator<T, Q> {
1926
2118
  else this.dropInterval(logical.id);
1927
2119
  }
1928
2120
 
1929
- /**
1930
- * Splits a logical interval by checking each item individually.
1931
- * Items overlapping anchoredInterval are merged into it.
1932
- * Others stay in a retained logical interval.
1933
- */
2121
+ /** Merges the logical interval's items that belong to `anchored` into it; the rest stay. */
1934
2122
  protected mergeItemsFromLogicalInterval(
1935
2123
  logical: LogicalInterval,
1936
2124
  anchored: Interval,
@@ -1963,10 +2151,9 @@ export abstract class BasePaginator<T, Q> {
1963
2151
  }
1964
2152
 
1965
2153
  /**
1966
- * Merges all intervals (anchored + logical head/tail).
1967
- * Returns:
1968
- * - merged anchored interval (or null if none merged)
1969
- * - possibly reduced logical head / tail intervals
2154
+ * Merges the anchored intervals and folds in the logical head/tail items that belong to the
2155
+ * result. Returns the merged interval (`null` if none) and the possibly reduced logical
2156
+ * intervals.
1970
2157
  */
1971
2158
  protected mergeIntervals(
1972
2159
  intervals: AnyInterval[],
@@ -1980,29 +2167,24 @@ export abstract class BasePaginator<T, Q> {
1980
2167
 
1981
2168
  const anchored: Interval[] = [];
1982
2169
 
1983
- // Separate logical vs anchored
1984
2170
  for (const itv of intervals) {
1985
2171
  if (isLiveHeadInterval(itv)) logicalHead = itv;
1986
2172
  else if (isLiveTailInterval(itv)) logicalTail = itv;
1987
2173
  else anchored.push(itv);
1988
2174
  }
1989
2175
 
1990
- // nothing to merge
1991
2176
  if (anchored.length === 0 && logicalHead && logicalTail) {
1992
2177
  return { logicalHead, merged: null, logicalTail };
1993
2178
  }
1994
2179
 
1995
- // Merge anchored intervals into one interval (if possible)
1996
2180
  const mergedAnchored = this.mergeAnchoredIntervals(anchored, baseInterval);
1997
2181
 
1998
- // No anchored intervals → just return logical ones
1999
2182
  if (!mergedAnchored) {
2000
2183
  return { logicalHead, merged: null, logicalTail };
2001
2184
  }
2002
2185
 
2003
2186
  let merged = mergedAnchored;
2004
2187
 
2005
- // Merge items from logical HEAD interval
2006
2188
  if (logicalHead) {
2007
2189
  const { mergedAnchored, remainingLogical } = this.mergeItemsFromLogicalInterval(
2008
2190
  logicalHead,
@@ -2012,7 +2194,6 @@ export abstract class BasePaginator<T, Q> {
2012
2194
  logicalHead = remainingLogical;
2013
2195
  }
2014
2196
 
2015
- // Merge items from logical TAIL interval
2016
2197
  if (logicalTail) {
2017
2198
  const { mergedAnchored, remainingLogical } = this.mergeItemsFromLogicalInterval(
2018
2199
  logicalTail,
@@ -2025,13 +2206,7 @@ export abstract class BasePaginator<T, Q> {
2025
2206
  return { logicalHead, merged, logicalTail };
2026
2207
  }
2027
2208
 
2028
- // ---------------------------------------------------------------------------
2029
- // Consume and manage items
2030
- // ---------------------------------------------------------------------------
2031
-
2032
- /**
2033
- * Ingests the whole page into intervals and returns the resulting anchored interval.
2034
- */
2209
+ /** Ingests the page into intervals; returns the resulting anchored interval (`null` if empty). */
2035
2210
  ingestPage({
2036
2211
  page,
2037
2212
  policy = 'auto',
@@ -2042,10 +2217,8 @@ export abstract class BasePaginator<T, Q> {
2042
2217
  }: {
2043
2218
  page: T[];
2044
2219
  /**
2045
- * Describes the policy for merging intervals.
2046
- * - 'auto' (default): Merge intervals if they overlap.
2047
- * - 'strict-overlap-only': Merge intervals only if they strictly overlap. Useful for jumping to a specific message.
2048
- * - This is useful for jumping to a specific message.
2220
+ * 'auto' merges overlapping intervals. 'strict-overlap-only' merges only strictly overlapping
2221
+ * ones, e.g. when jumping to a specific item. Defaults to 'auto'.
2049
2222
  */
2050
2223
  policy?: IntervalMergePolicy;
2051
2224
  isHead?: boolean;
@@ -2061,8 +2234,7 @@ export abstract class BasePaginator<T, Q> {
2061
2234
  isTail,
2062
2235
  });
2063
2236
 
2064
- // Coalesce per-item change notifications into a single flush, so a page of N
2065
- // items wakes each subscribing paginator once rather than N times.
2237
+ // One flush for the whole page: subscribing paginators wake once, not per item.
2066
2238
  this._itemIndex.batch(() => {
2067
2239
  for (const item of page) {
2068
2240
  this._itemIndex.setOne(item);
@@ -2073,20 +2245,14 @@ export abstract class BasePaginator<T, Q> {
2073
2245
  ? this._itemIntervals.get(targetIntervalId)
2074
2246
  : undefined;
2075
2247
 
2076
- // Set the base interval in the following order of importance
2077
- // 1. if target interval
2078
- // a) is not logical interval and
2079
- // b) merge would not lead to corrupted interval sorting
2080
- // (pages: [a], [b,c], merging page [x] to [a] -> [a,x], [b,c] or pages: [b,c], [x] and merging [a] to [x] => [b,c], [a,x] )
2081
- // 2. if one of the overlappingLogical is an active interval, use it as a base
2082
- // 3. if existing single anchored interval use it as a base
2248
+ // Base interval, in order of preference: an anchored target interval, an overlapping active
2249
+ // anchored interval, the single overlapping anchored interval.
2083
2250
  let baseInterval: Interval | undefined;
2084
2251
 
2085
- // Find intervals that overlap with this page
2086
2252
  const overlappingAnchored: Interval[] = [];
2087
2253
  const overlappingLogical: LogicalInterval[] = [];
2088
2254
  for (const itv of this.itemIntervals) {
2089
- // target interval will be used as base
2255
+ // The target interval is the base.
2090
2256
  if (targetInterval?.id === itv.id) continue;
2091
2257
  if (this.intervalsOverlap(pageInterval, itv, policy)) {
2092
2258
  if (this.isActiveInterval(itv) && !isLogicalInterval(itv)) {
@@ -2103,13 +2269,8 @@ export abstract class BasePaginator<T, Q> {
2103
2269
  }
2104
2270
  }
2105
2271
 
2106
- // If caller specifies an anchored target interval, treat it as the merge anchor.
2107
- // The role of ingestPage method is to merge intervals that overlap + the target
2108
- // interval. Decision, whether target interval is a correct base interval is
2109
- // upon the ingestPage method caller, not ingestPage method, because the method
2110
- // does not know, in which context it has been invoked and cannot reliably tell,
2111
- // whether it is a valid move to merge into the target interval as when
2112
- // paginating linearly, the ingested page will never overlap with the previous page.
2272
+ // An anchored target interval is always the merge base: whether that is valid is the caller's
2273
+ // call (linear pagination never overlaps the previous page).
2113
2274
  if (targetInterval && !isLogicalInterval(targetInterval)) {
2114
2275
  baseInterval = targetInterval;
2115
2276
  } else if (!baseInterval && overlappingAnchored.length === 1) {
@@ -2129,7 +2290,6 @@ export abstract class BasePaginator<T, Q> {
2129
2290
  );
2130
2291
 
2131
2292
  let resultingInterval = pageInterval;
2132
- // Remove all intervals that participated
2133
2293
  if (merged) {
2134
2294
  resultingInterval = merged;
2135
2295
  for (const itv of toMerge) {
@@ -2138,9 +2298,8 @@ export abstract class BasePaginator<T, Q> {
2138
2298
  }
2139
2299
  }
2140
2300
 
2141
- // Store logical head/tail (if any)
2142
2301
  if (logicalHead) {
2143
- // the leftovers that do not pertain to the first page should be migrated to a separate anchored interval
2302
+ // Leftovers that do not belong to the first page become a separate anchored interval.
2144
2303
  if (merged?.isHead) {
2145
2304
  const convertedInterval = {
2146
2305
  id: this.generateIntervalId(logicalHead.itemIds),
@@ -2157,7 +2316,7 @@ export abstract class BasePaginator<T, Q> {
2157
2316
  }
2158
2317
 
2159
2318
  if (logicalTail) {
2160
- // the leftovers that do not pertain to the last page should be migrated to a separate anchored interval
2319
+ // Leftovers that do not belong to the last page become a separate anchored interval.
2161
2320
  if (merged?.isTail) {
2162
2321
  const convertedInterval = {
2163
2322
  id: this.generateIntervalId(logicalTail.itemIds),
@@ -2176,7 +2335,6 @@ export abstract class BasePaginator<T, Q> {
2176
2335
  resultingInterval = this.reconcileLogicalIntervalsAgainst(resultingInterval);
2177
2336
 
2178
2337
  this.commitInterval(resultingInterval);
2179
- // keep the intervals sorted
2180
2338
  this.setIntervals(this.sortIntervals(this.itemIntervals));
2181
2339
 
2182
2340
  if (
@@ -2195,23 +2353,27 @@ export abstract class BasePaginator<T, Q> {
2195
2353
  }
2196
2354
 
2197
2355
  /**
2198
- * Ingests a single item on live update:
2199
- * - update the ItemIndex
2200
- * - find an anchored interval whose sort bounds contain the item
2201
- * - insert the item into that interval using locate+plateau logic
2202
- * - if this is the active interval, re-emit state.items from interval
2356
+ * Ingests a single live-updated item: updates the item index, inserts the item into the anchored
2357
+ * interval whose sort bounds contain it, and re-emits `state.items` when that interval is active.
2203
2358
  */
2204
2359
  ingestItem(ingestedItem: T): boolean {
2360
+ let ingested = false;
2361
+ this.withSingleActiveIntervalPublish(() => {
2362
+ ingested = this.applyItemIngestion(ingestedItem);
2363
+ });
2364
+ return ingested;
2365
+ }
2366
+
2367
+ private applyItemIngestion(ingestedItem: T): boolean {
2205
2368
  const id = this.getItemId(ingestedItem);
2206
2369
  const previousItem = this._itemIndex.get(id);
2207
2370
 
2208
- // 0. PRE-ANALYSIS: capture previous coordinates BEFORE any mutations
2371
+ // Capture the previous coordinates before any mutation.
2209
2372
  const previousCoords = this.locateByItem(previousItem || ingestedItem);
2210
2373
 
2211
2374
  const originalIndexInState = previousCoords?.state?.currentIndex ?? -1;
2212
2375
  const keepOrderInState = this.config.lockItemOrder && originalIndexInState >= 0;
2213
2376
 
2214
- // 1. Remove the old snapshot from state & intervals.
2215
2377
  const activeIntervalIdBeforeRemoval = this._activeIntervalId;
2216
2378
  let removedItemCoordinates: ItemCoordinates | undefined;
2217
2379
  if (previousCoords) {
@@ -2220,18 +2382,23 @@ export abstract class BasePaginator<T, Q> {
2220
2382
  const itemHasBeenRemoved =
2221
2383
  !!removedItemCoordinates?.state && removedItemCoordinates.state.currentIndex > -1;
2222
2384
 
2223
- // 2. Update canonical storage (ItemIndex) to the *new* snapshot,
2224
- // regardless of filters – this keeps the index authoritative.
2225
- this._itemIndex.setOne(ingestedItem);
2385
+ // Stored only if already present or it matches the paginator's filter.
2386
+ if (this._itemIndex.has(id) || this.matchesFilter(ingestedItem)) {
2387
+ this._itemIndex.setOne(ingestedItem);
2388
+ }
2226
2389
 
2227
- // 3. If it no longer matches the filter, we’re done (it has been removed above).
2390
+ // No longer matches the filter: it was removed above.
2228
2391
  if (!this.matchesFilter(ingestedItem)) {
2229
- // left the result set, not just this list
2392
+ // It left the result set, not just this list.
2230
2393
  this.shrinkOffsetAfterRemoval(removedItemCoordinates);
2231
- // Throttled: the removal above deferred its emit — publish the (settled) window once.
2232
- // Suspended (coalescing batch): removeItemAtCoordinates recorded it; batch() emits once on exit.
2233
- if (!this.isWindowPublishSuspended && this.isStateThrottled && itemHasBeenRemoved)
2234
- this.scheduleWindowPublish();
2394
+ // Throttled: the removal deferred its emit, so publish the settled interval once. Suspended
2395
+ // (coalescing batch): `removeItemAtCoordinates` recorded it and `batch()` emits on exit.
2396
+ if (
2397
+ !this.isActiveIntervalPublishSuspended &&
2398
+ this.isStateThrottled &&
2399
+ itemHasBeenRemoved
2400
+ )
2401
+ this.scheduleActiveIntervalPublish();
2235
2402
  return itemHasBeenRemoved;
2236
2403
  }
2237
2404
 
@@ -2240,15 +2407,13 @@ export abstract class BasePaginator<T, Q> {
2240
2407
  const onlyLogicalIntervals =
2241
2408
  this.itemIntervals.length <= 2 &&
2242
2409
  this.itemIntervals.every((itv) => isLogicalInterval(itv));
2243
- // IMPORTANT: decide if the new snapshot still belongs to the same anchored interval,
2244
- // using the OLD bounds.
2410
+ // Decide with the old bounds whether the new snapshot still belongs to the same interval.
2245
2411
  const stillBelongsToPreviousAnchoredInterval =
2246
2412
  previousInterval &&
2247
- // 1) If we *only* have logical intervals and the item used to live in one of them,
2248
- // keep it there. This prevents items from disappearing on update.
2413
+ // Only logical intervals exist and the item was in one: keep it there so it does not
2414
+ // disappear on update.
2249
2415
  ((onlyLogicalIntervals && isLogicalInterval(previousInterval)) ||
2250
- // 2) Normal: for anchored intervals, only reuse if the new snapshot is still
2251
- // within that interval's sort bounds.
2416
+ // Anchored: reuse only while the new snapshot is within the interval's sort bounds.
2252
2417
  (!isLogicalInterval(previousInterval) &&
2253
2418
  this.belongsToInterval(ingestedItem, previousInterval)));
2254
2419
 
@@ -2259,11 +2424,11 @@ export abstract class BasePaginator<T, Q> {
2259
2424
  const { liveHeadLogical, liveTailLogical } = this;
2260
2425
 
2261
2426
  if (!targetInterval) {
2262
- // No anchored interval currently contains the new snapshot.
2263
- // Decide whether it belongs to logical head, logical tail,
2264
- // or to a brand-new anchored interval.
2427
+ // No anchored interval contains the new snapshot: place it relative to the loaded intervals
2428
+ // (logical head or tail, the head-anchored interval it slid out of, or nowhere if its page is
2429
+ // unloaded).
2265
2430
  if (this._itemIntervals.size === 0) {
2266
- // No pages at all yet → keep in logical head.
2431
+ // No pages yet: keep it in the logical head.
2267
2432
  targetInterval = {
2268
2433
  id: LOGICAL_HEAD_INTERVAL_ID,
2269
2434
  itemIds: [this.getItemId(ingestedItem)],
@@ -2279,7 +2444,7 @@ export abstract class BasePaginator<T, Q> {
2279
2444
  const tailEdges = tailInterval && this.getIntervalPaginationEdges(tailInterval);
2280
2445
 
2281
2446
  if (headEdges && this.aIsMoreHeadwardThanB(ingestedItem, headEdges.head)) {
2282
- // Falls before the loaded head → logical head.
2447
+ // Before the loaded head: logical head.
2283
2448
  targetInterval = liveHeadLogical
2284
2449
  ? this.insertItemIdIntoInterval(liveHeadLogical, ingestedItem)
2285
2450
  : {
@@ -2287,21 +2452,18 @@ export abstract class BasePaginator<T, Q> {
2287
2452
  itemIds: [this.getItemId(ingestedItem)],
2288
2453
  };
2289
2454
  } else if (tailEdges && this.aIsMoreTailwardThanB(ingestedItem, tailEdges.tail)) {
2290
- // Falls after the loaded tail: normally the item moved into a page this paginator has
2291
- // not loaded, so it waits in the pending tail region. Not so when the window it left is
2292
- // anchored at the head — that window is "the first N items" and the item is one of them,
2293
- // it only slid to the bottom. Exiling it is what made unpinning the bottom-most loaded
2294
- // channel look like a deletion; its rank is then approximate until the next page settles
2295
- // it. A floating middle window has unloaded pages on both sides, so there it really is
2296
- // on another page.
2297
- const slidOutOfHeadAnchoredWindow =
2455
+ // After the loaded tail: normally the item moved to an unloaded page, so it waits in the
2456
+ // logical tail. Not when it slid out of a head-anchored interval (the "first N items"): it
2457
+ // is still one of them, and exiling it looked like a deletion. Its rank is approximate
2458
+ // until the next page settles it.
2459
+ const slidOutOfHeadAnchoredInterval =
2298
2460
  !!previousInterval &&
2299
2461
  !isLogicalInterval(previousInterval) &&
2300
2462
  previousInterval.isHead &&
2301
2463
  previousInterval.id === tailInterval?.id &&
2302
2464
  (previousCoords?.interval?.currentIndex ?? -1) > -1;
2303
2465
 
2304
- targetInterval = slidOutOfHeadAnchoredWindow
2466
+ targetInterval = slidOutOfHeadAnchoredInterval
2305
2467
  ? this.insertItemIdIntoInterval(previousInterval, ingestedItem)
2306
2468
  : liveTailLogical
2307
2469
  ? this.insertItemIdIntoInterval(liveTailLogical, ingestedItem)
@@ -2310,28 +2472,23 @@ export abstract class BasePaginator<T, Q> {
2310
2472
  itemIds: [this.getItemId(ingestedItem)],
2311
2473
  };
2312
2474
  } else {
2313
- // Falls somewhere *inside* the global bounds, but we don't have that page loaded.
2314
- // We’ve already removed any old occurrence, so from the paginator's perspective
2315
- // this item won't be visible again until the relevant page is fetched.
2475
+ // Inside the global bounds but on an unloaded page: it stays invisible until that page is
2476
+ // fetched.
2316
2477
  if (
2317
- !this.isWindowPublishSuspended &&
2478
+ !this.isActiveIntervalPublishSuspended &&
2318
2479
  this.isStateThrottled &&
2319
2480
  itemHasBeenRemoved
2320
2481
  )
2321
- this.scheduleWindowPublish();
2482
+ this.scheduleActiveIntervalPublish();
2322
2483
  return itemHasBeenRemoved;
2323
2484
  }
2324
2485
  }
2325
2486
  } else {
2326
- // Found an anchored interval whose bounds contain the new snapshot.
2327
2487
  targetInterval = this.insertItemIdIntoInterval(targetInterval, ingestedItem);
2328
2488
  }
2329
2489
 
2330
- // If removing the previous snapshot emptied and dropped what was the active interval
2331
- // (e.g. the sole reply in a freshly-opened thread), and we are re-adding the item into
2332
- // that same interval, restore it as the active interval. Otherwise the re-added item is
2333
- // never emitted to state.items below — the emit is gated on _activeIntervalId — so it
2334
- // silently disappears from the visible list until the interval is reloaded.
2490
+ // Removing the previous snapshot may have dropped the (now empty) active interval. Re-adding
2491
+ // the item into it restores it as active: the emit below is gated on `_activeIntervalId`.
2335
2492
  const removedIntervalId = removedItemCoordinates?.interval?.interval.id;
2336
2493
  if (
2337
2494
  !this._activeIntervalId &&
@@ -2341,10 +2498,14 @@ export abstract class BasePaginator<T, Q> {
2341
2498
  ) {
2342
2499
  this.setActiveInterval(
2343
2500
  targetInterval,
2344
- this.isWindowPublishSuspended ? { updateState: false } : undefined,
2501
+ this.isActiveIntervalPublishSuspended ? { updateState: false } : undefined,
2345
2502
  );
2346
2503
  }
2347
2504
 
2505
+ // Prune before committing: `targetInterval` is still the uncommitted copy, so the
2506
+ // `commitInterval` below stores the pruned interval (see {@link pruneTailToLimit}).
2507
+ const prunedNow = this.pruneTailToLimit(targetInterval);
2508
+
2348
2509
  const addedNewInterval = !this._itemIntervals.has(targetInterval.id);
2349
2510
  this.commitInterval(targetInterval);
2350
2511
 
@@ -2352,37 +2513,36 @@ export abstract class BasePaginator<T, Q> {
2352
2513
  this.setIntervals(this.sortIntervals(this.itemIntervals));
2353
2514
  }
2354
2515
 
2355
- // emit new state if active interval impacted by ingestion
2356
2516
  if (
2357
2517
  this._activeIntervalId &&
2358
2518
  [targetInterval.id, removedItemCoordinates?.interval?.interval.id].includes(
2359
2519
  this._activeIntervalId,
2360
2520
  )
2361
2521
  ) {
2362
- if (this.isWindowPublishSuspended) {
2363
- // Coalescing batch: record the change; batch() emits the settled window once on exit.
2364
- this._suspendedWindowDirty = true;
2522
+ if (this.isActiveIntervalPublishSuspended) {
2523
+ // Coalescing batch: record the change; batch() emits the settled interval once on exit.
2524
+ this._staleActiveIntervalState = this.state.getLatestValue();
2365
2525
  } else if (this.isStateThrottled) {
2366
- this.scheduleWindowPublish();
2526
+ this.scheduleActiveIntervalPublish();
2367
2527
  } else {
2368
2528
  const items = this.items ?? [];
2369
- /**
2370
- * Having config.lockItemOrder enabled when working with intervals will lead to
2371
- * discrepancies once active intervals are switched:
2372
- * 1. state.items [a,b,c] intervals [a,b,c], [d]
2373
- * 2. a changed and is moved to another interval state.items is now [a,b,c], intervals [b,c,], [d, a]
2374
- * 3. jumping / changing active interval to [d,a] - state.items is now [d,a], intervals [b,c], [d,a]
2375
- */
2529
+ // With `lockItemOrder`, `state.items` can keep an item the intervals moved elsewhere, so
2530
+ // switching the active interval then shows a different list.
2376
2531
  if (keepOrderInState) {
2377
- // Item was visible before → reinsert at its old index
2532
+ // The item was visible: reinsert it at its old index.
2378
2533
  const nextView = items.slice();
2379
2534
  const insertAt = Math.min(originalIndexInState, nextView.length);
2380
2535
  nextView.splice(insertAt, 0, ingestedItem);
2381
- this.state.partialNext({ items: nextView });
2536
+ this.state.partialNext({
2537
+ // This branch republishes the last published array rather than re-projecting, so IDs a
2538
+ // prune just removed would resurrect: drop them, keeping survivors' relative positions.
2539
+ items: prunedNow
2540
+ ? this.retainIntervalMembers(nextView, targetInterval)
2541
+ : nextView,
2542
+ ...this.consumePendingPrunePaginationState(),
2543
+ });
2382
2544
  } else {
2383
- /**
2384
- * Select a correct interval from which the state.items array is derived
2385
- */
2545
+ // Derive from the active interval (the one the item left, or the target).
2386
2546
  this.state.partialNext({
2387
2547
  items: this.intervalToItems(
2388
2548
  this._activeIntervalId === removedItemCoordinates?.interval?.interval.id &&
@@ -2390,6 +2550,7 @@ export abstract class BasePaginator<T, Q> {
2390
2550
  ? removedItemCoordinates.interval.interval
2391
2551
  : targetInterval,
2392
2552
  ),
2553
+ ...this.consumePendingPrunePaginationState(),
2393
2554
  });
2394
2555
  }
2395
2556
  }
@@ -2399,44 +2560,23 @@ export abstract class BasePaginator<T, Q> {
2399
2560
  }
2400
2561
 
2401
2562
  /**
2402
- * Run `fn` as one batched mutation over this paginator's items, collapsing the redundant emits a
2403
- * naive per-item loop would produce:
2404
- *
2405
- * - **Shared-store fan-out** (always, via the `_itemIndex.batch` wrapper): per-item store
2406
- * notifications fold into a single flush, so sibling holders of the same ids (e.g. a thread /
2407
- * pinned paginator sharing the entity) re-project once, not once per item. Inert for single-home
2408
- * paginators (channels, reminders, user groups) whose index is over a private store with no
2409
- * sibling subscribers — there it is a plain passthrough.
2410
- * - **This paginator's own active window** (`coalesce: true`): every `ingestItem` / `removeItem`
2411
- * inside `fn` records that the window changed instead of publishing it, then `batch` emits the
2412
- * settled window exactly once on exit via {@link flushWindowPublish}. This is deterministic and
2413
- * independent of state throttling — unlike leaving it off, where an un-throttled paginator emits
2414
- * once per item and a throttled one merely coalesces within its 500ms window. Use it for one-shot
2415
- * operations (reconciliation, reload re-ingest) that must settle in a single update. Omit it in WS
2416
- * event handlers, where per-event publishes should ride the throttle so successive events coalesce
2417
- * across its trailing edge rather than each forcing a synchronous emit.
2563
+ * Runs `fn` as one batched mutation: per-item store notifications fold into one flush, so sibling
2564
+ * holders of the same IDs re-project once. With `coalesce: true` the active interval also emits
2565
+ * exactly once on exit ({@link flushActiveIntervalPublish}), independent of throttling: for
2566
+ * one-shot operations. Omit it in WS event handlers so events ride the throttle. If `fn`
2567
+ * publishes the interval after its last change (see {@link publishActiveInterval}), `batch`
2568
+ * publishes nothing.
2418
2569
  */
2419
2570
  batch(fn: () => void, { coalesce = false }: { coalesce?: boolean } = {}): void {
2420
2571
  if (!coalesce) {
2421
2572
  this._itemIndex.batch(fn);
2422
2573
  return;
2423
2574
  }
2424
- this._windowPublishSuspendDepth += 1;
2425
- try {
2426
- this._itemIndex.batch(fn);
2427
- } finally {
2428
- this._windowPublishSuspendDepth -= 1;
2429
- }
2430
- if (this._windowPublishSuspendDepth === 0 && this._suspendedWindowDirty) {
2431
- this._suspendedWindowDirty = false;
2432
- this.flushWindowPublish();
2433
- }
2575
+ this.withSingleActiveIntervalPublish(() => this._itemIndex.batch(fn), {
2576
+ exit: 'sync',
2577
+ });
2434
2578
  }
2435
2579
 
2436
- // ---------------------------------------------------------------------------
2437
- // Remove / contains
2438
- // ---------------------------------------------------------------------------
2439
-
2440
2580
  protected removeItemAtCoordinates(coords: ItemCoordinates): ItemCoordinates {
2441
2581
  const { state: stateLocation, interval: intervalLocation } = coords;
2442
2582
 
@@ -2444,15 +2584,12 @@ export abstract class BasePaginator<T, Q> {
2444
2584
  state: { currentIndex: -1, insertionIndex: -1 },
2445
2585
  };
2446
2586
 
2447
- // 1) Remove from interval, if present
2448
2587
  if (intervalLocation && intervalLocation.currentIndex > -1) {
2449
2588
  const updatedInterval = this.removeItemIdFromInterval(intervalLocation);
2450
2589
  const { interval } = updatedInterval;
2451
2590
  if (interval.itemIds.length === 0) {
2452
- // Drop empty interval
2453
2591
  this.dropInterval(interval.id);
2454
2592
 
2455
- // If it was active -> clear active
2456
2593
  if (this.isActiveInterval(interval)) {
2457
2594
  this.setActiveInterval(undefined);
2458
2595
  }
@@ -2462,17 +2599,16 @@ export abstract class BasePaginator<T, Q> {
2462
2599
  result.interval = updatedInterval;
2463
2600
  }
2464
2601
 
2465
- // 2) Remove from visible state.items, if present
2466
2602
  if (stateLocation && stateLocation.currentIndex > -1) {
2467
- if (this.isWindowPublishSuspended) {
2468
- this._suspendedWindowDirty = true;
2603
+ if (this.isActiveIntervalPublishSuspended) {
2604
+ this._staleActiveIntervalState = this.state.getLatestValue();
2469
2605
  } else if (!this.isStateThrottled) {
2470
2606
  const newItems = [...(this.items ?? [])];
2471
2607
  newItems.splice(stateLocation.currentIndex, 1);
2472
2608
  this.state.partialNext({ items: newItems });
2473
2609
  }
2474
2610
 
2475
- // keep insertionIndex consistent if someone uses it later
2611
+ // Keep `insertionIndex` consistent after the removal.
2476
2612
  if (stateLocation.insertionIndex > stateLocation.currentIndex) {
2477
2613
  stateLocation.insertionIndex--;
2478
2614
  }
@@ -2485,12 +2621,12 @@ export abstract class BasePaginator<T, Q> {
2485
2621
 
2486
2622
  /**
2487
2623
  * Keeps `offset` addressing the same position in the *server's* result set after an item left the
2488
- * loaded window.
2624
+ * loaded interval.
2489
2625
  */
2490
2626
  protected shrinkOffsetAfterRemoval(coordinates?: ItemCoordinates) {
2491
2627
  // cursor pagination does not address items by position, so nothing can drift
2492
2628
  if (this.isCursorPagination) return;
2493
- // not part of the loaded window, so no page ever counted it
2629
+ // not part of the loaded interval, so no page ever counted it
2494
2630
  if ((coordinates?.state?.currentIndex ?? -1) < 0) return;
2495
2631
 
2496
2632
  const { offset } = this.state.getLatestValue();
@@ -2500,13 +2636,9 @@ export abstract class BasePaginator<T, Q> {
2500
2636
  }
2501
2637
 
2502
2638
  /**
2503
- * Meaning of location values
2504
- * - currentIndex === -1 could not be found
2505
- * - insertionIndex === -1 insertion index was no intended to be determined
2506
- *
2507
- * If we are removing the last item from the currently active interval, we do not search for a new active interval.
2508
- * If the number of items approach 0 in an active interval, we expect from the UI to load new pages to populate
2509
- * the active interval.
2639
+ * In the returned coordinates `currentIndex === -1` means not found and `insertionIndex === -1`
2640
+ * that none was determined. Removing the last item of the active interval does not activate
2641
+ * another one: the UI is expected to load pages to repopulate it.
2510
2642
  */
2511
2643
  removeItem({ id, item: inputItem }: { id?: string; item?: T }): ItemCoordinates {
2512
2644
  const noAction = { state: { currentIndex: -1, insertionIndex: -1 } };
@@ -2520,9 +2652,9 @@ export abstract class BasePaginator<T, Q> {
2520
2652
  const result = this.removeItemAtCoordinates(coords);
2521
2653
  this._itemIndex.remove(this.getItemId(item));
2522
2654
  this.shrinkOffsetAfterRemoval(result);
2523
- // Throttled: removeItemAtCoordinates deferred its emit — publish the (settled) window once.
2524
- if (!this.isWindowPublishSuspended && this.isStateThrottled)
2525
- this.scheduleWindowPublish();
2655
+ // Throttled: the removal deferred its emit, so publish the settled interval once.
2656
+ if (!this.isActiveIntervalPublishSuspended && this.isStateThrottled)
2657
+ this.scheduleActiveIntervalPublish();
2526
2658
  return result;
2527
2659
  }
2528
2660
 
@@ -2542,8 +2674,6 @@ export abstract class BasePaginator<T, Q> {
2542
2674
  ? valueOrFactory(currentItems)
2543
2675
  : valueOrFactory;
2544
2676
 
2545
- // If the references between the two values are the same, just return the
2546
- // current state; otherwise trigger a state change.
2547
2677
  if (currentItems === newItems) {
2548
2678
  return current;
2549
2679
  }
@@ -2566,13 +2696,22 @@ export abstract class BasePaginator<T, Q> {
2566
2696
  newState.hasMoreTail = interval.hasMoreTail;
2567
2697
  }
2568
2698
 
2699
+ // Before the publish below: subscribers read `hasLoadedPage` from inside it.
2700
+ this._pageSetWithoutQuery = true;
2569
2701
  return newState;
2570
2702
  });
2571
2703
 
2572
- // A populated page means a first page is effectively "loaded". Record a query shape so the
2573
- // paginator counts as initialized and the next pagination continues from this page - otherwise
2574
- // an undefined `_lastQueryShape` makes the first query look like a shape change, triggering a
2575
- // first page reset that wipes the seeded items and re-fetches the first page before paginating.
2704
+ this.recordLoadedIntervalQueryShape();
2705
+ }
2706
+
2707
+ /**
2708
+ * Records the query shape of the loaded interval so the next pagination continues it. Data that
2709
+ * arrives without the paginator's own query (`setItems`, a page from a query it did not run, a
2710
+ * subclass reconciling a loaded interval) would otherwise make the next query a first page that
2711
+ * publishes `items: undefined` first, and an empty response then loses the interval. Needs items:
2712
+ * an empty interval has no shape to continue from.
2713
+ */
2714
+ protected recordLoadedIntervalQueryShape() {
2576
2715
  if (
2577
2716
  typeof this._lastQueryShape === 'undefined' &&
2578
2717
  (this.state.getLatestValue().items?.length ?? 0) > 0
@@ -2581,53 +2720,37 @@ export abstract class BasePaginator<T, Q> {
2581
2720
  }
2582
2721
  }
2583
2722
 
2584
- // ---------------------------------------------------------------------------
2585
- // Debounce & query execution
2586
- // ---------------------------------------------------------------------------
2587
-
2588
2723
  setDebounceOptions = ({ debounceMs }: PaginatorDebounceOptions) => {
2589
2724
  this._executeQueryDebounced = debounce(this.executeQuery.bind(this), debounceMs);
2590
2725
  };
2591
2726
 
2592
- /**
2593
- * Rebuilds the state-publish throttles for a new interval, or drops them when the interval is unset.
2594
- *
2595
- * This exists because `stateThrottleMs` is read *once*: the throttles capture the interval in their
2596
- * closures, so assigning `config.stateThrottleMs` afterwards does nothing at all — an unthrottled
2597
- * paginator never gains a throttle, and a throttled one keeps its original interval. Anything
2598
- * changing the value at runtime (declarative configuration registered after construction, or
2599
- * `client.config.reset()`) has to come through here.
2600
- *
2601
- * Pending publishes are flushed first, so a swap cannot swallow a trailing-edge emit that was
2602
- * already scheduled.
2603
- */
2727
+ /** Changes `stateThrottleMs` at runtime. The config controller rebuilds the throttles. */
2604
2728
  setStateThrottleOptions = ({ stateThrottleMs }: { stateThrottleMs?: number }) => {
2605
- // Released surface. It no longer has to pair the write with the rebuild — the controller's
2606
- // `onChanged` does that for whichever route the value arrives by, including a declarative change.
2607
2729
  this.updateConfig({ stateThrottleMs } as Partial<BasePaginatorConfig<T, Q>>);
2608
2730
  };
2609
2731
 
2610
- /** Rebuilds the state-publish throttles for a new interval, or drops them when it is unset. */
2732
+ /**
2733
+ * Rebuilds the state-publish throttles for a new interval, or drops them when it is unset.
2734
+ * Pending publishes are flushed first so a swap cannot swallow a scheduled trailing-edge emit.
2735
+ */
2611
2736
  private rebuildStatePublishThrottles(stateThrottleMs?: number) {
2612
2737
  this.flushPendingPublishes();
2613
2738
 
2614
- this._windowPublishThrottle = undefined;
2739
+ this._activeIntervalPublishThrottle = undefined;
2615
2740
  this._viewPublishThrottle = undefined;
2616
2741
 
2617
2742
  if (!stateThrottleMs) return;
2618
2743
 
2619
- // Coalesce the paginator's own live `state.items` publishes (see `stateThrottleMs` doc). The
2620
- // trailing edge re-projects the active window fresh, so a burst emits ~once per interval.
2621
- this._windowPublishThrottle = throttle(
2622
- () => this.flushWindowPublish(),
2744
+ // The trailing edge re-projects the active interval, so a burst emits about once per throttle
2745
+ // interval.
2746
+ this._activeIntervalPublishThrottle = throttle(
2747
+ () => this.flushActiveIntervalPublish(),
2623
2748
  stateThrottleMs,
2624
2749
  {
2625
2750
  leading: true,
2626
2751
  trailing: true,
2627
2752
  },
2628
2753
  );
2629
- // Interval view publishes ride their own throttle so they coalesce like `state.items` but land on
2630
- // an independent trailing edge (see {@link _viewPublishThrottle}).
2631
2754
  this._viewPublishThrottle = throttle(
2632
2755
  () => this.flushIntervalViewPublish(),
2633
2756
  stateThrottleMs,
@@ -2636,27 +2759,10 @@ export abstract class BasePaginator<T, Q> {
2636
2759
  }
2637
2760
 
2638
2761
  /**
2639
- * Re-derives this paginator's configuration from its real inputs: package defaults, the options it
2640
- * was constructed with, and the declarative slice passed in.
2641
- *
2642
- * Called by the constructor and by `client.config.reset()` (through the owning `Channel` / `Thread`),
2643
- * so the two share one code path and cannot drift. Both read-once fields are routed through their
2644
- * rebuild setters, because assigning them would be silently discarded.
2762
+ * Rebuilds the configuration from defaults, options and the declarative slice, dropping earlier
2763
+ * `updateConfig` changes.
2645
2764
  *
2646
- * Structural wiring is untouched here because it never reaches `config` in the first place:
2647
- * `itemIndex` and `createItemIndex` are destructured out of the constructor's options and resolved
2648
- * once into {@link _itemIndex}, so there is nothing in the derived config for a re-derivation to drop.
2649
- *
2650
- * Subclass behaviour overrides are folded in through {@link getBehaviourOverrides} rather than written
2651
- * afterwards, so one re-derivation is one `configState` publish carrying a complete config. It used to
2652
- * be a second write from an `initializeConfig` override, and the claim that both writes carried a
2653
- * complete config was wrong: the base derivation knows nothing of the overlay, so it published the
2654
- * config with `doRequest`, `deriveCursor` and `itemOrderComparator` **stripped**, and the subclass then
2655
- * put them back. A `PinnedMessagePaginator` re-derivation emitted three notifications, of which the
2656
- * first had no request function at all — a subscriber that paginated during that synchronous window
2657
- * would have found none.
2658
- *
2659
- * Applied last, so the overlay still wins over constructor options exactly as the second write did.
2765
+ * @param declarativeConfig - The declarative slice. Leave it out to rebuild without one.
2660
2766
  */
2661
2767
  initializeConfig(declarativeConfig?: DeclarativePaginatorConfig): void {
2662
2768
  this.configController.initialize(
@@ -2665,16 +2771,9 @@ export abstract class BasePaginator<T, Q> {
2665
2771
  }
2666
2772
 
2667
2773
  /**
2668
- * Behaviour a subclass installs that no set of options can express — a comparator or `deriveCursor`
2669
- * closed over `this`, a `doRequest` bound to a particular endpoint. Empty on the base paginator.
2670
- *
2671
- * Folded into the single derivation in {@link initializeConfig}, which is why an override must return
2672
- * **stable references**: rebuilding the closures on each call makes every derived config differ from
2673
- * the last, defeating the guard above and republishing on every unrelated re-derivation. Memoize them
2674
- * — their inputs are fixed at construction.
2675
- *
2676
- * Called only after construction. The base constructor builds `configState` directly rather than
2677
- * through `initializeConfig`, so an override is never invoked before its own fields are initialized.
2774
+ * Behaviour a subclass installs that options cannot express (a comparator, `deriveCursor` or
2775
+ * `doRequest` closed over `this`). Applied last in `initializeConfig`. Must return stable
2776
+ * references (memoize them), or every derivation republishes. Called only after construction.
2678
2777
  */
2679
2778
  protected getBehaviourOverrides(): Partial<BasePaginatorConfig<T, Q>> {
2680
2779
  return {};
@@ -2696,7 +2795,7 @@ export abstract class BasePaginator<T, Q> {
2696
2795
  }: { direction?: PaginationDirection } & Pick<PaginationQueryParams<Q>, 'reset'>) =>
2697
2796
  !this.isLoading &&
2698
2797
  (reset === 'yes' ||
2699
- // If direction is undefined, we are jumping to a specific message.
2798
+ // No direction: a jump query.
2700
2799
  typeof direction === 'undefined' ||
2701
2800
  (direction === 'tailward' && this.hasMoreTail) ||
2702
2801
  (direction === 'headward' && this.hasMoreHead));
@@ -2704,10 +2803,9 @@ export abstract class BasePaginator<T, Q> {
2704
2803
  isFirstPageQuery = (
2705
2804
  params: { queryShape?: unknown } & Pick<PaginationQueryParams<Q>, 'reset'>,
2706
2805
  ): boolean => {
2707
- // A paginator with no loaded window starts its pagination from the first page. Note the third
2708
- // branch below covers the case where items are present without any page having been loaded (a
2709
- // live event ingested one into a never-queried list): no query shape has been recorded yet, so
2710
- // `shouldResetStateBeforeQuery` reports a first page for it too.
2806
+ // No loaded interval: first page. Items without a loaded page (a live event ingested one into a
2807
+ // never-queried list) have no recorded query shape, so `shouldResetStateBeforeQuery` reports a
2808
+ // first page for them too.
2711
2809
  if (typeof this.items === 'undefined') return true;
2712
2810
  if (params.reset === 'yes') return true;
2713
2811
  if (params.reset === 'no') return false;
@@ -2720,12 +2818,9 @@ export abstract class BasePaginator<T, Q> {
2720
2818
  ...this.initialState,
2721
2819
  isLoading: true,
2722
2820
  };
2723
- // This is the one moment the loaded window is (re)established from its start offset. For offset
2724
- // pagination the head (beginning) is loaded exactly when that window starts at offset 0, so
2725
- // hasMoreHead is a constant known before the query runs — anchor it here, once. It must NOT be
2726
- // re-derived per page in postQueryReconcile, because the offset only grows tailward from here and
2727
- // would then read as "more headward" even for a list that started at the head. Cursor pagination
2728
- // learns hasMoreHead from the query response, so leave the optimistic default for it.
2821
+ // Offset pagination: the head is loaded exactly when the interval starts at offset 0, so
2822
+ // `hasMoreHead` is anchored here, not re-derived per page (the growing offset would read as
2823
+ // "more headward"). Cursor pagination learns it from the response.
2729
2824
  if (!this.isCursorPagination) {
2730
2825
  state.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
2731
2826
  }
@@ -2736,6 +2831,36 @@ export abstract class BasePaginator<T, Q> {
2736
2831
  return false;
2737
2832
  }
2738
2833
 
2834
+ /**
2835
+ * Whether a first page queried with this shape is the dataset's head page. True unless the shape
2836
+ * starts the page elsewhere, such as at a cursor.
2837
+ */
2838
+ protected isHeadPageQueryShape(_queryShape: Q | undefined): boolean {
2839
+ return true;
2840
+ }
2841
+
2842
+ /**
2843
+ * Whether a fetched page reaches the head of the dataset, whatever query fetched it — for example a
2844
+ * page around an item that turns out to include the headmost one. Consulted when the query result
2845
+ * does not say (a `null` {@link PaginationQueryReturnValue.headward} does), with the page sorted in
2846
+ * item order, before it is ingested.
2847
+ *
2848
+ * - `true`: the page reaches the head; the interval it lands in is marked as the head.
2849
+ * - `false`: the page does not reach the head.
2850
+ * - `undefined` (the default): not known.
2851
+ *
2852
+ * Only `true` acts. On `false` or `undefined` the query shape and the cursor derivation decide, so a
2853
+ * interval they mark as the head stays marked — for example a newest page that a live item joins.
2854
+ */
2855
+ protected pageReachesHead(_page: T[], _queryShape: Q | undefined): boolean | undefined {
2856
+ return undefined;
2857
+ }
2858
+
2859
+ /** The page size a query's results are measured against when deriving the head/tail flags. */
2860
+ protected getRequestedPageSize(_queryShape: Q | undefined): number {
2861
+ return this.pageSize;
2862
+ }
2863
+
2739
2864
  protected getStateAfterQuery(
2740
2865
  stateUpdate: Partial<PaginatorState<T>>,
2741
2866
 
@@ -2760,26 +2885,34 @@ export abstract class BasePaginator<T, Q> {
2760
2885
  queryShape: Q | undefined;
2761
2886
  }): Promise<T[] | undefined> | T[] | undefined => undefined;
2762
2887
 
2763
- protected async runQueryRetryable(
2888
+ /**
2889
+ * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
2890
+ * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
2891
+ * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
2892
+ * caller to end the query.
2893
+ */
2894
+ protected async fetchQueryResponseWithRetries(
2764
2895
  params: PaginationQueryParams<Q> = {},
2765
- ): Promise<PaginationQueryReturnValue<T> | null> {
2896
+ ): Promise<R | null> {
2766
2897
  const remainingRetries = params.retryCount ?? 0;
2767
2898
  try {
2768
- return await this.query(params);
2899
+ return await this.fetchQueryResponse(params);
2769
2900
  } catch (e) {
2770
- const isOfflineSupportEnabledWithItems =
2771
- this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
2772
- if (!isOfflineSupportEnabledWithItems) {
2773
- this.state.partialNext({ lastQueryError: e as Error });
2774
- }
2775
-
2776
2901
  if (remainingRetries > 0) {
2777
2902
  await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
2778
- return await this.runQueryRetryable({
2903
+ return await this.fetchQueryResponseWithRetries({
2779
2904
  ...params,
2780
2905
  retryCount: remainingRetries - 1,
2781
2906
  });
2782
2907
  }
2908
+
2909
+ // run only once all retries are exhausted
2910
+ const isOfflineSupportEnabledWithItems =
2911
+ this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
2912
+ if (!isOfflineSupportEnabledWithItems) {
2913
+ this.state.partialNext({ lastQueryError: e as Error });
2914
+ }
2915
+
2783
2916
  if (this.config.throwErrors) {
2784
2917
  this.state.partialNext({ isLoading: false });
2785
2918
  throw e;
@@ -2789,181 +2922,392 @@ export abstract class BasePaginator<T, Q> {
2789
2922
  }
2790
2923
 
2791
2924
  /**
2792
- * Falsy return value means query was not successful.
2925
+ * Runs one query through the query pipeline, step by step:
2926
+ *
2927
+ * 1. {@link prepareQuery}: the query shape, read from the paginator state, and the loading flag.
2928
+ * A first page of a paginator not initialized yet shows what the offline database holds,
2929
+ * before the request is sent.
2930
+ * 2. {@link fetchQueryResponse}, retried as configured: the response.
2931
+ * 3. {@link extractQueryPage}: the page in the response.
2932
+ * 4. {@link placeQueryPage}: the page placed (shown unless only stored) and the query ended;
2933
+ * when fetching, extracting or placing failed, only the query ended.
2934
+ * 5. {@link applyQueryResponseRest}: the response's data besides its page, once that is placed.
2935
+ *
2936
+ * A failed fetch skips the steps after it; any other failed step skips none. Either is recorded
2937
+ * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
2938
+ * rejects the call only with `throwErrors` set.
2939
+ *
2940
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
2941
+ * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
2942
+ * placed, with `isSuperseded`.
2793
2943
  *
2794
2944
  * @param params - Query parameters.
2945
+ * @param params.claimsActiveInterval - Whether the query claims the active interval.
2795
2946
  * @param params.direction - Direction to paginate in (headward or tailward).
2796
- * @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a first-page query.
2947
+ * @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a
2948
+ * first-page query.
2797
2949
  * @param params.queryShape - Explicit query shape overriding the one derived from current state.
2798
- * @param params.reset - Whether to reset the loaded state before querying.
2799
- * @param params.retryCount - Number of remaining retry attempts on failure.
2800
- * @param params.silent - Suppress loading/state updates for this query.
2801
- * @param params.updateState - Whether to write the query results back to state.
2950
+ * Its page starts a separate interval (see `QueryPagePlacement.startsSeparateInterval`).
2951
+ * @param params.requestOptions - Request options outside the query shape.
2952
+ * @param params.reset - 'yes' forces a first page, 'no' continues, else the query shape decides.
2953
+ * @param params.retryCount - Number of retries after a failure.
2954
+ * @param params.silent - Skip the `isLoading: true` publish of a non-first-page or
2955
+ * `keepPreviousItems` query.
2956
+ * @param params.updateState - Whether the page's interval becomes the active one.
2957
+ */
2958
+ async executeQuery(
2959
+ params: PaginationQueryParams<Q> = {},
2960
+ ): Promise<ExecuteQueryReturnValue<T> | void> {
2961
+ const prepared = this.prepareQuery(params);
2962
+ if (!prepared) return;
2963
+ const result = await this.runPreparedQuery(prepared);
2964
+ // read once the query ended: a claim made while it ran overtakes the query's own
2965
+ const isSuperseded = this.claimIsSuperseded(prepared.placeParams);
2966
+ return result && { ...result, isSuperseded };
2967
+ }
2968
+
2969
+ /** The steps after {@link prepareQuery} of the query pipeline (see {@link executeQuery}). */
2970
+ private async runPreparedQuery({
2971
+ fetchParams,
2972
+ offlinePreloadPromise,
2973
+ placeParams,
2974
+ }: PreparedQuery<Q>): Promise<ExecuteQueryReturnValue<T> | undefined> {
2975
+ if (offlinePreloadPromise) await offlinePreloadPromise;
2976
+
2977
+ const response = await this.fetchQueryResponseWithRetries(fetchParams);
2978
+ if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
2979
+
2980
+ // Every step after the fetch runs, whichever fails: the rest of a response that arrived is
2981
+ // always applied. The first error is reported once they all ran.
2982
+ const errors: unknown[] = [];
2983
+ const runStep = <V>(step: () => V): V | undefined => {
2984
+ try {
2985
+ return step();
2986
+ } catch (error) {
2987
+ errors.push(error);
2988
+ return undefined;
2989
+ }
2990
+ };
2991
+ const page = runStep(() => this.extractQueryPage(response, fetchParams));
2992
+ let placed =
2993
+ page && runStep(() => this.placeQueryPage({ ...placeParams, results: page }));
2994
+ // a page that could not be extracted or placed ends the query without one
2995
+ placed ??= runStep(() => this.placeQueryPage({ ...placeParams, results: null }));
2996
+ runStep(() => this.applyQueryResponseRest(response, placeParams));
2997
+ return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
2998
+ }
2999
+
3000
+ /**
3001
+ * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
3002
+ * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
3003
+ * placed with the error in its state, so a caller committing that state keeps the error.
3004
+ */
3005
+ private reportQueryError(
3006
+ error: unknown,
3007
+ placed: ExecuteQueryReturnValue<T> | undefined,
3008
+ ): ExecuteQueryReturnValue<T> {
3009
+ const stateUpdate = { isLoading: false, lastQueryError: error as Error };
3010
+ this.state.partialNext(stateUpdate);
3011
+ if (this.config.throwErrors) throw error;
3012
+ return {
3013
+ stateCandidate: { ...placed?.stateCandidate, ...stateUpdate },
3014
+ targetInterval: placed?.targetInterval ?? null,
3015
+ };
3016
+ }
3017
+
3018
+ /**
3019
+ * Whether a query claims the active interval by default (see
3020
+ * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
3021
+ * - a reload (`reset: 'yes'`);
3022
+ * - a query at a shape the caller gave, unless `updateState` is `false`.
2802
3023
  */
2803
- async executeQuery({
3024
+ private decidesActiveInterval({
3025
+ queryShape,
3026
+ reset,
3027
+ updateState,
3028
+ }: Pick<PaginationQueryParams<Q>, 'queryShape' | 'reset' | 'updateState'>): boolean {
3029
+ const isReload = reset === 'yes';
3030
+ const showsPageAtCallersShape = !!queryShape && updateState !== false;
3031
+ return isReload || showsPageAtCallersShape;
3032
+ }
3033
+
3034
+ /**
3035
+ * The preparing step of the query pipeline (see {@link executeQuery}): resets the state when
3036
+ * asked, builds the query shape from the paginator state and publishes the loading flag. A first
3037
+ * page of a paginator not initialized yet also starts loading what the offline database holds,
3038
+ * returned as `offlinePreloadPromise`. `undefined` when the query cannot run now (see
3039
+ * {@link canExecuteQuery}).
3040
+ */
3041
+ private prepareQuery({
3042
+ claimsActiveInterval,
2804
3043
  direction,
2805
3044
  keepPreviousItems,
2806
3045
  queryShape: forcedQueryShape,
3046
+ requestOptions,
2807
3047
  reset,
2808
3048
  retryCount = this.config.retryCount,
2809
3049
  silent,
2810
3050
  updateState = true,
2811
- }: PaginationQueryParams<Q> = {}): Promise<ExecuteQueryReturnValue<T> | void> {
2812
- if (!this.canExecuteQuery({ direction, reset })) return;
2813
-
2814
- // A forced reset must happen BEFORE the request is built: `getNextQueryShape()` reads the
2815
- // pagination position (offset / cursor) out of state, so building first would re-query the page
2816
- // the previous pagination stopped at — a `reload()` at offset 20 would return the third page.
2817
- // `reset: 'yes'` is a first page by definition, so no query shape is needed to decide.
2818
- //
2819
- // Clearing the interval storage here also stops the incoming page from merging into stale
2820
- // intervals. Only a forced reset clears it: a first page reached through ordinary shape-change
2821
- // detection (cursor pagination looks like a new shape every page) must keep the cache so
2822
- // adjacent pages merge; filter/sort changes clear it via `resetState()` in their setters.
3051
+ }: PaginationQueryParams<Q>): PreparedQuery<Q> | undefined {
3052
+ if (!this.canExecuteQuery({ direction, reset })) return undefined;
3053
+ const claims =
3054
+ claimsActiveInterval ??
3055
+ this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
3056
+ const activeIntervalClaim = claims ? this.claimActiveInterval() : undefined;
3057
+
3058
+ // Reset before the query shape is built: `getNextQueryShape()` reads the position (offset,
3059
+ // cursor) from state, so a `reload()` at offset 20 would otherwise fetch the third page.
3060
+ // A forced reset also clears the loaded intervals, so the page cannot merge into stale ones.
3061
+ // Other first pages keep them: with cursors every page looks like a first page, and filter or
3062
+ // sort changes clear the intervals themselves (`resetState()`).
2823
3063
  const isForcedReset = reset === 'yes' && !keepPreviousItems;
3064
+ let positionBeforeReset: QueryPagePlacement<Q>['positionBeforeReset'];
2824
3065
  if (isForcedReset) {
2825
- this.setIntervals([]);
2826
- this.setActiveInterval(undefined);
2827
- this._itemIndex.clear();
2828
- this.clearIntervalViews();
3066
+ this.clearItemStorage();
2829
3067
  this.state.next(this.getStateBeforeFirstQuery());
2830
3068
  } else if (reset === 'yes' && !forcedQueryShape) {
2831
- // A `keepPreviousItems` refresh (reconnect / pull-to-refresh) must still restart pagination from
2832
- // page 1, but WITHOUT clearing the loaded window — the list stays visible while the fresh first
2833
- // page loads. Reset only the pagination position; `getNextQueryShape()` below reads it from state.
3069
+ // A refresh keeping the items (reconnect, pull-to-refresh) restarts from the first page but
3070
+ // leaves the list visible until that page arrives: only the position is reset.
3071
+ positionBeforeReset = { cursor: this.cursor, offset: this.offset };
2834
3072
  this.state.partialNext({
2835
3073
  cursor: this.config.initialCursor,
2836
3074
  offset: this.config.initialOffset ?? 0,
2837
3075
  });
2838
3076
  }
2839
3077
 
2840
- const queryShape = forcedQueryShape ?? this.getNextQueryShape({ direction });
3078
+ // A refresh keeping the items fetches as much of the loaded list as the server returns at once.
3079
+ const isRefresh = reset === 'yes' && keepPreviousItems && !forcedQueryShape;
3080
+ const pageSize = isRefresh
3081
+ ? Math.max(this.pageSize, this.items?.length ?? 0)
3082
+ : this.pageSize;
3083
+ const queryShape =
3084
+ forcedQueryShape ?? this.getNextQueryShape({ direction, pageSize });
2841
3085
 
2842
3086
  const isFirstPage = this.isFirstPageQuery({ queryShape, reset });
2843
3087
 
3088
+ let offlinePreloadPromise: Promise<void> | undefined;
2844
3089
  if (isFirstPage && !keepPreviousItems) {
2845
- const state = this.getStateBeforeFirstQuery();
2846
- let items: T[] | undefined = undefined;
2847
- if (!this.isInitialized) {
2848
- items =
2849
- (await this.preloadFirstPageFromOfflineDb({
3090
+ const stateBeforeFirstQuery = this.getStateBeforeFirstQuery();
3091
+ // The loading flag goes out now, before anything is awaited: `canExecuteQuery` checks it, and
3092
+ // a second call in the same tick would otherwise send the same first-page request again (an
3093
+ // empty list calls `toTail()` and `toHead()` together, being at both ends at once).
3094
+ // Only the flag: the rest of `stateBeforeFirstQuery` would blank the items the offline
3095
+ // database is about to fill. A forced reset has published all of it already.
3096
+ if (!isForcedReset) {
3097
+ this.state.partialNext({ isLoading: true });
3098
+ }
3099
+ const publishStateBeforeFirstQuery = (items: T[] | undefined) => {
3100
+ // after a forced reset this state is published already, so only offline items are news
3101
+ if (!isForcedReset || items !== undefined) {
3102
+ this.state.next({ ...stateBeforeFirstQuery, items });
3103
+ }
3104
+ };
3105
+ if (this.isInitialized) {
3106
+ publishStateBeforeFirstQuery(undefined);
3107
+ } else {
3108
+ offlinePreloadPromise = (async () => {
3109
+ const items = await this.preloadFirstPageFromOfflineDb({
2850
3110
  direction,
2851
3111
  queryShape,
2852
3112
  reset,
2853
3113
  retryCount,
2854
- })) ?? state.items;
2855
- }
2856
- // A forced reset already published this state above; re-publishing an identical value would
2857
- // only emit a second time. Publish again solely when the offline preload produced items.
2858
- if (!isForcedReset || items !== undefined) {
2859
- this.state.next({ ...state, items });
3114
+ });
3115
+ publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
3116
+ })();
2860
3117
  }
2861
3118
  } else if (!silent) {
2862
- // Non-first-page, or a keepPreviousItems refresh: surface loading without blanking the list. The
2863
- // freshly fetched page is merged into the still-loaded intervals in postQueryReconcile.
3119
+ // A next page, or a refresh keeping the items: loading shows without blanking the list, and
3120
+ // the page merges into the loaded intervals in `placeQueryPage`.
2864
3121
  this.state.partialNext({ isLoading: true });
2865
3122
  }
2866
3123
 
2867
- this._nextQueryShape = queryShape;
2868
- const results = await this.runQueryRetryable({
2869
- direction,
2870
- queryShape,
2871
- reset,
2872
- retryCount,
2873
- });
2874
- return this.postQueryReconcile({
2875
- direction,
2876
- isFirstPage,
2877
- keepPreviousItems,
2878
- queryShape,
2879
- requestedPageSize: this.pageSize,
2880
- results,
2881
- updateState,
2882
- });
2883
- }
2884
-
2885
- postQueryReconcile({
2886
- direction,
2887
- isFirstPage,
2888
- keepPreviousItems,
2889
- queryShape,
2890
- requestedPageSize,
2891
- results,
2892
- updateState = true,
2893
- }: PostQueryReconcileParams<T, Q>): ExecuteQueryReturnValue<T> {
2894
- this._lastQueryShape = queryShape;
2895
- this._nextQueryShape = undefined;
3124
+ // a page at the caller's shape has no known place relative to the active interval
3125
+ const isAtCallersShape = !!forcedQueryShape;
3126
+ const continuesOwnCursor = !isFirstPage && !isAtCallersShape;
2896
3127
 
2897
- const stateUpdate: Partial<PaginatorState<T>> = {
2898
- isLoading: false,
3128
+ return {
3129
+ fetchParams: { direction, queryShape, requestOptions, reset, retryCount },
3130
+ offlinePreloadPromise,
3131
+ placeParams: {
3132
+ activeIntervalClaim,
3133
+ startsSeparateInterval: isAtCallersShape,
3134
+ continuesIntervalId: continuesOwnCursor ? this._activeIntervalId : undefined,
3135
+ direction,
3136
+ isFirstPage,
3137
+ keepPreviousItems,
3138
+ positionBeforeReset,
3139
+ queryShape,
3140
+ requestedPageSize: this.getRequestedPageSize(queryShape),
3141
+ updateState,
3142
+ },
2899
3143
  };
3144
+ }
2900
3145
 
3146
+ /**
3147
+ * The placing step of the query pipeline (see {@link executeQuery}): places the page (see
3148
+ * {@link placePage}), shown unless only stored (see {@link isPageOnlyStored}), and ends the
3149
+ * query. Without a page (`results: null`), it only ends the query.
3150
+ */
3151
+ placeQueryPage(params: PlaceQueryPageParams<T, Q>): ExecuteQueryReturnValue<T> {
3152
+ this._lastQueryShape = params.queryShape;
3153
+ const { results } = params;
2901
3154
  if (!results) {
3155
+ const stateUpdate: Partial<PaginatorState<T>> = {
3156
+ isLoading: false,
3157
+ ...params.positionBeforeReset,
3158
+ };
2902
3159
  this.state.partialNext(stateUpdate);
2903
3160
  return { stateCandidate: stateUpdate, targetInterval: null };
2904
3161
  }
3162
+ if (this.isPageOnlyStored(params)) {
3163
+ return this.placePage(
3164
+ { ...params, results, startsSeparateInterval: true, updateState: false },
3165
+ { endsQuery: true },
3166
+ );
3167
+ }
3168
+ return this.placePage({ ...params, results }, { endsQuery: true });
3169
+ }
2905
3170
 
2906
- // Backward compatibility for custom BasePaginator subclasses:
2907
- // - old PaginationQueryReturnValue used next/prev
2908
- // - new contract uses tailward/headward
2909
- //
2910
- // Internal SDK paginators already return tailward/headward, so this fallback is
2911
- // only to keep non-migrated external subclasses working during transition.
2912
- const { items, headward, tailward, next, prev } = results;
2913
- const resolvedHeadward = headward ?? prev;
2914
- const resolvedTailward = tailward ?? next;
2915
-
2916
- stateUpdate.lastQueryError = undefined;
2917
- // Filtering is a synchronous local predicate (see filterQueryResults), so the whole
2918
- // reconciliation runs in a single tick. The channel-open seed relies on this to populate the
2919
- // paginator synchronously (MessagePaginator.seedFirstPageSync) before read-state hydration.
3171
+ /**
3172
+ * Whether the page is only stored, leaving the active interval as it is, rather than shown:
3173
+ * - the interval it continues is no longer active (see {@link continuedIntervalIsInactive});
3174
+ * - a later claim on the active interval was made (see {@link claimIsSuperseded}).
3175
+ */
3176
+ private isPageOnlyStored(params: QueryPagePlacement<Q>): boolean {
3177
+ return this.continuedIntervalIsInactive(params) || this.claimIsSuperseded(params);
3178
+ }
3179
+
3180
+ /**
3181
+ * Whether the interval the page continues stopped being active while the request ran, leaving
3182
+ * the page with no known place relative to the active interval.
3183
+ */
3184
+ private continuedIntervalIsInactive({
3185
+ continuesIntervalId,
3186
+ }: QueryPagePlacement<Q>): boolean {
3187
+ return (
3188
+ continuesIntervalId !== undefined && continuesIntervalId !== this._activeIntervalId
3189
+ );
3190
+ }
3191
+
3192
+ /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
3193
+ private claimIsSuperseded({ activeIntervalClaim }: QueryPagePlacement<Q>): boolean {
3194
+ return (
3195
+ activeIntervalClaim !== undefined &&
3196
+ !this.isLatestActiveIntervalClaim(activeIntervalClaim)
3197
+ );
3198
+ }
3199
+
3200
+ /**
3201
+ * Places a page in the paginator's intervals — in the interval it continues, or in an interval of
3202
+ * its own merged with the intervals it overlaps — and derives the cursors and the more-pages
3203
+ * flags. With `updateState` (the default), its interval becomes the shown one and the state is
3204
+ * published. Without it, the page is only stored, and published only if it landed in the active
3205
+ * interval, so the shown items never go stale. A page proven to reach the head of the dataset
3206
+ * makes its interval the only head (see {@link makeOnlyHead}). Where cursors are derived from the
3207
+ * interval (`config.deriveCursor`), an interval a headward page joins to the head interval
3208
+ * reaches the head, whatever the page says (see {@link inheritsHeadMark}).
3209
+ *
3210
+ * `endsQuery` says the page comes from the paginator's own query, which placing it ends: the
3211
+ * loading flag goes off, the last query error is cleared, and a first page goes to the offline
3212
+ * database. A page from a query the paginator did not run is placed without any of that, as one
3213
+ * of the paginator's own queries may still be running.
3214
+ */
3215
+ protected placePage(
3216
+ {
3217
+ startsSeparateInterval,
3218
+ direction,
3219
+ isFirstPage,
3220
+ keepPreviousItems,
3221
+ queryShape,
3222
+ requestedPageSize,
3223
+ results,
3224
+ updateState = true,
3225
+ }: QueryPagePlacement<Q> & { results: PaginationQueryReturnValue<T> },
3226
+ { endsQuery }: { endsQuery: boolean },
3227
+ ): ExecuteQueryReturnValue<T> {
3228
+ const stateUpdate: Partial<PaginatorState<T>> = endsQuery
3229
+ ? { isLoading: false, lastQueryError: undefined }
3230
+ : {};
3231
+
3232
+ const { items, headward, tailward } = results;
3233
+ // Filtering is a synchronous local predicate (see filterQueryResults), so placing the page
3234
+ // runs in a single tick. A subclass placing a page outside its own queries relies on this:
3235
+ // the page is in place as soon as this returns.
2920
3236
  const filteredItems = this.filterQueryResults(items);
2921
3237
  stateUpdate.items = filteredItems;
2922
3238
 
2923
3239
  const isJumpQuery = !!queryShape && this.isJumpQueryShape(queryShape);
3240
+ const isSeparateInterval = isJumpQuery || !!startsSeparateInterval;
3241
+ // Asked before the ingest, which may itself advance what the paginator knows about the head.
3242
+ const reachesHead =
3243
+ headward === null || this.pageReachesHead(items, queryShape) === true;
3244
+ const reachesTail = tailward === null;
3245
+ // A non-destructive refresh merges page 1 into the interval it kept, so the ids that interval
3246
+ // held have to be read before the ingest below adds the page to it.
3247
+ const keptItemIds =
3248
+ isFirstPage && keepPreviousItems && !this.isCursorPagination && this.items?.length
3249
+ ? new Set(this.items.map((item) => this.getItemId(item)))
3250
+ : undefined;
3251
+ // Read before the ingest, which may merge them into the page's interval.
3252
+ const headIntervalIds = this.getHeadIntervalIds();
2924
3253
  const interval = this.ingestPage({
2925
3254
  page: stateUpdate.items,
2926
- policy: isJumpQuery ? 'strict-overlap-only' : 'auto',
2927
- // the first page should be always marked as head
2928
- isHead: isJumpQuery
2929
- ? undefined //head/tail doesn't apply / is unknown for this ingestion
2930
- : isFirstPage ||
2931
- (direction === 'headward' ? requestedPageSize > items.length : undefined),
2932
- // even though the page is first, we have to compare the requested vs returned page size
2933
- isTail: isJumpQuery
2934
- ? undefined //head/tail doesn't apply / is unknown for this ingestion
2935
- : isFirstPage || direction === 'tailward'
2936
- ? requestedPageSize > items.length
2937
- : undefined,
2938
- targetIntervalId: isJumpQuery ? undefined : this._activeIntervalId,
3255
+ policy: isSeparateInterval ? 'strict-overlap-only' : 'auto',
3256
+ // a first page is the head unless its query started it elsewhere (at a cursor)
3257
+ isHead: reachesHead
3258
+ ? true
3259
+ : isJumpQuery
3260
+ ? undefined //head/tail doesn't apply / is unknown for this ingestion
3261
+ : (isFirstPage && this.isHeadPageQueryShape(queryShape)) ||
3262
+ (direction === 'headward' ? requestedPageSize > items.length : undefined),
3263
+ // even though the page is first, we have to compare the requested vs returned page size;
3264
+ // a first page queried towards the head says nothing about the tail
3265
+ isTail: reachesTail
3266
+ ? true
3267
+ : isJumpQuery
3268
+ ? undefined //head/tail doesn't apply / is unknown for this ingestion
3269
+ : (isFirstPage && direction !== 'headward') || direction === 'tailward'
3270
+ ? requestedPageSize > items.length
3271
+ : undefined,
3272
+ targetIntervalId: isSeparateInterval ? undefined : this._activeIntervalId,
2939
3273
  });
3274
+ const intervalReachesHead =
3275
+ reachesHead ||
3276
+ (!!interval && this.inheritsHeadMark(interval, direction, headIntervalIds));
2940
3277
  if (interval && updateState) {
2941
3278
  this.setActiveInterval(interval, { updateState: false });
2942
3279
  stateUpdate.items = this.intervalToItems(interval);
2943
- } else if (updateState && !items.length && (keepPreviousItems || !isFirstPage)) {
2944
- // An empty page must NOT wipe the loaded items on a non-destructive refresh
2945
- // (keepPreviousItems) or an incremental query. `ingestPage` returns null for an empty page
2946
- // (leaving the active interval untouched), so `stateUpdate.items` still holds the empty
2947
- // `filteredItems` here and committing that would blank the list. This happens when a refresh
2948
- // finds nothing, or when a paginate hits the dataset edge. Preserve the current view instead.
2949
- // A genuine reset (isFirstPage without keepPreviousItems) still blanks, so an emptied dataset
2950
- // shows empty.
3280
+ } else if (
3281
+ updateState &&
3282
+ !filteredItems.length &&
3283
+ (keepPreviousItems || !isFirstPage)
3284
+ ) {
3285
+ // A page left empty, by the server or by `filterQueryResults`, must not wipe the loaded items
3286
+ // on a `keepPreviousItems` refresh or an incremental query (`ingestPage` returns null for it).
3287
+ // A genuine reset still blanks.
2951
3288
  stateUpdate.items = this.items;
2952
3289
  }
2953
3290
 
2954
- /**
2955
- * Cursor can be calculated client-side or returned from the server.
2956
- * Therefore, the BasePaginator.cursorSource can be 'derived' | 'query'
2957
- * - derived - the BasePaginator applies the default client-side logic based on the pagination options (id_lt, id_gt, id_around...)
2958
- * - query - BasePaginator.query() resp. BasePaginator.config.doRequest (called inside query()) is expected to provide the cursor and abide by the rules that when the wall is hit in
2959
- * a given direction, the cursor will be set to null.
2960
- *
2961
- * The 'derived' calculation will perform the following steps:
2962
- * 1. After ingesting into the parent interval determine the cursor candidate values from the first and the last item in the interval.
2963
- * 2. Decide, whether the candidates can be set based on the requested vs real page size
2964
- * 3. If the page size from the response is smaller that the requested page size, then in the given direction
2965
- * the cursor will be set to null.
2966
- */
3291
+ // The cursor comes from `config.deriveCursor` (derived from the ingested interval) or from the
3292
+ // extracted page (`headward`/`tailward`, `null` meaning the edge was hit).
3293
+ // The flags the derivation starts from. A page in the active interval continues that interval's
3294
+ // flags; a page in an interval of its own (a jump, or a page whose place relative to the active
3295
+ // interval is unknown) starts from that interval's own, as the active interval says nothing
3296
+ // about it.
3297
+ const continuesActiveIntervalFlags =
3298
+ !isSeparateInterval || (!!interval && this.isActiveInterval(interval));
3299
+ const knownFlags =
3300
+ continuesActiveIntervalFlags || !interval
3301
+ ? {
3302
+ cursor: this.cursor,
3303
+ hasMoreHead: this.hasMoreHead,
3304
+ hasMoreTail: this.hasMoreTail,
3305
+ }
3306
+ : {
3307
+ cursor: undefined,
3308
+ hasMoreHead: interval.hasMoreHead,
3309
+ hasMoreTail: interval.hasMoreTail,
3310
+ };
2967
3311
  if (this.isCursorPagination) {
2968
3312
  if (this.config.deriveCursor && interval) {
2969
3313
  const { cursor, hasMoreTail, hasMoreHead } = this.config.deriveCursor({
@@ -2972,55 +3316,94 @@ export abstract class BasePaginator<T, Q> {
2972
3316
  queryShape,
2973
3317
  page: results.items,
2974
3318
  requestedPageSize,
2975
- cursor: this.cursor,
2976
- hasMoreHead: this.hasMoreHead,
2977
- hasMoreTail: this.hasMoreTail,
3319
+ ...knownFlags,
2978
3320
  });
2979
3321
  stateUpdate.cursor = cursor;
2980
3322
  stateUpdate.hasMoreTail = hasMoreTail;
2981
3323
  stateUpdate.hasMoreHead = hasMoreHead;
3324
+ } else if (this.config.deriveCursor && direction && !isFirstPage) {
3325
+ // Nothing was ingested, so there is no interval to derive from: only the direction
3326
+ // paginated in is resolved and the other side keeps its cursor.
3327
+ stateUpdate.cursor =
3328
+ direction === 'headward'
3329
+ ? {
3330
+ headward: headward || null,
3331
+ tailward: this.cursor?.tailward ?? null,
3332
+ }
3333
+ : {
3334
+ headward: this.cursor?.headward ?? null,
3335
+ tailward: tailward || null,
3336
+ };
3337
+ if (direction === 'headward') stateUpdate.hasMoreHead = !!headward;
3338
+ else stateUpdate.hasMoreTail = !!tailward;
2982
3339
  } else {
2983
3340
  stateUpdate.cursor = {
2984
- tailward: resolvedTailward || null,
2985
- headward: resolvedHeadward || null,
3341
+ tailward: tailward || null,
3342
+ headward: headward || null,
3343
+ };
3344
+ stateUpdate.hasMoreTail = !!tailward;
3345
+ stateUpdate.hasMoreHead = !!headward;
3346
+ }
3347
+ if (interval && (intervalReachesHead || reachesTail)) {
3348
+ // The interval reaches an end of the dataset, whatever the derivation guessed from the
3349
+ // page's shape and size.
3350
+ const cursor = stateUpdate.cursor ?? this.cursor;
3351
+ stateUpdate.cursor = {
3352
+ headward: intervalReachesHead ? null : (cursor?.headward ?? null),
3353
+ tailward: reachesTail ? null : (cursor?.tailward ?? null),
2986
3354
  };
2987
- stateUpdate.hasMoreTail = !!resolvedTailward;
2988
- stateUpdate.hasMoreHead = !!resolvedHeadward;
3355
+ if (intervalReachesHead) stateUpdate.hasMoreHead = false;
3356
+ if (reachesTail) stateUpdate.hasMoreTail = false;
2989
3357
  }
2990
3358
  } else {
2991
3359
  // todo: we could keep the offset in two directions (initial tailward offset would be taken from config.initialOffset)
2992
3360
  const startOffset = this.offset ?? 0;
2993
3361
  stateUpdate.offset = startOffset + items.length;
2994
- // Only hasMoreTail depends on the page result. hasMoreHead is fixed by where the loaded window
2995
- // starts (offset 0 => head loaded) and was anchored once at the reset (getStateBeforeFirstQuery);
2996
- // the offset only grows tailward from here, so leave hasMoreHead untouched.
2997
- stateUpdate.hasMoreTail = items.length === this.pageSize;
3362
+ // After a `keepPreviousItems` refresh whose page connects to the kept interval, continue from
3363
+ // the interval's end instead of re-fetching it.
3364
+ const lastPageItem = items[items.length - 1];
3365
+ if (
3366
+ interval &&
3367
+ keptItemIds &&
3368
+ lastPageItem &&
3369
+ keptItemIds.has(this.getItemId(lastPageItem))
3370
+ ) {
3371
+ stateUpdate.offset = Math.max(
3372
+ stateUpdate.offset,
3373
+ startOffset + this.intervalToItems(interval).length,
3374
+ );
3375
+ }
3376
+ // Only `hasMoreTail` depends on the page result: `hasMoreHead` was anchored at the reset
3377
+ // ({@link getStateBeforeFirstQuery}).
3378
+ stateUpdate.hasMoreTail = items.length >= this.pageSize;
3379
+ // A `keepPreviousItems` first page never publishes `getStateBeforeFirstQuery()`, so anchor
3380
+ // its `hasMoreHead` from the start offset here.
3381
+ if (isFirstPage) stateUpdate.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
2998
3382
  }
2999
3383
 
3000
3384
  if (interval) {
3001
- const current = this.state.getLatestValue();
3002
3385
  const resolvedHasMoreHead =
3003
3386
  typeof stateUpdate.hasMoreHead === 'boolean'
3004
3387
  ? stateUpdate.hasMoreHead
3005
- : current.hasMoreHead;
3388
+ : knownFlags.hasMoreHead;
3006
3389
  const resolvedHasMoreTail =
3007
3390
  typeof stateUpdate.hasMoreTail === 'boolean'
3008
3391
  ? stateUpdate.hasMoreTail
3009
- : current.hasMoreTail;
3392
+ : knownFlags.hasMoreTail;
3010
3393
 
3011
3394
  const wasHead = interval.isHead;
3012
3395
  interval.hasMoreHead = resolvedHasMoreHead;
3013
3396
  interval.hasMoreTail = resolvedHasMoreTail;
3014
3397
  interval.isHead = resolvedHasMoreHead === false;
3015
3398
  interval.isTail = resolvedHasMoreTail === false;
3016
- // `isHead` is decided here (not at ingest); reflect any head-status flip in `anchoredHead`.
3399
+ // `isHead` is decided here, not at ingest: reflect a flip in `anchoredHead`.
3017
3400
  this.syncAnchoredHeadAfterHeadFlip(interval, wasHead);
3018
- } else if (!items.length && direction) {
3019
- // An empty directional response means the dataset edge was reached in `direction`, but
3020
- // `ingestPage` returns no interval for an empty page so the block above never runs. Flag the
3021
- // currently active interval as reaching that edge; otherwise its `isHead`/`isTail` stay stale
3022
- // (e.g. `jumpToTheLatestMessage` would never see the head as loaded, and a "scroll to latest"
3023
- // affordance would never clear).
3401
+ if (reachesHead && interval.isHead) this.makeOnlyHead(interval);
3402
+ } else if (!items.length && direction && !isSeparateInterval) {
3403
+ // An empty directional response continuing the active interval means the dataset edge was
3404
+ // reached, but `ingestPage` returns no interval for an empty page: flag the active interval,
3405
+ // or its `isHead`/`isTail` stay stale and the head never reads as loaded. An empty page whose
3406
+ // place relative to the active interval is unknown says nothing about it.
3024
3407
  const activeInterval = this._activeIntervalId
3025
3408
  ? this._itemIntervals.get(this._activeIntervalId)
3026
3409
  : undefined;
@@ -3029,7 +3412,6 @@ export abstract class BasePaginator<T, Q> {
3029
3412
  const wasHead = activeInterval.isHead;
3030
3413
  activeInterval.isHead = true;
3031
3414
  activeInterval.hasMoreHead = false;
3032
- // The active page just reached the dataset head; reflect the flip in `anchoredHead`.
3033
3415
  this.syncAnchoredHeadAfterHeadFlip(activeInterval, wasHead);
3034
3416
  } else if (direction === 'tailward') {
3035
3417
  activeInterval.isTail = true;
@@ -3038,9 +3420,17 @@ export abstract class BasePaginator<T, Q> {
3038
3420
  }
3039
3421
  }
3040
3422
 
3041
- const state = this.getStateAfterQuery(stateUpdate, isFirstPage);
3423
+ const state = endsQuery
3424
+ ? this.getStateAfterQuery(stateUpdate, isFirstPage)
3425
+ : { ...this.state.getLatestValue(), ...stateUpdate };
3426
+ // `updateState` decides whether the results are committed, not whether the query is over: a
3427
+ // caller that commits its own state must not be left with the `isLoading` executeQuery published.
3042
3428
  if (updateState) this.state.next(state);
3043
- this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
3429
+ else this.publishStoredPage({ endsQuery, interval, state });
3430
+ // Only the first page of the paginator's own query is cached; a later page cannot change it.
3431
+ if (endsQuery && isFirstPage) {
3432
+ this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
3433
+ }
3044
3434
 
3045
3435
  return {
3046
3436
  stateCandidate: state,
@@ -3048,38 +3438,52 @@ export abstract class BasePaginator<T, Q> {
3048
3438
  };
3049
3439
  }
3050
3440
 
3051
- // ---------------------------------------------------------------------------
3052
- // Public API: navigation
3053
- // ---------------------------------------------------------------------------
3441
+ /**
3442
+ * Publishes what placing an only-stored page changed (see {@link placePage}): the active interval
3443
+ * if the page landed in it, and the end of the query with `endsQuery`.
3444
+ */
3445
+ private publishStoredPage({
3446
+ endsQuery,
3447
+ interval,
3448
+ state,
3449
+ }: {
3450
+ endsQuery: boolean;
3451
+ interval: Interval | null;
3452
+ state: PaginatorState<T>;
3453
+ }) {
3454
+ const endsLoading = endsQuery && (this.isLoading || !!this.lastQueryError);
3455
+ const queryEnd = endsLoading ? { isLoading: false, lastQueryError: undefined } : {};
3456
+ if (interval && this.isActiveInterval(interval)) {
3457
+ const { cursor, hasMoreHead, hasMoreTail } = state;
3458
+ this.publishActiveInterval({ ...queryEnd, cursor, hasMoreHead, hasMoreTail });
3459
+ } else if (endsLoading) {
3460
+ this.state.partialNext(queryEnd);
3461
+ }
3462
+ }
3054
3463
 
3055
3464
  cancelScheduledQuery() {
3056
3465
  this._executeQueryDebounced.cancel();
3057
3466
  }
3058
3467
 
3059
3468
  resetState() {
3469
+ // Nothing is loaded, so the next query is a first page again. A stale shape would make a
3470
+ // re-query with an unchanged shape a continuation, ingested without `isHead`. Cleared before
3471
+ // the publish below, whose subscribers read `isInitialized` / `hasLoadedPage`.
3472
+ this._lastQueryShape = undefined;
3473
+ this._pageSetWithoutQuery = false;
3060
3474
  this.state.next(this.initialState);
3061
3475
  this.setIntervals([]);
3062
3476
  this.setActiveInterval(undefined);
3063
3477
  this.clearIntervalViews();
3064
- // Nothing is loaded anymore, so the next query is a first page again. Without this the reset
3065
- // paginator would still report itself as initialized and a re-query with an unchanged shape
3066
- // (a filter/sort setter that resets, `ChannelManager.resetPaginatorStates()` on disconnect)
3067
- // would be treated as a continuation — ingested without `isHead`, leaving any live-updated
3068
- // logical interval unreconciled.
3069
- this._lastQueryShape = undefined;
3070
3478
  }
3071
3479
 
3072
3480
  /**
3073
- * Releases this paginator's hold on its item content. With a shared, refcounted item index this
3074
- * unlinks every member id from the backing store, so the store no longer strong-references this
3075
- * paginator through its subscriber registry — otherwise a discarded owner stays pinned, keeps
3076
- * receiving change notifications, and its items never garbage-collect. Call on teardown of the
3077
- * owner: a discard, not a reset (the owner is not reused; a re-appearing id gets a fresh instance;
3078
- * leftover interval/state caches die with the paginator when it is dropped). Also cancels any
3079
- * pending throttled window/view publish, so nothing emits after teardown.
3481
+ * Releases this paginator's hold on its item content (unlinks every member ID from the shared
3482
+ * store, which otherwise pins a discarded owner) and cancels pending throttled publishes. A
3483
+ * teardown, not a reset: the owner is not reused.
3080
3484
  */
3081
3485
  dispose(): void {
3082
- this._windowPublishThrottle?.cancelTimer();
3486
+ this._activeIntervalPublishThrottle?.cancelTimer();
3083
3487
  this._viewPublishThrottle?.cancelTimer();
3084
3488
  this._pendingViewChangedIds.clear();
3085
3489
  this._itemIndex.clear();
@@ -3091,18 +3495,6 @@ export abstract class BasePaginator<T, Q> {
3091
3495
  toHead = (params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {}) =>
3092
3496
  this.executeQuery({ direction: 'headward', ...params });
3093
3497
 
3094
- /**
3095
- * @deprecated Use `toTail` instead.
3096
- */
3097
- next = (params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {}) =>
3098
- this.toTail(params);
3099
-
3100
- /**
3101
- * @deprecated Use `toHead` instead.
3102
- */
3103
- prev = (params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {}) =>
3104
- this.toHead(params);
3105
-
3106
3498
  toTailDebounced = (
3107
3499
  params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {},
3108
3500
  ) => {
@@ -3115,24 +3507,6 @@ export abstract class BasePaginator<T, Q> {
3115
3507
  this._executeQueryDebounced({ direction: 'headward', ...params });
3116
3508
  };
3117
3509
 
3118
- /**
3119
- * @deprecated Use `toTailDebounced` instead.
3120
- */
3121
- nextDebounced = (
3122
- params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {},
3123
- ) => {
3124
- this.toTailDebounced(params);
3125
- };
3126
-
3127
- /**
3128
- * @deprecated Use `toHeadDebounced` instead.
3129
- */
3130
- prevDebounced = (
3131
- params: Omit<PaginationQueryParams<Q>, 'direction' | 'queryShape'> = {},
3132
- ) => {
3133
- this.toHeadDebounced(params);
3134
- };
3135
-
3136
3510
  reload = async () => {
3137
3511
  await this.toTail({ reset: 'yes' });
3138
3512
  };