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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
@@ -1,7 +1,8 @@
1
1
  import type { ItemLocation } from '../sortCompiler';
2
+ import { deepFreezeConfig } from '../../configuration/utils/deepFreezeConfig';
2
3
  import { binarySearch } from '../sortCompiler';
3
4
  import { itemMatchesFilter } from '../filterCompiler';
4
- import { isPatch, StateStore, type ValueOrPatch } from '../../store';
5
+ import { isPatch, StateStore, type ValueOrPatch } from '@stream-io/state-store';
5
6
  import { debounce, type DebouncedFunc, generateUUIDv4, sleep } from '../../utils';
6
7
  import { throttle, type Throttled } from '../../utils/throttling/throttle';
7
8
  import { isStateThrottlingEnabled } from './stateThrottling';
@@ -10,6 +11,7 @@ import { ComparisonResult } from '../types.normalization';
10
11
  import type { ItemIndexApi } from '../ItemIndex';
11
12
  import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
12
13
  import { isEqual } from '../../utils/mergeWith/mergeWithCore';
14
+ import { ConfigController } from '../../configuration/ConfigController';
13
15
  import { DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES } from '../../constants';
14
16
 
15
17
  const noOrderChange = () => 0;
@@ -193,6 +195,12 @@ export type PaginationQueryParams<Q> = {
193
195
  queryShape?: Q;
194
196
  /** Per-call override of the reset behavior. */
195
197
  reset?: StateResetPolicy;
198
+ /**
199
+ * Options for the request the query sends that are not part of its query shape, so they don't
200
+ * decide whether the query starts a new first page. Each paginator documents the ones it reads;
201
+ * others are ignored. Retries send them again.
202
+ */
203
+ requestOptions?: Record<string, unknown>;
196
204
  /**
197
205
  * How many times to **retry** a failed request, i.e. `retryCount + 1` attempts in total. Per-call
198
206
  * override of `PaginatorOptions.retryCount`, which defaults to 0 (no retry).
@@ -319,7 +327,36 @@ export interface PaginatorPlugin<T> {
319
327
  */
320
328
  // plugins?: PaginatorPlugin<T, Q>[];
321
329
 
330
+ /**
331
+ * The value-level subset of paginator configuration that can be supplied declaratively through
332
+ * `client.config`. Structural inputs (`itemIndex`, `createItemIndex`) and subclass behaviour overrides
333
+ * (`doRequest`, `itemOrderComparator`, `deriveCursor`) are deliberately absent — see
334
+ * {@link BasePaginator.initializeConfig}.
335
+ *
336
+ * Declared standalone rather than derived from {@link PaginatorOptions} to avoid a circular type.
337
+ */
338
+ export type DeclarativePaginatorConfig = {
339
+ debounceMs?: number;
340
+ hasPaginationQueryShapeChanged?: PaginationQueryShapeChangeIdentifier<any>;
341
+ initialCursor?: PaginatorCursor;
342
+ initialOffset?: number;
343
+ lockItemOrder?: boolean;
344
+ maxLoadedItems?: number;
345
+ pageSize?: number;
346
+ retryCount?: number;
347
+ stateThrottleMs?: number;
348
+ throwErrors?: boolean;
349
+ };
350
+
322
351
  export type PaginatorOptions<T, Q> = {
352
+ /**
353
+ * Declarative configuration for this paginator, supplied by whoever constructs it from
354
+ * `client.config`. Kept separate from the other options so {@link BasePaginator.initializeConfig}
355
+ * can re-derive with a *fresh* slice — a reset then drops declarative values while preserving
356
+ * constructor-injected ones. Excluded from {@link BasePaginatorConfig}: it is an input, not part of
357
+ * the resolved configuration.
358
+ */
359
+ declarativeConfig?: DeclarativePaginatorConfig;
323
360
  /** The number of milliseconds to debounce the search query. The default interval is 300ms. */
324
361
  debounceMs?: number;
325
362
  /**
@@ -370,6 +407,17 @@ export type PaginatorOptions<T, Q> = {
370
407
  * It does not guarantee global stability across interval changes or page jumps.
371
408
  */
372
409
  lockItemOrder?: boolean;
410
+ /**
411
+ * Caps how many items this paginator keeps loaded. Once the head window holds more than this, the
412
+ * oldest are dropped from it as new ones arrive — the paginator's membership is released and the
413
+ * shared store garbage-collects whatever no other holder still references. Pagination stays intact:
414
+ * the window re-opens its tailward edge, so scrolling back simply re-fetches.
415
+ *
416
+ * Unset (the default) means unbounded — see {@link BasePaginator.pruneTailToLimit} for the
417
+ * preconditions a prune must meet. Values below `pageSize` are clamped up to it: a cap smaller than
418
+ * a page would have the next page pruned away the moment it lands.
419
+ */
420
+ maxLoadedItems?: number;
373
421
  /** The item page size to be requested from the server. */
374
422
  pageSize?: number;
375
423
  /**
@@ -384,33 +432,47 @@ export type PaginatorOptions<T, Q> = {
384
432
 
385
433
  type OptionalPaginatorConfigFields =
386
434
  | 'stateThrottleMs'
435
+ | 'maxLoadedItems'
387
436
  | 'deriveCursor'
388
437
  | 'doRequest'
389
438
  | 'initialCursor'
390
439
  | 'initialOffset'
391
- | 'itemIndex'
392
- | 'createItemIndex'
393
440
  | 'itemOrderComparator'
394
441
  | 'throwErrors';
395
442
 
396
- export type BasePaginatorConfig<T, Q> = Pick<
443
+ /**
444
+ * Construction-only inputs that are not part of the resolved configuration.
445
+ *
446
+ * `itemIndex` and `createItemIndex` are here rather than in {@link BasePaginatorConfig} because the
447
+ * constructor destructures them out before building the config and resolves them once into
448
+ * {@link BasePaginator._itemIndex}. They were typed as config members and never written, so
449
+ * `paginator.config.itemIndex` compiled and returned `undefined` for every paginator ever built.
450
+ */
451
+ type ResolvedPaginatorOptions<T, Q> = Omit<
397
452
  PaginatorOptions<T, Q>,
453
+ 'createItemIndex' | 'declarativeConfig' | 'itemIndex'
454
+ >;
455
+
456
+ export type BasePaginatorConfig<T, Q> = Pick<
457
+ ResolvedPaginatorOptions<T, Q>,
398
458
  OptionalPaginatorConfigFields
399
459
  > &
400
- Required<Omit<PaginatorOptions<T, Q>, OptionalPaginatorConfigFields>>;
460
+ Required<Omit<ResolvedPaginatorOptions<T, Q>, OptionalPaginatorConfigFields>>;
401
461
 
402
462
  const baseHasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
403
463
  unknown
404
464
  > = (prevQueryShape, nextQueryShape) => !isEqual(prevQueryShape, nextQueryShape);
405
465
 
406
- export const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any> = {
407
- debounceMs: 300,
408
- lockItemOrder: false,
409
- pageSize: 10,
410
- hasPaginationQueryShapeChanged: baseHasPaginationQueryShapeChanged,
411
- retryCount: 0,
412
- throwErrors: false,
413
- } as const;
466
+ export const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any> = deepFreezeConfig(
467
+ {
468
+ debounceMs: 300,
469
+ lockItemOrder: false,
470
+ pageSize: 10,
471
+ hasPaginationQueryShapeChanged: baseHasPaginationQueryShapeChanged,
472
+ retryCount: 0,
473
+ throwErrors: false,
474
+ } as const,
475
+ );
414
476
 
415
477
  export abstract class BasePaginator<T, Q> {
416
478
  state: StateStore<PaginatorState<T>>;
@@ -423,7 +485,34 @@ export abstract class BasePaginator<T, Q> {
423
485
  * active window + pagination status.
424
486
  */
425
487
  intervalViews: StateStore<PaginatorIntervalViews<T>>;
426
- config: BasePaginatorConfig<T, Q>;
488
+
489
+ /** The shared configuration machinery — see {@link ConfigController}. */
490
+ private readonly configController: ConfigController<BasePaginatorConfig<T, Q>>;
491
+ /**
492
+ * The paginator's resolved configuration, as a store so consumers can react to it.
493
+ *
494
+ * Every configurable class exposes its resolved configuration this way — `configState` for the store,
495
+ * {@link config} for the current value. Before this, paginators held a plain object that changed
496
+ * silently, so anything displaying a paginator's settings had to poll to notice a
497
+ * `client.config.set()` or `reset()`.
498
+ *
499
+ * This is *resolved* configuration, distinct from `client.config`, which holds the configuration you
500
+ * registered. The registered tree is an input to {@link initializeConfig}; this is its output.
501
+ */
502
+ get configState(): StateStore<BasePaginatorConfig<T, Q>> {
503
+ return this.configController.state;
504
+ }
505
+
506
+ /**
507
+ * Options this paginator was constructed with, kept so {@link initializeConfig} can rebuild the
508
+ * config from its real inputs instead of restoring a snapshot of the result. Excludes the
509
+ * declarative slice, which is supplied fresh on every call — that is what lets a reset drop
510
+ * declarative configuration while keeping constructor-injected options.
511
+ */
512
+ private readonly explicitOptions: Omit<
513
+ PaginatorOptions<T, Q>,
514
+ 'createItemIndex' | 'declarativeConfig' | 'itemIndex'
515
+ >;
427
516
 
428
517
  /**
429
518
  * Throttle for the active-window `state.items` publish (message list). Created only when
@@ -443,6 +532,22 @@ export abstract class BasePaginator<T, Q> {
443
532
  /** Changed ids buffered since the last {@link flushIntervalViewPublish} (throttled paginators only). */
444
533
  private _pendingViewChangedIds = new Set<string>();
445
534
 
535
+ /**
536
+ * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem` / `removeItem` record
537
+ * that the active window changed (see {@link _suspendedWindowDirty}) instead of publishing it, so
538
+ * the whole batch produces a single `state.items` emit — independent of state throttling.
539
+ */
540
+ private _windowPublishSuspendDepth = 0;
541
+ /**
542
+ * The interval a prune just shortened. A prune also moves `hasMoreTail` and `cursor` and those come with
543
+ * the next `state.items` publish rather than emitting their own. We use the id instead of direct values
544
+ * because that publish can be a throttle interval late, so {@link consumePendingPrunePaginationState} rereads them
545
+ * when it fires.
546
+ */
547
+ private _prunedIntervalId?: string;
548
+ /** Set by a suspended op that changed the active window, so {@link batch} publishes once on exit. */
549
+ private _suspendedWindowDirty = false;
550
+
446
551
  /**
447
552
  * Intervals keep items in disconnected ranges.
448
553
  * That is a scenario of jumping to non-sequential pages.
@@ -506,41 +611,56 @@ export abstract class BasePaginator<T, Q> {
506
611
  return 'asc';
507
612
  }
508
613
 
509
- protected constructor({
510
- initialCursor,
511
- initialOffset,
512
- itemIndex,
513
- createItemIndex,
514
- ...options
515
- }: PaginatorOptions<T, Q> = {}) {
516
- this.config = {
517
- ...DEFAULT_PAGINATION_OPTIONS,
614
+ /**
615
+ * @param options - what the **integrator** passed. Stage 3, so it outranks the declarative tree.
616
+ * @param builtInDefaults - what the SDK supplies on this instance's behalf — a subclass's defaults, or
617
+ * an owner's for the object it builds. Stage 1, so a `client.config.set()` overrides it. Keeping the
618
+ * two apart is what lets the documented layer order apply here at all: they arrive through the same
619
+ * object otherwise, and a paginator built with no configuration already carries four of them.
620
+ */
621
+ protected constructor(
622
+ {
623
+ declarativeConfig,
518
624
  initialCursor,
519
625
  initialOffset,
520
- ...options,
521
- };
626
+ itemIndex,
627
+ createItemIndex,
628
+ ...options
629
+ }: PaginatorOptions<T, Q> = {},
630
+ builtInDefaults: Partial<BasePaginatorConfig<T, Q>> = {},
631
+ ) {
632
+ this.explicitOptions = { initialCursor, initialOffset, ...options };
633
+ this.configController = new ConfigController<BasePaginatorConfig<T, Q>>({
634
+ defaults: DEFAULT_PAGINATION_OPTIONS as BasePaginatorConfig<T, Q>,
635
+ builtInDefaults,
636
+ constructorOptions: this.explicitOptions as Partial<BasePaginatorConfig<T, Q>>,
637
+ initialSlice: declarativeConfig as Partial<BasePaginatorConfig<T, Q>> | undefined,
638
+ getBehaviourOverrides: () => this.getBehaviourOverrides(),
639
+ // Both of these are read once into a closure, so storing a new value achieves nothing on its own.
640
+ // Pairing the write with the rebuild here rather than in `initializeConfig` is what finally makes
641
+ // `updateConfig({ debounceMs })` work: it used to store 900 and leave the debounce running at 300,
642
+ // so `config.debounceMs` reported a value the paginator was not using.
643
+ onChanged: (next, previous) => {
644
+ if (next.debounceMs !== previous.debounceMs) {
645
+ this.setDebounceOptions({ debounceMs: next.debounceMs });
646
+ }
647
+ if (next.stateThrottleMs !== previous.stateThrottleMs) {
648
+ this.rebuildStatePublishThrottles(next.stateThrottleMs);
649
+ }
650
+ },
651
+ });
522
652
  const { debounceMs } = this.config;
523
653
  this.state = new StateStore<PaginatorState<T>>({
524
654
  ...this.initialState,
525
- cursor: initialCursor,
526
- offset: initialOffset ?? 0,
655
+ // Seeded from the *resolved* config, not the raw constructor argument. These two are the reason
656
+ // `initialCursor`/`initialOffset` are construction-only: they prime state, not just configuration.
657
+ // Reading the argument directly missed a subclass's own default once those moved to stage 1 — and
658
+ // it also meant a declaratively registered cursor configured the paginator without seeding it.
659
+ cursor: this.config.initialCursor,
660
+ offset: this.config.initialOffset ?? 0,
527
661
  });
528
- if (this.config.stateThrottleMs) {
529
- // Coalesce the paginator's own live `state.items` publishes (see `stateThrottleMs` doc). The
530
- // trailing edge re-projects the active window fresh, so a burst emits ~once per interval.
531
- this._windowPublishThrottle = throttle(
532
- () => this.flushWindowPublish(),
533
- this.config.stateThrottleMs,
534
- { leading: true, trailing: true },
535
- );
536
- // Interval view publishes ride their own throttle so they coalesce like `state.items` but land
537
- // on an independent trailing edge (see {@link _viewPublishThrottle}).
538
- this._viewPublishThrottle = throttle(
539
- () => this.flushIntervalViewPublish(),
540
- this.config.stateThrottleMs,
541
- { leading: true, trailing: true },
542
- );
543
- }
662
+ // Direct, not through the setter: `onChanged` fires on *changes*, and this is the initial build.
663
+ this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
544
664
  this.intervalViews = new StateStore<PaginatorIntervalViews<T>>({
545
665
  logicalHead: [],
546
666
  logicalTail: [],
@@ -552,7 +672,10 @@ export abstract class BasePaginator<T, Q> {
552
672
  this._itemIndex =
553
673
  itemIndex ??
554
674
  createItemIndex?.(this) ??
555
- new StoreBackedItemIndex({ getEntityId: this.getItemId.bind(this) });
675
+ new StoreBackedItemIndex({
676
+ getEntityId: this.getItemId.bind(this),
677
+ holderName: 'base-paginator',
678
+ });
556
679
  }
557
680
 
558
681
  // ---------------------------------------------------------------------------
@@ -657,20 +780,40 @@ export abstract class BasePaginator<T, Q> {
657
780
  return this.state.getLatestValue().offset;
658
781
  }
659
782
 
783
+ /**
784
+ * The current resolved configuration.
785
+ *
786
+ * `Readonly` on purpose: the value is the store's live object, so assigning to a field of it would
787
+ * mutate state without notifying anyone. That used to be the only way to change these values, so the
788
+ * type is what turns those call sites into compile errors rather than silent non-reactive writes —
789
+ * use {@link updateConfig}.
790
+ */
791
+ get config(): Readonly<BasePaginatorConfig<T, Q>> {
792
+ return this.configState.getLatestValue();
793
+ }
794
+
795
+ /**
796
+ * Merges a partial configuration into the resolved config and notifies subscribers, unless every
797
+ * field in the patch already holds an equal value.
798
+ */
799
+ updateConfig(config: Partial<BasePaginatorConfig<T, Q>>) {
800
+ this.configController.patch(config);
801
+ }
802
+
660
803
  get pageSize() {
661
804
  return this.config.pageSize;
662
805
  }
663
806
 
664
807
  set pageSize(size: number) {
665
- this.config.pageSize = size;
808
+ this.updateConfig({ pageSize: size });
666
809
  }
667
810
 
668
811
  set initialCursor(cursor: PaginatorCursor) {
669
- this.config.initialCursor = cursor;
812
+ this.updateConfig({ initialCursor: cursor });
670
813
  }
671
814
 
672
815
  set initialOffset(offset: number) {
673
- this.config.initialOffset = offset;
816
+ this.updateConfig({ initialOffset: offset });
674
817
  }
675
818
 
676
819
  /** Single point of truth: always use the effective comparator */
@@ -810,6 +953,17 @@ export abstract class BasePaginator<T, Q> {
810
953
  * {@link setIntervals}), which bypasses the per-interval {@link commitInterval}/{@link dropInterval}
811
954
  * publishing. No-ops when the views are already empty so a reset does not emit needlessly.
812
955
  */
956
+ /**
957
+ * Drops every loaded interval and item without publishing anything, so the next ingest starts from
958
+ * empty storage while `state.items` keeps showing the previous window until the caller publishes.
959
+ */
960
+ protected clearItemStorage() {
961
+ this.setIntervals([]);
962
+ this.setActiveInterval(undefined);
963
+ this._itemIndex.clear();
964
+ this.clearIntervalViews();
965
+ }
966
+
813
967
  protected clearIntervalViews() {
814
968
  this._pendingViewChangedIds.clear();
815
969
  const { logicalHead, logicalTail, anchoredHead } =
@@ -840,7 +994,7 @@ export abstract class BasePaginator<T, Q> {
840
994
  * Subclasses must return the query shape.
841
995
  */
842
996
  protected getNextQueryShape(
843
- _params: Pick<PaginationQueryParams<Q>, 'direction'> = {},
997
+ _params: Pick<PaginationQueryParams<Q>, 'direction'> & { pageSize?: number } = {},
844
998
  ): Q {
845
999
  throw new Error('Paginator.getNextQueryShape() is not implemented');
846
1000
  }
@@ -896,6 +1050,11 @@ export abstract class BasePaginator<T, Q> {
896
1050
  );
897
1051
  }
898
1052
 
1053
+ /** True while a coalescing {@link batch} scope is suspending this paginator's own window publishes. */
1054
+ protected get isWindowPublishSuspended(): boolean {
1055
+ return this._windowPublishSuspendDepth > 0;
1056
+ }
1057
+
899
1058
  /** Re-project the active window from its (live, source-of-truth) interval. `undefined` when inactive. */
900
1059
  private projectActiveWindow(): T[] | undefined {
901
1060
  if (!this._activeIntervalId) return undefined;
@@ -912,11 +1071,11 @@ export abstract class BasePaginator<T, Q> {
912
1071
  private flushWindowPublish(): void {
913
1072
  const items = this.projectActiveWindow();
914
1073
  if (items) {
915
- this.state.partialNext({ items });
1074
+ this.state.partialNext({ items, ...this.consumePendingPrunePaginationState() });
916
1075
  return;
917
1076
  }
918
1077
  if ((this.state.getLatestValue().items?.length ?? 0) > 0) {
919
- this.state.partialNext({ items: [] });
1078
+ this.state.partialNext({ items: [], ...this.consumePendingPrunePaginationState() });
920
1079
  }
921
1080
  }
922
1081
 
@@ -929,6 +1088,45 @@ export abstract class BasePaginator<T, Q> {
929
1088
  this._windowPublishThrottle?.throttledFn();
930
1089
  }
931
1090
 
1091
+ /**
1092
+ * Run `fn` with this paginator's window publishes suspended, emitting once on exit.
1093
+ *
1094
+ * A replace is internally remove-then-insert and each half changes the window, so without this one
1095
+ * logical `ingestItem` emits twice.
1096
+ *
1097
+ * `exit` decides how the single emit leaves the scope: `auto` rides the throttle when there is one
1098
+ * (live ops, where successive events should coalesce across the trailing edge), `sync` always
1099
+ * flushes ({@link batch}, whose contract is that a one-shot operation settles in a single update).
1100
+ *
1101
+ * **`lockItemOrder` lists are excluded.** Their emit is not a re-projection but a republish of the
1102
+ * last-published array with the item spliced back at its original index, and exiting through
1103
+ * {@link flushWindowPublish} re-derives from the active interval — reordering the list and dropping
1104
+ * whatever the interval no longer holds, which is the whole point of locking the order.
1105
+ *
1106
+ * Re-entrant: only the outermost scope emits, so an `ingestItem` inside a coalescing `batch`
1107
+ * defers to the batch.
1108
+ */
1109
+ protected withSingleWindowPublish(
1110
+ fn: () => void,
1111
+ { exit = 'auto' }: { exit?: 'auto' | 'sync' } = {},
1112
+ ): void {
1113
+ if (this.config.lockItemOrder) {
1114
+ fn();
1115
+ return;
1116
+ }
1117
+ const isOutermost = this._windowPublishSuspendDepth === 0;
1118
+ this._windowPublishSuspendDepth += 1;
1119
+ try {
1120
+ fn();
1121
+ } finally {
1122
+ this._windowPublishSuspendDepth -= 1;
1123
+ }
1124
+ if (!isOutermost || !this._suspendedWindowDirty) return;
1125
+ this._suspendedWindowDirty = false;
1126
+ if (exit === 'auto' && this.isStateThrottled) this.scheduleWindowPublish();
1127
+ else this.flushWindowPublish();
1128
+ }
1129
+
932
1130
  /**
933
1131
  * Flush any pending throttled window + interval-view publishes immediately. No-op when nothing
934
1132
  * is pending or throttling is off.
@@ -938,6 +1136,214 @@ export abstract class BasePaginator<T, Q> {
938
1136
  this._viewPublishThrottle?.flush();
939
1137
  }
940
1138
 
1139
+ // ---------------------------------------------------------------------------
1140
+ // Window cap (pruning)
1141
+ // ---------------------------------------------------------------------------
1142
+
1143
+ /**
1144
+ * Whether pruning is on hold. `false` here means a paginator with no UI attached or a UI that
1145
+ * never reports, still gets its configured cap. For example, a specific UI can ask pruning
1146
+ * to not happen unless we are near to the tailing edge.
1147
+ */
1148
+ protected get isPruningSuspended(): boolean {
1149
+ return false;
1150
+ }
1151
+
1152
+ /**
1153
+ * Whether the server knows about `item`. That is what makes its id safe to send as a cursor, and it
1154
+ * is all this checks — the id itself is never looked at. `true` here for anything present;
1155
+ * subclasses holding locally-created items (an unsent message) narrow it. Both halves of a prune
1156
+ * ask: an item the server knows may be dropped, and only such an item may become the window's new
1157
+ * tailward cursor.
1158
+ */
1159
+ protected isPaginationAnchorable(item: T | undefined): boolean {
1160
+ return !!item;
1161
+ }
1162
+
1163
+ /**
1164
+ * The configured window cap, or `undefined` when unbounded. Clamped up to `pageSize`: a cap below a
1165
+ * page would prune the page that a tailward query had just fetched, and `onEndReached` would fetch
1166
+ * it again — a loop. Read fresh (both inputs are runtime-configurable), never cached.
1167
+ */
1168
+ protected get effectiveMaxLoadedItems(): number | undefined {
1169
+ const { maxLoadedItems, pageSize } = this.config;
1170
+ if (typeof maxLoadedItems !== 'number' || maxLoadedItems <= 0) return undefined;
1171
+ return Math.max(maxLoadedItems, pageSize);
1172
+ }
1173
+
1174
+ /**
1175
+ * Drops the oldest items from `interval` until at most `maxLoadedItems` remain, releasing each from
1176
+ * the item index so the shared store can garbage-collect whatever no other holder references.
1177
+ *
1178
+ * ## Where this is called from, and why that matters
1179
+ *
1180
+ * From `ingestItem`, on the interval `insertItemIdIntoInterval` just returned — a **copy that has
1181
+ * not been committed yet**. So this mutates an object nothing can observe, the single
1182
+ * `commitInterval` that follows stores and republishes the already-pruned interval, and the window
1183
+ * emit after it projects from the same interval. A prune therefore costs **no publish of its own**:
1184
+ * it rides the ones the ingest was going to make anyway. That is the whole design — see
1185
+ * {@link _prunedIntervalId} for the pagination half.
1186
+ *
1187
+ * ## Preconditions
1188
+ *
1189
+ * All must hold, or this is a no-op:
1190
+ * - a cap is configured
1191
+ * - the consumer has not suspended pruning ({@link isPruningSuspended})
1192
+ * - the interval is anchored, is the dataset head, and is the active one. A jumped-away window is
1193
+ * what the user is reading, and a logical interval has no pagination provenance — nothing dropped
1194
+ * from it could ever be fetched back
1195
+ * - it actually holds more than the cap
1196
+ *
1197
+ * Assumes cursor pagination: it drops ids without going through `removeItem`, so
1198
+ * {@link shrinkOffsetAfterRemoval} never runs and an offset-paginated list would drift. That is not
1199
+ * a reachable configuration today — `maxLoadedItems` only reaches message paginators — so it is
1200
+ * stated rather than guarded.
1201
+ *
1202
+ * Items the server does not know about ({@link isPaginationAnchorable}) are **skipped, not stopped
1203
+ * at**: an unsent message sorts by the time it was composed, so a cap would otherwise destroy it.
1204
+ * Skipping leaves the window a few items above the cap at worst, and the next arrival trims it again.
1205
+ *
1206
+ * @returns whether anything was pruned.
1207
+ */
1208
+ protected pruneTailToLimit(interval: AnyInterval): boolean {
1209
+ const limit = this.effectiveMaxLoadedItems;
1210
+ if (typeof limit === 'undefined' || this.isPruningSuspended) return false;
1211
+
1212
+ // Anchored intervals only. A logical interval has no pagination provenance, so anything dropped
1213
+ // from it could never be fetched back. Separated out because it is also the type guard the field
1214
+ // reads below depend on — `LogicalInterval` declares no `isHead`/`isTail`/`hasMore*`, so folding
1215
+ // it into the condition below would merely be redundant at runtime while still being required to
1216
+ // compile.
1217
+ if (isLogicalInterval(interval)) return false;
1218
+
1219
+ if (
1220
+ !interval.isHead ||
1221
+ this._activeIntervalId !== interval.id ||
1222
+ interval.itemIds.length <= limit
1223
+ )
1224
+ return false;
1225
+
1226
+ const ids = interval.itemIds;
1227
+ // The tail (oldest) edge is index 0 unless the interval stores ids head-first.
1228
+ const tailEdgeIsFirst = !this.intervalItemIdsAreHeadFirst;
1229
+ const step = tailEdgeIsFirst ? 1 : -1;
1230
+ const dropped = new Set<string>();
1231
+
1232
+ let remaining = ids.length - limit;
1233
+ for (
1234
+ let i = tailEdgeIsFirst ? 0 : ids.length - 1;
1235
+ remaining > 0 && i >= 0 && i < ids.length;
1236
+ i += step
1237
+ ) {
1238
+ const id = ids[i];
1239
+ const item = this._itemIndex.get(id);
1240
+ if (item && !this.isPaginationAnchorable(item)) continue;
1241
+ dropped.add(id);
1242
+ remaining -= 1;
1243
+ }
1244
+
1245
+ if (!dropped.size) return false;
1246
+
1247
+ // Rebuild rather than splice: skipped local items leave the dropped ids non-contiguous.
1248
+ interval.itemIds = ids.filter((id) => !dropped.has(id));
1249
+
1250
+ // One store transaction, so sibling holders of these ids re-project once rather than per id.
1251
+ // `remove` releases this paginator's reference and the store deletes the content only when the last
1252
+ // holder lets go, so a pruned message still pinned or held by an open thread survives intact.
1253
+ this._itemIndex.batch(() => {
1254
+ for (const id of dropped) this._itemIndex.remove(id);
1255
+ });
1256
+
1257
+ // Older messages provably exist on the server again, so re-open the tailward edge — even if this
1258
+ // window had reached the start. Leaving `isTail` set would also mislead interval merging.
1259
+ interval.isTail = false;
1260
+ interval.hasMoreTail = true;
1261
+
1262
+ // Only record which interval it was. The matching `state` fields are derived at publish time,
1263
+ // from this interval as committed then — see {@link _prunedIntervalId}.
1264
+ this._prunedIntervalId = interval.id;
1265
+
1266
+ return true;
1267
+ }
1268
+
1269
+ /**
1270
+ * The id at one pagination edge of `interval` that is usable as a cursor — the edge-most item the
1271
+ * server knows about. Not simply `itemIds[0]`: a prune skips locally-created items, so the outermost
1272
+ * id can be one the server has never seen, and paginating from it would send a client-generated id
1273
+ * as `id_lt`.
1274
+ */
1275
+ private getPaginationEdgeId(interval: Interval, edge: 'head' | 'tail'): string | null {
1276
+ const ids = interval.itemIds;
1277
+ const fromFirst =
1278
+ edge === 'tail'
1279
+ ? !this.intervalItemIdsAreHeadFirst
1280
+ : this.intervalItemIdsAreHeadFirst;
1281
+ const step = fromFirst ? 1 : -1;
1282
+ for (let i = fromFirst ? 0 : ids.length - 1; i >= 0 && i < ids.length; i += step) {
1283
+ const id = ids[i];
1284
+ if (this.isPaginationAnchorable(this._itemIndex.get(id))) return id;
1285
+ }
1286
+ return null;
1287
+ }
1288
+
1289
+ /**
1290
+ * Filters `items` down to the members of `interval`, preserving their given order. Used by the
1291
+ * order-locked emit path, which composes its array from the previously published one instead of
1292
+ * re-projecting, and so needs pruned ids taken out explicitly.
1293
+ */
1294
+ private retainIntervalMembers(items: T[], interval: AnyInterval): T[] {
1295
+ const members = new Set(interval.itemIds);
1296
+ return items.filter((item) => members.has(this.getItemId(item)));
1297
+ }
1298
+
1299
+ /**
1300
+ * The `state` pagination fields that a prune moved, derived from the **committed** active interval
1301
+ * at call time and cleared. Called by every path that publishes the active window, so they ride that
1302
+ * publish instead of emitting their own ({@link _prunedIntervalId} explains why this derives rather
1303
+ * than replaying what the prune saw).
1304
+ *
1305
+ * Returns only fields that actually changed, so an unchanged `cursor` keeps its object identity and
1306
+ * consumers selecting it are not woken.
1307
+ *
1308
+ * Three things it deliberately leaves alone:
1309
+ * - a window that is no longer the pruned one. `state` tracks the active interval, so once the
1310
+ * consumer has jumped elsewhere the prune says nothing about what is being published.
1311
+ * - `cursor.headward`, which the prune never touched — carried over verbatim rather than re-derived,
1312
+ * so a `config.deriveCursor` hook's verdict on the head edge survives.
1313
+ * - a null tail edge (a window whose every remaining item is locally-created). Publishing `null`
1314
+ * would read as "tailward exhausted"; the existing cursor still names a message the *server* has,
1315
+ * so leaving it in place keeps back-pagination working.
1316
+ */
1317
+ private consumePendingPrunePaginationState(): Partial<PaginatorState<T>> {
1318
+ const prunedIntervalId = this._prunedIntervalId;
1319
+ if (!prunedIntervalId) return {};
1320
+ this._prunedIntervalId = undefined;
1321
+
1322
+ // Whatever is being published now is a window the prune never touched.
1323
+ if (this._activeIntervalId !== prunedIntervalId) return {};
1324
+
1325
+ const active = this._itemIntervals.get(prunedIntervalId);
1326
+ // A logical interval is never pruned, and an absent one has no window left to paginate.
1327
+ if (!active || isLogicalInterval(active)) return {};
1328
+
1329
+ const current = this.state.getLatestValue();
1330
+ const next: Partial<PaginatorState<T>> = {};
1331
+
1332
+ // Read this off the interval instead of assuming the prune's `true`. Pruning reopens the
1333
+ // tailward (older) edge, but this publish can run a throttle interval later and a `toTail()` in
1334
+ // between may have loaded the rest of the history - so there may be nothing older left after all.
1335
+ if (current.hasMoreTail !== active.hasMoreTail) next.hasMoreTail = active.hasMoreTail;
1336
+
1337
+ if (this.isCursorPagination) {
1338
+ const tailward = this.getPaginationEdgeId(active, 'tail');
1339
+ if (tailward !== null && current.cursor?.tailward !== tailward) {
1340
+ next.cursor = { headward: current.cursor?.headward, tailward };
1341
+ }
1342
+ }
1343
+
1344
+ return next;
1345
+ }
1346
+
941
1347
  /**
942
1348
  * {@link _viewPublishThrottle} boundary: apply every interval-view change buffered since the last
943
1349
  * flush, then clear the buffer. Independent of the `state.items` window publish, so a view update
@@ -1016,12 +1422,24 @@ export abstract class BasePaginator<T, Q> {
1016
1422
  const activeInterval = this._itemIntervals.get(this._activeIntervalId);
1017
1423
  if (!activeInterval) return;
1018
1424
 
1019
- // Throttled (message list): the slot-swap fast path below reads the last-published `items`, which
1020
- // lags the live intervals while throttled — so skip it. Gate on membership only and schedule a
1021
- // single coalesced re-projection; the boundary re-derives the window fresh from the interval.
1425
+ // Throttling happens, so this.items lags the intervals and we can't slot swap here. Schedule a
1426
+ // re-projection instead, but only if something actually changed — a sibling may have written the
1427
+ // same object this window is already showing.
1022
1428
  if (this.isStateThrottled) {
1023
- for (const id of activeInterval.itemIds) {
1024
- if (changedIds.has(id)) {
1429
+ const currentItems = this.items;
1430
+ if (!currentItems || currentItems.length !== activeInterval.itemIds.length) {
1431
+ // Nothing to pair the interval against so window positions only line up with interval
1432
+ // positions when the two have the same length and gate on membership alone.
1433
+ if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
1434
+ this.scheduleWindowPublish();
1435
+ }
1436
+ return;
1437
+ }
1438
+ for (let i = 0; i < currentItems.length; i++) {
1439
+ const id = this.getItemId(currentItems[i]);
1440
+ if (!changedIds.has(id)) continue;
1441
+ const updated = this._itemIndex.get(id);
1442
+ if (!updated || updated !== currentItems[i]) {
1025
1443
  this.scheduleWindowPublish();
1026
1444
  return;
1027
1445
  }
@@ -1066,11 +1484,8 @@ export abstract class BasePaginator<T, Q> {
1066
1484
 
1067
1485
  // Fallback: membership/order drifted (or no window to patch, or a boost is active). Re-project,
1068
1486
  // but only if a changed id is actually in the active interval.
1069
- for (const id of activeInterval.itemIds) {
1070
- if (changedIds.has(id)) {
1071
- this.state.partialNext({ items: this.intervalToItems(activeInterval) });
1072
- return;
1073
- }
1487
+ if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
1488
+ this.state.partialNext({ items: this.intervalToItems(activeInterval) });
1074
1489
  }
1075
1490
  }
1076
1491
 
@@ -2083,6 +2498,14 @@ export abstract class BasePaginator<T, Q> {
2083
2498
  * - if this is the active interval, re-emit state.items from interval
2084
2499
  */
2085
2500
  ingestItem(ingestedItem: T): boolean {
2501
+ let ingested = false;
2502
+ this.withSingleWindowPublish(() => {
2503
+ ingested = this.applyItemIngestion(ingestedItem);
2504
+ });
2505
+ return ingested;
2506
+ }
2507
+
2508
+ private applyItemIngestion(ingestedItem: T): boolean {
2086
2509
  const id = this.getItemId(ingestedItem);
2087
2510
  const previousItem = this._itemIndex.get(id);
2088
2511
 
@@ -2101,14 +2524,21 @@ export abstract class BasePaginator<T, Q> {
2101
2524
  const itemHasBeenRemoved =
2102
2525
  !!removedItemCoordinates?.state && removedItemCoordinates.state.currentIndex > -1;
2103
2526
 
2104
- // 2. Update canonical storage (ItemIndex) to the *new* snapshot,
2105
- // regardless of filters – this keeps the index authoritative.
2106
- this._itemIndex.setOne(ingestedItem);
2527
+ // 2. Update canonical storage (ItemIndex) to the *new* snapshot.
2528
+ // Written only if it either already exists or matches the filter
2529
+ // of the paginator.
2530
+ if (this._itemIndex.has(id) || this.matchesFilter(ingestedItem)) {
2531
+ this._itemIndex.setOne(ingestedItem);
2532
+ }
2107
2533
 
2108
2534
  // 3. If it no longer matches the filter, we’re done (it has been removed above).
2109
2535
  if (!this.matchesFilter(ingestedItem)) {
2536
+ // left the result set, not just this list
2537
+ this.shrinkOffsetAfterRemoval(removedItemCoordinates);
2110
2538
  // Throttled: the removal above deferred its emit — publish the (settled) window once.
2111
- if (this.isStateThrottled && itemHasBeenRemoved) this.scheduleWindowPublish();
2539
+ // Suspended (coalescing batch): removeItemAtCoordinates recorded it; batch() emits once on exit.
2540
+ if (!this.isWindowPublishSuspended && this.isStateThrottled && itemHasBeenRemoved)
2541
+ this.scheduleWindowPublish();
2112
2542
  return itemHasBeenRemoved;
2113
2543
  }
2114
2544
 
@@ -2190,7 +2620,12 @@ export abstract class BasePaginator<T, Q> {
2190
2620
  // Falls somewhere *inside* the global bounds, but we don't have that page loaded.
2191
2621
  // We’ve already removed any old occurrence, so from the paginator's perspective
2192
2622
  // this item won't be visible again until the relevant page is fetched.
2193
- if (this.isStateThrottled && itemHasBeenRemoved) this.scheduleWindowPublish();
2623
+ if (
2624
+ !this.isWindowPublishSuspended &&
2625
+ this.isStateThrottled &&
2626
+ itemHasBeenRemoved
2627
+ )
2628
+ this.scheduleWindowPublish();
2194
2629
  return itemHasBeenRemoved;
2195
2630
  }
2196
2631
  }
@@ -2211,9 +2646,18 @@ export abstract class BasePaginator<T, Q> {
2211
2646
  activeIntervalIdBeforeRemoval === removedIntervalId &&
2212
2647
  targetInterval.id === removedIntervalId
2213
2648
  ) {
2214
- this.setActiveInterval(targetInterval);
2649
+ this.setActiveInterval(
2650
+ targetInterval,
2651
+ this.isWindowPublishSuspended ? { updateState: false } : undefined,
2652
+ );
2215
2653
  }
2216
2654
 
2655
+ // Enforce the window cap BEFORE committing: `targetInterval` is still the uncommitted copy
2656
+ // `insertItemIdIntoInterval` returned, so the single `commitInterval` below stores and publishes
2657
+ // the already-pruned interval, and the emit after it projects from that same interval. No-op
2658
+ // unless a cap is configured — see {@link pruneTailToLimit}.
2659
+ const prunedNow = this.pruneTailToLimit(targetInterval);
2660
+
2217
2661
  const addedNewInterval = !this._itemIntervals.has(targetInterval.id);
2218
2662
  this.commitInterval(targetInterval);
2219
2663
 
@@ -2228,7 +2672,10 @@ export abstract class BasePaginator<T, Q> {
2228
2672
  this._activeIntervalId,
2229
2673
  )
2230
2674
  ) {
2231
- if (this.isStateThrottled) {
2675
+ if (this.isWindowPublishSuspended) {
2676
+ // Coalescing batch: record the change; batch() emits the settled window once on exit.
2677
+ this._suspendedWindowDirty = true;
2678
+ } else if (this.isStateThrottled) {
2232
2679
  this.scheduleWindowPublish();
2233
2680
  } else {
2234
2681
  const items = this.items ?? [];
@@ -2244,7 +2691,15 @@ export abstract class BasePaginator<T, Q> {
2244
2691
  const nextView = items.slice();
2245
2692
  const insertAt = Math.min(originalIndexInState, nextView.length);
2246
2693
  nextView.splice(insertAt, 0, ingestedItem);
2247
- this.state.partialNext({ items: nextView });
2694
+ this.state.partialNext({
2695
+ // This branch republishes the LAST PUBLISHED array rather than re-projecting, so a prune
2696
+ // that just emptied ids out of the interval would resurrect them here. Drop them, keeping
2697
+ // every survivor's relative position — which is the whole point of `lockItemOrder`.
2698
+ items: prunedNow
2699
+ ? this.retainIntervalMembers(nextView, targetInterval)
2700
+ : nextView,
2701
+ ...this.consumePendingPrunePaginationState(),
2702
+ });
2248
2703
  } else {
2249
2704
  /**
2250
2705
  * Select a correct interval from which the state.items array is derived
@@ -2256,6 +2711,7 @@ export abstract class BasePaginator<T, Q> {
2256
2711
  ? removedItemCoordinates.interval.interval
2257
2712
  : targetInterval,
2258
2713
  ),
2714
+ ...this.consumePendingPrunePaginationState(),
2259
2715
  });
2260
2716
  }
2261
2717
  }
@@ -2264,6 +2720,32 @@ export abstract class BasePaginator<T, Q> {
2264
2720
  return true;
2265
2721
  }
2266
2722
 
2723
+ /**
2724
+ * Run `fn` as one batched mutation over this paginator's items, collapsing the redundant emits a
2725
+ * naive per-item loop would produce:
2726
+ *
2727
+ * - **Shared-store fan-out** (always, via the `_itemIndex.batch` wrapper): per-item store
2728
+ * notifications fold into a single flush, so sibling holders of the same ids (e.g. a thread /
2729
+ * pinned paginator sharing the entity) re-project once, not once per item. Inert for single-home
2730
+ * paginators (channels, reminders, user groups) whose index is over a private store with no
2731
+ * sibling subscribers — there it is a plain passthrough.
2732
+ * - **This paginator's own active window** (`coalesce: true`): every `ingestItem` / `removeItem`
2733
+ * inside `fn` records that the window changed instead of publishing it, then `batch` emits the
2734
+ * settled window exactly once on exit via {@link flushWindowPublish}. This is deterministic and
2735
+ * independent of state throttling — unlike leaving it off, where an un-throttled paginator emits
2736
+ * once per item and a throttled one merely coalesces within its 500ms window. Use it for one-shot
2737
+ * operations (reconciliation, reload re-ingest) that must settle in a single update. Omit it in WS
2738
+ * event handlers, where per-event publishes should ride the throttle so successive events coalesce
2739
+ * across its trailing edge rather than each forcing a synchronous emit.
2740
+ */
2741
+ batch(fn: () => void, { coalesce = false }: { coalesce?: boolean } = {}): void {
2742
+ if (!coalesce) {
2743
+ this._itemIndex.batch(fn);
2744
+ return;
2745
+ }
2746
+ this.withSingleWindowPublish(() => this._itemIndex.batch(fn), { exit: 'sync' });
2747
+ }
2748
+
2267
2749
  // ---------------------------------------------------------------------------
2268
2750
  // Remove / contains
2269
2751
  // ---------------------------------------------------------------------------
@@ -2295,7 +2777,9 @@ export abstract class BasePaginator<T, Q> {
2295
2777
 
2296
2778
  // 2) Remove from visible state.items, if present
2297
2779
  if (stateLocation && stateLocation.currentIndex > -1) {
2298
- if (!this.isStateThrottled) {
2780
+ if (this.isWindowPublishSuspended) {
2781
+ this._suspendedWindowDirty = true;
2782
+ } else if (!this.isStateThrottled) {
2299
2783
  const newItems = [...(this.items ?? [])];
2300
2784
  newItems.splice(stateLocation.currentIndex, 1);
2301
2785
  this.state.partialNext({ items: newItems });
@@ -2312,6 +2796,22 @@ export abstract class BasePaginator<T, Q> {
2312
2796
  return result;
2313
2797
  }
2314
2798
 
2799
+ /**
2800
+ * Keeps `offset` addressing the same position in the *server's* result set after an item left the
2801
+ * loaded window.
2802
+ */
2803
+ protected shrinkOffsetAfterRemoval(coordinates?: ItemCoordinates) {
2804
+ // cursor pagination does not address items by position, so nothing can drift
2805
+ if (this.isCursorPagination) return;
2806
+ // not part of the loaded window, so no page ever counted it
2807
+ if ((coordinates?.state?.currentIndex ?? -1) < 0) return;
2808
+
2809
+ const { offset } = this.state.getLatestValue();
2810
+ if (typeof offset !== 'number') return;
2811
+
2812
+ this.state.partialNext({ offset: Math.max(0, offset - 1) });
2813
+ }
2814
+
2315
2815
  /**
2316
2816
  * Meaning of location values
2317
2817
  * - currentIndex === -1 could not be found
@@ -2332,8 +2832,10 @@ export abstract class BasePaginator<T, Q> {
2332
2832
  if (!coords.state && !coords.interval) return noAction;
2333
2833
  const result = this.removeItemAtCoordinates(coords);
2334
2834
  this._itemIndex.remove(this.getItemId(item));
2835
+ this.shrinkOffsetAfterRemoval(result);
2335
2836
  // Throttled: removeItemAtCoordinates deferred its emit — publish the (settled) window once.
2336
- if (this.isStateThrottled) this.scheduleWindowPublish();
2837
+ if (!this.isWindowPublishSuspended && this.isStateThrottled)
2838
+ this.scheduleWindowPublish();
2337
2839
  return result;
2338
2840
  }
2339
2841
 
@@ -2380,10 +2882,25 @@ export abstract class BasePaginator<T, Q> {
2380
2882
  return newState;
2381
2883
  });
2382
2884
 
2383
- // A populated page means a first page is effectively "loaded". Record a query shape so the
2384
- // paginator counts as initialized and the next pagination continues from this page - otherwise
2385
- // an undefined `_lastQueryShape` makes the first query look like a shape change, triggering a
2386
- // first page reset that wipes the seeded items and re-fetches the first page before paginating.
2885
+ this.recordLoadedWindowQueryShape();
2886
+ }
2887
+
2888
+ /**
2889
+ * Records the shape a query would have used to produce the currently loaded window, so the next
2890
+ * pagination counts as a continuation rather than a shape change.
2891
+ *
2892
+ * Server data reaches a window without a query on two paths — a seeded page (`setItems`) and a
2893
+ * hydrate (`mergeNewestPage`). Leaving `_lastQueryShape` undefined afterwards makes the next
2894
+ * query look like a shape change, so `executeQuery` takes its first-page branch and publishes
2895
+ * `getStateBeforeFirstQuery()` (items `undefined`) BEFORE the request. A response with items
2896
+ * rebuilds the window from the surviving intervals, so that case merely churns; an empty one — a
2897
+ * tailward query on a thread whose replies are all loaded — has nothing to rebuild from and the
2898
+ * loaded window is lost.
2899
+ *
2900
+ * Only meaningful with items in hand: an empty window has no shape to continue from, and the
2901
+ * flags already say there is nothing more to fetch.
2902
+ */
2903
+ protected recordLoadedWindowQueryShape() {
2387
2904
  if (
2388
2905
  typeof this._lastQueryShape === 'undefined' &&
2389
2906
  (this.state.getLatestValue().items?.length ?? 0) > 0
@@ -2400,6 +2917,97 @@ export abstract class BasePaginator<T, Q> {
2400
2917
  this._executeQueryDebounced = debounce(this.executeQuery.bind(this), debounceMs);
2401
2918
  };
2402
2919
 
2920
+ /**
2921
+ * Rebuilds the state-publish throttles for a new interval, or drops them when the interval is unset.
2922
+ *
2923
+ * This exists because `stateThrottleMs` is read *once*: the throttles capture the interval in their
2924
+ * closures, so assigning `config.stateThrottleMs` afterwards does nothing at all — an unthrottled
2925
+ * paginator never gains a throttle, and a throttled one keeps its original interval. Anything
2926
+ * changing the value at runtime (declarative configuration registered after construction, or
2927
+ * `client.config.reset()`) has to come through here.
2928
+ *
2929
+ * Pending publishes are flushed first, so a swap cannot swallow a trailing-edge emit that was
2930
+ * already scheduled.
2931
+ */
2932
+ setStateThrottleOptions = ({ stateThrottleMs }: { stateThrottleMs?: number }) => {
2933
+ // Released surface. It no longer has to pair the write with the rebuild — the controller's
2934
+ // `onChanged` does that for whichever route the value arrives by, including a declarative change.
2935
+ this.updateConfig({ stateThrottleMs } as Partial<BasePaginatorConfig<T, Q>>);
2936
+ };
2937
+
2938
+ /** Rebuilds the state-publish throttles for a new interval, or drops them when it is unset. */
2939
+ private rebuildStatePublishThrottles(stateThrottleMs?: number) {
2940
+ this.flushPendingPublishes();
2941
+
2942
+ this._windowPublishThrottle = undefined;
2943
+ this._viewPublishThrottle = undefined;
2944
+
2945
+ if (!stateThrottleMs) return;
2946
+
2947
+ // Coalesce the paginator's own live `state.items` publishes (see `stateThrottleMs` doc). The
2948
+ // trailing edge re-projects the active window fresh, so a burst emits ~once per interval.
2949
+ this._windowPublishThrottle = throttle(
2950
+ () => this.flushWindowPublish(),
2951
+ stateThrottleMs,
2952
+ {
2953
+ leading: true,
2954
+ trailing: true,
2955
+ },
2956
+ );
2957
+ // Interval view publishes ride their own throttle so they coalesce like `state.items` but land on
2958
+ // an independent trailing edge (see {@link _viewPublishThrottle}).
2959
+ this._viewPublishThrottle = throttle(
2960
+ () => this.flushIntervalViewPublish(),
2961
+ stateThrottleMs,
2962
+ { leading: true, trailing: true },
2963
+ );
2964
+ }
2965
+
2966
+ /**
2967
+ * Re-derives this paginator's configuration from its real inputs: package defaults, the options it
2968
+ * was constructed with, and the declarative slice passed in.
2969
+ *
2970
+ * Called by the constructor and by `client.config.reset()` (through the owning `Channel` / `Thread`),
2971
+ * so the two share one code path and cannot drift. Both read-once fields are routed through their
2972
+ * rebuild setters, because assigning them would be silently discarded.
2973
+ *
2974
+ * Structural wiring is untouched here because it never reaches `config` in the first place:
2975
+ * `itemIndex` and `createItemIndex` are destructured out of the constructor's options and resolved
2976
+ * once into {@link _itemIndex}, so there is nothing in the derived config for a re-derivation to drop.
2977
+ *
2978
+ * Subclass behaviour overrides are folded in through {@link getBehaviourOverrides} rather than written
2979
+ * afterwards, so one re-derivation is one `configState` publish carrying a complete config. It used to
2980
+ * be a second write from an `initializeConfig` override, and the claim that both writes carried a
2981
+ * complete config was wrong: the base derivation knows nothing of the overlay, so it published the
2982
+ * config with `doRequest`, `deriveCursor` and `itemOrderComparator` **stripped**, and the subclass then
2983
+ * put them back. A `PinnedMessagePaginator` re-derivation emitted three notifications, of which the
2984
+ * first had no request function at all — a subscriber that paginated during that synchronous window
2985
+ * would have found none.
2986
+ *
2987
+ * Applied last, so the overlay still wins over constructor options exactly as the second write did.
2988
+ */
2989
+ initializeConfig(declarativeConfig?: DeclarativePaginatorConfig): void {
2990
+ this.configController.initialize(
2991
+ declarativeConfig as Partial<BasePaginatorConfig<T, Q>> | undefined,
2992
+ );
2993
+ }
2994
+
2995
+ /**
2996
+ * Behaviour a subclass installs that no set of options can express — a comparator or `deriveCursor`
2997
+ * closed over `this`, a `doRequest` bound to a particular endpoint. Empty on the base paginator.
2998
+ *
2999
+ * Folded into the single derivation in {@link initializeConfig}, which is why an override must return
3000
+ * **stable references**: rebuilding the closures on each call makes every derived config differ from
3001
+ * the last, defeating the guard above and republishing on every unrelated re-derivation. Memoize them
3002
+ * — their inputs are fixed at construction.
3003
+ *
3004
+ * Called only after construction. The base constructor builds `configState` directly rather than
3005
+ * through `initializeConfig`, so an override is never invoked before its own fields are initialized.
3006
+ */
3007
+ protected getBehaviourOverrides(): Partial<BasePaginatorConfig<T, Q>> {
3008
+ return {};
3009
+ }
3010
+
2403
3011
  protected shouldResetStateBeforeQuery(
2404
3012
  prevQueryShape: unknown | undefined,
2405
3013
  nextQueryShape: unknown | undefined,
@@ -2524,6 +3132,7 @@ export abstract class BasePaginator<T, Q> {
2524
3132
  direction,
2525
3133
  keepPreviousItems,
2526
3134
  queryShape: forcedQueryShape,
3135
+ requestOptions,
2527
3136
  reset,
2528
3137
  retryCount = this.config.retryCount,
2529
3138
  silent,
@@ -2542,10 +3151,7 @@ export abstract class BasePaginator<T, Q> {
2542
3151
  // adjacent pages merge; filter/sort changes clear it via `resetState()` in their setters.
2543
3152
  const isForcedReset = reset === 'yes' && !keepPreviousItems;
2544
3153
  if (isForcedReset) {
2545
- this.setIntervals([]);
2546
- this.setActiveInterval(undefined);
2547
- this._itemIndex.clear();
2548
- this.clearIntervalViews();
3154
+ this.clearItemStorage();
2549
3155
  this.state.next(this.getStateBeforeFirstQuery());
2550
3156
  } else if (reset === 'yes' && !forcedQueryShape) {
2551
3157
  // A `keepPreviousItems` refresh (reconnect / pull-to-refresh) must still restart pagination from
@@ -2557,12 +3163,32 @@ export abstract class BasePaginator<T, Q> {
2557
3163
  });
2558
3164
  }
2559
3165
 
2560
- const queryShape = forcedQueryShape ?? this.getNextQueryShape({ direction });
3166
+ // A non-destructive refresh re-fetches as much of the loaded list as the server returns at once.
3167
+ const isRefresh = reset === 'yes' && keepPreviousItems && !forcedQueryShape;
3168
+ const pageSize = isRefresh
3169
+ ? Math.max(this.pageSize, this.items?.length ?? 0)
3170
+ : this.pageSize;
3171
+ const queryShape =
3172
+ forcedQueryShape ?? this.getNextQueryShape({ direction, pageSize });
2561
3173
 
2562
3174
  const isFirstPage = this.isFirstPageQuery({ queryShape, reset });
2563
3175
 
2564
3176
  if (isFirstPage && !keepPreviousItems) {
2565
3177
  const state = this.getStateBeforeFirstQuery();
3178
+ // Publish the loading flag BEFORE the offline preload is awaited. `canExecuteQuery` gates on
3179
+ // `isLoading`, so anything published after an await leaves a window in which a second call
3180
+ // made in the same tick still reads `false` and proceeds — and on a paginator with no loaded
3181
+ // window both directions resolve to the SAME first page, so the two calls issue byte-identical
3182
+ // requests. A UI that loads both ends at once does exactly that: an empty list sits within the
3183
+ // scroll threshold of its top AND its bottom, so the scroll handler calls `toTail` and `toHead`
3184
+ // one line apart.
3185
+ //
3186
+ // Only the flag: `state` carries `items: undefined`, so publishing all of it here would blank
3187
+ // a list that offline data is about to fill — the reason the full publish waits for the preload.
3188
+ // A forced reset published it (loading included) synchronously above, so it needs nothing.
3189
+ if (!isForcedReset) {
3190
+ this.state.partialNext({ isLoading: true });
3191
+ }
2566
3192
  let items: T[] | undefined = undefined;
2567
3193
  if (!this.isInitialized) {
2568
3194
  items =
@@ -2588,6 +3214,7 @@ export abstract class BasePaginator<T, Q> {
2588
3214
  const results = await this.runQueryRetryable({
2589
3215
  direction,
2590
3216
  queryShape,
3217
+ requestOptions,
2591
3218
  reset,
2592
3219
  retryCount,
2593
3220
  });
@@ -2641,6 +3268,12 @@ export abstract class BasePaginator<T, Q> {
2641
3268
  stateUpdate.items = filteredItems;
2642
3269
 
2643
3270
  const isJumpQuery = !!queryShape && this.isJumpQueryShape(queryShape);
3271
+ // A non-destructive refresh merges page 1 into the window it kept, so the ids that window held
3272
+ // have to be read before the ingest below adds the page to it.
3273
+ const keptItemIds =
3274
+ isFirstPage && keepPreviousItems && !this.isCursorPagination && this.items?.length
3275
+ ? new Set(this.items.map((item) => this.getItemId(item)))
3276
+ : undefined;
2644
3277
  const interval = this.ingestPage({
2645
3278
  page: stateUpdate.items,
2646
3279
  policy: isJumpQuery ? 'strict-overlap-only' : 'auto',
@@ -2711,10 +3344,26 @@ export abstract class BasePaginator<T, Q> {
2711
3344
  // todo: we could keep the offset in two directions (initial tailward offset would be taken from config.initialOffset)
2712
3345
  const startOffset = this.offset ?? 0;
2713
3346
  stateUpdate.offset = startOffset + items.length;
3347
+ // After a `keepPreviousItems` refresh whose page connects to the kept window, continue from the window's end instead of re-fetching it.
3348
+ const lastPageItem = items[items.length - 1];
3349
+ if (
3350
+ interval &&
3351
+ keptItemIds &&
3352
+ lastPageItem &&
3353
+ keptItemIds.has(this.getItemId(lastPageItem))
3354
+ ) {
3355
+ stateUpdate.offset = Math.max(
3356
+ stateUpdate.offset,
3357
+ startOffset + this.intervalToItems(interval).length,
3358
+ );
3359
+ }
2714
3360
  // Only hasMoreTail depends on the page result. hasMoreHead is fixed by where the loaded window
2715
3361
  // starts (offset 0 => head loaded) and was anchored once at the reset (getStateBeforeFirstQuery);
2716
3362
  // the offset only grows tailward from here, so leave hasMoreHead untouched.
2717
- stateUpdate.hasMoreTail = items.length === this.pageSize;
3363
+ stateUpdate.hasMoreTail = items.length >= this.pageSize;
3364
+ // Anchor a first page's hasMoreHead from the start offset, as getStateBeforeFirstQuery() does: a
3365
+ // keepPreviousItems first page never publishes that state, and would keep a stale `true`.
3366
+ if (isFirstPage) stateUpdate.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
2718
3367
  }
2719
3368
 
2720
3369
  if (interval) {
@@ -2760,7 +3409,8 @@ export abstract class BasePaginator<T, Q> {
2760
3409
 
2761
3410
  const state = this.getStateAfterQuery(stateUpdate, isFirstPage);
2762
3411
  if (updateState) this.state.next(state);
2763
- this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
3412
+ // Only the first page is cached and a later page cannot change it.
3413
+ if (isFirstPage) this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
2764
3414
 
2765
3415
  return {
2766
3416
  stateCandidate: state,