stream-chat 10.0.0-rc.23 → 10.0.0-rc.24

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 (59) hide show
  1. package/dist/cjs/index.browser.js +2033 -821
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +2033 -821
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +2033 -821
  6. package/dist/esm/index.mjs.map +3 -3
  7. package/dist/types/ChannelManager.d.ts +4 -4
  8. package/dist/types/channel.d.ts +127 -30
  9. package/dist/types/channel_state.d.ts +1 -1
  10. package/dist/types/client.d.ts +5 -3
  11. package/dist/types/gen/chat/ChatApi.d.ts +16 -19
  12. package/dist/types/gen/models/index.d.ts +125 -36
  13. package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
  14. package/dist/types/messageComposer/linkPreviewsManager.d.ts +1 -1
  15. package/dist/types/offline-support/offline_support_api.d.ts +3 -2
  16. package/dist/types/offline-support/types.d.ts +1 -1
  17. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +15 -1
  18. package/dist/types/pagination/paginators/BasePaginator.d.ts +323 -84
  19. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +6 -6
  20. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +443 -74
  21. package/dist/types/pagination/paginators/MessagePaginator.d.ts +187 -47
  22. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -0
  23. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +3 -2
  24. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +3 -8
  25. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +3 -2
  26. package/dist/types/thread.d.ts +19 -6
  27. package/dist/types/thread_manager.d.ts +6 -5
  28. package/dist/types/types.d.ts +3 -2
  29. package/dist/types/utils/time.d.ts +1 -1
  30. package/dist/types/utils.d.ts +2 -0
  31. package/package.json +1 -1
  32. package/src/ChannelManager.ts +4 -4
  33. package/src/CooldownTimer.ts +11 -3
  34. package/src/channel.ts +236 -126
  35. package/src/channel_state.ts +1 -1
  36. package/src/client.ts +52 -35
  37. package/src/connection/wsConnection/StableWSConnection.ts +3 -2
  38. package/src/gen/chat/ChatApi.ts +17 -22
  39. package/src/gen/models/index.ts +127 -38
  40. package/src/gen/moderation/ModerationApi.ts +4 -0
  41. package/src/messageDelivery/MessageDeliveryReporter.ts +9 -9
  42. package/src/offline-support/offline_support_api.ts +5 -3
  43. package/src/offline-support/offline_sync_manager.ts +3 -2
  44. package/src/offline-support/queueableOperations.ts +1 -1
  45. package/src/offline-support/types.ts +1 -1
  46. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +47 -25
  47. package/src/pagination/paginators/BasePaginator.ts +749 -265
  48. package/src/pagination/paginators/ChannelPaginator.ts +22 -15
  49. package/src/pagination/paginators/MessageIntervalPaginator.ts +1074 -335
  50. package/src/pagination/paginators/MessagePaginator.ts +375 -113
  51. package/src/pagination/paginators/PinnedMessagePaginator.ts +17 -4
  52. package/src/pagination/paginators/ReminderPaginator.ts +8 -2
  53. package/src/pagination/paginators/ThreadPaginator.ts +19 -20
  54. package/src/pagination/paginators/UserGroupPaginator.ts +10 -3
  55. package/src/thread.ts +110 -104
  56. package/src/thread_manager.ts +14 -11
  57. package/src/types.ts +5 -4
  58. package/src/utils/time.ts +1 -1
  59. package/src/utils.ts +5 -0
@@ -932,6 +932,7 @@ var runDetached = (callback, options) => {
932
932
  }
933
933
  promise.catch(onError);
934
934
  };
935
+ var isThreadOnlyReply = (message) => !!message.parent_id && !message.show_in_channel;
935
936
  var getEnv = (envKey) => {
936
937
  if (typeof process !== "undefined" && (Object.hasOwn(process, "env") || "env" in process)) {
937
938
  return process.env[envKey];
@@ -5057,14 +5058,14 @@ var BasePaginator = class {
5057
5058
  /** Changed IDs buffered since the last {@link flushIntervalViewPublish} (throttled only). */
5058
5059
  this._pendingViewChangedIds = /* @__PURE__ */ new Set();
5059
5060
  /**
5060
- * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`/`removeItem` mark the
5061
- * window dirty ({@link _suspendedWindowDirty}) instead of publishing.
5061
+ * Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`/`removeItem` record
5062
+ * the changed window ({@link _staleWindowState}) instead of publishing.
5062
5063
  */
5063
5064
  this._windowPublishSuspendDepth = 0;
5064
- /** Set when a suspended op changed the active window, so {@link batch} publishes on exit. */
5065
- this._suspendedWindowDirty = false;
5066
5065
  /** Disconnected ranges of items, e.g. after jumping to non-sequential pages. */
5067
5066
  this._itemIntervals = /* @__PURE__ */ new Map();
5067
+ /** How many claims on the active interval were made; the latest one decides it. */
5068
+ this._activeIntervalClaimCount = 0;
5068
5069
  this.boosts = /* @__PURE__ */ new Map();
5069
5070
  this._maxBoostSeq = 0;
5070
5071
  /** Boosted items first (higher `seq` first), then `itemOrderComparator`. */
@@ -5119,32 +5120,12 @@ var BasePaginator = class {
5119
5120
  this.populateOfflineDbAfterQuery = (_params) => void 0;
5120
5121
  this.toTail = (params = {}) => this.executeQuery({ direction: "tailward", ...params });
5121
5122
  this.toHead = (params = {}) => this.executeQuery({ direction: "headward", ...params });
5122
- /**
5123
- * @deprecated Use `toTail` instead.
5124
- */
5125
- this.next = (params = {}) => this.toTail(params);
5126
- /**
5127
- * @deprecated Use `toHead` instead.
5128
- */
5129
- this.prev = (params = {}) => this.toHead(params);
5130
5123
  this.toTailDebounced = (params = {}) => {
5131
5124
  this._executeQueryDebounced({ direction: "tailward", ...params });
5132
5125
  };
5133
5126
  this.toHeadDebounced = (params = {}) => {
5134
5127
  this._executeQueryDebounced({ direction: "headward", ...params });
5135
5128
  };
5136
- /**
5137
- * @deprecated Use `toTailDebounced` instead.
5138
- */
5139
- this.nextDebounced = (params = {}) => {
5140
- this.toTailDebounced(params);
5141
- };
5142
- /**
5143
- * @deprecated Use `toHeadDebounced` instead.
5144
- */
5145
- this.prevDebounced = (params = {}) => {
5146
- this.toHeadDebounced(params);
5147
- };
5148
5129
  this.reload = async () => {
5149
5130
  await this.toTail({ reset: "yes" });
5150
5131
  };
@@ -5213,18 +5194,6 @@ var BasePaginator = class {
5213
5194
  get hasMoreHead() {
5214
5195
  return this.state.getLatestValue().hasMoreHead;
5215
5196
  }
5216
- /**
5217
- * @deprecated Use `hasMoreTail` instead.
5218
- */
5219
- get hasNext() {
5220
- return this.hasMoreTail;
5221
- }
5222
- /**
5223
- * @deprecated Use `hasMoreHead` instead.
5224
- */
5225
- get hasPrev() {
5226
- return this.hasMoreHead;
5227
- }
5228
5197
  get hasResults() {
5229
5198
  return Array.isArray(this.state.getLatestValue().items);
5230
5199
  }
@@ -5258,20 +5227,6 @@ var BasePaginator = class {
5258
5227
  get items() {
5259
5228
  return this.state.getLatestValue().items;
5260
5229
  }
5261
- /**
5262
- * The newest loaded window, independent of the active interval: the head-most loaded interval
5263
- * under the paginator's ordering. It does not require `isHead` (seeds do not reliably set it), so
5264
- * after a jump to an older window with the latest not loaded, that older window is returned.
5265
- */
5266
- get headItems() {
5267
- const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
5268
- return head ? this.intervalToItems(head) : [];
5269
- }
5270
- /** The item on the head edge of the `headItems` interval; `undefined` when nothing is loaded. */
5271
- get headmostItem() {
5272
- const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
5273
- return head ? this.getIntervalPaginationEdges(head)?.head ?? void 0 : void 0;
5274
- }
5275
5230
  get cursor() {
5276
5231
  return this.state.getLatestValue().cursor;
5277
5232
  }
@@ -5341,9 +5296,33 @@ var BasePaginator = class {
5341
5296
  get logicalTailItems() {
5342
5297
  return this.intervalViews.getLatestValue().logicalTail;
5343
5298
  }
5344
- /** `intervalViews.anchoredHead`: the page bounded at the dataset head. */
5299
+ /**
5300
+ * The anchored head interval: the loaded window that reaches the head of the dataset (`isHead`).
5301
+ * `undefined` while that window is not loaded, for example when only a window reached by a jump is.
5302
+ */
5303
+ get anchoredHeadInterval() {
5304
+ for (const interval of this._itemIntervals.values()) {
5305
+ if (!isLogicalInterval(interval) && interval.isHead) return interval;
5306
+ }
5307
+ return void 0;
5308
+ }
5309
+ /**
5310
+ * The items of the anchored head interval; empty while it is not loaded (a window reached by a
5311
+ * jump never counts). Reactive counterpart: `intervalViews.anchoredHead`.
5312
+ */
5345
5313
  get anchoredHeadItems() {
5346
- return this.intervalViews.getLatestValue().anchoredHead;
5314
+ const head = this.anchoredHeadInterval;
5315
+ return head ? this.intervalToItems(head) : [];
5316
+ }
5317
+ /**
5318
+ * The item at the head edge of the anchored head interval (see {@link anchoredHeadItems}).
5319
+ * `undefined` while that window is not loaded, including once a window is known to lack items
5320
+ * toward the head (see {@link unmarkHead}). A loaded window always holds an item, so this also
5321
+ * tells whether it is loaded.
5322
+ */
5323
+ get anchoredHeadItem() {
5324
+ const head = this.anchoredHeadInterval;
5325
+ return head ? this.getIntervalPaginationEdges(head)?.head ?? void 0 : void 0;
5347
5326
  }
5348
5327
  /**
5349
5328
  * Commits an interval to storage and republishes its {@link intervalViews} field when tracked.
@@ -5361,7 +5340,8 @@ var BasePaginator = class {
5361
5340
  }
5362
5341
  /**
5363
5342
  * Republishes the {@link intervalViews} field backed by the interval (untracked ones change
5364
- * nothing). {@link postQueryReconcile} also publishes the anchored head when `isHead` flips.
5343
+ * nothing). Placing a page also publishes the anchored head when `isHead` flips (see
5344
+ * {@link publishAsAnchoredHead}).
5365
5345
  */
5366
5346
  publishIntervalViewFor(interval, { removed = false } = {}) {
5367
5347
  if (interval.id === LOGICAL_HEAD_INTERVAL_ID) {
@@ -5381,13 +5361,75 @@ var BasePaginator = class {
5381
5361
  this.intervalViews.partialNext({ anchoredHead: this.intervalItemsOrEmpty(interval) });
5382
5362
  }
5383
5363
  /**
5384
- * Keeps `anchoredHead` in sync after `isHead` was recomputed in query reconciliation (`wasHead`
5364
+ * Keeps `anchoredHead` in sync after `isHead` was recomputed while a page was placed (`wasHead`
5385
5365
  * is the previous value): publishes the page on becoming the head, clears it on losing that.
5386
5366
  */
5387
5367
  syncAnchoredHeadAfterHeadFlip(interval, wasHead) {
5388
5368
  if (interval.isHead === wasHead) return;
5389
5369
  this.publishAsAnchoredHead(interval.isHead ? interval : void 0);
5390
5370
  }
5371
+ /**
5372
+ * Clears the head mark of `interval`: it no longer reaches the head of the dataset, which holds
5373
+ * more items toward the head. It stops being the anchored head ({@link anchoredHeadItem} is then
5374
+ * `undefined`) and can load toward the head, which the paginator state reflects when it is the
5375
+ * active interval.
5376
+ */
5377
+ unmarkHead(interval) {
5378
+ this.clearHeadMark(interval);
5379
+ this.syncAnchoredHeadAfterHeadFlip(interval, true);
5380
+ }
5381
+ /** {@link unmarkHead} without touching the anchored head view. */
5382
+ clearHeadMark(interval) {
5383
+ interval.isHead = false;
5384
+ interval.hasMoreHead = true;
5385
+ if (this.isActiveInterval(interval)) {
5386
+ this.state.partialNext({
5387
+ hasMoreHead: true,
5388
+ cursor: this.getCursorFromInterval(interval)
5389
+ });
5390
+ }
5391
+ }
5392
+ /**
5393
+ * Makes `interval`, marked as the head and proven to reach it, the only head: two separate
5394
+ * intervals cannot both reach it. Other heads lose the mark and can load toward the head, up to
5395
+ * `interval`, except one reaching further headward, which contradicts the proof: it keeps the
5396
+ * mark and is published as the anchored head (see {@link anchoredHeadInterval}).
5397
+ */
5398
+ makeOnlyHead(interval) {
5399
+ let keptOtherHead = false;
5400
+ for (const other of this.itemIntervals) {
5401
+ if (other.id === interval.id || isLogicalInterval(other) || !other.isHead) continue;
5402
+ if (this.reachesFurtherHeadwardThan(other, interval)) keptOtherHead = true;
5403
+ else this.clearHeadMark(other);
5404
+ }
5405
+ if (keptOtherHead) this.publishAsAnchoredHead(this.anchoredHeadInterval);
5406
+ }
5407
+ /** The ids of the anchored intervals marked as reaching the head of the dataset. */
5408
+ getHeadIntervalIds() {
5409
+ const ids = [];
5410
+ for (const interval of this._itemIntervals.values()) {
5411
+ if (!isLogicalInterval(interval) && interval.isHead) ids.push(interval.id);
5412
+ }
5413
+ return ids;
5414
+ }
5415
+ /**
5416
+ * Whether `interval` reaches the head because a headward page joined it to the head interval:
5417
+ * it is, or merged, one of `headIntervalIds` (the intervals marked as the head before the page
5418
+ * was placed). Only where cursors are derived from the interval (`config.deriveCursor`): a
5419
+ * cursor a response returned stays as sent.
5420
+ */
5421
+ inheritsHeadMark(interval, direction, headIntervalIds) {
5422
+ if (!this.config.deriveCursor || direction !== "headward") return false;
5423
+ return headIntervalIds.some(
5424
+ (id) => id === interval.id || !this._itemIntervals.has(id)
5425
+ );
5426
+ }
5427
+ /** Whether `a`'s head edge (see {@link getServerKnownEdges}) is further headward than `b`'s. */
5428
+ reachesFurtherHeadwardThan(a, b) {
5429
+ const aHeadEdge = this.getServerKnownEdges(a).head;
5430
+ const bHeadEdge = this.getServerKnownEdges(b).head;
5431
+ return !!aHeadEdge && !!bHeadEdge && this.aIsMoreHeadwardThanB(aHeadEdge, bHeadEdge);
5432
+ }
5391
5433
  intervalItemsOrEmpty(interval) {
5392
5434
  return interval ? this.intervalToItems(interval) : [];
5393
5435
  }
@@ -5413,6 +5455,20 @@ var BasePaginator = class {
5413
5455
  anchoredHead: []
5414
5456
  });
5415
5457
  }
5458
+ /**
5459
+ * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
5460
+ * besides its page, once the page is placed with `placeParams`. Runs once for every response that
5461
+ * arrived, also when extracting or placing its page failed. Does nothing by default.
5462
+ */
5463
+ applyQueryResponseRest(_response, _placeParams) {
5464
+ }
5465
+ /**
5466
+ * Filters a fetched page's items before the page is placed, synchronously, as placing runs in a
5467
+ * single tick. Keeps every item by default; a paginator that drops some overrides it.
5468
+ */
5469
+ filterQueryResults(items) {
5470
+ return items;
5471
+ }
5416
5472
  /** Subclasses must override it and return the query shape. */
5417
5473
  getNextQueryShape(_params = {}) {
5418
5474
  throw new Error("Paginator.getNextQueryShape() is not implemented");
@@ -5473,6 +5529,18 @@ var BasePaginator = class {
5473
5529
  this.state.partialNext({ items: [], ...this.consumePendingPrunePaginationState() });
5474
5530
  }
5475
5531
  }
5532
+ /**
5533
+ * Publishes the active interval's items with `state` and any pending prune changes, at once.
5534
+ * Inside a coalescing {@link batch}, call it after the batch's last window change: the batch then
5535
+ * publishes nothing more.
5536
+ */
5537
+ publishActiveInterval(state = {}) {
5538
+ this.state.partialNext({
5539
+ items: this.projectActiveWindow(),
5540
+ ...this.consumePendingPrunePaginationState(),
5541
+ ...state
5542
+ });
5543
+ }
5476
5544
  /**
5477
5545
  * Schedules a throttled (leading and trailing) active-window publish. Live mutations call it
5478
5546
  * instead of publishing inline when {@link isStateThrottled}. Repeated calls coalesce.
@@ -5482,10 +5550,10 @@ var BasePaginator = class {
5482
5550
  }
5483
5551
  /**
5484
5552
  * Runs `fn` with window publishes suspended and emits once on exit (a replace is
5485
- * remove-then-insert, which would emit twice). Only the outermost scope emits. `exit: 'auto'`
5486
- * rides the throttle when there is one, `'sync'` always flushes ({@link batch}). Skipped for
5487
- * `lockItemOrder` lists, whose emit republishes the last array and must not be re-derived from
5488
- * the interval.
5553
+ * remove-then-insert, which would emit twice), unless the window was published after its last
5554
+ * change. Only the outermost scope emits. `exit: 'auto'` rides the throttle when there is one,
5555
+ * `'sync'` always flushes ({@link batch}). Skipped for `lockItemOrder` lists, whose emit
5556
+ * republishes the last array and must not be re-derived from the interval.
5489
5557
  */
5490
5558
  withSingleWindowPublish(fn, { exit = "auto" } = {}) {
5491
5559
  if (this.config.lockItemOrder) {
@@ -5499,8 +5567,10 @@ var BasePaginator = class {
5499
5567
  } finally {
5500
5568
  this._windowPublishSuspendDepth -= 1;
5501
5569
  }
5502
- if (!isOutermost || !this._suspendedWindowDirty) return;
5503
- this._suspendedWindowDirty = false;
5570
+ const staleState = this._staleWindowState;
5571
+ if (!isOutermost || !staleState) return;
5572
+ this._staleWindowState = void 0;
5573
+ if (this.items !== staleState.items) return;
5504
5574
  if (exit === "auto" && this.isStateThrottled) this.scheduleWindowPublish();
5505
5575
  else this.flushWindowPublish();
5506
5576
  }
@@ -5572,18 +5642,14 @@ var BasePaginator = class {
5572
5642
  return true;
5573
5643
  }
5574
5644
  /**
5575
- * The edge-most ID at `edge` that the server knows, so it is usable as a cursor. Not simply
5576
- * `itemIds[0]`: a prune skips locally-created items, so the outermost ID may be client-generated.
5645
+ * The interval's outermost items the server knows about (see {@link isPaginationAnchorable}), at
5646
+ * its head and tail; `undefined` where it holds none. Items the server never saw do not count:
5647
+ * they cannot continue its pagination as a cursor, nor be reached by a page the server returns.
5577
5648
  */
5578
- getPaginationEdgeId(interval, edge) {
5579
- const ids = interval.itemIds;
5580
- const fromFirst = edge === "tail" ? !this.intervalItemIdsAreHeadFirst : this.intervalItemIdsAreHeadFirst;
5581
- const step = fromFirst ? 1 : -1;
5582
- for (let i = fromFirst ? 0 : ids.length - 1; i >= 0 && i < ids.length; i += step) {
5583
- const id = ids[i];
5584
- if (this.isPaginationAnchorable(this._itemIndex.get(id))) return id;
5585
- }
5586
- return null;
5649
+ getServerKnownEdges(interval) {
5650
+ const items = interval.itemIds.map((id) => this._itemIndex.get(id));
5651
+ const known = items.filter((item) => this.isPaginationAnchorable(item));
5652
+ return this.getPagePaginationEdges(known);
5587
5653
  }
5588
5654
  /** Keeps the `items` that are members of `interval`, in order. */
5589
5655
  retainIntervalMembers(items, interval) {
@@ -5608,7 +5674,8 @@ var BasePaginator = class {
5608
5674
  const next = {};
5609
5675
  if (current.hasMoreTail !== active.hasMoreTail) next.hasMoreTail = active.hasMoreTail;
5610
5676
  if (this.isCursorPagination) {
5611
- const tailward = this.getPaginationEdgeId(active, "tail");
5677
+ const { tail } = this.getServerKnownEdges(active);
5678
+ const tailward = tail ? this.getItemId(tail) : null;
5612
5679
  if (tailward !== null && current.cursor?.tailward !== tailward) {
5613
5680
  next.cursor = { headward: current.cursor?.headward, tailward };
5614
5681
  }
@@ -5776,31 +5843,38 @@ var BasePaginator = class {
5776
5843
  isTail: !!isTail
5777
5844
  };
5778
5845
  }
5779
- getCursorFromInterval(interval) {
5780
- const edges = this.getIntervalPaginationEdges(interval);
5781
- const fallbackFirstId = interval.itemIds[0] ?? null;
5782
- const fallbackLastId = interval.itemIds.slice(-1)[0] ?? null;
5783
- const fallbackHeadId = this.intervalItemIdsAreHeadFirst ? fallbackFirstId : fallbackLastId;
5784
- const fallbackTailId = this.intervalItemIdsAreHeadFirst ? fallbackLastId : fallbackFirstId;
5785
- const headId = edges?.head ? this.getItemId(edges.head) : fallbackHeadId;
5786
- const tailId = edges?.tail ? this.getItemId(edges.tail) : fallbackTailId;
5846
+ /**
5847
+ * The cursor continuing `interval` where it has more items (by default, per its own flags), at
5848
+ * its outermost items the server knows about (see {@link getServerKnownEdges}).
5849
+ */
5850
+ getCursorFromInterval(interval, { hasMoreHead, hasMoreTail } = interval) {
5851
+ const { head, tail } = this.getServerKnownEdges(interval);
5787
5852
  return {
5788
- headward: interval.hasMoreHead ? headId : null,
5789
- tailward: interval.hasMoreTail ? tailId : null
5853
+ headward: hasMoreHead && head ? this.getItemId(head) : null,
5854
+ tailward: hasMoreTail && tail ? this.getItemId(tail) : null
5790
5855
  };
5791
5856
  }
5792
5857
  isActiveInterval(interval) {
5793
5858
  return this._activeIntervalId === interval.id;
5794
5859
  }
5795
- /**
5796
- * Whether the active interval is the anchored head. Re-seeding a loaded paginator with a fresh
5797
- * newest page is only safe then (the page overlaps it). After a jump to an older window it would
5798
- * force-merge the newest page across the gap, so the re-seed is skipped.
5799
- */
5860
+ /** Whether the active (shown) interval is the loaded one reaching the head of the dataset. */
5800
5861
  get isActiveIntervalAtHead() {
5801
5862
  const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
5802
5863
  return !!head && !isLogicalInterval(head) && !!head.isHead && this.isActiveInterval(head);
5803
5864
  }
5865
+ /**
5866
+ * Claims the active interval for a call that decides it, and returns the claim; a query claims
5867
+ * it as `claimsActiveInterval` says (see {@link decidesActiveInterval}). The latest claim wins: a
5868
+ * page arriving after a later claim is only stored.
5869
+ */
5870
+ claimActiveInterval() {
5871
+ this._activeIntervalClaimCount += 1;
5872
+ return this._activeIntervalClaimCount;
5873
+ }
5874
+ /** Whether no claim on the active interval followed `claim` (see {@link claimActiveInterval}). */
5875
+ isLatestActiveIntervalClaim(claim) {
5876
+ return claim === this._activeIntervalClaimCount;
5877
+ }
5804
5878
  setActiveInterval(interval, opts) {
5805
5879
  this._activeIntervalId = interval?.id;
5806
5880
  if (opts?.updateState === false) return;
@@ -5818,6 +5892,14 @@ var BasePaginator = class {
5818
5892
  const end = this._itemIndex?.get?.(ids[ids.length - 1]);
5819
5893
  return { start, end };
5820
5894
  }
5895
+ /**
5896
+ * The items at the head and tail edges of a page given in item order (`sortComparator` order), as
5897
+ * {@link getIntervalPaginationEdges} gives them for an interval. Both `undefined` for an empty page.
5898
+ */
5899
+ getPagePaginationEdges(page) {
5900
+ const [first, last] = [page[0], page[page.length - 1]];
5901
+ return this.intervalItemIdsAreHeadFirst ? { head: first, tail: last } : { head: last, tail: first };
5902
+ }
5821
5903
  /**
5822
5904
  * Pagination head/tail edges of an interval, taken from its sort bounds.
5823
5905
  * `intervalItemIdsAreHeadFirst` decides which bound is the head: where new items appear, not
@@ -5862,9 +5944,33 @@ var BasePaginator = class {
5862
5944
  setIntervals(intervals) {
5863
5945
  this._itemIntervals = new Map(intervals.map((i) => [i.id, i]));
5864
5946
  }
5947
+ /**
5948
+ * The span pages and items are matched against: from the interval's outermost items the server
5949
+ * knows about (see {@link isPaginationAnchorable}), or its sort bounds when it holds none. An
5950
+ * item the server never saw does not stretch it, as its sort key may come from the client.
5951
+ */
5952
+ getIntervalSpan(interval) {
5953
+ const ids = interval.itemIds;
5954
+ const knownItemAt = (index) => {
5955
+ const item = this._itemIndex.get(ids[index]);
5956
+ return this.isPaginationAnchorable(item) ? item : void 0;
5957
+ };
5958
+ let start;
5959
+ let end;
5960
+ for (let index = 0; index < ids.length && !start; index++) start = knownItemAt(index);
5961
+ for (let index = ids.length - 1; index >= 0 && !end; index--)
5962
+ end = knownItemAt(index);
5963
+ return start && end ? { start, end } : this.getIntervalSortBounds(interval);
5964
+ }
5965
+ /** The head and tail edges of the interval's span (see {@link getIntervalSpan}). */
5966
+ getIntervalSpanEdges(interval) {
5967
+ const span = this.getIntervalSpan(interval);
5968
+ if (!span) return null;
5969
+ return this.intervalItemIdsAreHeadFirst ? { head: span.start, tail: span.end } : { head: span.end, tail: span.start };
5970
+ }
5865
5971
  intervalsStrictlyOverlap(a, b) {
5866
- const aBounds = this.getIntervalSortBounds(a);
5867
- const bBounds = this.getIntervalSortBounds(b);
5972
+ const aBounds = this.getIntervalSpan(a);
5973
+ const bBounds = this.getIntervalSpan(b);
5868
5974
  if (!aBounds || !bBounds) return false;
5869
5975
  return this.itemOrderComparator(aBounds.start, bBounds.end) <= 0 && this.itemOrderComparator(bBounds.start, aBounds.end) <= 0;
5870
5976
  }
@@ -5874,8 +5980,8 @@ var BasePaginator = class {
5874
5980
  * `isHead`/`isTail` and the other extends beyond its pagination head/tail edge.
5875
5981
  */
5876
5982
  intervalsOverlap(a, b, policy = "auto") {
5877
- const aBounds = this.getIntervalSortBounds(a);
5878
- const bBounds = this.getIntervalSortBounds(b);
5983
+ const aBounds = this.getIntervalSpan(a);
5984
+ const bBounds = this.getIntervalSpan(b);
5879
5985
  if (!aBounds || !bBounds) return false;
5880
5986
  if (this.itemOrderComparator(aBounds.start, bBounds.end) <= 0 && this.itemOrderComparator(bBounds.start, aBounds.end) <= 0)
5881
5987
  return true;
@@ -5884,8 +5990,8 @@ var BasePaginator = class {
5884
5990
  const bIsHead = b.isHead;
5885
5991
  const aIsTail = a.isTail;
5886
5992
  const bIsTail = b.isTail;
5887
- const aEdges = this.getIntervalPaginationEdges(a);
5888
- const bEdges = this.getIntervalPaginationEdges(b);
5993
+ const aEdges = this.getIntervalSpanEdges(a);
5994
+ const bEdges = this.getIntervalSpanEdges(b);
5889
5995
  if (!aEdges || !bEdges) return false;
5890
5996
  if (bIsHead && this.aIsMoreHeadwardThanB(aEdges.head, bEdges.head)) return true;
5891
5997
  if (aIsHead && this.aIsMoreHeadwardThanB(bEdges.head, aEdges.head)) return true;
@@ -5893,13 +5999,20 @@ var BasePaginator = class {
5893
5999
  if (aIsTail && this.aIsMoreTailwardThanB(bEdges.tail, aEdges.tail)) return true;
5894
6000
  return false;
5895
6001
  }
6002
+ /**
6003
+ * Whether `item` belongs in `interval`: within its span (see {@link getIntervalSpan}), or beyond
6004
+ * the edge of a head or tail interval. An item the server never saw stays in the interval holding
6005
+ * it, so updating it does not move it.
6006
+ */
5896
6007
  belongsToInterval(item, interval) {
5897
- const sortBounds = this.getIntervalSortBounds(interval);
5898
- if (!sortBounds) return false;
5899
- const { start, end } = sortBounds;
6008
+ if (!this.isPaginationAnchorable(item) && interval.itemIds.includes(this.getItemId(item)))
6009
+ return true;
6010
+ const span = this.getIntervalSpan(interval);
6011
+ if (!span) return false;
6012
+ const { start, end } = span;
5900
6013
  if (this.itemOrderComparator(start, item) <= 0 && this.itemOrderComparator(item, end) <= 0)
5901
6014
  return true;
5902
- const edges = this.getIntervalPaginationEdges(interval);
6015
+ const edges = this.getIntervalSpanEdges(interval);
5903
6016
  if (!edges) return false;
5904
6017
  if (interval.isHead && this.aIsMoreHeadwardThanB(item, edges.head))
5905
6018
  return true;
@@ -6405,7 +6518,7 @@ var BasePaginator = class {
6405
6518
  this._activeIntervalId
6406
6519
  )) {
6407
6520
  if (this.isWindowPublishSuspended) {
6408
- this._suspendedWindowDirty = true;
6521
+ this._staleWindowState = this.state.getLatestValue();
6409
6522
  } else if (this.isStateThrottled) {
6410
6523
  this.scheduleWindowPublish();
6411
6524
  } else {
@@ -6436,7 +6549,8 @@ var BasePaginator = class {
6436
6549
  * Runs `fn` as one batched mutation: per-item store notifications fold into one flush, so sibling
6437
6550
  * holders of the same IDs re-project once. With `coalesce: true` the active window also emits
6438
6551
  * exactly once on exit ({@link flushWindowPublish}), independent of throttling: for one-shot
6439
- * operations. Omit it in WS event handlers so events ride the throttle.
6552
+ * operations. Omit it in WS event handlers so events ride the throttle. If `fn` publishes the
6553
+ * window after its last change (see {@link publishActiveInterval}), `batch` publishes nothing.
6440
6554
  */
6441
6555
  batch(fn, { coalesce = false } = {}) {
6442
6556
  if (!coalesce) {
@@ -6465,7 +6579,7 @@ var BasePaginator = class {
6465
6579
  }
6466
6580
  if (stateLocation && stateLocation.currentIndex > -1) {
6467
6581
  if (this.isWindowPublishSuspended) {
6468
- this._suspendedWindowDirty = true;
6582
+ this._staleWindowState = this.state.getLatestValue();
6469
6583
  } else if (!this.isStateThrottled) {
6470
6584
  const newItems = [...this.items ?? []];
6471
6585
  newItems.splice(stateLocation.currentIndex, 1);
@@ -6545,9 +6659,10 @@ var BasePaginator = class {
6545
6659
  }
6546
6660
  /**
6547
6661
  * Records the query shape of the loaded window so the next pagination continues it. Data that
6548
- * arrives without a query (`setItems`, `mergeNewestPage`) would otherwise make the next query a
6549
- * first page that publishes `items: undefined` first, and an empty response then loses the
6550
- * window. Needs items: an empty window has no shape to continue from.
6662
+ * arrives without the paginator's own query (`setItems`, a page from a query it did not run, a
6663
+ * subclass reconciling a loaded window) would otherwise make the next query a first page that
6664
+ * publishes `items: undefined` first, and an empty response then loses the window. Needs items:
6665
+ * an empty window has no shape to continue from.
6551
6666
  */
6552
6667
  recordLoadedWindowQueryShape() {
6553
6668
  if (typeof this._lastQueryShape === "undefined" && (this.state.getLatestValue().items?.length ?? 0) > 0) {
@@ -6612,6 +6727,29 @@ var BasePaginator = class {
6612
6727
  isJumpQueryShape(_queryShape) {
6613
6728
  return false;
6614
6729
  }
6730
+ /**
6731
+ * Whether a first page queried with this shape is the dataset's head page. True unless the shape
6732
+ * starts the page elsewhere, such as at a cursor.
6733
+ */
6734
+ isHeadPageQueryShape(_queryShape) {
6735
+ return true;
6736
+ }
6737
+ /**
6738
+ * Whether a fetched page reaches the head of the dataset, whatever query fetched it — for example a
6739
+ * page around an item that turns out to include the headmost one. Consulted when the query result
6740
+ * does not say (a `null` {@link PaginationQueryReturnValue.headward} does), with the page sorted in
6741
+ * item order, before it is ingested.
6742
+ *
6743
+ * - `true`: the page reaches the head; the window it lands in is marked as the head.
6744
+ * - `false`: the page does not reach the head.
6745
+ * - `undefined` (the default): not known.
6746
+ *
6747
+ * Only `true` acts. On `false` or `undefined` the query shape and the cursor derivation decide, so a
6748
+ * window they mark as the head stays marked — for example a newest page that a live item joins.
6749
+ */
6750
+ pageReachesHead(_page, _queryShape) {
6751
+ return void 0;
6752
+ }
6615
6753
  /** The page size a query's results are measured against when deriving the head/tail flags. */
6616
6754
  getRequestedPageSize(_queryShape) {
6617
6755
  return this.pageSize;
@@ -6626,14 +6764,20 @@ var BasePaginator = class {
6626
6764
  items: stateUpdate.items
6627
6765
  };
6628
6766
  }
6629
- async runQueryRetryable(params = {}) {
6767
+ /**
6768
+ * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
6769
+ * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
6770
+ * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
6771
+ * caller to end the query.
6772
+ */
6773
+ async fetchQueryResponseWithRetries(params = {}) {
6630
6774
  const remainingRetries = params.retryCount ?? 0;
6631
6775
  try {
6632
- return await this.query(params);
6776
+ return await this.fetchQueryResponse(params);
6633
6777
  } catch (e) {
6634
6778
  if (remainingRetries > 0) {
6635
6779
  await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6636
- return await this.runQueryRetryable({
6780
+ return await this.fetchQueryResponseWithRetries({
6637
6781
  ...params,
6638
6782
  retryCount: remainingRetries - 1
6639
6783
  });
@@ -6650,23 +6794,108 @@ var BasePaginator = class {
6650
6794
  }
6651
6795
  }
6652
6796
  /**
6653
- * Runs a pagination query and reconciles its result into the paginator state.
6797
+ * Runs one query through the query pipeline, step by step:
6798
+ *
6799
+ * 1. {@link prepareQuery}: the query shape, read from the paginator state, and the loading flag.
6800
+ * A first page of a paginator not initialized yet shows what the offline database holds,
6801
+ * before the request is sent.
6802
+ * 2. {@link fetchQueryResponse}, retried as configured: the response.
6803
+ * 3. {@link extractQueryPage}: the page in the response.
6804
+ * 4. {@link placeQueryPage}: the page placed (shown unless only stored) and the query ended;
6805
+ * when fetching, extracting or placing failed, only the query ended.
6806
+ * 5. {@link applyQueryResponseRest}: the response's data besides its page, once that is placed.
6807
+ *
6808
+ * A failed fetch skips the steps after it; any other failed step skips none. Either is recorded
6809
+ * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
6810
+ * rejects the call only with `throwErrors` set.
6811
+ *
6812
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
6813
+ * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
6814
+ * placed, with `isSuperseded`.
6654
6815
  *
6655
6816
  * @param params - Query parameters.
6817
+ * @param params.claimsActiveInterval - Whether the query claims the active interval.
6656
6818
  * @param params.direction - Direction to paginate in (headward or tailward).
6657
6819
  * @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a
6658
6820
  * first-page query.
6659
6821
  * @param params.queryShape - Explicit query shape overriding the one derived from current state.
6822
+ * Its page starts a separate interval (see `QueryPagePlacement.startsSeparateInterval`).
6660
6823
  * @param params.requestOptions - Request options outside the query shape.
6661
6824
  * @param params.reset - 'yes' forces a first page, 'no' continues, else the query shape decides.
6662
6825
  * @param params.retryCount - Number of retries after a failure.
6663
6826
  * @param params.silent - Skip the `isLoading: true` publish of a non-first-page or
6664
6827
  * `keepPreviousItems` query.
6665
- * @param params.updateState - Whether to write the query results back to state.
6666
- * @returns The reconciled result (`targetInterval` is `null` when nothing was ingested, e.g. a
6667
- * failed request or an empty page), or nothing when the query did not run.
6828
+ * @param params.updateState - Whether the page's interval becomes the active one.
6829
+ */
6830
+ async executeQuery(params = {}) {
6831
+ const prepared = this.prepareQuery(params);
6832
+ if (!prepared) return;
6833
+ const result = await this.runPreparedQuery(prepared);
6834
+ const isSuperseded = this.claimIsSuperseded(prepared.placeParams);
6835
+ return result && { ...result, isSuperseded };
6836
+ }
6837
+ /** The steps after {@link prepareQuery} of the query pipeline (see {@link executeQuery}). */
6838
+ async runPreparedQuery({
6839
+ fetchParams,
6840
+ offlinePreloadPromise,
6841
+ placeParams
6842
+ }) {
6843
+ if (offlinePreloadPromise) await offlinePreloadPromise;
6844
+ const response = await this.fetchQueryResponseWithRetries(fetchParams);
6845
+ if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
6846
+ const errors = [];
6847
+ const runStep = (step) => {
6848
+ try {
6849
+ return step();
6850
+ } catch (error) {
6851
+ errors.push(error);
6852
+ return void 0;
6853
+ }
6854
+ };
6855
+ const page = runStep(() => this.extractQueryPage(response, fetchParams));
6856
+ let placed = page && runStep(() => this.placeQueryPage({ ...placeParams, results: page }));
6857
+ placed ?? (placed = runStep(() => this.placeQueryPage({ ...placeParams, results: null })));
6858
+ runStep(() => this.applyQueryResponseRest(response, placeParams));
6859
+ return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
6860
+ }
6861
+ /**
6862
+ * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
6863
+ * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
6864
+ * placed with the error in its state, so a caller committing that state keeps the error.
6865
+ */
6866
+ reportQueryError(error, placed) {
6867
+ const stateUpdate = { isLoading: false, lastQueryError: error };
6868
+ this.state.partialNext(stateUpdate);
6869
+ if (this.config.throwErrors) throw error;
6870
+ return {
6871
+ stateCandidate: { ...placed?.stateCandidate, ...stateUpdate },
6872
+ targetInterval: placed?.targetInterval ?? null
6873
+ };
6874
+ }
6875
+ /**
6876
+ * Whether a query claims the active interval by default (see
6877
+ * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
6878
+ * - a reload (`reset: 'yes'`);
6879
+ * - a query at a shape the caller gave, unless `updateState` is `false`.
6668
6880
  */
6669
- async executeQuery({
6881
+ decidesActiveInterval({
6882
+ queryShape,
6883
+ reset,
6884
+ updateState
6885
+ }) {
6886
+ const isReload = reset === "yes";
6887
+ const showsPageAtCallersShape = !!queryShape && updateState !== false;
6888
+ return isReload || showsPageAtCallersShape;
6889
+ }
6890
+ /**
6891
+ * The preparing step of the query pipeline (see {@link executeQuery}): resets the state when
6892
+ * asked, builds the query shape from the paginator state and publishes the loading flag. A first
6893
+ * page of a paginator not initialized yet also starts loading what the offline database holds,
6894
+ * returned as `offlinePreloadPromise`. `undefined` when the query cannot run now (see
6895
+ * {@link canExecuteQuery}).
6896
+ */
6897
+ prepareQuery({
6898
+ claimsActiveInterval,
6670
6899
  direction,
6671
6900
  keepPreviousItems,
6672
6901
  queryShape: forcedQueryShape,
@@ -6675,8 +6904,10 @@ var BasePaginator = class {
6675
6904
  retryCount = this.config.retryCount,
6676
6905
  silent,
6677
6906
  updateState = true
6678
- } = {}) {
6679
- if (!this.canExecuteQuery({ direction, reset })) return;
6907
+ }) {
6908
+ if (!this.canExecuteQuery({ direction, reset })) return void 0;
6909
+ const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
6910
+ const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
6680
6911
  const isForcedReset = reset === "yes" && !keepPreviousItems;
6681
6912
  if (isForcedReset) {
6682
6913
  this.clearItemStorage();
@@ -6691,45 +6922,110 @@ var BasePaginator = class {
6691
6922
  const pageSize = isRefresh ? Math.max(this.pageSize, this.items?.length ?? 0) : this.pageSize;
6692
6923
  const queryShape = forcedQueryShape ?? this.getNextQueryShape({ direction, pageSize });
6693
6924
  const isFirstPage = this.isFirstPageQuery({ queryShape, reset });
6925
+ let offlinePreloadPromise;
6694
6926
  if (isFirstPage && !keepPreviousItems) {
6695
- const state = this.getStateBeforeFirstQuery();
6927
+ const stateBeforeFirstQuery = this.getStateBeforeFirstQuery();
6696
6928
  if (!isForcedReset) {
6697
6929
  this.state.partialNext({ isLoading: true });
6698
6930
  }
6699
- let items = void 0;
6700
- if (!this.isInitialized) {
6701
- items = await this.preloadFirstPageFromOfflineDb({
6702
- direction,
6703
- queryShape,
6704
- reset,
6705
- retryCount
6706
- }) ?? state.items;
6707
- }
6708
- if (!isForcedReset || items !== void 0) {
6709
- this.state.next({ ...state, items });
6931
+ const publishStateBeforeFirstQuery = (items) => {
6932
+ if (!isForcedReset || items !== void 0) {
6933
+ this.state.next({ ...stateBeforeFirstQuery, items });
6934
+ }
6935
+ };
6936
+ if (this.isInitialized) {
6937
+ publishStateBeforeFirstQuery(void 0);
6938
+ } else {
6939
+ offlinePreloadPromise = (async () => {
6940
+ const items = await this.preloadFirstPageFromOfflineDb({
6941
+ direction,
6942
+ queryShape,
6943
+ reset,
6944
+ retryCount
6945
+ });
6946
+ publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
6947
+ })();
6710
6948
  }
6711
6949
  } else if (!silent) {
6712
6950
  this.state.partialNext({ isLoading: true });
6713
6951
  }
6714
- this._nextQueryShape = queryShape;
6715
- const results = await this.runQueryRetryable({
6716
- direction,
6717
- queryShape,
6718
- requestOptions,
6719
- reset,
6720
- retryCount
6721
- });
6722
- return this.postQueryReconcile({
6723
- direction,
6724
- isFirstPage,
6725
- keepPreviousItems,
6726
- queryShape,
6727
- requestedPageSize: this.getRequestedPageSize(queryShape),
6728
- results,
6729
- updateState
6730
- });
6952
+ const isAtCallersShape = !!forcedQueryShape;
6953
+ const continuesOwnCursor = !isFirstPage && !isAtCallersShape;
6954
+ return {
6955
+ fetchParams: { direction, queryShape, requestOptions, reset, retryCount },
6956
+ offlinePreloadPromise,
6957
+ placeParams: {
6958
+ activeIntervalClaim,
6959
+ startsSeparateInterval: isAtCallersShape,
6960
+ continuesIntervalId: continuesOwnCursor ? this._activeIntervalId : void 0,
6961
+ direction,
6962
+ isFirstPage,
6963
+ keepPreviousItems,
6964
+ queryShape,
6965
+ requestedPageSize: this.getRequestedPageSize(queryShape),
6966
+ updateState
6967
+ }
6968
+ };
6969
+ }
6970
+ /**
6971
+ * The placing step of the query pipeline (see {@link executeQuery}): places the page (see
6972
+ * {@link placePage}), shown unless only stored (see {@link isPageOnlyStored}), and ends the
6973
+ * query. Without a page (`results: null`), it only ends the query.
6974
+ */
6975
+ placeQueryPage(params) {
6976
+ this._lastQueryShape = params.queryShape;
6977
+ const { results } = params;
6978
+ if (!results) {
6979
+ const stateUpdate = { isLoading: false };
6980
+ this.state.partialNext(stateUpdate);
6981
+ return { stateCandidate: stateUpdate, targetInterval: null };
6982
+ }
6983
+ if (this.isPageOnlyStored(params)) {
6984
+ return this.placePage(
6985
+ { ...params, results, startsSeparateInterval: true, updateState: false },
6986
+ { endsQuery: true }
6987
+ );
6988
+ }
6989
+ return this.placePage({ ...params, results }, { endsQuery: true });
6990
+ }
6991
+ /**
6992
+ * Whether the page is only stored, leaving the active interval as it is, rather than shown:
6993
+ * - the interval it continues is no longer active (see {@link continuedIntervalIsInactive});
6994
+ * - a later claim on the active interval was made (see {@link claimIsSuperseded}).
6995
+ */
6996
+ isPageOnlyStored(params) {
6997
+ return this.continuedIntervalIsInactive(params) || this.claimIsSuperseded(params);
6998
+ }
6999
+ /**
7000
+ * Whether the interval the page continues stopped being active while the request ran, leaving
7001
+ * the page with no known place relative to the active interval.
7002
+ */
7003
+ continuedIntervalIsInactive({
7004
+ continuesIntervalId
7005
+ }) {
7006
+ return continuesIntervalId !== void 0 && continuesIntervalId !== this._activeIntervalId;
6731
7007
  }
6732
- postQueryReconcile({
7008
+ /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
7009
+ claimIsSuperseded({ activeIntervalClaim }) {
7010
+ return activeIntervalClaim !== void 0 && !this.isLatestActiveIntervalClaim(activeIntervalClaim);
7011
+ }
7012
+ /**
7013
+ * Places a page in the paginator's windows — in the window it continues, or in a window of its
7014
+ * own merged with the windows it overlaps — and derives the cursors and the more-pages flags.
7015
+ * With `updateState` (the default), its window becomes the shown one and the state is published.
7016
+ * Without it, the page is only stored, and published only if it landed in the active interval,
7017
+ * so the shown items never go stale. A page proven to reach the head of the dataset makes its
7018
+ * interval the only head (see {@link makeOnlyHead}). Where cursors are derived from the
7019
+ * interval (`config.deriveCursor`), an interval a headward page joins to the head interval
7020
+ * reaches the head, whatever the page says (see {@link inheritsHeadMark}).
7021
+ *
7022
+ * `endsQuery` says the page comes from the paginator's own query, which placing it ends: the
7023
+ * loading flag goes off, the last query error is cleared, and a first page goes to the offline
7024
+ * database. A page from a query the paginator did not run is placed without any of that, as one
7025
+ * of the paginator's own queries may still be running.
7026
+ */
7027
+ placePage({
7028
+ startsSeparateInterval,
6733
7029
  direction,
6734
7030
  isFirstPage,
6735
7031
  keepPreviousItems,
@@ -6737,39 +7033,44 @@ var BasePaginator = class {
6737
7033
  requestedPageSize,
6738
7034
  results,
6739
7035
  updateState = true
6740
- }) {
6741
- this._lastQueryShape = queryShape;
6742
- this._nextQueryShape = void 0;
6743
- const stateUpdate = {
6744
- isLoading: false
6745
- };
6746
- if (!results) {
6747
- this.state.partialNext(stateUpdate);
6748
- return { stateCandidate: stateUpdate, targetInterval: null };
6749
- }
6750
- const { items, headward, tailward, next, prev } = results;
6751
- const resolvedHeadward = headward ?? prev;
6752
- const resolvedTailward = tailward ?? next;
6753
- stateUpdate.lastQueryError = void 0;
7036
+ }, { endsQuery }) {
7037
+ const stateUpdate = endsQuery ? { isLoading: false, lastQueryError: void 0 } : {};
7038
+ const { items, headward, tailward } = results;
6754
7039
  const filteredItems = this.filterQueryResults(items);
6755
7040
  stateUpdate.items = filteredItems;
6756
7041
  const isJumpQuery = !!queryShape && this.isJumpQueryShape(queryShape);
7042
+ const isSeparateInterval = isJumpQuery || !!startsSeparateInterval;
7043
+ const reachesHead = headward === null || this.pageReachesHead(items, queryShape) === true;
7044
+ const reachesTail = tailward === null;
6757
7045
  const keptItemIds = isFirstPage && keepPreviousItems && !this.isCursorPagination && this.items?.length ? new Set(this.items.map((item) => this.getItemId(item))) : void 0;
7046
+ const headIntervalIds = this.getHeadIntervalIds();
6758
7047
  const interval = this.ingestPage({
6759
7048
  page: stateUpdate.items,
6760
- policy: isJumpQuery ? "strict-overlap-only" : "auto",
6761
- // The first page is always the head.
6762
- isHead: isJumpQuery ? void 0 : isFirstPage || (direction === "headward" ? requestedPageSize > items.length : void 0),
6763
- // Even a first page compares the requested vs returned page size.
6764
- isTail: isJumpQuery ? void 0 : isFirstPage || direction === "tailward" ? requestedPageSize > items.length : void 0,
6765
- targetIntervalId: isJumpQuery ? void 0 : this._activeIntervalId
7049
+ policy: isSeparateInterval ? "strict-overlap-only" : "auto",
7050
+ // a first page is the head unless its query started it elsewhere (at a cursor)
7051
+ isHead: reachesHead ? true : isJumpQuery ? void 0 : isFirstPage && this.isHeadPageQueryShape(queryShape) || (direction === "headward" ? requestedPageSize > items.length : void 0),
7052
+ // even though the page is first, we have to compare the requested vs returned page size;
7053
+ // a first page queried towards the head says nothing about the tail
7054
+ isTail: reachesTail ? true : isJumpQuery ? void 0 : isFirstPage && direction !== "headward" || direction === "tailward" ? requestedPageSize > items.length : void 0,
7055
+ targetIntervalId: isSeparateInterval ? void 0 : this._activeIntervalId
6766
7056
  });
7057
+ const intervalReachesHead = reachesHead || !!interval && this.inheritsHeadMark(interval, direction, headIntervalIds);
6767
7058
  if (interval && updateState) {
6768
7059
  this.setActiveInterval(interval, { updateState: false });
6769
7060
  stateUpdate.items = this.intervalToItems(interval);
6770
7061
  } else if (updateState && !items.length && (keepPreviousItems || !isFirstPage)) {
6771
7062
  stateUpdate.items = this.items;
6772
7063
  }
7064
+ const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
7065
+ const knownFlags = continuesActiveIntervalFlags || !interval ? {
7066
+ cursor: this.cursor,
7067
+ hasMoreHead: this.hasMoreHead,
7068
+ hasMoreTail: this.hasMoreTail
7069
+ } : {
7070
+ cursor: void 0,
7071
+ hasMoreHead: interval.hasMoreHead,
7072
+ hasMoreTail: interval.hasMoreTail
7073
+ };
6773
7074
  if (this.isCursorPagination) {
6774
7075
  if (this.config.deriveCursor && interval) {
6775
7076
  const { cursor, hasMoreTail, hasMoreHead } = this.config.deriveCursor({
@@ -6778,30 +7079,37 @@ var BasePaginator = class {
6778
7079
  queryShape,
6779
7080
  page: results.items,
6780
7081
  requestedPageSize,
6781
- cursor: this.cursor,
6782
- hasMoreHead: this.hasMoreHead,
6783
- hasMoreTail: this.hasMoreTail
7082
+ ...knownFlags
6784
7083
  });
6785
7084
  stateUpdate.cursor = cursor;
6786
7085
  stateUpdate.hasMoreTail = hasMoreTail;
6787
7086
  stateUpdate.hasMoreHead = hasMoreHead;
6788
7087
  } else if (this.config.deriveCursor && direction && !isFirstPage) {
6789
7088
  stateUpdate.cursor = direction === "headward" ? {
6790
- headward: resolvedHeadward || null,
7089
+ headward: headward || null,
6791
7090
  tailward: this.cursor?.tailward ?? null
6792
7091
  } : {
6793
7092
  headward: this.cursor?.headward ?? null,
6794
- tailward: resolvedTailward || null
7093
+ tailward: tailward || null
6795
7094
  };
6796
- if (direction === "headward") stateUpdate.hasMoreHead = !!resolvedHeadward;
6797
- else stateUpdate.hasMoreTail = !!resolvedTailward;
7095
+ if (direction === "headward") stateUpdate.hasMoreHead = !!headward;
7096
+ else stateUpdate.hasMoreTail = !!tailward;
6798
7097
  } else {
6799
7098
  stateUpdate.cursor = {
6800
- tailward: resolvedTailward || null,
6801
- headward: resolvedHeadward || null
7099
+ tailward: tailward || null,
7100
+ headward: headward || null
6802
7101
  };
6803
- stateUpdate.hasMoreTail = !!resolvedTailward;
6804
- stateUpdate.hasMoreHead = !!resolvedHeadward;
7102
+ stateUpdate.hasMoreTail = !!tailward;
7103
+ stateUpdate.hasMoreHead = !!headward;
7104
+ }
7105
+ if (interval && (intervalReachesHead || reachesTail)) {
7106
+ const cursor = stateUpdate.cursor ?? this.cursor;
7107
+ stateUpdate.cursor = {
7108
+ headward: intervalReachesHead ? null : cursor?.headward ?? null,
7109
+ tailward: reachesTail ? null : cursor?.tailward ?? null
7110
+ };
7111
+ if (intervalReachesHead) stateUpdate.hasMoreHead = false;
7112
+ if (reachesTail) stateUpdate.hasMoreTail = false;
6805
7113
  }
6806
7114
  } else {
6807
7115
  const startOffset = this.offset ?? 0;
@@ -6817,16 +7125,16 @@ var BasePaginator = class {
6817
7125
  if (isFirstPage) stateUpdate.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
6818
7126
  }
6819
7127
  if (interval) {
6820
- const current = this.state.getLatestValue();
6821
- const resolvedHasMoreHead = typeof stateUpdate.hasMoreHead === "boolean" ? stateUpdate.hasMoreHead : current.hasMoreHead;
6822
- const resolvedHasMoreTail = typeof stateUpdate.hasMoreTail === "boolean" ? stateUpdate.hasMoreTail : current.hasMoreTail;
7128
+ const resolvedHasMoreHead = typeof stateUpdate.hasMoreHead === "boolean" ? stateUpdate.hasMoreHead : knownFlags.hasMoreHead;
7129
+ const resolvedHasMoreTail = typeof stateUpdate.hasMoreTail === "boolean" ? stateUpdate.hasMoreTail : knownFlags.hasMoreTail;
6823
7130
  const wasHead = interval.isHead;
6824
7131
  interval.hasMoreHead = resolvedHasMoreHead;
6825
7132
  interval.hasMoreTail = resolvedHasMoreTail;
6826
7133
  interval.isHead = resolvedHasMoreHead === false;
6827
7134
  interval.isTail = resolvedHasMoreTail === false;
6828
7135
  this.syncAnchoredHeadAfterHeadFlip(interval, wasHead);
6829
- } else if (!items.length && direction) {
7136
+ if (reachesHead && interval.isHead) this.makeOnlyHead(interval);
7137
+ } else if (!items.length && direction && !isSeparateInterval) {
6830
7138
  const activeInterval = this._activeIntervalId ? this._itemIntervals.get(this._activeIntervalId) : void 0;
6831
7139
  if (activeInterval && !isLogicalInterval(activeInterval)) {
6832
7140
  if (direction === "headward") {
@@ -6840,15 +7148,35 @@ var BasePaginator = class {
6840
7148
  }
6841
7149
  }
6842
7150
  }
6843
- const state = this.getStateAfterQuery(stateUpdate, isFirstPage);
7151
+ const state = endsQuery ? this.getStateAfterQuery(stateUpdate, isFirstPage) : { ...this.state.getLatestValue(), ...stateUpdate };
6844
7152
  if (updateState) this.state.next(state);
6845
- else if (this.isLoading) this.state.partialNext({ isLoading: false });
6846
- if (isFirstPage) this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7153
+ else this.publishStoredPage({ endsQuery, interval, state });
7154
+ if (endsQuery && isFirstPage) {
7155
+ this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7156
+ }
6847
7157
  return {
6848
7158
  stateCandidate: state,
6849
7159
  targetInterval: interval
6850
7160
  };
6851
7161
  }
7162
+ /**
7163
+ * Publishes what placing an only-stored page changed (see {@link placePage}): the active interval
7164
+ * if the page landed in it, and the end of the query with `endsQuery`.
7165
+ */
7166
+ publishStoredPage({
7167
+ endsQuery,
7168
+ interval,
7169
+ state
7170
+ }) {
7171
+ const endsLoading = endsQuery && (this.isLoading || !!this.lastQueryError);
7172
+ const queryEnd = endsLoading ? { isLoading: false, lastQueryError: void 0 } : {};
7173
+ if (interval && this.isActiveInterval(interval)) {
7174
+ const { cursor, hasMoreHead, hasMoreTail } = state;
7175
+ this.publishActiveInterval({ ...queryEnd, cursor, hasMoreHead, hasMoreTail });
7176
+ } else if (endsLoading) {
7177
+ this.state.partialNext(queryEnd);
7178
+ }
7179
+ }
6852
7180
  cancelScheduledQuery() {
6853
7181
  this._executeQueryDebounced.cancel();
6854
7182
  }
@@ -6981,7 +7309,7 @@ var hiddenFilterResolver = {
6981
7309
  var lastUpdatedFilterResolver = {
6982
7310
  matchesField: (field) => field === "last_updated",
6983
7311
  // the server uses the creation time for a channel without messages
6984
- resolve: (channel) => channel.messagePaginator.lastMessageAt ?? channel.data?.created_at
7312
+ resolve: (channel) => channel.messagePaginator.latestMessageAt ?? channel.data?.created_at
6985
7313
  };
6986
7314
  var membersFilterResolver = {
6987
7315
  matchesField: (field) => field === "members",
@@ -7030,7 +7358,7 @@ var createChannelSortPathResolver = (client) => {
7030
7358
  return (channel, path) => {
7031
7359
  switch (path) {
7032
7360
  case "last_message_at":
7033
- return channel.messagePaginator.lastMessageAt;
7361
+ return channel.messagePaginator.latestMessageAt;
7034
7362
  case "has_unread": {
7035
7363
  return hasUnreadResolver.resolve(channel, path);
7036
7364
  }
@@ -7132,16 +7460,16 @@ var ChannelPaginator = class extends BasePaginator {
7132
7460
  request
7133
7461
  });
7134
7462
  };
7135
- this.query = async () => {
7463
+ this.fetchQueryResponse = async ({
7464
+ queryShape: preparedQueryShape
7465
+ } = {}) => {
7136
7466
  if (this._itemsLoadedFromOfflineDB) this._replaceOfflineSeedOnResponse = true;
7137
7467
  this._itemsLoadedFromOfflineDB = false;
7138
- if (!this._nextQueryShape) {
7139
- this._nextQueryShape = this.getNextQueryShape();
7140
- }
7141
- const { stateOptions, ...request } = this._nextQueryShape;
7468
+ const queryShape = preparedQueryShape ?? this.getNextQueryShape();
7469
+ const { stateOptions, ...request } = queryShape;
7142
7470
  let items;
7143
7471
  if (this.config.doRequest) {
7144
- items = (await this.config.doRequest(this._nextQueryShape)).items;
7472
+ items = (await this.config.doRequest(queryShape)).items;
7145
7473
  } else {
7146
7474
  const response = await this.client.queryChannelsAndHydrate(request, {
7147
7475
  ...stateOptions,
@@ -7152,7 +7480,6 @@ var ChannelPaginator = class extends BasePaginator {
7152
7480
  }
7153
7481
  return { items };
7154
7482
  };
7155
- this.filterQueryResults = (items) => items;
7156
7483
  const definedSort = sort?.length ? sort : DEFAULT_BACKEND_SORT;
7157
7484
  this.client = client;
7158
7485
  this._id = id ?? `channel-paginator-${generateUUIDv4()}`;
@@ -7276,7 +7603,7 @@ var ChannelPaginator = class extends BasePaginator {
7276
7603
  * failed query keeps the loaded list's). It is committed before `super`, which filters and ingests
7277
7604
  * the page using `matchesFilter` and the comparator this metadata feeds.
7278
7605
  */
7279
- postQueryReconcile(params) {
7606
+ placeQueryPage(params) {
7280
7607
  const pendingPredefinedFilter = this._pendingPredefinedFilter;
7281
7608
  this._pendingPredefinedFilter = void 0;
7282
7609
  if (params.isFirstPage && params.results) {
@@ -7286,9 +7613,9 @@ var ChannelPaginator = class extends BasePaginator {
7286
7613
  this._replaceOfflineSeedOnResponse = false;
7287
7614
  if (replaceOfflineSeed && params.results) {
7288
7615
  this.clearItemStorage();
7289
- return super.postQueryReconcile({ ...params, keepPreviousItems: false });
7616
+ return super.placeQueryPage({ ...params, keepPreviousItems: false });
7290
7617
  }
7291
- return super.postQueryReconcile(params);
7618
+ return super.placeQueryPage(params);
7292
7619
  }
7293
7620
  getNextQueryShape({
7294
7621
  pageSize
@@ -7394,6 +7721,10 @@ var ChannelPaginator = class extends BasePaginator {
7394
7721
  await this.executeQuery(refreshParams);
7395
7722
  });
7396
7723
  }
7724
+ /** The extracting step of the query pipeline: the response is the page. */
7725
+ extractQueryPage(response, _params) {
7726
+ return response;
7727
+ }
7397
7728
  setItems(params) {
7398
7729
  super.setItems(params);
7399
7730
  this.persistLoadedCids();
@@ -7520,11 +7851,17 @@ var HEADWARD_QUERY_PROPERTIES = [
7520
7851
  "id_gt",
7521
7852
  "id_gte"
7522
7853
  ];
7854
+ var hasAnyOf = (queryShape, properties) => !!queryShape && properties.some((p) => typeof queryShape[p] !== "undefined");
7855
+ var getLinearQueryDirection = (queryShape) => {
7856
+ if (hasAnyOf(queryShape, HEADWARD_QUERY_PROPERTIES)) return "headward";
7857
+ if (hasAnyOf(queryShape, TAILWARD_QUERY_PROPERTIES)) return "tailward";
7858
+ return void 0;
7859
+ };
7523
7860
  var deriveLinearPaginationFlags = ({
7524
7861
  direction,
7525
7862
  hasMoreHead,
7526
7863
  hasMoreTail,
7527
- interval,
7864
+ intervalEdges,
7528
7865
  page,
7529
7866
  queryShape,
7530
7867
  requestedPageSize
@@ -7532,29 +7869,30 @@ var deriveLinearPaginationFlags = ({
7532
7869
  const flags = { hasMoreHead, hasMoreTail };
7533
7870
  const [firstPageMsg, lastPageMsg] = [page[0], page.slice(-1)[0]];
7534
7871
  const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
7535
- firstPageMsg?.id && firstPageMsg.id === interval.itemIds[0],
7536
- lastPageMsg?.id && lastPageMsg.id === interval.itemIds.slice(-1)[0]
7872
+ firstPageMsg?.id && firstPageMsg.id === intervalEdges.tail?.id,
7873
+ lastPageMsg?.id && lastPageMsg.id === intervalEdges.head?.id
7537
7874
  ];
7538
- const containsCursorPaginationProperties = !!queryShape && HEADWARD_QUERY_PROPERTIES.concat(TAILWARD_QUERY_PROPERTIES).some(
7539
- (p) => typeof queryShape[p] !== "undefined"
7875
+ const containsCursorPaginationProperties = hasAnyOf(
7876
+ queryShape,
7877
+ HEADWARD_QUERY_PROPERTIES.concat(TAILWARD_QUERY_PROPERTIES)
7540
7878
  );
7541
- const queriedMessagesTowardsHead = direction === "headward" || !!queryShape && HEADWARD_QUERY_PROPERTIES.some((p) => typeof queryShape[p] !== "undefined");
7542
- const queriedMessagesTowardsTail = direction === "tailward" || typeof queryShape === "undefined" || TAILWARD_QUERY_PROPERTIES.some((p) => typeof queryShape[p] !== "undefined");
7879
+ const queriedMessagesTowardsHead = direction === "headward" || hasAnyOf(queryShape, HEADWARD_QUERY_PROPERTIES);
7880
+ const queriedMessagesTowardsTail = direction === "tailward" || typeof queryShape === "undefined" || hasAnyOf(queryShape, TAILWARD_QUERY_PROPERTIES);
7543
7881
  const containsNonLinearPaginationProperties = !!queryShape?.id_around || !!queryShape?.created_at_around;
7544
7882
  const containsUnrecognizedOptionsOnly = !queriedMessagesTowardsHead && !queriedMessagesTowardsTail && !containsNonLinearPaginationProperties;
7545
7883
  const isFirstPage = !containsCursorPaginationProperties;
7546
7884
  const hasMore = page.length >= requestedPageSize;
7547
- if (typeof queriedMessagesTowardsTail !== "undefined" || containsUnrecognizedOptionsOnly) {
7885
+ const pageIsEmpty = page.length === 0;
7886
+ if (queriedMessagesTowardsTail || isFirstPage || containsUnrecognizedOptionsOnly) {
7548
7887
  hasMoreTail = isFirstPage ? hasMore : !hasMoreTail ? false : hasMore;
7888
+ if (firstPageMsgIsFirstInSet || pageIsEmpty) flags.hasMoreTail = hasMoreTail;
7549
7889
  }
7550
- if (typeof queriedMessagesTowardsHead !== "undefined") {
7551
- hasMoreHead = !hasMoreHead || isFirstPage ? false : hasMore;
7890
+ if (isFirstPage) {
7891
+ flags.hasMoreHead = false;
7892
+ } else if (queriedMessagesTowardsHead) {
7893
+ hasMoreHead = !hasMoreHead ? false : hasMore;
7894
+ if (lastPageMsgIsLastInSet || pageIsEmpty) flags.hasMoreHead = hasMoreHead;
7552
7895
  }
7553
- const pageIsEmpty = page.length === 0;
7554
- if ((firstPageMsgIsFirstInSet || pageIsEmpty) && typeof hasMoreTail !== "undefined")
7555
- flags.hasMoreTail = hasMoreTail;
7556
- if ((lastPageMsgIsLastInSet || pageIsEmpty) && typeof hasMoreHead !== "undefined")
7557
- flags.hasMoreHead = hasMoreHead;
7558
7896
  return flags;
7559
7897
  };
7560
7898
 
@@ -7566,6 +7904,7 @@ var DEFAULT_BACKEND_SORT2 = [
7566
7904
  }
7567
7905
  ];
7568
7906
  var DEFAULT_CHANNEL_MESSAGE_LIST_PAGE_SIZE = 100;
7907
+ var isQueryForNoMessages = (limit) => limit === 0;
7569
7908
  var hasPaginationQueryShapeChanged2 = () => false;
7570
7909
  var dataFieldFilterResolver2 = {
7571
7910
  matchesField: () => true,
@@ -7584,7 +7923,8 @@ var MessageIntervalPaginator = class extends BasePaginator {
7584
7923
  requestSort,
7585
7924
  sort,
7586
7925
  itemOrder,
7587
- paginatorOptions
7926
+ paginatorOptions,
7927
+ thread
7588
7928
  }, builtInDefaults = {}) {
7589
7929
  const resolvedRequestSort = requestSort ?? sort ?? DEFAULT_BACKEND_SORT2;
7590
7930
  const resolvedItemOrder = itemOrder ?? resolvedRequestSort;
@@ -7632,58 +7972,61 @@ var MessageIntervalPaginator = class extends BasePaginator {
7632
7972
  direction,
7633
7973
  items
7634
7974
  }) => {
7635
- if (!items.length) {
7975
+ const { head, tail } = this.getPagePaginationEdges(items);
7976
+ if (!head || !tail) {
7636
7977
  return {
7637
7978
  tailward: void 0,
7638
7979
  headward: void 0
7639
7980
  };
7640
7981
  }
7641
- const start = items[0];
7642
- const end = items[items.length - 1];
7643
- const head = this.intervalItemIdsAreHeadFirst ? start : end;
7644
- const tail = this.intervalItemIdsAreHeadFirst ? end : start;
7645
7982
  return {
7646
7983
  tailward: !direction || direction === "tailward" ? this.getItemId(tail) : void 0,
7647
7984
  headward: !direction || direction === "headward" ? this.getItemId(head) : void 0
7648
7985
  };
7649
7986
  };
7650
7987
  /**
7651
- * Reads `requestOptions.watch`: `true` also watches the channel with the request. Ignored for a
7652
- * thread's reply list and with `doRequest`.
7988
+ * The fetching step of the query pipeline: requests a page through a custom `doRequest`, the
7989
+ * replies endpoint for a thread's reply list, or the channel query otherwise, which takes in what
7990
+ * the response says about the channel itself and leaves the rest for the last step (see
7991
+ * `Channel.requestChannelState`). Reads `requestOptions.watch`: `true` also watches the channel
7992
+ * with the request. Ignored for a thread's reply list and with `doRequest`.
7653
7993
  */
7654
- this.query = async ({
7994
+ this.fetchQueryResponse = async ({
7655
7995
  direction,
7996
+ queryShape,
7656
7997
  requestOptions
7657
7998
  }) => {
7658
- if (!this._nextQueryShape) {
7659
- this._nextQueryShape = this.getNextQueryShape({ direction });
7660
- }
7661
- const options = this._nextQueryShape;
7662
- let items;
7663
- let tailward;
7664
- let headward;
7999
+ const options = queryShape ?? this.getNextQueryShape({ direction });
7665
8000
  if (this.config.doRequest) {
7666
- const result = await this.config.doRequest(options);
7667
- items = this.getCanonicalQueryItems(result?.items ?? []);
7668
- tailward = !direction || direction === "tailward" ? result.cursor?.tailward ?? void 0 : void 0;
7669
- headward = !direction || direction === "headward" ? result.cursor?.headward ?? void 0 : void 0;
7670
- } else {
7671
- const { messages } = this.parentMessageId ? await this.channel.getClient().getReplies(
8001
+ return {
8002
+ doRequestResponse: await this.config.doRequest(options),
8003
+ source: "doRequest"
8004
+ };
8005
+ }
8006
+ if (this.parentMessageId) {
8007
+ const repliesResponse = await this.channel.getClient().getReplies(
7672
8008
  { parent_id: this.parentMessageId },
7673
8009
  { ...options, sort: this.requestSort }
7674
- ) : await this.channel.query({
8010
+ );
8011
+ return { repliesResponse, source: "replies" };
8012
+ }
8013
+ const watch = requestOptions?.watch === true;
8014
+ const channelResponse = await this.channel.requestChannelState(
8015
+ {
7675
8016
  messages: options,
7676
- ...requestOptions?.watch === true && { watch: true }
8017
+ ...watch && { watch: true }
7677
8018
  // todo: why do we query for watchers?
7678
8019
  // watchers: { limit: this.pageSize },
7679
- });
7680
- items = this.getCanonicalQueryItems(messages.map(formatMessage));
7681
- const cursor = this.getCursorFromQueryResults({ direction, items });
7682
- tailward = cursor.tailward;
7683
- headward = cursor.headward;
7684
- }
7685
- return { items, headward, tailward };
8020
+ },
8021
+ void 0
8022
+ );
8023
+ return { channelResponse, source: "channel", watch };
7686
8024
  };
8025
+ /**
8026
+ * Makes the interval holding the message the active one, querying the page around it when it is
8027
+ * not loaded. Resolves `false` when the message cannot be shown, or when a later claim on the
8028
+ * active interval (see `claimActiveInterval`) was made before the page arrived.
8029
+ */
7687
8030
  this.jumpToMessage = async (messageId, {
7688
8031
  focusReason,
7689
8032
  focusSignalTtlMs,
@@ -7694,7 +8037,6 @@ var MessageIntervalPaginator = class extends BasePaginator {
7694
8037
  const watch = !!watchChannel && !this.parentMessageId && !this.config.doRequest && this.channel.watchStatus !== ChannelWatchStatus.Watching;
7695
8038
  let localMessage = this.getItem(messageId);
7696
8039
  let interval;
7697
- let state;
7698
8040
  if (localMessage) {
7699
8041
  interval = this.locateIntervalForItem(localMessage);
7700
8042
  if (interval && !isLogicalInterval(interval) && !interval.itemIds.includes(messageId)) {
@@ -7704,19 +8046,17 @@ var MessageIntervalPaginator = class extends BasePaginator {
7704
8046
  }
7705
8047
  }
7706
8048
  if (!watch && localMessage && interval && !isLogicalInterval(interval)) {
7707
- state = {
7708
- hasMoreHead: interval.hasMoreHead,
7709
- hasMoreTail: interval.hasMoreTail,
7710
- cursor: this.getCursorFromInterval(interval),
7711
- items: this.intervalToItems(interval)
7712
- };
8049
+ this.claimActiveInterval();
8050
+ this.showLoadedInterval(interval);
7713
8051
  } else {
7714
8052
  const result = await this.executeQuery({
8053
+ claimsActiveInterval: true,
7715
8054
  // Always send a limit: the replies endpoint ignores `id_around` without one.
7716
8055
  queryShape: { id_around: messageId, limit: pageSize ?? this.pageSize },
7717
8056
  ...watch && { requestOptions: { watch: true } },
7718
8057
  updateState: false
7719
8058
  });
8059
+ if (result?.isSuperseded) return false;
7720
8060
  localMessage = this.getItem(messageId);
7721
8061
  if (!localMessage || !result || !result.targetInterval) {
7722
8062
  this.channel.getClient().notifications.addError({
@@ -7727,19 +8067,18 @@ var MessageIntervalPaginator = class extends BasePaginator {
7727
8067
  return false;
7728
8068
  }
7729
8069
  interval = result.targetInterval;
7730
- state = isLogicalInterval(interval) ? result.stateCandidate : {
7731
- ...result.stateCandidate,
7732
- hasMoreHead: interval.hasMoreHead,
7733
- hasMoreTail: interval.hasMoreTail,
7734
- // Falls back to the interval-derived cursor when the stateCandidate is partial.
7735
- cursor: result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
7736
- items: this.intervalToItems(interval)
7737
- };
7738
- }
7739
- if (!this.isActiveInterval(interval)) {
7740
- this.setActiveInterval(interval, { updateState: false });
8070
+ this.showInterval(
8071
+ interval,
8072
+ isLogicalInterval(interval) ? result.stateCandidate : {
8073
+ ...result.stateCandidate,
8074
+ hasMoreHead: interval.hasMoreHead,
8075
+ hasMoreTail: interval.hasMoreTail,
8076
+ // Falls back to the interval-derived cursor when the stateCandidate is partial.
8077
+ cursor: result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
8078
+ items: this.intervalToItems(interval)
8079
+ }
8080
+ );
7741
8081
  }
7742
- if (state) this.state.partialNext(state);
7743
8082
  if (!suppressFocusSignal) {
7744
8083
  this.emitMessageFocusSignal({
7745
8084
  messageId,
@@ -7749,15 +8088,24 @@ var MessageIntervalPaginator = class extends BasePaginator {
7749
8088
  }
7750
8089
  return true;
7751
8090
  };
8091
+ /**
8092
+ * Shows the window holding the latest message and jumps to that message. Without a loaded head
8093
+ * window (see {@link latestHeadInterval}), the newest page is queried first: no cursor, so it
8094
+ * holds the latest message however many pages are missing. The page merges with a window it
8095
+ * overlaps and is a window of its own otherwise, and is shown either way. Resolves `false` when
8096
+ * the latest message cannot be shown, or when a later claim on the active interval (see
8097
+ * `claimActiveInterval`) was made before the page arrived: that page is then only stored.
8098
+ */
7752
8099
  this.jumpToTheLatestMessage = async (options) => {
7753
- let latestMessageId;
7754
- if (!this.itemIntervals[0]?.isHead) {
7755
- await this.executeQuery({ direction: "headward", updateState: false });
7756
- }
7757
- const headInterval = this.itemIntervals[0];
7758
- if (headInterval?.isHead) {
7759
- latestMessageId = headInterval.itemIds.slice(-1)[0];
8100
+ if (!this.latestHeadInterval) {
8101
+ const result = await this.executeQuery({
8102
+ claimsActiveInterval: true,
8103
+ queryShape: { limit: this.pageSize },
8104
+ updateState: false
8105
+ });
8106
+ if (result?.isSuperseded) return false;
7760
8107
  }
8108
+ const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
7761
8109
  if (!latestMessageId) {
7762
8110
  this.channel.getClient().notifications.addError({
7763
8111
  message: "Jump to latest message unsuccessful",
@@ -7773,101 +8121,102 @@ var MessageIntervalPaginator = class extends BasePaginator {
7773
8121
  });
7774
8122
  };
7775
8123
  /**
7776
- * Folds an already fetched newest (head) page into the loaded items without a query. A page that
7777
- * shares an ID with the loaded head merges in place (reconciling by ID, appending new items,
7778
- * keeping older pages), sets the tail boundary via {@link pageReachedChannelStart} and runs
7779
- * {@link reconcileHeadAgainstPage}. A disjoint page would weld the two across a gap, so the
7780
- * loaded set is rebuilt from it as a fresh head (`hasMoreTail: true`) and the gap loads when
7781
- * paginating older.
8124
+ * Reconciles the loaded newest messages with a fresh newest page, without issuing a query: they
8125
+ * are brought up to date in place — messages added and updated, those the page proves were
8126
+ * hard-deleted removed — rather than blanked and reloaded. The page comes from an external query
8127
+ * (a reload, a channel-list query, connection recovery). In an active paginator (see
8128
+ * {@link isActivePaginator}) the active interval stays active, the head window included
8129
+ * (changing it is `jumpToTheLatestMessage()`'s job); in an inactive one, the head window is shown.
8130
+ *
8131
+ * Where the page goes depends on the head window, the loaded window reaching the newest message:
7782
8132
  *
7783
- * Merges only when the head interval is loaded and in view (or only live content is loaded,
7784
- * which the page then anchors). When the caller jumped to an older window only offline
7785
- * hard-deletes are pruned from the hidden head. An empty page never wipes the list, except that
7786
- * with `options.candidateIds` it reads as "the channel has no messages". The query shape is
7787
- * recorded on every exit (see `recordLoadedWindowQueryShape`).
8133
+ * 1. NO HEAD WINDOW (only live messages, a jumped-to window, or a cleared head mark, see
8134
+ * {@link unmarkHead}) - the page becomes the head window, merging with the windows it
8135
+ * overlaps, live messages included, minus what it proves was hard-deleted. It is shown if the
8136
+ * live messages it absorbed were active; an active window that it overlaps grows. A
8137
+ * page separated by a gap from the window whose head mark was cleared is placed as in 2.
7788
8138
  *
7789
- * @param page - The fetched newest window (may be empty). Ingest normalizes `created_at` order.
7790
- * @param options - See {@link MergeNewestPageOptions}. Omit to prune only within the page's own
7791
- * span.
8139
+ * 2. SEPARATED BY A GAP (see {@link isSeparatedFromHeadByGap}) - merging would weld the two
8140
+ * across the gap, hiding the messages in between, so the page takes the place of the head
8141
+ * window (see {@link placeNewestPageAcrossGap}): stored beside the active interval when that
8142
+ * is an older window, shown in place of the loaded windows otherwise.
8143
+ *
8144
+ * 3. OTHERWISE - the page merges into the head window, which keeps every loaded message and drops
8145
+ * what the page proves was hard-deleted (see {@link reconcileHeadAgainstPage}). An active head
8146
+ * window gets its tail boundary from the page (see {@link showHeadInterval}); otherwise the
8147
+ * active interval stays active, and grows into the head window if the page overlaps it.
8148
+ *
8149
+ * Only a gap drops loaded windows, never an older active window, and with nothing loaded it
8150
+ * does nothing: placing a first page is {@link placeQueryPage}'s job. An empty page changes
8151
+ * nothing on its own but, given a pre-fetch snapshot (`options.headIntervalItemIdsAtRequest`), is
8152
+ * reconciled as "the channel has no messages": every server-confirmed message of the head window
8153
+ * is removed.
8154
+ *
8155
+ * The query shape of the loaded window is recorded on every exit (see
8156
+ * `recordLoadedWindowQueryShape`): a window left without one loses itself on the next pagination.
8157
+ *
8158
+ * @param page - The fetched newest window (may be empty). `created_at` order is normalized on
8159
+ * ingest.
8160
+ * @param options - See {@link ReconcileNewestMessagesOptions}. Omit to prune only within the
8161
+ * page's own span.
7792
8162
  */
7793
- this.mergeNewestPage = (page, options) => {
7794
- this._mergeNewestPage(page, options);
8163
+ this.reconcileNewestMessages = (page, options) => {
8164
+ if (this.state.getLatestValue().lastQueryError) {
8165
+ this.state.partialNext({ lastQueryError: void 0 });
8166
+ }
8167
+ this._reconcileNewestMessages(page, options);
7795
8168
  this.recordLoadedWindowQueryShape();
7796
8169
  };
7797
- this._mergeNewestPage = (page, options) => {
8170
+ this._reconcileNewestMessages = (page, options) => {
7798
8171
  const headInterval = this.itemIntervals[0];
7799
8172
  if (!headInterval?.isHead) {
7800
8173
  const logicalHead = this.liveHeadLogical;
7801
8174
  const hasAnchoredHead = this.itemIntervals.some(
7802
8175
  (interval2) => !isLogicalInterval(interval2) && interval2.isHead
7803
8176
  );
7804
- if (!logicalHead || hasAnchoredHead || !page?.length) return;
7805
- const takeOverView = this.isActiveInterval(logicalHead);
8177
+ if (!this.itemIntervals.length || hasAnchoredHead || !page?.length) return;
8178
+ const unmarkedHead = this.unmarkedHeadInterval;
8179
+ this.unmarkedHeadEdgeId = void 0;
8180
+ if (unmarkedHead && this.isSeparatedFromHeadByGap(unmarkedHead, page, options)) {
8181
+ this.placeNewestPageAcrossGap(page, unmarkedHead, options);
8182
+ return;
8183
+ }
8184
+ const takeOverView = !this.isActivePaginator() || !!logicalHead && this.isActiveInterval(logicalHead);
7806
8185
  const anchored = this.ingestPage({ page, isHead: true, setActive: false });
7807
- if (!anchored || !takeOverView) return;
7808
- const hasMoreTail2 = !this.pageReachedChannelStart(page, options);
7809
- anchored.hasMoreTail = hasMoreTail2;
7810
- anchored.isTail = !hasMoreTail2;
7811
- this.setActiveInterval(anchored, { updateState: false });
7812
- this.state.partialNext({
7813
- items: this.intervalToItems(anchored),
7814
- hasMoreHead: false,
7815
- hasMoreTail: hasMoreTail2,
7816
- cursor: {
7817
- headward: null,
7818
- tailward: hasMoreTail2 ? anchored.itemIds[0] ?? null : null
8186
+ if (!anchored) return;
8187
+ this.reconcileHeadAgainstPage(page, options);
8188
+ if (!takeOverView) {
8189
+ if (this.isActiveInterval(anchored)) {
8190
+ this.publishActiveIntervalGrownIntoHead();
7819
8191
  }
7820
- });
8192
+ return;
8193
+ }
8194
+ this.showHeadInterval(page, options);
7821
8195
  return;
7822
8196
  }
7823
8197
  const wasAtChannelStart = !this.state.getLatestValue().hasMoreTail;
7824
8198
  const preMergeLoadedCount = headInterval.itemIds.length;
7825
- if (!this.isActiveInterval(headInterval)) {
7826
- this.reconcileHeadAgainstPage(page, options);
7827
- return;
7828
- }
7829
8199
  if (!page?.length) {
7830
8200
  this.reconcileHeadAgainstPage([], options);
7831
8201
  return;
7832
8202
  }
7833
- const loadedIds = new Set(headInterval.itemIds);
7834
- const overlapsLoadedHead = page.some((item) => loadedIds.has(this.getItemId(item)));
7835
- if (!overlapsLoadedHead) {
7836
- this.setIntervals([]);
7837
- this.setActiveInterval(void 0);
7838
- const resetInterval = this.ingestPage({
7839
- page,
7840
- isHead: true,
7841
- // The loaded head was entirely older than this window, so older data (the gap) always exists.
7842
- isTail: false,
7843
- setActive: false
7844
- });
7845
- if (!resetInterval) return;
7846
- this.setActiveInterval(resetInterval, { updateState: false });
7847
- this.state.partialNext({
7848
- items: this.intervalToItems(resetInterval),
7849
- cursor: this.getCursorFromInterval(resetInterval),
7850
- hasMoreHead: resetInterval.hasMoreHead,
7851
- hasMoreTail: resetInterval.hasMoreTail
7852
- });
8203
+ if (this.isSeparatedFromHeadByGap(headInterval, page, options)) {
8204
+ this.placeNewestPageAcrossGap(page, headInterval, options);
7853
8205
  return;
7854
8206
  }
7855
- const interval = this.ingestPage({ page, isHead: true, setActive: false });
7856
- if (!interval) return;
7857
- const hasMoreTail = !this.pageReachedChannelStart(page, options);
7858
- interval.hasMoreTail = hasMoreTail;
7859
- interval.isTail = !hasMoreTail;
7860
- this.setActiveInterval(interval, { updateState: false });
7861
- this.state.partialNext({
7862
- items: this.intervalToItems(interval),
7863
- hasMoreHead: false,
7864
- hasMoreTail,
7865
- // The oldest loaded ID (IDs are `created_at` ascending), `null` at the channel start.
7866
- cursor: {
7867
- headward: null,
7868
- tailward: hasMoreTail ? interval.itemIds[0] ?? null : null
7869
- }
8207
+ if (!this.isActiveInterval(headInterval)) {
8208
+ this.reconcileHeadAgainstPage(page, options);
8209
+ this.mergePageIntoInactiveHead(page, options);
8210
+ return;
8211
+ }
8212
+ const interval = this.ingestPage({
8213
+ page,
8214
+ isHead: true,
8215
+ setActive: false,
8216
+ targetIntervalId: headInterval.id
7870
8217
  });
8218
+ if (!interval) return;
8219
+ this.showHeadInterval(page, options);
7871
8220
  const belowWindow = this.reconcileHeadAgainstPage(page, options);
7872
8221
  const requestedLimit = options?.requestedLimit;
7873
8222
  if (belowWindow.length && wasAtChannelStart && typeof requestedLimit === "number" && requestedLimit >= preMergeLoadedCount) {
@@ -8012,25 +8361,23 @@ var MessageIntervalPaginator = class extends BasePaginator {
8012
8361
  /**
8013
8362
  * The last loaded message created at or before `timestamp` (a floor), or `null` when it precedes
8014
8363
  * every loaded message. With `exactTsMatch`, only a message created exactly at `timestamp` matches.
8015
- * Searches the newest loaded window (already sorted) in O(log n). Used by the receipts tracker to
8016
- * resolve read/delivered cursors.
8364
+ * Searches the loaded windows from the head down (each already sorted, O(log n) per window): the
8365
+ * first holding a message at or before `timestamp` holds the answer. Used by the receipts tracker
8366
+ * to resolve read/delivered cursors.
8017
8367
  */
8018
8368
  this.findItemByTimestamp = (timestamp, exactTsMatch = false) => {
8019
- const items = this.headItems;
8020
- if (!items.length) return null;
8021
- const firstAfter = lowerBound(items.length, (i) => {
8022
- const t = getMessageCreatedAtTimestamp(items[i]);
8023
- return t === null || t > timestamp;
8024
- });
8025
- if (firstAfter === 0) return null;
8026
- const found = items[firstAfter - 1];
8027
- const foundTimestamp = getMessageCreatedAtTimestamp(found);
8028
- if (foundTimestamp === null) return null;
8029
- if (!exactTsMatch) return found;
8030
- return foundTimestamp === timestamp ? found : null;
8031
- };
8032
- this.filterQueryResults = (items) => items.filter(this.shouldIncludeMessageInInterval.bind(this));
8369
+ for (const interval of this.sortIntervals(this.itemIntervals)) {
8370
+ const found = this.findItemByTimestampIn(
8371
+ this.intervalToItems(interval),
8372
+ timestamp,
8373
+ exactTsMatch
8374
+ );
8375
+ if (found !== void 0) return found;
8376
+ }
8377
+ return null;
8378
+ };
8033
8379
  this.channel = channel;
8380
+ this.thread = thread;
8034
8381
  this.parentMessageId = parentMessageId;
8035
8382
  this._id = id ?? `message-paginator-${generateUUIDv4()}`;
8036
8383
  this._requestSort = resolvedRequestSort;
@@ -8108,7 +8455,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8108
8455
  buildIntervalBehaviour() {
8109
8456
  if (!this.intervalBehaviour) {
8110
8457
  this.intervalBehaviour = {
8111
- deriveCursor: makeDeriveCursor(this),
8458
+ deriveCursor: (ctx) => this.deriveCursorFromPage(ctx),
8112
8459
  itemOrderComparator: makeComparator({
8113
8460
  sort: this._itemOrder,
8114
8461
  resolvePathValue: resolveDotPathValue,
@@ -8151,63 +8498,567 @@ var MessageIntervalPaginator = class extends BasePaginator {
8151
8498
  getNextQueryShape({
8152
8499
  direction
8153
8500
  }) {
8501
+ const cursorId = direction ? this.cursor?.[direction] : void 0;
8154
8502
  return {
8155
8503
  limit: this.pageSize,
8156
- [direction === "tailward" ? "id_lt" : "id_gt"]: direction && this.cursor?.[direction]
8504
+ ...cursorId && { [direction === "tailward" ? "id_lt" : "id_gt"]: cursorId }
8157
8505
  };
8158
8506
  }
8159
8507
  /**
8160
- * Seeds the paginator with the page a channel-open query just fetched (`Channel.query` with
8161
- * `watch`/`create`, `client.hydrateChannels`). Those paths hydrate the read state in the same
8162
- * synchronous tick (`Channel._initializeState`), and the read patch drives
8163
- * `MessageReceiptsTracker`, which resolves cursors against this paginator
8164
- * (`findItemByTimestamp`) when the server omits the message IDs, so the paginator must be
8165
- * populated first. First-page reconciliation also takes the unread snapshot.
8166
- *
8167
- * The page is not always the latest window: a channel can open around a message (`id_around` /
8168
- * `created_at_around`), so the original pagination options are passed as the query shape and
8169
- * `postQueryReconcile` applies jump semantics instead of flagging the window as the newest page.
8508
+ * Runs the query pipeline (see `BasePaginator.executeQuery`). A query that goes to the channel —
8509
+ * not a thread's reply list, not a custom `doRequest` — runs as a tracked query of the channel
8510
+ * (`Channel.runTrackedQuery`), so the channel store keeps the channel until the query ends. A
8511
+ * disposed channel's query is not tracked: its fetch step is refused, and fails as any failed
8512
+ * request does.
8513
+ */
8514
+ executeQuery(params = {}) {
8515
+ const queriesChannel = !this.parentMessageId && !this.config.doRequest && !this.channel.pendingDisposal;
8516
+ if (!queriesChannel) return super.executeQuery(params);
8517
+ return this.channel.runTrackedQuery(() => super.executeQuery(params));
8518
+ }
8519
+ /**
8520
+ * The extracting step of the query pipeline: the messages in item order and their cursors, which
8521
+ * a custom `doRequest` reports and which are derived from the messages otherwise.
8522
+ */
8523
+ extractQueryPage(response, { direction }) {
8524
+ if (response.source === "doRequest") {
8525
+ const { cursor, items: items2 } = response.doRequestResponse;
8526
+ return {
8527
+ headward: !direction || direction === "headward" ? cursor?.headward : void 0,
8528
+ items: this.getCanonicalQueryItems(items2),
8529
+ tailward: !direction || direction === "tailward" ? cursor?.tailward : void 0
8530
+ };
8531
+ }
8532
+ const messages = response.source === "replies" ? response.repliesResponse.messages : response.channelResponse.messages ?? [];
8533
+ const items = this.getCanonicalQueryItems(messages.map(formatMessage));
8534
+ return { items, ...this.getCursorFromQueryResults({ direction, items }) };
8535
+ }
8536
+ /**
8537
+ * The last step of the query pipeline: the rest of a channel query's response, applied once its
8538
+ * page is placed (see `Channel.applyChannelStateFromResponse`). The other sources return nothing
8539
+ * else.
8540
+ */
8541
+ applyQueryResponseRest(response, _placeParams) {
8542
+ if (response.source === "channel") {
8543
+ this.channel.applyChannelStateFromResponse(response.channelResponse, {
8544
+ isLatestMessageSet: false,
8545
+ watch: response.watch
8546
+ });
8547
+ }
8548
+ }
8549
+ /**
8550
+ * Whether this paginator is active: the thread it lists is active (see `Thread.activate()`), or,
8551
+ * without a thread, its channel is (see `Channel.activate()`). A page from a query an active
8552
+ * paginator did not run leaves its active interval active; an inactive paginator shows a fresh
8553
+ * newest page instead, also one separated from the loaded messages by a gap (see
8554
+ * {@link reconcileNewestMessages}).
8555
+ */
8556
+ isActivePaginator() {
8557
+ return (this.thread ?? this.channel).active;
8558
+ }
8559
+ /**
8560
+ * Places a page from an external query — one this paginator did not run, whose page the caller
8561
+ * chose — in the windows it belongs to, never removing anything loaded. Bringing the loaded
8562
+ * newest messages up to date with a fresh newest page, removals included, is
8563
+ * {@link reconcileNewestMessages}'s job instead.
8564
+ *
8565
+ * External queries are a channel query (`watch()`, see {@link prepareExternalQuery}), the
8566
+ * channel list's query (`client.hydrateChannels`), and the channel state the pinned list's first
8567
+ * page comes with. `messagePaginationParams` are the
8568
+ * options the page was queried with; they decide where it goes:
8569
+ *
8570
+ * - The newest page: when no window is active yet (nothing loaded, or only live messages), its
8571
+ * window becomes the active one, as the channel's first page. When the active window is the
8572
+ * newest window, the page lands in it.
8573
+ * - Any other page — a page at a cursor or around a message, or the newest page while an older
8574
+ * window is active — is only stored, as a separate interval merged only with an interval it
8575
+ * overlaps.
8576
+ *
8577
+ * The active interval stays active: changing it is this paginator's own methods' job
8578
+ * (`jumpToMessage()` and the like). The exception is an inactive paginator (see
8579
+ * {@link isActivePaginator}), where the newest page is shown as when no window is
8580
+ * active. A newest
8581
+ * page for loaded messages goes to {@link reconcileNewestMessages} instead
8582
+ * (`prepareExternalQuery`, the channel list's query). When a page lands in the active window,
8583
+ * overlaps it, or takes in an active window of live messages only, that window is shown again
8584
+ * with the page. The paginator's own queries are left alone too: a running one keeps its loading
8585
+ * flag, and its last query error and query shape stay.
8586
+ *
8587
+ * It runs synchronously, so a caller can apply the rest of the response right after with the page
8588
+ * in place, as it has to: read and delivery positions that come without a message id are looked
8589
+ * up among the loaded messages.
8590
+ *
8591
+ * Returns whether it showed the page as a first page.
8592
+ */
8593
+ placeExternalQueryPage(page, requestedPageSize, messagePaginationParams) {
8594
+ const queryShape = {
8595
+ ...messagePaginationParams,
8596
+ limit: requestedPageSize
8597
+ };
8598
+ const isJump = this.isJumpQueryShape(queryShape);
8599
+ const isNewestPage = this.isHeadPageQueryShape(queryShape);
8600
+ const items = this.getCanonicalQueryItems(page);
8601
+ const { head: headItem, tail: tailItem } = this.getPagePaginationEdges(items);
8602
+ const isFirstPage = typeof this.items === "undefined" || isNewestPage;
8603
+ const activeInterval = this.itemIntervals.find(
8604
+ (interval) => this.isActiveInterval(interval)
8605
+ );
8606
+ const hasActiveInterval = !!activeInterval && !isLogicalInterval(activeInterval) && this.isActivePaginator();
8607
+ const landsInActiveInterval = isNewestPage && this.isActiveIntervalAtHead;
8608
+ const showsPage = isNewestPage && (!hasActiveInterval || landsInActiveInterval);
8609
+ const placed = this.placePage(
8610
+ {
8611
+ startsSeparateInterval: !landsInActiveInterval,
8612
+ // A jump/around page spans both directions; a page at a cursor pages the way its cursor
8613
+ // points, and a plain latest page paginates tailward (older).
8614
+ direction: isJump ? void 0 : getLinearQueryDirection(queryShape) ?? "tailward",
8615
+ isFirstPage,
8616
+ queryShape,
8617
+ requestedPageSize,
8618
+ results: {
8619
+ items,
8620
+ headward: isJump ? headItem?.id : void 0,
8621
+ tailward: tailItem?.id
8622
+ },
8623
+ updateState: showsPage
8624
+ },
8625
+ { endsQuery: false }
8626
+ );
8627
+ const tookInActiveInterval = !!activeInterval && !this.itemIntervals.some((interval) => this.isActiveInterval(interval));
8628
+ const intervalTakingOver = tookInActiveInterval ? placed.targetInterval : null;
8629
+ if (intervalTakingOver) {
8630
+ this.setActiveInterval(intervalTakingOver, { updateState: false });
8631
+ const { cursor, hasMoreHead, hasMoreTail } = placed.stateCandidate;
8632
+ this.publishActiveInterval({ cursor, hasMoreHead, hasMoreTail });
8633
+ }
8634
+ if (showsPage) {
8635
+ this.recordLoadedWindowQueryShape();
8636
+ }
8637
+ return showsPage && isFirstPage;
8638
+ }
8639
+ /**
8640
+ * Whether messages are loaded for {@link reconcileNewestMessages} to bring up to date. A list
8641
+ * loaded empty has none (no interval, not even live messages), so a fresh newest page is placed
8642
+ * as a first page instead ({@link placeExternalQueryPage}); reconciling would find nothing to
8643
+ * merge it into and drop it.
8644
+ */
8645
+ get canReconcileNewestMessages() {
8646
+ return typeof this.items !== "undefined" && this.itemIntervals.length > 0;
8647
+ }
8648
+ /**
8649
+ * The snapshot a newest page is reconciled against (see
8650
+ * {@link ReconcileNewestMessagesOptions.headIntervalItemIdsAtRequest}): the IDs of the head
8651
+ * window's server-confirmed messages. Take it right before the request goes out. Unsent messages
8652
+ * are left out: one confirmed during the request proves neither that the page connects to the
8653
+ * head window nor, when the page lacks it, that it was deleted. `undefined` while no head window
8654
+ * is loaded.
8655
+ *
8656
+ * @internal
8657
+ */
8658
+ getHeadIntervalItemIdsAtRequest() {
8659
+ const head = this.anchoredHeadInterval;
8660
+ if (!head) return void 0;
8661
+ return new Set(head.itemIds.filter((id) => this.isServerConfirmedItemId(id)));
8662
+ }
8663
+ /**
8664
+ * Whether the loaded message with this ID is server-confirmed
8665
+ * (see {@link isServerConfirmedMessage}).
8666
+ */
8667
+ isServerConfirmedItemId(id) {
8668
+ const message = this.getItem(id);
8669
+ return !!message && this.isServerConfirmedMessage(message);
8670
+ }
8671
+ /**
8672
+ * Prepares an external query for a page of these messages: the channel query `channel.watch()`
8673
+ * sends with the `messages` options its caller gave. Call it before
8674
+ * sending the query, and place the returned page with `placePage` before the response's read
8675
+ * state is applied: the read state is resolved against the loaded messages.
8676
+ *
8677
+ * - `messagePaginationParams`: the options to send as the query's `messages`, with `limit` set to
8678
+ * the page size when not given.
8679
+ * - `isNewestPage`: whether the query asks for the newest page — no cursor, not around a message,
8680
+ * and some messages.
8681
+ * - `placePage`: places the returned page. The newest page goes to
8682
+ * {@link placeExternalNewestPage}, reconciled against the messages loaded when the query was
8683
+ * prepared; any other page is placed by {@link placeExternalQueryPage}. A query for no messages
8684
+ * (`limit: 0`) places nothing. Returns whether it showed a first page.
8685
+ */
8686
+ prepareExternalQuery(messages) {
8687
+ const messagePaginationParams = {
8688
+ ...messages,
8689
+ limit: messages?.limit ?? this.pageSize
8690
+ };
8691
+ const limit = messagePaginationParams.limit ?? this.pageSize;
8692
+ if (isQueryForNoMessages(limit)) {
8693
+ return { messagePaginationParams, isNewestPage: false, placePage: () => false };
8694
+ }
8695
+ const isNewestPage = this.isHeadPageQueryShape(messagePaginationParams);
8696
+ const headIntervalItemIdsAtRequest = isNewestPage ? this.getHeadIntervalItemIdsAtRequest() : void 0;
8697
+ return {
8698
+ messagePaginationParams,
8699
+ isNewestPage,
8700
+ placePage: (page) => isNewestPage ? this.placeExternalNewestPage(page, {
8701
+ headIntervalItemIdsAtRequest,
8702
+ requestedLimit: limit
8703
+ }) : this.placeExternalQueryPage(page, limit, messagePaginationParams)
8704
+ };
8705
+ }
8706
+ /**
8707
+ * Places the newest page of an external query (a channel query, the channel list's query): it
8708
+ * reconciles the loaded newest messages ({@link reconcileNewestMessages}), or is placed as a
8709
+ * first page when none are loaded ({@link placeExternalQueryPage}). A query for no messages
8710
+ * (`requestedLimit: 0`) places nothing. Returns whether it showed a first page.
8711
+ *
8712
+ * @internal
8713
+ */
8714
+ placeExternalNewestPage(page, {
8715
+ headIntervalItemIdsAtRequest,
8716
+ requestedLimit
8717
+ }) {
8718
+ if (isQueryForNoMessages(requestedLimit)) return false;
8719
+ if (!this.canReconcileNewestMessages) {
8720
+ return this.placeExternalQueryPage(page, requestedLimit);
8721
+ }
8722
+ this.reconcileNewestMessages(page, { headIntervalItemIdsAtRequest, requestedLimit });
8723
+ return false;
8724
+ }
8725
+ isJumpQueryShape(queryShape) {
8726
+ return !!queryShape?.id_around || !!queryShape?.created_at_around;
8727
+ }
8728
+ /** Only a query without a cursor and not around a message returns the newest page. */
8729
+ isHeadPageQueryShape(queryShape) {
8730
+ return !queryShape || !this.isJumpQueryShape(queryShape) && !getLinearQueryDirection(queryShape);
8731
+ }
8732
+ /** A jump sends its own `limit`: head/tail flags are derived against it, not `pageSize`. */
8733
+ getRequestedPageSize(queryShape) {
8734
+ return queryShape && this.isJumpQueryShape(queryShape) ? queryShape.limit ?? this.pageSize : this.pageSize;
8735
+ }
8736
+ /**
8737
+ * Shows a loaded window as it is: its items, its own pagination flags and the cursor continuing
8738
+ * it. Claiming the active interval is the caller's choice (see `claimActiveInterval`).
8739
+ */
8740
+ showLoadedInterval(interval) {
8741
+ this.showInterval(interval, {
8742
+ hasMoreHead: interval.hasMoreHead,
8743
+ hasMoreTail: interval.hasMoreTail,
8744
+ cursor: this.getCursorFromInterval(interval),
8745
+ items: this.intervalToItems(interval)
8746
+ });
8747
+ }
8748
+ /** Makes `interval` the active window and publishes `state` for it in one update. */
8749
+ showInterval(interval, state) {
8750
+ if (!this.isActiveInterval(interval)) {
8751
+ this.setActiveInterval(interval, { updateState: false });
8752
+ }
8753
+ this.state.partialNext(state);
8754
+ this.recordLoadedWindowQueryShape();
8755
+ }
8756
+ /**
8757
+ * The head window when it is the newest loaded interval, so its newest message is the latest
8758
+ * one; `undefined` while no head window is loaded or live messages newer than it are.
8759
+ */
8760
+ get latestHeadInterval() {
8761
+ const newest = this.itemIntervals[0];
8762
+ return newest && !isLogicalInterval(newest) && newest.isHead ? newest : void 0;
8763
+ }
8764
+ /**
8765
+ * Shows the head window a fresh newest page merged into, with no newer messages to load. It has
8766
+ * older ones unless the page reached the channel start (see {@link pageReachedChannelStart});
8767
+ * `isTail` follows, which also clears a stale offline-DB `isTail: true` that would let
8768
+ * `intervalsOverlap` weld a far page across a gap.
8769
+ */
8770
+ showHeadInterval(page, options) {
8771
+ const interval = this.anchoredHeadInterval;
8772
+ if (!interval) return;
8773
+ const hasMoreTail = !this.pageReachedChannelStart(page, options);
8774
+ interval.hasMoreTail = hasMoreTail;
8775
+ interval.isTail = !hasMoreTail;
8776
+ this.setActiveInterval(interval, { updateState: false });
8777
+ const flags = { hasMoreHead: false, hasMoreTail };
8778
+ this.publishActiveInterval({
8779
+ ...flags,
8780
+ cursor: this.getCursorFromInterval(interval, flags)
8781
+ });
8782
+ }
8783
+ /**
8784
+ * Whether a fresh newest page and the head window (or the window whose head mark was cleared, see
8785
+ * {@link unmarkedHeadInterval}) are separated by a gap, with messages between them possibly not
8786
+ * loaded. They are not when the two together form one unbroken stretch of the channel:
8787
+ *
8788
+ * - the page starts inside the head window (see {@link pageStartsInsideHead});
8789
+ * - the page covers the head window (see {@link pageCoversHead});
8790
+ * - the page reached the channel start (see {@link pageReachedChannelStart}), so nothing older
8791
+ * than it exists to be missing.
8792
+ *
8793
+ * Sharing a message is not enough on its own: a message the user sent while offline is confirmed
8794
+ * by the server before the reconnect's newest page is requested, so it sits at the top of the
8795
+ * head window and in the page, with the messages missed below it in neither. For example, the
8796
+ * window holds m1–m100 and the user's queued "hello"; the server got m101–m210 meanwhile. A page
8797
+ * of 25 holds m187–m210 and "hello": it does not start inside the window (m187 was never loaded)
8798
+ * nor cover it (m1 is not in it), so it is past a gap. When the user wrote the last 10 loaded
8799
+ * messages and others sent 20 since, a page of 25 holds the user's last 5 and the 20 new ones:
8800
+ * its oldest was loaded, so it starts inside the window.
8801
+ *
8802
+ * A message missed while the socket was down comes with connection recovery's newest page.
8803
+ */
8804
+ isSeparatedFromHeadByGap(head, page, options) {
8805
+ if (this.pageStartsInsideHead(head, page, options)) return false;
8806
+ if (this.pageCoversHead(head, page)) return false;
8807
+ if (this.pageReachedChannelStart(page, options)) return false;
8808
+ return true;
8809
+ }
8810
+ /**
8811
+ * Whether the page's oldest message the head window could hold (see
8812
+ * {@link getPageOldestHoldableMessage}) was in the head window when the request went out. The
8813
+ * page runs unbroken from that message to the newest and the window is taken to run unbroken
8814
+ * below it, so nothing between them is missing.
8815
+ *
8816
+ * With a snapshot of the request (`options.headIntervalItemIdsAtRequest`), the message must be
8817
+ * in it and held by no window other than the head window: a message that reached the window
8818
+ * during the request, live or as a send confirmed meanwhile, may sit above messages the window
8819
+ * never loaded. One no longer loaded at all still counts: if the head window holds messages
8820
+ * older than it, the window ran unbroken through it and it was removed (e.g. hard-deleted);
8821
+ * if not, the page covers the window anyway. Without a snapshot, the message must be in the
8822
+ * head window and server-confirmed now.
8823
+ *
8824
+ * The window is not unbroken below a send the server confirmed while the channel received no
8825
+ * events, such as one replayed from the offline queue before the reconnect's newest page is
8826
+ * requested. If that send is exactly the page's oldest (as many newer messages as the page has
8827
+ * room for were sent after it), the page is taken to start inside the window although messages
8828
+ * below the send were missed. The page and the window cannot tell this apart from a send
8829
+ * confirmed while events were arriving.
8830
+ */
8831
+ pageStartsInsideHead(head, page, options) {
8832
+ const pageOldest = this.getPageOldestHoldableMessage(page);
8833
+ if (!pageOldest) return false;
8834
+ const id = this.getItemId(pageOldest);
8835
+ const idsAtRequest = options?.headIntervalItemIdsAtRequest;
8836
+ if (!idsAtRequest) {
8837
+ return head.itemIds.includes(id) && this.isServerConfirmedItemId(id);
8838
+ }
8839
+ const heldByAnotherWindow = !head.itemIds.includes(id) && !!this.getItem(id);
8840
+ return idsAtRequest.has(id) && !heldByAnotherWindow;
8841
+ }
8842
+ /**
8843
+ * Whether the page spans the whole head window: the window holds no server-confirmed message
8844
+ * older than the page. What the window holds beyond the page is newer (it arrived as an event
8845
+ * after the page was produced) or unsent (it carries the device's clock).
8846
+ */
8847
+ pageCoversHead(head, page) {
8848
+ const pageOldest = this.getPageOldestMessage(page);
8849
+ if (!pageOldest) return true;
8850
+ return !head.itemIds.some((id) => {
8851
+ const message = this.getItem(id);
8852
+ return !!message && this.isServerConfirmedMessage(message) && this.aIsMoreTailwardThanB(message, pageOldest);
8853
+ });
8854
+ }
8855
+ /**
8856
+ * The page's oldest message that the head window could have loaded: server-confirmed and kept
8857
+ * in intervals (see {@link filterQueryResults}). A message the window filters out, such as a
8858
+ * shadowed one, would never be found in it. {@link pageCoversHead} compares with the page's
8859
+ * oldest message of any kind instead: it only needs the page's span.
8860
+ */
8861
+ getPageOldestHoldableMessage(page) {
8862
+ const holdable = this.filterQueryResults(page).filter(
8863
+ (message) => this.isServerConfirmedMessage(message)
8864
+ );
8865
+ return this.getPageOldestMessage(holdable);
8866
+ }
8867
+ /**
8868
+ * The window whose head mark was cleared last (see {@link unmarkHead}), while it is still loaded.
8869
+ * It reached the newest message until then, so a newest page is judged against it while no head
8870
+ * window is loaded.
8871
+ */
8872
+ get unmarkedHeadInterval() {
8873
+ const id = this.unmarkedHeadEdgeId;
8874
+ if (!id) return void 0;
8875
+ return this.itemIntervals.find(
8876
+ (interval) => !isLogicalInterval(interval) && interval.itemIds.includes(id)
8877
+ );
8878
+ }
8879
+ /**
8880
+ * Remembers the window by a message that stays in it: a server-confirmed one, as an unsent one
8881
+ * may be deleted or retried; the raw newest item only when the window holds none.
8882
+ */
8883
+ unmarkHead(interval) {
8884
+ const edge = this.getServerKnownEdges(interval).head ?? this.getIntervalPaginationEdges(interval)?.head;
8885
+ this.unmarkedHeadEdgeId = edge ? this.getItemId(edge) : void 0;
8886
+ super.unmarkHead(interval);
8887
+ }
8888
+ clearItemStorage() {
8889
+ this.unmarkedHeadEdgeId = void 0;
8890
+ super.clearItemStorage();
8891
+ }
8892
+ resetState() {
8893
+ this.unmarkedHeadEdgeId = void 0;
8894
+ super.resetState();
8895
+ }
8896
+ getPageOldestMessage(page) {
8897
+ return this.getPagePaginationEdges(this.getCanonicalQueryItems(page)).tail;
8898
+ }
8899
+ /**
8900
+ * Places a fresh newest page separated by a gap from `headWindow` (the head window, or the
8901
+ * window whose head mark was cleared, see {@link isSeparatedFromHeadByGap}). The page becomes
8902
+ * the head window either way, and the windows nothing brought up to date are dropped, as a
8903
+ * message deleted meanwhile would come back with them:
8904
+ *
8905
+ * - an active interval other than the head window (see {@link getActiveIntervalApartFromHead})
8906
+ * stays active, and the page is stored beside it (see
8907
+ * {@link storeNewestPageBesideActiveInterval});
8908
+ * - otherwise the page replaces the loaded windows and is shown (see
8909
+ * {@link replaceWindowsWithNewestPage}).
8910
+ */
8911
+ placeNewestPageAcrossGap(page, headWindow, options) {
8912
+ const activeInterval = this.getActiveIntervalApartFromHead(headWindow);
8913
+ if (activeInterval) {
8914
+ this.storeNewestPageBesideActiveInterval(page, activeInterval, options);
8915
+ } else {
8916
+ this.replaceWindowsWithNewestPage(page, options);
8917
+ }
8918
+ }
8919
+ /**
8920
+ * The active loaded window when it is not `headWindow`, such as a window jumped to; `undefined`
8921
+ * when `headWindow` or live messages only are active, and in an inactive paginator (see
8922
+ * {@link isActivePaginator}).
8923
+ */
8924
+ getActiveIntervalApartFromHead(headWindow) {
8925
+ if (!this.isActivePaginator()) return void 0;
8926
+ return this.itemIntervals.find(
8927
+ (interval) => !isLogicalInterval(interval) && this.isActiveInterval(interval) && interval.id !== headWindow.id
8928
+ );
8929
+ }
8930
+ /**
8931
+ * Replaces the loaded windows with a fresh newest page separated from the head window by a gap
8932
+ * (see {@link placeNewestPageAcrossGap}) and shows it. The page's window keeps the loaded
8933
+ * messages that must not be lost (see {@link getMessagesKeptAcrossGap}) and has older messages
8934
+ * to load.
8935
+ */
8936
+ replaceWindowsWithNewestPage(page, options) {
8937
+ const keptMessages = this.getMessagesKeptAcrossGap(page, this.itemIntervals);
8938
+ this.batch(
8939
+ () => {
8940
+ this.clearItemStorage();
8941
+ this.ingestPageAsHeadWindow(page, keptMessages, options);
8942
+ this.showHeadInterval(page, options);
8943
+ },
8944
+ { coalesce: true }
8945
+ );
8946
+ }
8947
+ /**
8948
+ * Stores a fresh newest page separated from the head window by a gap (see
8949
+ * {@link placeNewestPageAcrossGap}) as the head window, beside `activeInterval`, which stays
8950
+ * active and shown as it is. Every other loaded window is dropped and loads again on
8951
+ * demand. The page's window keeps the messages of the dropped windows that must not be lost (see
8952
+ * {@link getMessagesKeptAcrossGap}) and has older messages to load.
8953
+ *
8954
+ * The active interval keeps all its messages, unsent ones included, so nothing moves in the
8955
+ * shown list, and it is not brought up to date: a message deleted or edited meanwhile stays as it was
8956
+ * loaded. It can load newer messages, up to the head window it then joins.
8957
+ */
8958
+ storeNewestPageBesideActiveInterval(page, activeInterval, options) {
8959
+ const droppedWindows = this.itemIntervals.filter(
8960
+ (interval) => interval.id !== activeInterval.id
8961
+ );
8962
+ const keptMessages = this.getMessagesKeptAcrossGap(page, droppedWindows);
8963
+ const keepingIds = new Set(
8964
+ [...page, ...keptMessages].map((message) => this.getItemId(message))
8965
+ );
8966
+ this.batch(
8967
+ () => {
8968
+ this.dropWindows(droppedWindows, { keepingIds });
8969
+ this.unmarkedHeadEdgeId = void 0;
8970
+ activeInterval.isHead = false;
8971
+ const pageWindow = this.ingestPageAsHeadWindow(page, keptMessages, options);
8972
+ if (pageWindow && this.isActiveInterval(pageWindow)) {
8973
+ this.publishActiveIntervalGrownIntoHead();
8974
+ return;
8975
+ }
8976
+ this.markActiveIntervalBelowHead(activeInterval);
8977
+ },
8978
+ { coalesce: true }
8979
+ );
8980
+ }
8981
+ /**
8982
+ * Ingests a fresh newest page placed across a gap, with `keptMessages`, as the head window, which
8983
+ * has older messages to load, and removes from it what the page proves was hard-deleted (see
8984
+ * {@link reconcileHeadAgainstPage}). Returns the window the page landed in.
8985
+ */
8986
+ ingestPageAsHeadWindow(page, keptMessages, options) {
8987
+ const pageWindow = this.ingestPage({
8988
+ page: [...page, ...keptMessages],
8989
+ isHead: true,
8990
+ isTail: false,
8991
+ setActive: false
8992
+ });
8993
+ this.reconcileHeadAgainstPage(page, options);
8994
+ return pageWindow;
8995
+ }
8996
+ /**
8997
+ * Drops `windows` from storage and releases their messages, except those with `keepingIds`,
8998
+ * which the caller ingests again.
8999
+ */
9000
+ dropWindows(windows, { keepingIds }) {
9001
+ for (const window2 of windows) {
9002
+ this.dropInterval(window2.id);
9003
+ for (const id of window2.itemIds) {
9004
+ if (!keepingIds.has(id)) this._itemIndex.remove(id);
9005
+ }
9006
+ }
9007
+ }
9008
+ /**
9009
+ * Marks the active interval, which does not reach the newest message, as able to load newer
9010
+ * messages. Publishes the flag and cursor only when they changed, so the window shown stays as
9011
+ * it is.
9012
+ */
9013
+ markActiveIntervalBelowHead(window2) {
9014
+ window2.hasMoreHead = true;
9015
+ const cursor = this.getCursorFromInterval(window2);
9016
+ const shown = this.state.getLatestValue();
9017
+ if (shown.hasMoreHead && shown.cursor?.headward === cursor.headward) return;
9018
+ this.state.partialNext({ hasMoreHead: true, cursor });
9019
+ }
9020
+ /**
9021
+ * The messages of `windows`, missing from a newest page placed across a gap, that the page's
9022
+ * window keeps:
9023
+ *
9024
+ * - unsent messages (see {@link isServerConfirmedMessage});
9025
+ * - messages from the page's oldest on: those that arrived during the request stay, and
9026
+ * reconciling removes those the page proves were hard-deleted.
9027
+ */
9028
+ getMessagesKeptAcrossGap(page, windows) {
9029
+ const pageIds = new Set(page.map((message) => this.getItemId(message)));
9030
+ const pageOldest = this.getPageOldestMessage(page);
9031
+ const isOlderThanPage = (message) => !!pageOldest && this.aIsMoreTailwardThanB(message, pageOldest);
9032
+ return windows.flatMap((interval) => this.intervalToItems(interval)).filter(
9033
+ (message) => !pageIds.has(this.getItemId(message)) && (!this.isServerConfirmedMessage(message) || !isOlderThanPage(message))
9034
+ );
9035
+ }
9036
+ /**
9037
+ * Merges a fresh newest page, not separated by a gap, into the head window while another window
9038
+ * is shown. That window stays active and grows into the head window if the page overlaps it. In
9039
+ * an inactive paginator (see {@link isActivePaginator}), the head window is shown instead.
8170
9040
  */
8171
- seedFirstPageSync(messages, requestedPageSize, messagePaginationOptions, options) {
8172
- const queryShape = {
8173
- ...messagePaginationOptions,
8174
- limit: requestedPageSize
8175
- };
8176
- const isJump = this.isJumpQueryShape(queryShape);
8177
- if (options?.reconcile && !isJump && typeof this.items !== "undefined" && this.itemIntervals.length > 0) {
8178
- if (this.state.getLatestValue().lastQueryError) {
8179
- this.state.partialNext({ lastQueryError: void 0 });
8180
- }
8181
- this.mergeNewestPage(messages, {
8182
- candidateIds: options.candidateIds,
8183
- requestedLimit: requestedPageSize
8184
- });
8185
- return;
9041
+ mergePageIntoInactiveHead(page, options) {
9042
+ const interval = this.ingestPage({ page, isHead: true, setActive: false });
9043
+ if (!interval) return;
9044
+ if (!this.isActivePaginator()) {
9045
+ this.showHeadInterval(page, options);
9046
+ } else if (this.isActiveInterval(interval)) {
9047
+ this.publishActiveIntervalGrownIntoHead();
8186
9048
  }
8187
- this.postQueryReconcile({
8188
- // A jump/around page spans both directions; a plain latest page paginates tailward (older).
8189
- direction: isJump ? void 0 : "tailward",
8190
- isFirstPage: true,
8191
- queryShape,
8192
- requestedPageSize,
8193
- results: {
8194
- items: messages,
8195
- headward: isJump ? messages[messages.length - 1]?.id : void 0,
8196
- tailward: messages[0]?.id
8197
- }
8198
- });
8199
- }
8200
- isJumpQueryShape(queryShape) {
8201
- return !!queryShape?.id_around || !!queryShape?.created_at_around;
8202
9049
  }
8203
- /** A jump sends its own `limit`: head/tail flags are derived against it, not `pageSize`. */
8204
- getRequestedPageSize(queryShape) {
8205
- return queryShape && this.isJumpQueryShape(queryShape) ? queryShape.limit ?? this.pageSize : this.pageSize;
9050
+ /** Publishes the active interval once a newest page grew it into the head window. */
9051
+ publishActiveIntervalGrownIntoHead() {
9052
+ this.publishActiveInterval({
9053
+ hasMoreHead: false,
9054
+ cursor: { headward: null, tailward: this.cursor?.tailward ?? null }
9055
+ });
8206
9056
  }
8207
9057
  /**
8208
9058
  * Whether `page` proves it reached the channel's oldest message: the request was bounded by this
8209
- * paginator's own `pageSize` (so a short page means the end). A larger over-request (e.g.
8210
- * `channel.reload`) may have been server-capped and never proves it. Only gates `hasMoreTail`.
9059
+ * paginator's own `pageSize` and `page` came back shorter. A larger over-request (e.g.
9060
+ * `channel.reload`) may have been server-capped and never proves it. Gates `hasMoreTail` and the
9061
+ * gap rule ({@link isSeparatedFromHeadByGap}), never removing a message.
8211
9062
  */
8212
9063
  pageReachedChannelStart(page, options) {
8213
9064
  const requestedLimit = options?.requestedLimit;
@@ -8250,18 +9101,63 @@ var MessageIntervalPaginator = class extends BasePaginator {
8250
9101
  return message.status !== "sending" && message.status !== "failed" && message.type !== "error";
8251
9102
  }
8252
9103
  /**
8253
- * Destructive half of {@link mergeNewestPage}: removes loaded head-interval messages that `page`
8254
- * (the fresh newest window) proves were hard-deleted while offline, by `created_at`:
9104
+ * Whether this list holds `message`: it passes the filter and, in a channel's main list (no
9105
+ * `parentMessageId`), is not a reply only its thread lists (see `isThreadOnlyReply`).
9106
+ */
9107
+ isListedMessage(message) {
9108
+ if (!this.matchesFilter(message)) return false;
9109
+ return !!this.parentMessageId || !isThreadOnlyReply(message);
9110
+ }
9111
+ /**
9112
+ * The failed messages a reload restores with {@link restoreFailedMessages}: those of the shown
9113
+ * window and the head window, and those of `persisted` (e.g. the offline database's rows of the
9114
+ * channel) this list holds (see {@link isListedMessage}). The loaded copy wins, as it is at least
9115
+ * as fresh. Take them before the reload's request.
9116
+ *
9117
+ * @internal
9118
+ */
9119
+ getFailedMessagesToRestore(persisted = []) {
9120
+ const failedById = /* @__PURE__ */ new Map();
9121
+ const listed = persisted.filter((message) => this.isListedMessage(message));
9122
+ const loaded = [...this.items ?? [], ...this.anchoredHeadItems];
9123
+ for (const message of [...listed, ...loaded]) {
9124
+ if (message.status === "failed") failedById.set(this.getItemId(message), message);
9125
+ }
9126
+ return [...failedById.values()];
9127
+ }
9128
+ /**
9129
+ * Ingests again each failed message taken before a reload (see
9130
+ * {@link getFailedMessagesToRestore}) that no window holds after it, so a reload never loses the
9131
+ * user's unsent work. One a window holds is left as it is: it may have been resent.
9132
+ *
9133
+ * @internal
9134
+ */
9135
+ restoreFailedMessages(failedMessages) {
9136
+ const isNoLongerLoaded = (message) => !this.findIntervalHoldingItem(message);
9137
+ const toRestore = failedMessages.filter(isNoLongerLoaded);
9138
+ if (!toRestore.length) return;
9139
+ this.batch(
9140
+ () => {
9141
+ for (const message of toRestore) this.ingestItem(message);
9142
+ },
9143
+ { coalesce: true }
9144
+ );
9145
+ }
9146
+ /**
9147
+ * Destructive half of {@link reconcileNewestMessages}: removes loaded head-interval messages
9148
+ * that `page` (the fresh newest window) proves were hard-deleted while the client received no
9149
+ * events, by `created_at`:
8255
9150
  *
8256
9151
  * - within `page`'s span: a server-confirmed message absent from `page` was deleted (a live
8257
9152
  * arrival is newer than `page`'s newest, so this needs no snapshot);
8258
- * - at or above `page`'s newest, and for an empty `page`: only IDs in the pre-fetch `candidateIds`
8259
- * snapshot, which tells a just-deleted message from a live arrival.
9153
+ * - at or above `page`'s newest, and for an empty `page`: only IDs in the pre-fetch
9154
+ * `headIntervalItemIdsAtRequest` snapshot, which tells a just-deleted message from a live
9155
+ * arrival or a send confirmed during the request.
8260
9156
  *
8261
9157
  * Messages below `page`'s oldest are kept (a hard-deleted oldest looks like a server-capped
8262
9158
  * over-request) and returned for {@link pruneBelowWindowIfReachedStart}. Removal goes through
8263
9159
  * {@link removeItem}, so the index, intervals, message store and any subclass bookkeeping (e.g.
8264
- * an overridden `removeItem`) stay correct.
9160
+ * the latest message of {@link MessagePaginator}) stay correct.
8265
9161
  *
8266
9162
  * @returns The below-window leftover IDs. Empty for the no-head and empty-page paths.
8267
9163
  */
@@ -8269,14 +9165,12 @@ var MessageIntervalPaginator = class extends BasePaginator {
8269
9165
  const headInterval = this.itemIntervals[0];
8270
9166
  if (!headInterval?.isHead) return [];
8271
9167
  const loadedIds = headInterval.itemIds;
8272
- const candidateIds = options?.candidateIds;
9168
+ const headIntervalItemIdsAtRequest = options?.headIntervalItemIdsAtRequest;
8273
9169
  if (!page.length) {
8274
- if (!candidateIds) return [];
8275
- const toRemove2 = loadedIds.filter((id) => {
8276
- if (!candidateIds.has(id)) return false;
8277
- const message = this.getItem(id);
8278
- return !!message && this.isServerConfirmedMessage(message);
8279
- });
9170
+ if (!headIntervalItemIdsAtRequest) return [];
9171
+ const toRemove2 = loadedIds.filter(
9172
+ (id) => headIntervalItemIdsAtRequest.has(id) && this.isServerConfirmedItemId(id)
9173
+ );
8280
9174
  this.removeReconciledItems(toRemove2);
8281
9175
  return [];
8282
9176
  }
@@ -8293,7 +9187,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8293
9187
  const ts = getMessageCreatedAtTimestamp(message);
8294
9188
  if (ts === null) continue;
8295
9189
  if (newestReturnedTs !== null && ts >= newestReturnedTs) {
8296
- if (candidateIds?.has(id)) toRemove.push(id);
9190
+ if (headIntervalItemIdsAtRequest?.has(id)) toRemove.push(id);
8297
9191
  continue;
8298
9192
  }
8299
9193
  if (ts > windowLowTs) toRemove.push(id);
@@ -8409,69 +9303,69 @@ var MessageIntervalPaginator = class extends BasePaginator {
8409
9303
  });
8410
9304
  }
8411
9305
  }
9306
+ /**
9307
+ * {@link findItemByTimestamp} within one window (`items` ascending by `created_at`). `undefined`
9308
+ * when every item is newer than `timestamp`, so an older window has to be searched.
9309
+ */
9310
+ findItemByTimestampIn(items, timestamp, exactTsMatch) {
9311
+ if (!items.length) return void 0;
9312
+ const firstAfter = lowerBound(items.length, (i) => {
9313
+ const t = getMessageCreatedAtTimestamp(items[i]);
9314
+ return t === null || t > timestamp;
9315
+ });
9316
+ if (firstAfter === 0) return void 0;
9317
+ const found = items[firstAfter - 1];
9318
+ const foundTimestamp = getMessageCreatedAtTimestamp(found);
9319
+ if (foundTimestamp === null) return null;
9320
+ if (!exactTsMatch) return found;
9321
+ return foundTimestamp === timestamp ? found : null;
9322
+ }
9323
+ filterQueryResults(items) {
9324
+ return items.filter(this.shouldIncludeMessageInInterval.bind(this));
9325
+ }
8412
9326
  getCanonicalQueryItems(items) {
8413
9327
  return [...items].sort(this.itemOrderComparator);
8414
9328
  }
8415
- };
8416
- var makeDeriveCursor = (paginator) => (ctx) => {
8417
- const pageWithPermittedMessages = [];
8418
- let filteredLocallyCount = 0;
8419
- for (const message of ctx.page) {
8420
- if (!paginator.shouldIncludeMessageInInterval(message)) {
8421
- filteredLocallyCount++;
8422
- } else {
8423
- pageWithPermittedMessages.push(message);
9329
+ /**
9330
+ * The cursor and more-messages flags after a page is placed (`deriveCursor`), comparing the page
9331
+ * with the interval's outermost server-known messages (see {@link getServerKnownEdges}): a page
9332
+ * never holds an unsent message, so one at an edge must not hide that the page reached the edge.
9333
+ */
9334
+ deriveCursorFromPage(ctx) {
9335
+ const pageWithPermittedMessages = [];
9336
+ let filteredLocallyCount = 0;
9337
+ for (const message of ctx.page) {
9338
+ if (!this.shouldIncludeMessageInInterval(message)) {
9339
+ filteredLocallyCount++;
9340
+ } else {
9341
+ pageWithPermittedMessages.push(message);
9342
+ }
8424
9343
  }
8425
- }
8426
- const requestedPageSizeAfterAdjustment = Math.max(
8427
- 0,
8428
- ctx.requestedPageSize - filteredLocallyCount
8429
- );
8430
- if (ctx.interval && ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length) {
8431
- console.error(
8432
- "error",
8433
- "Corrupted message set state: parent set size < returned page size"
9344
+ const requestedPageSizeAfterAdjustment = Math.max(
9345
+ 0,
9346
+ ctx.requestedPageSize - filteredLocallyCount
8434
9347
  );
8435
- return {
8436
- cursor: ctx.cursor,
8437
- hasMoreHead: ctx.hasMoreHead,
8438
- hasMoreTail: ctx.hasMoreTail
8439
- };
8440
- }
8441
- const injectCursor = ({
8442
- hasMoreHead,
8443
- hasMoreTail
8444
- }) => {
8445
- const cursor = {
8446
- headward: !hasMoreHead ? null : ctx.interval?.itemIds.slice(-1)[0] ?? null,
8447
- tailward: !hasMoreTail ? null : ctx.interval?.itemIds[0] ?? null
9348
+ if (ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length) {
9349
+ console.error(
9350
+ "error",
9351
+ "Corrupted message set state: parent set size < returned page size"
9352
+ );
9353
+ return {
9354
+ cursor: ctx.cursor,
9355
+ hasMoreHead: ctx.hasMoreHead,
9356
+ hasMoreTail: ctx.hasMoreTail
9357
+ };
9358
+ }
9359
+ const derivationCtx = {
9360
+ ...ctx,
9361
+ intervalEdges: this.getServerKnownEdges(ctx.interval),
9362
+ page: pageWithPermittedMessages,
9363
+ requestedPageSize: requestedPageSizeAfterAdjustment
8448
9364
  };
8449
- return { cursor, hasMoreHead, hasMoreTail };
8450
- };
8451
- if (ctx.queryShape?.created_at_around) {
8452
- return injectCursor(
8453
- deriveCreatedAtAroundPaginationFlags({
8454
- ...ctx,
8455
- page: pageWithPermittedMessages,
8456
- requestedPageSize: requestedPageSizeAfterAdjustment
8457
- })
8458
- );
8459
- } else if (ctx.queryShape?.id_around) {
8460
- return injectCursor(
8461
- deriveIdAroundPaginationFlags({
8462
- ...ctx,
8463
- page: pageWithPermittedMessages,
8464
- requestedPageSize: requestedPageSizeAfterAdjustment
8465
- })
8466
- );
8467
- } else {
8468
- return injectCursor(
8469
- deriveLinearPaginationFlags({
8470
- ...ctx,
8471
- page: pageWithPermittedMessages,
8472
- requestedPageSize: requestedPageSizeAfterAdjustment
8473
- })
8474
- );
9365
+ const flags = ctx.queryShape?.created_at_around ? deriveCreatedAtAroundPaginationFlags(
9366
+ derivationCtx
9367
+ ) : ctx.queryShape?.id_around ? deriveIdAroundPaginationFlags(derivationCtx) : deriveLinearPaginationFlags(derivationCtx);
9368
+ return { ...flags, cursor: this.getCursorFromInterval(ctx.interval, flags) };
8475
9369
  }
8476
9370
  };
8477
9371
 
@@ -8488,9 +9382,11 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8488
9382
  ...builtInDefaults
8489
9383
  });
8490
9384
  /**
8491
- * (Re)seeds the unread snapshot from the own read state. Runs after the first-page query, and the
8492
- * SDK calls it again when a channel is reopened from a cached paginator (no first-page query), so
8493
- * the separator, unread count and jump target follow the current read boundary.
9385
+ * (Re)seeds the unread snapshot from the own read state. Runs once a first page and the rest of
9386
+ * its response are in (the paginator's own first-page queries, `watch()` and the channel-list
9387
+ * hydrate, when these place one), and the SDK calls it again when a channel is reopened from a
9388
+ * cached paginator (no first-page query), so the separator, unread count and jump target follow
9389
+ * the current read boundary.
8494
9390
  *
8495
9391
  * `firstUnreadMessageId` is reset to `null`: it holds only an explicit mark-unread
8496
9392
  * (`notification.mark_unread`), and a computed value would suppress auto-mark-read.
@@ -8551,6 +9447,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8551
9447
  });
8552
9448
  if (!inferredLastReadMessageId) {
8553
9449
  const result = await this.executeQuery({
9450
+ claimsActiveInterval: true,
8554
9451
  queryShape: {
8555
9452
  // `created_at_around` is a request field and still takes a `Date`.
8556
9453
  created_at_around: nsToDate(lastReadBoundary),
@@ -8558,6 +9455,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8558
9455
  },
8559
9456
  updateState: false
8560
9457
  });
9458
+ if (result?.isSuperseded) return false;
8561
9459
  if (result) {
8562
9460
  ({
8563
9461
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -8615,141 +9513,349 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8615
9513
  isViewingLive: false
8616
9514
  });
8617
9515
  this.aggregateState = new import_state_store11.StateStore({
8618
- lastMessage: null,
8619
- seededLastMessageAt: null
9516
+ latestMessage: null,
9517
+ queriedLatestMessageAt: null
8620
9518
  });
8621
9519
  }
8622
9520
  get holderName() {
8623
9521
  return "message-paginator";
8624
9522
  }
8625
9523
  /**
8626
- * Channel-list sort key: the later of the newest loaded message's `created_at` and the server seed.
8627
- * Derived, so it cannot drift from {@link lastMessage}. `null` until seeded or a message arrives.
9524
+ * The time of the channel's latest message as far as the client knows: the later of
9525
+ * {@link latestMessage}'s `created_at` and the `last_message_at` of the latest response (see
9526
+ * {@link setQueriedLatestMessageAt}). Later than {@link latestMessage} when the server has newer
9527
+ * messages the client does not hold. The channel-list sort key. **Derived** (never stored) so it
9528
+ * cannot drift from {@link latestMessage}. `null` until a query sets it or a message is ingested.
9529
+ */
9530
+ get latestMessageAt() {
9531
+ return this.latestMessageAtIncluding(this.latestMessage);
9532
+ }
9533
+ /**
9534
+ * {@link latestMessageAt} as the server knows it (see {@link pageReachesHead}): an unsent latest
9535
+ * message carries the device's clock, so the latest server-known message counts in its place.
8628
9536
  */
8629
- get lastMessageAt() {
8630
- const { lastMessage, seededLastMessageAt } = this.aggregateState.getLatestValue();
8631
- const fromMessage = getMessageCreatedAtTimestamp(lastMessage);
8632
- if (fromMessage !== null && seededLastMessageAt !== null) {
8633
- return asTimestampNS(Math.max(fromMessage, seededLastMessageAt));
9537
+ get latestServerMessageAt() {
9538
+ const { latestMessage } = this.aggregateState.getLatestValue();
9539
+ const isUnsent = !!latestMessage && !this.isServerConfirmedMessage(latestMessage);
9540
+ return this.latestMessageAtIncluding(
9541
+ isUnsent ? this.recomputeLatestMessage({ serverConfirmedOnly: true }) : latestMessage
9542
+ );
9543
+ }
9544
+ /** The later of `message`'s `created_at` and the queried `last_message_at`. */
9545
+ latestMessageAtIncluding(message) {
9546
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
9547
+ const fromMessage = getMessageCreatedAtTimestamp(message);
9548
+ if (fromMessage !== null && queriedLatestMessageAt !== null) {
9549
+ return asTimestampNS(Math.max(fromMessage, queriedLatestMessageAt));
8634
9550
  }
8635
- return fromMessage ?? seededLastMessageAt;
9551
+ return fromMessage ?? queriedLatestMessageAt;
8636
9552
  }
8637
9553
  /**
8638
- * The tracked newest channel-relevant message ({@link aggregateState}), for display. `null` until
8639
- * one is ingested (a server-only seed advances {@link lastMessageAt} but not this).
9554
+ * The newest message the client holds that counts as the channel's latest (see
9555
+ * {@link shouldAdvanceLatestMessage}), from any loaded window or from an event. Not necessarily
9556
+ * the server's latest message: {@link latestMessageAt} is later than its `created_at` when the
9557
+ * server has newer messages the client does not hold. `null` until a message is ingested (a
9558
+ * `last_message_at` from a query sets {@link latestMessageAt} but leaves this `null`).
9559
+ * Convenience read of {@link aggregateState}; subscribe to `aggregateState` for reactivity.
9560
+ *
9561
+ * It differs from {@link anchoredHeadItem}, the newest message of the window known to reach the
9562
+ * server's latest message, in two ways:
9563
+ * - It skips messages that do not count. With system messages skipped, a system message can be
9564
+ * `anchoredHeadItem` but never `latestMessage`.
9565
+ * - It does not need that window. A channel opened at its first unread message loads m40–m60
9566
+ * while the server's newest is m95: `latestMessage` is m60, `latestMessageAt` is m95's time and
9567
+ * `anchoredHeadItem` is `undefined`.
9568
+ */
9569
+ get latestMessage() {
9570
+ return this.aggregateState.getLatestValue().latestMessage;
9571
+ }
9572
+ /**
9573
+ * The newest server-confirmed message of the window that reaches the newest message (see
9574
+ * {@link anchoredHeadItems}). Any message the window holds counts, system messages included, but
9575
+ * not an unsent one: its id is local. `undefined` while that window is not loaded or holds no
9576
+ * server-confirmed message.
9577
+ *
9578
+ * @internal
8640
9579
  */
8641
- get lastMessage() {
8642
- return this.aggregateState.getLatestValue().lastMessage;
9580
+ get anchoredHeadServerConfirmedItem() {
9581
+ const head = this.anchoredHeadInterval;
9582
+ return head ? this.getServerKnownEdges(head).head : void 0;
8643
9583
  }
8644
9584
  /**
8645
- * Whether `message` may become the "latest message" behind `channel.state.last_message_at`: not
8646
- * shadowed and, in the main list, not a thread-only reply nor (with
8647
- * `skip_last_msg_update_for_system_msgs`) a system message. A reply list (`parentMessageId` set)
8648
- * holds only thread replies, so only the shadow rule applies there.
9585
+ * Whether `message` counts as the channel's latest message: not shadowed and, in the main list,
9586
+ * not a thread-only reply nor (with `skip_last_msg_update_for_system_msgs`, which the server also
9587
+ * applies to `last_message_at`) a system message. A reply list (`parentMessageId` set) holds only
9588
+ * thread replies, so only the shadow rule applies there.
8649
9589
  */
8650
- shouldAdvanceLastMessage(message) {
9590
+ shouldAdvanceLatestMessage(message) {
8651
9591
  if (message.shadowed) return false;
8652
9592
  if (this.parentMessageId) return true;
8653
- const isThreadOnlyReply = !!message.parent_id && !message.show_in_channel;
8654
- if (isThreadOnlyReply) return false;
9593
+ if (isThreadOnlyReply(message)) return false;
8655
9594
  const skipSystemMessage = !!this.channel.serverConfig?.skip_last_msg_update_for_system_msgs && message.type === "system";
8656
9595
  return !skipSystemMessage;
8657
9596
  }
8658
9597
  /**
8659
- * Advances the tracked latest message (and so {@link lastMessageAt}) to `message` when it is newer
8660
- * and {@link shouldAdvanceLastMessage} permits. Writes {@link aggregateState} only, so it is safe
8661
- * inside a `state.next` updater (`ingestPage`). Returns `true` when the value moved. Public for
8662
- * callers that advance it without an in-window ingest, e.g. offline pending-message replay.
9598
+ * Advances {@link latestMessage} (and so {@link latestMessageAt}) to `message` when it is newer
9599
+ * and {@link shouldAdvanceLatestMessage} permits. Writes {@link aggregateState} only, so it is
9600
+ * safe inside a `state.next` updater (`ingestPage`). Returns `true` when the value moved. Public
9601
+ * for callers that advance it without an in-window ingest, e.g. offline pending-message replay.
8663
9602
  */
8664
- trackLastMessage(message) {
8665
- if (!this.shouldAdvanceLastMessage(message)) return false;
9603
+ trackLatestMessage(message) {
9604
+ if (!this.shouldAdvanceLatestMessage(message)) return false;
8666
9605
  const incoming = getMessageCreatedAtTimestamp(message);
8667
9606
  if (incoming === null) return false;
8668
- const current = this.aggregateState.getLatestValue().lastMessage;
9607
+ const current = this.aggregateState.getLatestValue().latestMessage;
8669
9608
  if (current && current.id === message.id) {
8670
- this.aggregateState.partialNext({ lastMessage: message });
9609
+ this.aggregateState.partialNext({ latestMessage: message });
8671
9610
  return true;
8672
9611
  }
8673
9612
  const currentTs = current ? getMessageCreatedAtTimestamp(current) : null;
8674
9613
  if (currentTs !== null && incoming <= currentTs) return false;
8675
- this.aggregateState.partialNext({ lastMessage: message });
9614
+ this.aggregateState.partialNext({ latestMessage: message });
8676
9615
  return true;
8677
9616
  }
8678
9617
  /**
8679
- * Seeds {@link lastMessageAt} from `ChannelResponse.last_message_at`. Monotonic: a value not newer
8680
- * than the current seed is ignored, so seed order does not matter.
9618
+ * Sets {@link MessagePaginatorAggregateState.queriedLatestMessageAt} from a query result's
9619
+ * `last_message_at` (a channel's, or a thread's for a reply list), which {@link latestMessageAt}
9620
+ * then takes into account. Each result replaces the previous value, even with an earlier one:
9621
+ * the newest message may have been hard-deleted, which no event reports with the new value. A
9622
+ * message ingested after the result was produced, such as a new one from an event, still counts,
9623
+ * through {@link latestMessage}. `null` clears it (no messages); `undefined` (not in the result)
9624
+ * leaves it.
9625
+ */
9626
+ setQueriedLatestMessageAt(value) {
9627
+ if (value === void 0) return;
9628
+ const next = value !== null && Number.isFinite(value) ? value : null;
9629
+ if (next === this.aggregateState.getLatestValue().queriedLatestMessageAt) return;
9630
+ this.aggregateState.partialNext({ queriedLatestMessageAt: next });
9631
+ }
9632
+ /**
9633
+ * Clears the head mark of the head window when it is stale (see {@link unmarkHead}). It is stale
9634
+ * when its newest message is older than the `last_message_at` the latest query returned (see
9635
+ * {@link setQueriedLatestMessageAt}): the channel has newer messages the window lacks. The window
9636
+ * then stops being the head window ({@link anchoredHeadItem} becomes `undefined`) and can load
9637
+ * newer messages, and a message that then arrives from an event starts a separate head window
9638
+ * instead of joining it across the gap. Messages that exist only locally, such as a failed send,
9639
+ * are left out of the comparison: they carry the device's clock.
9640
+ *
9641
+ * For example, the window holds m1–m20 and the channel is not watched while m21–m25 are sent. A
9642
+ * query returns m25's time: the window can now load m21–m25, and m26 from an event does not land
9643
+ * right after m20.
9644
+ *
9645
+ * Call it with each response that does not bring the newest messages up to date, before any page
9646
+ * the response carries is placed: a page that reaches the newest message marks its own window as
9647
+ * the head. Call it only when no events were arriving before the response and nothing else
9648
+ * brings the newest messages: while the channel is watched, a message the window lacks is still
9649
+ * on its way, and a re-watch that places the newest page settles the window itself.
9650
+ */
9651
+ unmarkStaleHead() {
9652
+ const head = this.anchoredHeadInterval;
9653
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
9654
+ if (!head || queriedLatestMessageAt === null) return;
9655
+ let headNewestAt = null;
9656
+ for (const message of this.intervalToItems(head)) {
9657
+ if (!this.isServerConfirmedMessage(message)) continue;
9658
+ const createdAt = getMessageCreatedAtTimestamp(message);
9659
+ if (createdAt !== null && (headNewestAt === null || createdAt > headNewestAt))
9660
+ headNewestAt = createdAt;
9661
+ }
9662
+ if (headNewestAt !== null && headNewestAt >= queriedLatestMessageAt) return;
9663
+ this.unmarkHead(head);
9664
+ }
9665
+ /**
9666
+ * A page reaches the newest message when its newest message is at or after
9667
+ * {@link latestServerMessageAt}, as known before the page is ingested; one older than that is not
9668
+ * the newest. That value comes from the latest response (`ChannelResponse` for a channel,
9669
+ * `ThreadStateResponse` for a reply list, through {@link setQueriedLatestMessageAt}) and from the
9670
+ * messages ingested since, such as new ones from events. `undefined` while it is not known.
8681
9671
  */
8682
- seedLastMessageAt(value) {
8683
- if (value == null || !Number.isFinite(value)) return;
8684
- const current = this.aggregateState.getLatestValue().seededLastMessageAt;
8685
- if (current !== null && value <= current) return;
8686
- this.aggregateState.partialNext({ seededLastMessageAt: value });
9672
+ pageReachesHead(page) {
9673
+ const latestServerMessageAt = this.latestServerMessageAt;
9674
+ if (latestServerMessageAt === null) return void 0;
9675
+ const createdAt = getMessageCreatedAtTimestamp(
9676
+ this.getPagePaginationEdges(page).head
9677
+ );
9678
+ return createdAt !== null && createdAt >= latestServerMessageAt;
8687
9679
  }
9680
+ /**
9681
+ * Ingests a single message, from an event or an operation such as a send. A message that starts
9682
+ * the newest window is placed by {@link ingestAsNewestInterval}. Any other goes into the window
9683
+ * it belongs to and the active interval stays active, except for the current user's new send (see
9684
+ * {@link isOwnSendWhileOlderWindowIsActive}): the newest window holding it is shown, so the user
9685
+ * sees what they sent.
9686
+ */
8688
9687
  ingestItem(item) {
8689
9688
  if (this.matchesFilter(item)) {
8690
- this.trackLastMessage(item);
9689
+ if (this.isNewNewestMessage(item)) return this.ingestAsNewestInterval(item);
9690
+ this.trackLatestMessage(item);
9691
+ }
9692
+ const showsNewestWindow = this.isOwnSendWhileOlderWindowIsActive(item);
9693
+ const ingested = super.ingestItem(item);
9694
+ const newest = this.anchoredHeadInterval;
9695
+ if (ingested && showsNewestWindow && newest?.itemIds.includes(item.id)) {
9696
+ this.showWindowOfOwnSend(newest);
9697
+ }
9698
+ return ingested;
9699
+ }
9700
+ /**
9701
+ * Whether `message` is the current user's own send (see {@link isOwnSend}) that the paginator
9702
+ * does not hold yet, while the newest window is loaded but another window is active. A message
9703
+ * already held (a retry of a failed send, a replayed send, its server confirmation) is not new.
9704
+ */
9705
+ isOwnSendWhileOlderWindowIsActive(message) {
9706
+ const newest = this.anchoredHeadInterval;
9707
+ return !!newest && !this.isActiveInterval(newest) && !this.getItem(message.id) && this.isOwnSend(message);
9708
+ }
9709
+ /**
9710
+ * Shows the window holding the current user's own send. The send decides the window shown, so it
9711
+ * claims the active interval as a jump does: a page a query claimed earlier is then only stored.
9712
+ */
9713
+ showWindowOfOwnSend(interval) {
9714
+ this.claimActiveInterval();
9715
+ this.showLoadedInterval(interval);
9716
+ }
9717
+ /**
9718
+ * A message the paginator does not hold yet, at or after {@link latestMessageAt} (as known before
9719
+ * it arrives), while no loaded window reaches the newest message. It is then the newest message,
9720
+ * so it starts the newest window, as a page holding it would (see {@link pageReachesHead}).
9721
+ */
9722
+ isNewNewestMessage(message) {
9723
+ if (this.anchoredHeadItem !== void 0 || this.getItem(message.id)) return false;
9724
+ const latestMessageAt = this.latestMessageAt;
9725
+ const createdAt = getMessageCreatedAtTimestamp(message);
9726
+ return latestMessageAt !== null && createdAt !== null && createdAt >= latestMessageAt;
9727
+ }
9728
+ /**
9729
+ * The logical-head items (ingested one by one, usually from events, rather than as part of a
9730
+ * page) not older than `queriedLatestMessageAt`, the `last_message_at` of the latest channel or
9731
+ * thread response; all of them when no response has set it. They were ingested after that
9732
+ * response, one after another, so nothing is missing between them. Items older than that, such as
9733
+ * a message arriving out of order, are left out.
9734
+ */
9735
+ get logicalHeadItemsSinceQueriedLatestMessageAt() {
9736
+ const { queriedLatestMessageAt } = this.aggregateState.getLatestValue();
9737
+ return this.logicalHeadItems.filter((item) => {
9738
+ const createdAt = getMessageCreatedAtTimestamp(item);
9739
+ return queriedLatestMessageAt === null || createdAt !== null && createdAt >= queriedLatestMessageAt;
9740
+ });
9741
+ }
9742
+ /**
9743
+ * Starts the newest window with `message`, together with the
9744
+ * {@link logicalHeadItemsSinceQueriedLatestMessageAt} ingested before it. It can load older
9745
+ * messages unless none are left to load (see {@link hasNoMessagesBeforeLiveMessages}). It becomes
9746
+ * the active window when no window was active, when the logical head it takes items from was, or
9747
+ * when `message` is the current user's own send (see {@link isOwnSend}), as every own send shows
9748
+ * the newest window (see {@link ingestItem}).
9749
+ */
9750
+ ingestAsNewestInterval(message) {
9751
+ const liveHead = this.liveHeadLogical;
9752
+ const interval = this.ingestPage({
9753
+ page: [...this.logicalHeadItemsSinceQueriedLatestMessageAt, message],
9754
+ isHead: true,
9755
+ isTail: this.hasNoMessagesBeforeLiveMessages,
9756
+ setActive: false
9757
+ });
9758
+ if (!interval) return false;
9759
+ if (this.isOwnSend(message)) {
9760
+ this.showWindowOfOwnSend(interval);
9761
+ } else if (!this._activeIntervalId || !!liveHead && this.isActiveInterval(liveHead)) {
9762
+ this.showLoadedInterval(interval);
8691
9763
  }
8692
- return super.ingestItem(item);
9764
+ return true;
9765
+ }
9766
+ /**
9767
+ * Whether no message older than the live messages is left to load: no window of queried messages
9768
+ * is loaded and the list reports no older messages, as after a newest page that came back empty.
9769
+ * A list never queried, or one holding a window (a jumped-to one, or one whose head mark was
9770
+ * cleared), has older messages to load.
9771
+ */
9772
+ get hasNoMessagesBeforeLiveMessages() {
9773
+ return this.hasMoreTail === false && this.itemIntervals.every((interval) => isLogicalInterval(interval));
9774
+ }
9775
+ /**
9776
+ * Whether `message` is one the current user is sending from this device: status `sending` and
9777
+ * authored by the client's user. The same user's message from another device arrives
9778
+ * server-confirmed and is not one.
9779
+ */
9780
+ isOwnSend(message) {
9781
+ return message.status === "sending" && this.isOwnMessage(message);
9782
+ }
9783
+ /** Whether the client's user wrote `message`; never for a paginator without a client. */
9784
+ isOwnMessage(message) {
9785
+ const userId = this.channel.getClient?.()?.userId;
9786
+ return !!userId && message.user?.id === userId;
8693
9787
  }
8694
9788
  ingestPage(params) {
8695
9789
  const interval = super.ingestPage(params);
8696
9790
  if (params.page?.length) {
8697
- for (const item of params.page) this.trackLastMessage(item);
9791
+ for (const item of params.page) this.trackLatestMessage(item);
8698
9792
  }
8699
9793
  return interval;
8700
9794
  }
8701
9795
  onEntitiesChanged(batch) {
8702
9796
  super.onEntitiesChanged(batch);
8703
- const { lastMessage } = this.aggregateState.getLatestValue();
8704
- if (!lastMessage || !batch.changedIds.has(lastMessage.id)) return;
8705
- const stored = this.getItem(lastMessage.id);
8706
- if (stored) this.aggregateState.partialNext({ lastMessage: stored });
9797
+ const { latestMessage } = this.aggregateState.getLatestValue();
9798
+ if (!latestMessage || !batch.changedIds.has(latestMessage.id)) return;
9799
+ const stored = this.getItem(latestMessage.id);
9800
+ if (stored) this.aggregateState.partialNext({ latestMessage: stored });
8707
9801
  }
8708
9802
  reflectUserUpdate(user) {
8709
9803
  super.reflectUserUpdate(user);
8710
- const { lastMessage } = this.aggregateState.getLatestValue();
8711
- if (lastMessage?.user?.id !== user.id) return;
8712
- this.aggregateState.partialNext({ lastMessage: { ...lastMessage, user } });
9804
+ const { latestMessage } = this.aggregateState.getLatestValue();
9805
+ if (latestMessage?.user?.id !== user.id) return;
9806
+ this.aggregateState.partialNext({ latestMessage: { ...latestMessage, user } });
8713
9807
  }
8714
9808
  removeItem(params) {
8715
9809
  const removedId = params.id ?? (params.item ? this.getItemId(params.item) : void 0);
8716
- const { lastMessage, seededLastMessageAt } = this.aggregateState.getLatestValue();
8717
- const wasLatest = !!removedId && lastMessage?.id === removedId;
9810
+ const { latestMessage, queriedLatestMessageAt } = this.aggregateState.getLatestValue();
9811
+ const wasLatest = !!removedId && latestMessage?.id === removedId;
8718
9812
  const result = super.removeItem(params);
8719
9813
  if (wasLatest) {
8720
- const previous = this.recomputeLastMessage();
9814
+ const previous = this.recomputeLatestMessage();
8721
9815
  const previousAt = getMessageCreatedAtTimestamp(previous);
8722
- const removedAt = getMessageCreatedAtTimestamp(lastMessage);
8723
- const isSeedFromRemovedMessage = seededLastMessageAt !== null && removedAt !== null && seededLastMessageAt <= removedAt;
9816
+ const removedAt = getMessageCreatedAtTimestamp(latestMessage);
9817
+ const isQueriedFromRemovedMessage = queriedLatestMessageAt !== null && removedAt !== null && queriedLatestMessageAt <= removedAt;
8724
9818
  this.aggregateState.partialNext({
8725
- lastMessage: previous,
8726
- seededLastMessageAt: isSeedFromRemovedMessage && previousAt !== null ? previousAt : seededLastMessageAt
9819
+ latestMessage: previous,
9820
+ queriedLatestMessageAt: isQueriedFromRemovedMessage && previousAt !== null ? previousAt : queriedLatestMessageAt
8727
9821
  });
8728
9822
  }
8729
9823
  return result;
8730
9824
  }
8731
9825
  truncate(params) {
8732
9826
  super.truncate(params);
8733
- const { lastMessage, seededLastMessageAt } = this.aggregateState.getLatestValue();
9827
+ const { latestMessage, queriedLatestMessageAt } = this.aggregateState.getLatestValue();
8734
9828
  const isTruncated = (timestamp) => timestamp !== null && timestamp < params.truncatedAt;
8735
- const isLastMessageTruncated = isTruncated(getMessageCreatedAtTimestamp(lastMessage));
8736
- const isSeedTruncated = isTruncated(seededLastMessageAt);
8737
- if (!isLastMessageTruncated && !isSeedTruncated) return;
9829
+ const isLatestMessageTruncated = isTruncated(
9830
+ getMessageCreatedAtTimestamp(latestMessage)
9831
+ );
9832
+ const isQueriedLatestMessageAtTruncated = isTruncated(queriedLatestMessageAt);
9833
+ if (!isLatestMessageTruncated && !isQueriedLatestMessageAtTruncated) return;
8738
9834
  this.aggregateState.partialNext({
8739
- lastMessage: isLastMessageTruncated ? this.recomputeLastMessage() : lastMessage,
8740
- seededLastMessageAt: isSeedTruncated ? null : seededLastMessageAt
9835
+ latestMessage: isLatestMessageTruncated ? this.recomputeLatestMessage() : latestMessage,
9836
+ queriedLatestMessageAt: isQueriedLatestMessageAtTruncated ? null : queriedLatestMessageAt
8741
9837
  });
8742
9838
  }
8743
9839
  /**
8744
- * The message in `headItems` with the greatest `created_at` that passes
8745
- * {@link shouldAdvanceLastMessage}, or `null`. It compares timestamps rather than positions, so it
8746
- * holds for any `itemOrder` / `requestSort`.
9840
+ * The still-loaded message with the greatest `created_at` that passes
9841
+ * {@link shouldAdvanceLatestMessage} (skips system / thread-only per config), from the window
9842
+ * that reaches the newest message and the {@link logicalHeadItemsSinceQueriedLatestMessageAt}.
9843
+ * A window reached by a jump is not searched, nor an out-of-order older message: neither is the
9844
+ * channel's previous message. Used to recompute the tracked latest after the current one is
9845
+ * removed; `serverConfirmedOnly` skips unsent messages. `null` when nothing loaded qualifies.
9846
+ * It compares timestamps rather than positions, so it holds for any `itemOrder` / `requestSort`.
8747
9847
  */
8748
- recomputeLastMessage() {
9848
+ recomputeLatestMessage({
9849
+ serverConfirmedOnly = false
9850
+ } = {}) {
8749
9851
  let latest = null;
8750
9852
  let latestTimestamp = -Infinity;
8751
- for (const item of this.headItems) {
8752
- if (!this.shouldAdvanceLastMessage(item)) continue;
9853
+ for (const item of [
9854
+ ...this.anchoredHeadItems,
9855
+ ...this.logicalHeadItemsSinceQueriedLatestMessageAt
9856
+ ]) {
9857
+ if (!this.shouldAdvanceLatestMessage(item)) continue;
9858
+ if (serverConfirmedOnly && !this.isServerConfirmedMessage(item)) continue;
8753
9859
  const timestamp = getMessageCreatedAtTimestamp(item);
8754
9860
  if (timestamp === null || timestamp <= latestTimestamp) continue;
8755
9861
  latest = item;
@@ -8757,13 +9863,14 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8757
9863
  }
8758
9864
  return latest;
8759
9865
  }
8760
- /** Also seeds the unread snapshot on a first page, before the opened channel is marked read. */
8761
- postQueryReconcile(params) {
8762
- const result = super.postQueryReconcile(params);
8763
- if (params.isFirstPage) {
8764
- this.seedUnreadSnapshot();
8765
- }
8766
- return result;
9866
+ /**
9867
+ * Applies the rest of the response, then takes the unread snapshot after a first-page query, from
9868
+ * the read state the response brought. A viewed channel is marked read right after it opens, so
9869
+ * the snapshot keeps the unread state from before, for unread UI indicators.
9870
+ */
9871
+ applyQueryResponseRest(response, placeParams) {
9872
+ super.applyQueryResponseRest(response, placeParams);
9873
+ if (placeParams.isFirstPage) this.seedUnreadSnapshot();
8767
9874
  }
8768
9875
  get isViewingLive() {
8769
9876
  return this.liveViewState.getLatestValue().isViewingLive;
@@ -8771,7 +9878,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
8771
9878
  clearStateAndCache() {
8772
9879
  super.clearStateAndCache();
8773
9880
  this.clearUnreadSnapshot();
8774
- this.aggregateState.next({ lastMessage: null, seededLastMessageAt: null });
9881
+ this.aggregateState.next({ latestMessage: null, queriedLatestMessageAt: null });
8775
9882
  }
8776
9883
  };
8777
9884
 
@@ -8813,8 +9920,8 @@ var PinnedMessagePaginator = class extends MessageIntervalPaginator {
8813
9920
  resolvePathValue: resolveDotPathValue,
8814
9921
  tiebreaker: this.pinnedTiebreaker
8815
9922
  }),
8816
- // The base `query` passes the resolved shape (including `id_around` jumps) as `options`.
8817
- // Both cursors are returned and the base gates them by direction.
9923
+ // The base passes the resolved shape (including `id_around` jumps) as `options`. Both
9924
+ // cursors are returned and the base `extractQueryPage` gates them by direction.
8818
9925
  doRequest: async (options) => {
8819
9926
  const { messages } = await this.channel.getPinnedMessages({
8820
9927
  ...options,
@@ -8839,6 +9946,15 @@ var PinnedMessagePaginator = class extends MessageIntervalPaginator {
8839
9946
  });
8840
9947
  this.updateConfig(this.buildPinnedBehaviour());
8841
9948
  }
9949
+ /**
9950
+ * The newest page (no cursor, not around a message) holds the most recently pinned messages, so
9951
+ * it reaches the head: its window becomes the only newest window, and an older window that was
9952
+ * the newest one can load newer pins (see `makeOnlyHead`). A newest page comes from this
9953
+ * paginator's own query or with a channel response.
9954
+ */
9955
+ pageReachesHead(_page, queryShape) {
9956
+ return this.isHeadPageQueryShape(queryShape) ? true : void 0;
9957
+ }
8842
9958
  shouldIncludeMessageInInterval(message) {
8843
9959
  return !message.shadowed && !!message.pinned;
8844
9960
  }
@@ -8857,7 +9973,7 @@ var ReminderPaginator = class extends BasePaginator {
8857
9973
  }),
8858
9974
  ...options
8859
9975
  });
8860
- this.query = async ({
9976
+ this.fetchQueryResponse = async ({
8861
9977
  direction,
8862
9978
  queryShape
8863
9979
  }) => {
@@ -8870,7 +9986,6 @@ var ReminderPaginator = class extends BasePaginator {
8870
9986
  const { reminders: items, next, prev } = await this.client.queryReminders(request);
8871
9987
  return { items, headward: prev, tailward: next };
8872
9988
  };
8873
- this.filterQueryResults = (items) => items;
8874
9989
  this.client = client;
8875
9990
  this.sortComparator = this.buildSortComparator();
8876
9991
  }
@@ -8907,6 +10022,10 @@ var ReminderPaginator = class extends BasePaginator {
8907
10022
  limit: this.pageSize
8908
10023
  };
8909
10024
  }
10025
+ /** The extracting step of the query pipeline: the response is the page. */
10026
+ extractQueryPage(response, _params) {
10027
+ return response;
10028
+ }
8910
10029
  };
8911
10030
 
8912
10031
  // src/pagination/paginators/UserGroupPaginator.ts
@@ -8941,7 +10060,7 @@ var UserGroupPaginator = class extends BasePaginator {
8941
10060
  id_gt: lastItem.id
8942
10061
  });
8943
10062
  };
8944
- this.query = async ({
10063
+ this.fetchQueryResponse = async ({
8945
10064
  direction,
8946
10065
  queryShape
8947
10066
  }) => {
@@ -8957,7 +10076,6 @@ var UserGroupPaginator = class extends BasePaginator {
8957
10076
  const { user_groups: items } = await this.client.listUserGroups(options);
8958
10077
  return { items, tailward: this.buildNextCursor(items) };
8959
10078
  };
8960
- this.filterQueryResults = (items) => items;
8961
10079
  this.client = client;
8962
10080
  this.sortComparator = (a, b) => {
8963
10081
  if (a.created_at !== b.created_at) return a.created_at < b.created_at ? -1 : 1;
@@ -8978,13 +10096,18 @@ var UserGroupPaginator = class extends BasePaginator {
8978
10096
  this._teamId = teamId;
8979
10097
  this.resetState();
8980
10098
  }
8981
- // The cursor stays out of the shape (a shape change resets the list): `query` applies it.
10099
+ // The cursor stays out of the shape (a shape change resets the list): `fetchQueryResponse`
10100
+ // applies it.
8982
10101
  getNextQueryShape() {
8983
10102
  return {
8984
10103
  limit: this.pageSize,
8985
10104
  ...this.teamId ? { team_id: this.teamId } : {}
8986
10105
  };
8987
10106
  }
10107
+ /** The extracting step of the query pipeline: the response is the page. */
10108
+ extractQueryPage(response, _params) {
10109
+ return response;
10110
+ }
8988
10111
  };
8989
10112
 
8990
10113
  // src/pagination/paginators/ThreadPaginator.ts
@@ -9017,26 +10140,15 @@ var ThreadPaginator = class extends BasePaginator {
9017
10140
  pageSize: DEFAULT_THREAD_PAGE_SIZE,
9018
10141
  ...paginatorOptions
9019
10142
  });
9020
- this.query = async ({
10143
+ this.fetchQueryResponse = async ({
9021
10144
  queryShape
9022
10145
  }) => {
9023
10146
  const { threads, next } = await this.client.queryThreadsAndHydrate(queryShape);
9024
- return { items: threads.map(this.toStoredInstance), tailward: next };
9025
- };
9026
- /**
9027
- * Keeps one instance per ID (the index upserts, so a second one would replace the stored one). A
9028
- * stale stored thread is hydrated from the query unless it is active: it reloads itself, and
9029
- * hydrating would replace the replies on screen.
9030
- */
9031
- this.toStoredInstance = (incoming) => {
9032
- const stored = this.store.get(incoming.id);
9033
- if (!stored) return incoming;
9034
- if (stored.hasStaleState && !stored.state.getLatestValue().active) {
9035
- stored.hydrateState(incoming);
9036
- }
9037
- return stored;
10147
+ return {
10148
+ items: threads.map((thread) => this.store.get(thread.id) ?? thread),
10149
+ tailward: next
10150
+ };
9038
10151
  };
9039
- this.filterQueryResults = (threads) => threads;
9040
10152
  /**
9041
10153
  * Re-queries the first page and replaces the list in server order; also the first load. The
9042
10154
  * current threads stay until the response lands. A failed query leaves them and records
@@ -9048,11 +10160,13 @@ var ThreadPaginator = class extends BasePaginator {
9048
10160
  if (isFirstLoad) this.state.partialNext({ isLoading: true });
9049
10161
  let replaced = false;
9050
10162
  try {
9051
- const results = await this.runQueryRetryable({
10163
+ const fetchParams = {
9052
10164
  queryShape: { ...DEFAULT_THREAD_QUERY, limit },
9053
10165
  retryCount: this.config.retryCount
9054
- });
9055
- if (!results) return;
10166
+ };
10167
+ const response = await this.fetchQueryResponseWithRetries(fetchParams);
10168
+ if (!response) return;
10169
+ const results = this.extractQueryPage(response, fetchParams);
9056
10170
  const nextIds = new Set(results.items.map((thread) => thread.id));
9057
10171
  this.setIntervals([]);
9058
10172
  this.setActiveInterval(void 0);
@@ -9099,6 +10213,10 @@ var ThreadPaginator = class extends BasePaginator {
9099
10213
  ...cursor ? { [direction === "tailward" ? "next" : "prev"]: cursor } : {}
9100
10214
  };
9101
10215
  }
10216
+ /** The extracting step of the query pipeline: the response is the page. */
10217
+ extractQueryPage(response, _params) {
10218
+ return response;
10219
+ }
9102
10220
  /** Also clears the item index (the base reset keeps it), before the base publishes. */
9103
10221
  resetState() {
9104
10222
  this._itemIndex.clear();
@@ -12248,9 +13366,10 @@ var CooldownTimer = class extends WithSubscriptions {
12248
13366
  this.refresh = () => {
12249
13367
  const { cooldown: cooldownConfigSeconds = 0, own_capabilities } = this.channel.data ?? {};
12250
13368
  const canSkipCooldown = (own_capabilities ?? []).includes("skip-slow-mode");
13369
+ const paginator = this.channel.messagePaginator;
12251
13370
  const ownLatestMessageTimestamp = this.findOwnLatestMessageTimestamp({
12252
- messages: this.channel.messagePaginator.headItems
12253
- });
13371
+ messages: [...paginator.anchoredHeadItems, ...paginator.logicalHeadItems]
13372
+ }) ?? (paginator.anchoredHeadItem !== void 0 ? void 0 : this.ownLatestMessageTimestamp);
12254
13373
  if (cooldownConfigSeconds !== this.cooldownConfigSeconds || ownLatestMessageTimestamp !== this.ownLatestMessageTimestamp || canSkipCooldown !== this.canSkipCooldown) {
12255
13374
  this.state.partialNext({
12256
13375
  cooldownConfigSeconds,
@@ -12389,7 +13508,7 @@ var QUEUEABLE_OPERATIONS = {
12389
13508
  timestampChanged: true
12390
13509
  });
12391
13510
  }
12392
- channelOf(client, task).messagePaginator.trackLastMessage(formatMessage(message));
13511
+ channelOf(client, task).messagePaginator.trackLatestMessage(formatMessage(message));
12393
13512
  },
12394
13513
  run: ({ channel, client, task }) => channelOf(client, task, channel).sendMessage(...task.payload)
12395
13514
  },
@@ -12475,18 +13594,18 @@ var MessageDeliveryReporter = class _MessageDeliveryReporter {
12475
13594
  this.getNextDeliveryReportCandidate = (collection) => {
12476
13595
  const ownUserId = this.client.user?.id;
12477
13596
  if (!ownUserId) return;
12478
- let latestMessages = [];
13597
+ let latestMessage = null;
12479
13598
  let lastDeliveredAt;
12480
13599
  let lastReadAt;
12481
13600
  let key = void 0;
12482
13601
  if (isChannel(collection)) {
12483
- latestMessages = collection.messagePaginator.headItems;
13602
+ latestMessage = collection.messagePaginator.latestMessage;
12484
13603
  const ownReadState = collection.state.read[ownUserId] ?? {};
12485
13604
  lastReadAt = ownReadState?.last_read;
12486
13605
  lastDeliveredAt = ownReadState?.last_delivered_at;
12487
13606
  key = collection.cid;
12488
13607
  } else if (isThread(collection)) {
12489
- latestMessages = collection.messagePaginator.headItems;
13608
+ latestMessage = collection.messagePaginator.latestMessage;
12490
13609
  const ownReadState = collection.state.getLatestValue().read[ownUserId] ?? {};
12491
13610
  lastReadAt = ownReadState?.lastReadAt;
12492
13611
  lastDeliveredAt = ownReadState?.lastDeliveredAt;
@@ -12496,10 +13615,10 @@ var MessageDeliveryReporter = class _MessageDeliveryReporter {
12496
13615
  return;
12497
13616
  }
12498
13617
  if (!key) return;
12499
- const [latestMessage] = latestMessages.slice(-1);
12500
- const wholeCollectionIsRead = !latestMessage || (lastReadAt ?? 0) >= latestMessage.created_at;
13618
+ if (!latestMessage) return { key, id: null };
13619
+ const wholeCollectionIsRead = (lastReadAt ?? 0) >= latestMessage.created_at;
12501
13620
  if (wholeCollectionIsRead) return { key, id: null };
12502
- const wholeCollectionIsMarkedDelivered = !latestMessage || (lastDeliveredAt ?? 0) >= latestMessage.created_at;
13621
+ const wholeCollectionIsMarkedDelivered = (lastDeliveredAt ?? 0) >= latestMessage.created_at;
12503
13622
  if (wholeCollectionIsMarkedDelivered) return { key, id: null };
12504
13623
  return { key, id: latestMessage.id || null };
12505
13624
  };
@@ -14312,6 +15431,7 @@ var Channel = class extends ChannelApi {
14312
15431
  this._reloading = false;
14313
15432
  /** Refcount behind the `active` flag: several consumers can hold one instance. */
14314
15433
  this._activeRefCount = 0;
15434
+ /** Stops releaseUnusedChannels() from removing a channel while a query for it is still running. */
14315
15435
  this._channelQueriesInFlight = 0;
14316
15436
  /** Alias for {@link uploadChannelFile}. */
14317
15437
  this.uploadFile = (...args) => this.uploadChannelFile(...args);
@@ -14322,9 +15442,10 @@ var Channel = class extends ChannelApi {
14322
15442
  * Refcounted: the channel stays active until the last consumer releases, and releasing twice is a
14323
15443
  * no-op.
14324
15444
  *
14325
- * While active, channel-list hydration does not re-seed the message list (`channel.reload()` owns
14326
- * it) and the channel stays in the channel store. A disposed channel is not activated: a warning is
14327
- * logged and the returned release does nothing.
15445
+ * While active, channel-list hydration places no page in the message list (`channel.reload()`
15446
+ * owns it), the message list keeps its active interval (otherwise a fresh newest page from a
15447
+ * query the list did not run is shown), and the channel stays in the channel store. A disposed
15448
+ * channel is not activated: a warning is logged and the returned release does nothing.
14328
15449
  */
14329
15450
  this.activate = () => {
14330
15451
  if (this.pendingDisposal) {
@@ -14358,7 +15479,9 @@ var Channel = class extends ChannelApi {
14358
15479
  state: false,
14359
15480
  presence: false
14360
15481
  };
14361
- return await this.query(defaultOptions, "latest");
15482
+ return await this.runChannelQuery(defaultOptions, void 0, {
15483
+ placeMessages: false
15484
+ });
14362
15485
  };
14363
15486
  this._callChannelListeners = (event) => {
14364
15487
  const listeners = [
@@ -14668,11 +15791,13 @@ var Channel = class extends ChannelApi {
14668
15791
  /**
14669
15792
  * Disables slow mode.
14670
15793
  *
15794
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
15795
+ * second argument, as on the generated methods; pass `undefined`.
14671
15796
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
14672
15797
  * into the request (optional).
14673
15798
  * @returns The server response.
14674
15799
  */
14675
- async disableSlowMode(requestOptions) {
15800
+ async disableSlowMode(_request, requestOptions) {
14676
15801
  return await this.update({ cooldown: 0 }, requestOptions);
14677
15802
  }
14678
15803
  async sendSharedLocation(location) {
@@ -14864,11 +15989,13 @@ var Channel = class extends ChannelApi {
14864
15989
  * @example
14865
15990
  * await channel.archive();
14866
15991
  *
15992
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
15993
+ * second argument, as on the generated methods; pass `undefined`.
14867
15994
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
14868
15995
  * into the request (optional).
14869
15996
  * @returns The server response.
14870
15997
  */
14871
- async archive(requestOptions) {
15998
+ async archive(_request, requestOptions) {
14872
15999
  return await this.updateMemberPartial({ set: { archived: true } }, requestOptions);
14873
16000
  }
14874
16001
  /**
@@ -14877,11 +16004,13 @@ var Channel = class extends ChannelApi {
14877
16004
  * @example
14878
16005
  * await channel.unarchive();
14879
16006
  *
16007
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
16008
+ * second argument, as on the generated methods; pass `undefined`.
14880
16009
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
14881
16010
  * into the request (optional).
14882
16011
  * @returns The server response.
14883
16012
  */
14884
- async unarchive(requestOptions) {
16013
+ async unarchive(_request, requestOptions) {
14885
16014
  return await this.updateMemberPartial({ set: { archived: false } }, requestOptions);
14886
16015
  }
14887
16016
  /**
@@ -14890,11 +16019,13 @@ var Channel = class extends ChannelApi {
14890
16019
  * @example
14891
16020
  * await channel.pin();
14892
16021
  *
16022
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
16023
+ * second argument, as on the generated methods; pass `undefined`.
14893
16024
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
14894
16025
  * into the request (optional).
14895
16026
  * @returns The server response.
14896
16027
  */
14897
- async pin(requestOptions) {
16028
+ async pin(_request, requestOptions) {
14898
16029
  return await this.updateMemberPartial({ set: { pinned: true } }, requestOptions);
14899
16030
  }
14900
16031
  /**
@@ -14903,11 +16034,13 @@ var Channel = class extends ChannelApi {
14903
16034
  * @example
14904
16035
  * await channel.unpin();
14905
16036
  *
16037
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
16038
+ * second argument, as on the generated methods; pass `undefined`.
14906
16039
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
14907
16040
  * into the request (optional).
14908
16041
  * @returns The server response.
14909
16042
  */
14910
- async unpin(requestOptions) {
16043
+ async unpin(_request, requestOptions) {
14911
16044
  return await this.updateMemberPartial({ set: { pinned: false } }, requestOptions);
14912
16045
  }
14913
16046
  /**
@@ -15000,10 +16133,12 @@ var Channel = class extends ChannelApi {
15000
16133
  * Sends an event to notify watchers to clear the typing/thinking UI when the AI response starts streaming.
15001
16134
  * Typically used by the server connected to the AI service to inform clients that the AI response has started.
15002
16135
  *
16136
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
16137
+ * second argument, as on the generated methods; pass `undefined`.
15003
16138
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
15004
16139
  * into the request (optional).
15005
16140
  */
15006
- async clearAIIndicator(requestOptions) {
16141
+ async clearAIIndicator(_request, requestOptions) {
15007
16142
  await this.sendEvent(
15008
16143
  {
15009
16144
  event: {
@@ -15017,10 +16152,12 @@ var Channel = class extends ChannelApi {
15017
16152
  * Sends an event to stop AI response generation, leaving the message in its current state.
15018
16153
  * Triggered by the user to halt the AI response process.
15019
16154
  *
16155
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
16156
+ * second argument, as on the generated methods; pass `undefined`.
15020
16157
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
15021
16158
  * into the request (optional).
15022
16159
  */
15023
- async stopAIResponse(requestOptions) {
16160
+ async stopAIResponse(_request, requestOptions) {
15024
16161
  await this.sendEvent(
15025
16162
  {
15026
16163
  event: {
@@ -15164,8 +16301,9 @@ var Channel = class extends ChannelApi {
15164
16301
  this.state.partialNext({ watchStatus });
15165
16302
  }
15166
16303
  /**
15167
- * Whether a query for this channel (`watch()`, `query()`, `create()`) awaits its response. The
15168
- * channel store keeps the channel meanwhile.
16304
+ * Whether a query for this channel (`watch()`, `query()`, `create()` or one of the message
16305
+ * paginator's own queries, see {@link runTrackedQuery}) awaits its response. The channel store
16306
+ * keeps the channel meanwhile.
15169
16307
  *
15170
16308
  * @internal
15171
16309
  */
@@ -15200,6 +16338,12 @@ var Channel = class extends ChannelApi {
15200
16338
  * `message.read_locally` event, handled like `message.read` minus the delivery-report sync. With
15201
16339
  * offline support the reset is persisted.
15202
16340
  *
16341
+ * The event's `last_read_message_id` is the newest server-confirmed message, whatever its type,
16342
+ * of the window holding the channel's newest messages
16343
+ * (`messagePaginator.anchoredHeadServerConfirmedItem`). While that window is not loaded (e.g.
16344
+ * only a jumped-to window is), the event carries none and the read covers everything up to its
16345
+ * `created_at`.
16346
+ *
15203
16347
  * @returns The dispatched `message.read_locally` event, or `undefined` if there is no connected
15204
16348
  * user.
15205
16349
  */
@@ -15211,7 +16355,7 @@ var Channel = class extends ChannelApi {
15211
16355
  channel_type: this.type,
15212
16356
  cid: this.cid,
15213
16357
  created_at: nowNs(),
15214
- last_read_message_id: this.messagePaginator.headmostItem?.id,
16358
+ last_read_message_id: this.messagePaginator.anchoredHeadServerConfirmedItem?.id,
15215
16359
  team: this.data?.team,
15216
16360
  type: "message.read_locally",
15217
16361
  user: client.user
@@ -15274,8 +16418,9 @@ var Channel = class extends ChannelApi {
15274
16418
  return this.supersededBy ? this.supersededBy.ensureWatched(options) : this;
15275
16419
  }
15276
16420
  /**
15277
- * Loads the initial state and watches for changes. The latest message page is loaded when this
15278
- * resolves.
16421
+ * Loads the initial state and watches for changes. The message paginator places the page of
16422
+ * messages it fetched before this resolves (a page at a cursor or around a message is only
16423
+ * stored; show it with `messagePaginator.jumpToMessage()`).
15279
16424
  *
15280
16425
  * @param options - Additional options for the query endpoint (optional).
15281
16426
  * @param requestOptions - Per-request options such as an abort `signal` (optional). The signal
@@ -15289,47 +16434,35 @@ var Channel = class extends ChannelApi {
15289
16434
  presence: false
15290
16435
  };
15291
16436
  const combined = { ...defaultOptions, ...options };
15292
- const state = await this.query(combined, "latest", requestOptions);
16437
+ const state = await this.runChannelQuery(combined, requestOptions, {
16438
+ placeMessages: true
16439
+ });
15293
16440
  this.data = state.channel;
15294
16441
  logger8.withExtraTags("watch", this.cid).info("Started watching the channel.");
15295
16442
  return state;
15296
16443
  }
15297
16444
  /**
15298
- * Re-watches the channel and refreshes its whole loaded message window (the channel analog of
16445
+ * Re-watches the channel and refreshes its whole loaded message window (the channel analogue of
15299
16446
  * {@link Thread.reload}). Used on reconnect. Hard deletes reach other clients through no event, so
15300
- * `query()` (`seedFirstPageSync`) reconciles them by diffing the re-queried page.
16447
+ * the watch query reconciles the loaded newest messages with the re-queried page
16448
+ * (`messagePaginator.reconcileNewestMessages`, against the loaded IDs captured before its await).
15301
16449
  *
15302
- * Failed (unsent) messages are kept: any that fell out of the window are re-ingested. The offline DB
15303
- * is read too, since a failed message can be absent from memory (cold boot, eviction).
16450
+ * Failed (unsent) messages are kept: those loaded or in the offline DB (cold boot, eviction)
16451
+ * before the request that are no longer loaded after it are ingested again. The offline DB is
16452
+ * read on a best-effort basis.
15304
16453
  */
15305
16454
  async reload() {
15306
16455
  if (this._reloading || !this.initialized && !this.offlineMode) return;
15307
16456
  this._reloading = true;
15308
16457
  try {
15309
16458
  const paginator = this.messagePaginator;
15310
- const headItems = paginator.headItems;
15311
- const requestedLimit = Math.max(headItems.length, paginator.pageSize ?? 0) || void 0;
16459
+ const requestedLimit = Math.max(paginator.anchoredHeadItems.length, paginator.pageSize ?? 0) || void 0;
15312
16460
  const offlineDb = this.getClient().offlineDb;
15313
- const failedInMemory = headItems.filter((message) => message.status === "failed");
15314
- const failedInDb = offlineDb ? await offlineDb.getFailedMessages({ cid: this.cid }) : [];
15315
- const failedById = /* @__PURE__ */ new Map();
15316
- for (const message of [...failedInDb, ...failedInMemory]) {
15317
- failedById.set(message.id, message);
15318
- }
15319
- const failedBefore = [...failedById.values()];
16461
+ const failedInDb = offlineDb ? await offlineDb.getFailedMessages({ cid: this.cid }).catch(() => []) : [];
16462
+ const failedBefore = paginator.getFailedMessagesToRestore(failedInDb);
15320
16463
  await this.watch({ messages: { limit: requestedLimit } });
15321
16464
  this.offlineMode = false;
15322
- if (failedBefore.length) {
15323
- const visible = new Set((paginator.items ?? []).map((message) => message.id));
15324
- paginator.batch(
15325
- () => {
15326
- for (const failed of failedBefore) {
15327
- if (!visible.has(failed.id)) paginator.ingestItem(failed);
15328
- }
15329
- },
15330
- { coalesce: true }
15331
- );
15332
- }
16465
+ paginator.restoreFailedMessages(failedBefore);
15333
16466
  } finally {
15334
16467
  this._reloading = false;
15335
16468
  }
@@ -15374,7 +16507,7 @@ var Channel = class extends ChannelApi {
15374
16507
  _countMessageAsUnread(message) {
15375
16508
  if (message.shadowed) return false;
15376
16509
  if (message.silent) return false;
15377
- if (message.parent_id && !message.show_in_channel) return false;
16510
+ if (isThreadOnlyReply(message)) return false;
15378
16511
  if (message.user?.id === this.getClient().userId) return false;
15379
16512
  if (message.user?.id && this.getClient().userMuteStatus(message.user.id))
15380
16513
  return false;
@@ -15387,6 +16520,9 @@ var Channel = class extends ChannelApi {
15387
16520
  /**
15388
16521
  * Counts the unread messages.
15389
16522
  *
16523
+ * Counting from `lastRead` counts within the channel's newest messages that are loaded (see
16524
+ * {@link newestKnownMessages}).
16525
+ *
15390
16526
  * @param lastRead - The time the user read a message, in unix nanoseconds (optional). Defaults to
15391
16527
  * the current user's read state.
15392
16528
  * @returns The unread count.
@@ -15394,7 +16530,7 @@ var Channel = class extends ChannelApi {
15394
16530
  countUnread(lastRead) {
15395
16531
  if (lastRead == null) return this.state.unreadCount;
15396
16532
  let count = 0;
15397
- const latestMessages = this.messagePaginator.headItems;
16533
+ const latestMessages = this.newestKnownMessages();
15398
16534
  for (let i = 0; i < latestMessages.length; i += 1) {
15399
16535
  const message = latestMessages[i];
15400
16536
  if (message.created_at > lastRead && this._countMessageAsUnread(message)) {
@@ -15404,7 +16540,18 @@ var Channel = class extends ChannelApi {
15404
16540
  return count;
15405
16541
  }
15406
16542
  /**
15407
- * Counts the unread messages that mention the current user.
16543
+ * The channel's newest messages that are loaded: the window that reaches the newest message (the
16544
+ * paginator's anchored head), or, while that window is not loaded, the messages received live since.
16545
+ * A window reached by a jump is never part of it, as the messages between it and the newest are
16546
+ * unknown.
16547
+ */
16548
+ newestKnownMessages() {
16549
+ const paginator = this.messagePaginator;
16550
+ return paginator.anchoredHeadItem !== void 0 ? paginator.anchoredHeadItems : paginator.logicalHeadItems;
16551
+ }
16552
+ /**
16553
+ * Counts the unread messages that mention the current user, within the channel's newest messages
16554
+ * that are loaded (see {@link newestKnownMessages}).
15408
16555
  *
15409
16556
  * @returns The unread mentions count.
15410
16557
  */
@@ -15412,7 +16559,7 @@ var Channel = class extends ChannelApi {
15412
16559
  const lastRead = this.lastRead();
15413
16560
  const userId = this.getClient().userId;
15414
16561
  let count = 0;
15415
- const latestMessages = this.messagePaginator.headItems;
16562
+ const latestMessages = this.newestKnownMessages();
15416
16563
  for (let i = 0; i < latestMessages.length; i += 1) {
15417
16564
  const message = latestMessages[i];
15418
16565
  if (this._countMessageAsUnread(message) && (lastRead == null || message.created_at > lastRead) && message.mentioned_users?.some((user) => user.id === userId)) {
@@ -15454,35 +16601,91 @@ var Channel = class extends ChannelApi {
15454
16601
  /**
15455
16602
  * Queries the API for messages, members and other channel fields.
15456
16603
  *
15457
- * @param options - The query options. Defaults to `{}`.
15458
- * @param messageSetToAddToIfDoesNotExist - `'latest'` is what the open paths (`watch`,
15459
- * `create`) pass: it seeds the message paginator with the fetched page. Other values do not
15460
- * seed it. Defaults to `'current'`.
16604
+ * The returned messages are not added to {@link Channel.messagePaginator}: the paginator loads its
16605
+ * own pages, and {@link Channel.watch} / {@link Channel.create} place the page they query.
16606
+ *
16607
+ * @param options - The query options (optional, defaults to `{}`).
15461
16608
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
15462
16609
  * into the request (optional).
15463
16610
  * @returns The query response.
15464
16611
  */
15465
- async query(options = {}, messageSetToAddToIfDoesNotExist = "current", requestOptions) {
16612
+ async query(options = {}, requestOptions) {
16613
+ return await this.runChannelQuery(options, requestOptions, { placeMessages: false });
16614
+ }
16615
+ /**
16616
+ * The query behind `query()`, `watch()` and `create()`, in three steps: sends the request
16617
+ * ({@link requestChannelState}), has the message paginator place the returned page when
16618
+ * `placeMessages` is set (`watch()`), then applies the rest of the response
16619
+ * ({@link applyChannelStateFromResponse}), all as a tracked query ({@link runTrackedQuery}).
16620
+ *
16621
+ * The page is placed before the rest is applied, because the rest reads the loaded messages: read
16622
+ * and delivery positions that come without a message id are looked up among them, and the latest
16623
+ * message is reported as delivered. A first page then takes the unread snapshot, from the read
16624
+ * state the rest brought. The message paginator's own queries keep the same order: they place
16625
+ * their page, then apply the rest with {@link applyChannelStateFromResponse}.
16626
+ */
16627
+ async runChannelQuery(options, requestOptions, { placeMessages }) {
16628
+ return await this.runTrackedQuery(async () => {
16629
+ const externalQuery = placeMessages ? this.messagePaginator.prepareExternalQuery(options.messages) : void 0;
16630
+ const state = await this.requestChannelState(
16631
+ externalQuery ? { ...options, messages: externalQuery.messagePaginationParams } : options,
16632
+ requestOptions,
16633
+ { placesNewestPage: externalQuery?.isNewestPage ?? false }
16634
+ );
16635
+ let placedFirstPage = false;
16636
+ try {
16637
+ if (externalQuery && Array.isArray(state.messages)) {
16638
+ placedFirstPage = externalQuery.placePage(state.messages.map(formatMessage));
16639
+ }
16640
+ } finally {
16641
+ this.applyChannelStateFromResponse(state, {
16642
+ isLatestMessageSet: externalQuery?.isNewestPage ?? false,
16643
+ watch: options.watch
16644
+ });
16645
+ }
16646
+ if (placedFirstPage) this.messagePaginator.seedUnreadSnapshot();
16647
+ return state;
16648
+ });
16649
+ }
16650
+ /**
16651
+ * Runs `run`, a query of this channel, as a tracked query: refused for a disposed instance, and
16652
+ * the channel counts as being queried until `run` settles ({@link isQueryingChannel}), so the
16653
+ * channel store keeps it meanwhile. Used by {@link runChannelQuery} and by the message
16654
+ * paginator's own queries.
16655
+ *
16656
+ * `run` starts synchronously: a paginator query publishes its loading flag before anything is
16657
+ * awaited, which keeps a second query in the same tick from starting.
16658
+ *
16659
+ * @internal
16660
+ */
16661
+ async runTrackedQuery(run) {
15466
16662
  if (this.pendingDisposal) throw this.disposedError();
15467
16663
  this._channelQueriesInFlight += 1;
15468
16664
  try {
15469
- return await this.runQuery(
15470
- options,
15471
- messageSetToAddToIfDoesNotExist,
15472
- requestOptions
15473
- );
16665
+ return await run();
15474
16666
  } finally {
15475
16667
  this._channelQueriesInFlight -= 1;
15476
16668
  }
15477
16669
  }
15478
- async runQuery(options, messageSetToAddToIfDoesNotExist, requestOptions) {
15479
- const candidateIds = messageSetToAddToIfDoesNotExist === "latest" ? new Set(this.messagePaginator.headItems.map((message) => message.id)) : void 0;
15480
- const requestedPageSize = options?.messages?.limit ?? this.messagePaginator.pageSize;
16670
+ /**
16671
+ * Sends the channel query and takes in what the response says about the channel itself: its id,
16672
+ * the cid it is stored under, its config, and its `last_message_at`, against which the message
16673
+ * paginator's head window is checked before any page is placed (see
16674
+ * `MessagePaginator.unmarkStaleHead`). The request of {@link runChannelQuery} and of the message
16675
+ * paginator's own queries, which run it as a tracked query ({@link runTrackedQuery}); it does not
16676
+ * track the query itself. Refused for a disposed instance, before anything is sent.
16677
+ *
16678
+ * `placesNewestPage`: the caller places the newest page with this response, which brings the
16679
+ * newest messages up to date, so the head window is not checked.
16680
+ *
16681
+ * @internal
16682
+ */
16683
+ async requestChannelState(options, requestOptions, { placesNewestPage = false } = {}) {
16684
+ if (this.pendingDisposal) throw this.disposedError();
15481
16685
  const queryPayload = {
15482
16686
  data: this._data,
15483
16687
  state: true,
15484
- ...options,
15485
- messages: options?.messages ?? (messageSetToAddToIfDoesNotExist === "latest" ? { limit: requestedPageSize } : void 0)
16688
+ ...options
15486
16689
  };
15487
16690
  const state = this.id ? await this.getOrCreate(queryPayload, requestOptions) : await this.getClient().getOrCreateDistinctChannel(
15488
16691
  { type: this.type },
@@ -15496,22 +16699,39 @@ var Channel = class extends ChannelApi {
15496
16699
  }
15497
16700
  this.getClient()._addChannelConfig(channel);
15498
16701
  this.messageComposer.applyServerRestrictions();
15499
- if (messageSetToAddToIfDoesNotExist === "latest" && Array.isArray(state.messages)) {
15500
- this.messagePaginator.seedFirstPageSync(
15501
- state.messages.map(formatMessage),
15502
- requestedPageSize,
15503
- options?.messages,
15504
- // Re-seeding a loaded window reconciles it instead of blanking it.
15505
- { candidateIds, reconcile: true }
15506
- );
16702
+ this.messagePaginator.setQueriedLatestMessageAt(channel.last_message_at);
16703
+ if (!placesNewestPage && this.isHeadLeftWithoutRefresh(queryPayload)) {
16704
+ this.messagePaginator.unmarkStaleHead();
15507
16705
  }
16706
+ return state;
16707
+ }
16708
+ /**
16709
+ * Whether nothing but this query brings the head window up to date, so its `last_message_at` may
16710
+ * show the window stale: the watch was stopped (`NotWatching`), or this query itself watches
16711
+ * again after a dropped connection (`WasWatching`), leaving nothing to re-watch with the newest
16712
+ * page. While the channel is watched, a message the window lacks is still on its way; after a
16713
+ * dropped connection, the re-watch that follows places the newest page (see
16714
+ * `ConnectionRecoveryManager`).
16715
+ */
16716
+ isHeadLeftWithoutRefresh(query) {
16717
+ if (this.watchStatus === ChannelWatchStatus.NotWatching) return true;
16718
+ return this.watchStatus === ChannelWatchStatus.WasWatching && !!query.watch;
16719
+ }
16720
+ /**
16721
+ * Applies a channel query response: watch status, read/members state, polls, reminders, composer,
16722
+ * channel data, and the `channels.queried` event and offline write. Called once the response's
16723
+ * page of messages, if any, is placed (see {@link runChannelQuery}).
16724
+ *
16725
+ * @internal
16726
+ */
16727
+ applyChannelStateFromResponse(state, { isLatestMessageSet, watch }) {
16728
+ const channel = state.channel;
15508
16729
  if (this.supersededBy) {
15509
16730
  this.watchStatus = ChannelWatchStatus.NotWatching;
15510
- } else if (queryPayload.watch) {
16731
+ } else if (watch) {
15511
16732
  this.watchStatus = ChannelWatchStatus.Watching;
15512
16733
  }
15513
16734
  this._initializeState(state);
15514
- const isLatestMessageSet = messageSetToAddToIfDoesNotExist === "latest" && !options?.messages?.id_around && !options?.messages?.created_at_around;
15515
16735
  this.getClient().polls.hydratePollCache(state.messages, true);
15516
16736
  this.getClient().reminders.hydrateState(state.messages);
15517
16737
  this.messageComposer.initStateFromChannelResponse(state);
@@ -15542,7 +16762,6 @@ var Channel = class extends ChannelApi {
15542
16762
  { method: "upsertChannels" }
15543
16763
  );
15544
16764
  this.getClient().syncDeliveredCandidates([this]);
15545
- return state;
15546
16765
  }
15547
16766
  /**
15548
16767
  * Bans a user from this channel.
@@ -15841,8 +17060,7 @@ var Channel = class extends ChannelApi {
15841
17060
  if (event.message) {
15842
17061
  this._extendEventWithOwnReactions(event);
15843
17062
  const formattedMessage = formatMessage(event.message);
15844
- const isThreadReply = !!event.message.parent_id && !event.message.show_in_channel;
15845
- if (!isThreadReply) {
17063
+ if (!isThreadOnlyReply(event.message)) {
15846
17064
  if (event.hard_delete) {
15847
17065
  this.messagePaginator.removeItem({ id: event.message.id });
15848
17066
  this.pinnedMessagesPaginator.removeItem({ id: event.message.id });
@@ -15875,7 +17093,7 @@ var Channel = class extends ChannelApi {
15875
17093
  if (event.message) {
15876
17094
  const client = this.getClient();
15877
17095
  const ownMessage = event.user?.id === client.user?.id;
15878
- const isThreadMessage = event.message.parent_id && !event.message.show_in_channel;
17096
+ const isThreadMessage = isThreadOnlyReply(event.message);
15879
17097
  if (!isThreadMessage) {
15880
17098
  const formattedMessage = formatMessage(event.message);
15881
17099
  this.messagePaginator.ingestItem(formattedMessage);
@@ -15938,11 +17156,10 @@ var Channel = class extends ChannelApi {
15938
17156
  if (event.message) {
15939
17157
  this._extendEventWithOwnReactions(event);
15940
17158
  const formattedMessage = formatMessage(event.message);
15941
- const { parent_id: parentId, show_in_channel: shownInChannel } = event.message;
15942
- const isThreadReply = !!parentId && !shownInChannel;
17159
+ const { parent_id: parentId } = event.message;
15943
17160
  const { threads } = this.getClient();
15944
17161
  const isAppliedByThread = !!parentId && threads.hasSubscriptions && !!threads.get(parentId);
15945
- if (!isThreadReply && !isAppliedByThread) {
17162
+ if (!isThreadOnlyReply(event.message) && !isAppliedByThread) {
15946
17163
  this.messagePaginator.ingestItem(formattedMessage);
15947
17164
  this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
15948
17165
  this.pinnedMessagesPaginator.ingestItem(formattedMessage);
@@ -16136,8 +17353,8 @@ var Channel = class extends ChannelApi {
16136
17353
  clientState.updateUserReference(state.membership.user, this.cid);
16137
17354
  }
16138
17355
  }
16139
- this.messagePaginator.seedLastMessageAt(state.channel?.last_message_at);
16140
- this.pinnedMessagesPaginator.seedFirstPageSync(
17356
+ this.messagePaginator.setQueriedLatestMessageAt(state.channel?.last_message_at);
17357
+ this.pinnedMessagesPaginator.placeExternalQueryPage(
16141
17358
  (state.pinned_messages || []).map(formatMessage),
16142
17359
  this.pinnedMessagesPaginator.pageSize
16143
17360
  );
@@ -16157,7 +17374,7 @@ var Channel = class extends ChannelApi {
16157
17374
  }
16158
17375
  const readUpdates = {};
16159
17376
  if (userID != null) {
16160
- const last_read = this.messagePaginator.lastMessageAt ?? nowNs();
17377
+ const last_read = this.messagePaginator.latestMessageAt ?? nowNs();
16161
17378
  if (user) {
16162
17379
  readUpdates[user.id] = {
16163
17380
  user,
@@ -17161,9 +18378,12 @@ var Thread = class extends WithSubscriptions {
17161
18378
  };
17162
18379
  /**
17163
18380
  * Re-queries the replies, sized to the loaded window, and reconciles them in place (the thread
17164
- * analogue of {@link Channel.reload}; recovery calls it for active threads). Failed replies are
17165
- * kept, read from the reply paginator since `failedRepliesMap` misses threads never activated or
17166
- * listed. Rethrows, except for a not-found answer on a thread that never had replies.
18381
+ * analogue of {@link Channel.reload}; recovery calls it for active threads). The thread applies
18382
+ * the response to itself ({@link Thread.hydrateState}), whether or not it is registered in
18383
+ * `client.threads`. Failed replies are kept: those loaded in the reply paginator or in the
18384
+ * offline DB before the request that are no longer loaded after it are ingested again (the
18385
+ * offline DB read is best effort). Rethrows, except for a not-found answer on a thread that never
18386
+ * had replies.
17167
18387
  */
17168
18388
  this.reload = async () => {
17169
18389
  if (this.state.getLatestValue().isLoading) {
@@ -17171,35 +18391,28 @@ var Thread = class extends WithSubscriptions {
17171
18391
  }
17172
18392
  this.state.partialNext({ isLoading: true });
17173
18393
  try {
17174
- const loadedReplies = this.messagePaginator.items ?? [];
17175
- const loadedReplyCount = loadedReplies.length;
18394
+ const loadedReplyCount = this.messagePaginator.items?.length ?? 0;
17176
18395
  const requestedReplyLimit = Math.max(loadedReplyCount, this.messagePaginator.pageSize ?? 0) || void 0;
17177
- const reconcileCandidateIds = new Set(loadedReplies.map((reply) => reply.id));
17178
- const failedBefore = loadedReplies.filter((reply) => reply.status === "failed");
17179
- const thread = await this.client.getThreadAndHydrate(
18396
+ const offlineDb = this.client.offlineDb;
18397
+ const failedInDb = offlineDb ? await offlineDb.getFailedMessages({ cid: this.channel.cid }).catch(() => []) : [];
18398
+ const failedBefore = this.messagePaginator.getFailedMessagesToRestore(failedInDb);
18399
+ const headIntervalItemIdsAtRequest = this.messagePaginator.getHeadIntervalItemIdsAtRequest();
18400
+ const { thread: threadData } = await this.client.getThread(
17180
18401
  { message_id: this.id },
17181
18402
  {
18403
+ participant_limit: DEFAULT_THREAD_PARTICIPANT_LIMIT,
17182
18404
  watch: true,
17183
18405
  reply_limit: requestedReplyLimit
17184
18406
  }
17185
18407
  );
17186
- this.hydrateState(thread, {
18408
+ this.channel.watchStatus = ChannelWatchStatus.Watching;
18409
+ this.hydrateState(threadData, {
17187
18410
  reconcile: {
17188
18411
  requestedLimit: requestedReplyLimit,
17189
- candidateIds: reconcileCandidateIds
18412
+ headIntervalItemIdsAtRequest
17190
18413
  }
17191
18414
  });
17192
- if (failedBefore.length) {
17193
- const visible = new Set((this.messagePaginator.items ?? []).map((r) => r.id));
17194
- this.messagePaginator.batch(
17195
- () => {
17196
- for (const failed of failedBefore) {
17197
- if (!visible.has(failed.id)) this.messagePaginator.ingestItem(failed);
17198
- }
17199
- },
17200
- { coalesce: true }
17201
- );
17202
- }
18415
+ this.messagePaginator.restoreFailedMessages(failedBefore);
17203
18416
  } catch (error) {
17204
18417
  const notFound = isDoesNotExistError(error) || error?.status === 404;
17205
18418
  const neverExisted = notFound && this.state.getLatestValue().replyCount === 0;
@@ -17209,46 +18422,27 @@ var Thread = class extends WithSubscriptions {
17209
18422
  this.state.partialNext({ isLoading: false });
17210
18423
  }
17211
18424
  };
17212
- this.hydrateState = (thread, options) => {
17213
- if (thread === this) {
17214
- return;
17215
- }
17216
- if (thread.id !== this.id) {
17217
- throw new Error(
17218
- "Cannot hydrate thread's state using thread with different threadId"
17219
- );
18425
+ /**
18426
+ * Updates the thread's state and its channel's members and custom data, and merges the replies
18427
+ * into the loaded window (with `reconcile`) or replaces it (without).
18428
+ */
18429
+ this.hydrateState = (threadData, options) => {
18430
+ if (threadData.parent_message_id !== this.id) {
18431
+ throw new Error("Cannot hydrate thread's state from another thread's response");
17220
18432
  }
17221
- const {
17222
- createdAt,
17223
- custom,
17224
- title,
17225
- deletedAt,
17226
- parentMessage,
17227
- participants,
17228
- read,
17229
- replyCount,
17230
- updatedAt
17231
- } = thread.state.getLatestValue();
18433
+ const serverState = formatThreadState(threadData, this.client.userId);
18434
+ const reconcile = options?.reconcile;
17232
18435
  const pendingReplies = Array.from(this.failedRepliesMap.values());
17233
- this.state.partialNext({
17234
- title,
17235
- createdAt,
17236
- custom,
17237
- deletedAt,
17238
- parentMessage,
17239
- participants,
17240
- read,
17241
- replyCount,
17242
- updatedAt,
17243
- isStateStale: false
17244
- });
17245
- if (parentMessage && this.hasSubscriptions) {
17246
- this.client.messageStore.upsert(parentMessage);
18436
+ ensureThreadChannel(this.client, threadData);
18437
+ this.state.partialNext({ ...serverState, isStateStale: false });
18438
+ if (this.hasSubscriptions) {
18439
+ this.client.messageStore.upsert(serverState.parentMessage);
17247
18440
  }
17248
- const incomingReplies = thread.messagePaginator.state.getLatestValue().items ?? [];
17249
- if (!options?.reconcile) this.messagePaginator.clearStateAndCache();
18441
+ const incomingReplies = (threadData.latest_replies ?? []).map(formatMessage);
18442
+ if (!reconcile) this.messagePaginator.clearStateAndCache();
18443
+ this.messagePaginator.setQueriedLatestMessageAt(threadData.last_message_at);
17250
18444
  if (typeof this.messagePaginator.items === "undefined") {
17251
- const isLastPage = incomingReplies.length === replyCount;
18445
+ const isLastPage = holdsEveryReply(incomingReplies, threadData);
17252
18446
  this.messagePaginator.setItems({
17253
18447
  valueOrFactory: incomingReplies,
17254
18448
  cursor: getCursorFromReplies(incomingReplies, isLastPage),
@@ -17256,10 +18450,9 @@ var Thread = class extends WithSubscriptions {
17256
18450
  isLastPage
17257
18451
  });
17258
18452
  } else {
17259
- this.messagePaginator.mergeNewestPage(incomingReplies, options?.reconcile);
18453
+ this.messagePaginator.reconcileNewestMessages(incomingReplies, reconcile);
17260
18454
  }
17261
18455
  pendingReplies.forEach((reply) => this.messagePaginator.ingestItem(reply));
17262
- this.messagePaginator.seedLastMessageAt(thread.messagePaginator.lastMessageAt);
17263
18456
  };
17264
18457
  this.registerSubscriptions = () => {
17265
18458
  if (this.hasSubscriptions) {
@@ -17525,39 +18718,12 @@ var Thread = class extends WithSubscriptions {
17525
18718
  */
17526
18719
  this.markAsRead = ({ force = false } = {}) => this.markRead({ force });
17527
18720
  if (threadData) {
17528
- if (!threadData.channel) {
17529
- throw new Error("Thread channel is required when threadData is provided");
17530
- }
17531
- if (!threadData.parent_message) {
17532
- throw new Error("Thread parent_message is required when threadData is provided");
17533
- }
17534
- const threadChannel = client.channelManager.ensure({
17535
- type: threadData.channel.type,
17536
- id: threadData.channel.id,
17537
- data: { custom: threadData.channel.custom }
17538
- });
17539
- threadChannel._hydrateMembers({
17540
- members: threadData.channel.members ?? [],
17541
- overrideCurrentState: false
17542
- });
17543
18721
  this.state = new import_state_store20.StateStore({
17544
18722
  active: false,
17545
18723
  isLoading: false,
17546
18724
  isStateStale: false,
17547
- channel: threadChannel,
17548
- createdAt: threadData.created_at,
17549
- deletedAt: threadData.deleted_at ?? null,
17550
- parentMessage: formatMessage(threadData.parent_message),
17551
- participants: threadData.thread_participants,
17552
- read: formatReadState(
17553
- !threadData.read || threadData.read.length === 0 ? getPlaceholderReadResponse(client.userId) : threadData.read
17554
- ),
17555
- // From the parent message: the top-level `threadData.reply_count` excludes soft-deleted
17556
- // replies, the parent's (like the channel's) includes them.
17557
- replyCount: threadData.parent_message.reply_count ?? 0,
17558
- updatedAt: threadData.updated_at ?? null,
17559
- title: threadData.title,
17560
- custom: threadData.custom ?? {}
18725
+ ...formatThreadState(threadData, client.userId),
18726
+ channel: ensureThreadChannel(client, threadData)
17561
18727
  });
17562
18728
  this.id = threadData.parent_message_id;
17563
18729
  } else {
@@ -17601,6 +18767,7 @@ var Thread = class extends WithSubscriptions {
17601
18767
  this.messagePaginator = new MessagePaginator(
17602
18768
  {
17603
18769
  channel: this.channel,
18770
+ thread: this,
17604
18771
  parentMessageId: this.id,
17605
18772
  requestSort: DEFAULT_SORT2,
17606
18773
  itemOrder: DEFAULT_ITEM_ORDER,
@@ -17616,7 +18783,7 @@ var Thread = class extends WithSubscriptions {
17616
18783
  );
17617
18784
  if (threadData?.latest_replies?.length) {
17618
18785
  const replies = threadData.latest_replies.map(formatMessage);
17619
- const isLastPage = replies.length === (threadData.reply_count ?? 0);
18786
+ const isLastPage = holdsEveryReply(replies, threadData);
17620
18787
  this.messagePaginator.setItems({
17621
18788
  valueOrFactory: replies,
17622
18789
  cursor: getCursorFromReplies(replies, isLastPage),
@@ -17624,7 +18791,7 @@ var Thread = class extends WithSubscriptions {
17624
18791
  isLastPage
17625
18792
  });
17626
18793
  }
17627
- this.messagePaginator.seedLastMessageAt(threadData?.last_message_at);
18794
+ this.messagePaginator.setQueriedLatestMessageAt(threadData?.last_message_at);
17628
18795
  this.messageComposer = new MessageComposer({
17629
18796
  client,
17630
18797
  composition: threadData?.draft ?? draft,
@@ -17679,6 +18846,10 @@ var Thread = class extends WithSubscriptions {
17679
18846
  get ownUnreadCount() {
17680
18847
  return ownUnreadCountSelector(this.client.userId)(this.state.getLatestValue());
17681
18848
  }
18849
+ /** See {@link Thread.activate}. */
18850
+ get active() {
18851
+ return this.state.getLatestValue().active;
18852
+ }
17682
18853
  };
17683
18854
  var normalizeThreadParticipants = (participants, channelCid) => {
17684
18855
  if (!participants) return void 0;
@@ -17693,6 +18864,44 @@ var normalizeThreadParticipants = (participants, channelCid) => {
17693
18864
  })
17694
18865
  );
17695
18866
  };
18867
+ var DEFAULT_THREAD_PARTICIPANT_LIMIT = 100;
18868
+ var ensureThreadChannel = (client, threadData) => {
18869
+ if (!threadData.channel) {
18870
+ throw new Error("Thread channel is required when threadData is provided");
18871
+ }
18872
+ const channel = client.channelManager.ensure({
18873
+ type: threadData.channel.type,
18874
+ id: threadData.channel.id,
18875
+ data: { custom: threadData.channel.custom }
18876
+ });
18877
+ channel._hydrateMembers({
18878
+ members: threadData.channel.members ?? [],
18879
+ overrideCurrentState: false
18880
+ });
18881
+ return channel;
18882
+ };
18883
+ var holdsEveryReply = (replies, threadData) => replies.length === (threadData.reply_count ?? 0);
18884
+ var formatThreadState = (threadData, currentUserId) => {
18885
+ const parentMessage = threadData.parent_message;
18886
+ if (!parentMessage) {
18887
+ throw new Error("Thread parent_message is required when threadData is provided");
18888
+ }
18889
+ return {
18890
+ createdAt: threadData.created_at,
18891
+ custom: threadData.custom ?? {},
18892
+ deletedAt: threadData.deleted_at ?? null,
18893
+ parentMessage: formatMessage(parentMessage),
18894
+ participants: threadData.thread_participants,
18895
+ read: formatReadState(
18896
+ !threadData.read || threadData.read.length === 0 ? getPlaceholderReadResponse(currentUserId) : threadData.read
18897
+ ),
18898
+ // From the parent message: the top-level `threadData.reply_count` excludes soft-deleted
18899
+ // replies, the parent's (like the channel's) includes them.
18900
+ replyCount: parentMessage.reply_count ?? 0,
18901
+ title: threadData.title,
18902
+ updatedAt: threadData.updated_at ?? null
18903
+ };
18904
+ };
17696
18905
  var formatReadState = (read) => read.reduce((state, userRead) => {
17697
18906
  state[userRead.user.id] = {
17698
18907
  user: userRead.user,
@@ -17760,7 +18969,7 @@ var ModerationApi = class {
17760
18969
  requestOptions
17761
18970
  );
17762
18971
  }
17763
- deleteActionConfig(pathParams, requestOptions) {
18972
+ deleteActionConfig(pathParams, _request, requestOptions) {
17764
18973
  return this.apiClient.sendRequest(
17765
18974
  "DELETE",
17766
18975
  "/api/v2/moderation/action_config/{id}",
@@ -17782,7 +18991,7 @@ var ModerationApi = class {
17782
18991
  requestOptions
17783
18992
  );
17784
18993
  }
17785
- getAppeal(pathParams, requestOptions) {
18994
+ getAppeal(pathParams, _request, requestOptions) {
17786
18995
  return this.apiClient.sendRequest(
17787
18996
  "GET",
17788
18997
  "/api/v2/moderation/appeal/{id}",
@@ -17892,7 +19101,7 @@ var ModerationApi = class {
17892
19101
  requestOptions
17893
19102
  );
17894
19103
  }
17895
- listQueues(requestOptions) {
19104
+ listQueues(_request, requestOptions) {
17896
19105
  return this.apiClient.sendRequest(
17897
19106
  "GET",
17898
19107
  "/api/v2/moderation/queues",
@@ -17914,7 +19123,7 @@ var ModerationApi = class {
17914
19123
  requestOptions
17915
19124
  );
17916
19125
  }
17917
- getQueue(pathParams, requestOptions) {
19126
+ getQueue(pathParams, _request, requestOptions) {
17918
19127
  return this.apiClient.sendRequest(
17919
19128
  "GET",
17920
19129
  "/api/v2/moderation/queues/{id}",
@@ -18138,19 +19347,20 @@ var ThreadManager = class extends WithSubscriptions {
18138
19347
  return thread;
18139
19348
  };
18140
19349
  /**
18141
- * The registered instance for a thread a query just built, else the query's own, so events keep
18142
- * reaching the one managed instance. A stale registered thread is refreshed from the query unless
18143
- * it is active (it reloads itself).
19350
+ * The registered thread, or a new one when none is registered. Only a stale thread nobody has
19351
+ * open is hydrated from `threadData`: an open one reloads itself, and events keep any other
19352
+ * current (an answer that was in flight would roll them back). The channel's members and custom
19353
+ * data are applied either way, as the constructor does for a new thread.
18144
19354
  *
18145
19355
  * @internal
18146
19356
  */
18147
- this.resolveQueried = (incoming) => {
18148
- const stored = this.threadStore.get(incoming.id);
18149
- if (!stored) return incoming;
18150
- if (stored.hasStaleState && !stored.state.getLatestValue().active) {
18151
- stored.hydrateState(incoming);
18152
- }
18153
- return stored;
19357
+ this.resolveQueried = (threadData) => {
19358
+ const registered = this.threadStore.get(threadData.parent_message_id);
19359
+ if (!registered) return new Thread({ client: this.client, threadData });
19360
+ const { active, isStateStale } = registered.state.getLatestValue();
19361
+ if (isStateStale && !active) registered.hydrateState(threadData);
19362
+ else ensureThreadChannel(this.client, threadData);
19363
+ return registered;
18154
19364
  };
18155
19365
  /**
18156
19366
  * Keeps `thread` for the session: resolvable through {@link ThreadManager.get} and subscribed
@@ -19686,9 +20896,9 @@ var _ChannelManager = class _ChannelManager extends WithSubscriptions {
19686
20896
  * Removes every stored channel the app disconnected (`pendingDisposal`), whatever holds it, then
19687
20897
  * every one that is neither watched nor held; lists drop them. Kept: watched channels
19688
20898
  * (`watching`, or `wasWatching` until restored), active ones ({@link Channel.activate}), ones
19689
- * being loaded, and ones held in {@link ChannelManager.channelStore} (lists link theirs; threads,
19690
- * the composer cache and channel search hold theirs through claims,
19691
- * {@link EntityStore.addClaim}).
20899
+ * being queried (`Channel.isQueryingChannel`), and ones held in
20900
+ * {@link ChannelManager.channelStore} (lists link theirs; threads, the composer cache and channel
20901
+ * search hold theirs through claims, {@link EntityStore.addClaim}).
19692
20902
  *
19693
20903
  * The SDK never calls this, as it cannot see channels an app keeps in its own state. Call it when
19694
20904
  * the app is done with them (e.g. after `searchController.dispose()`), and keep a channel your
@@ -19941,7 +21151,7 @@ var _ChannelManager = class _ChannelManager extends WithSubscriptions {
19941
21151
  /**
19942
21152
  * Removes a paginator: it leaves `state.paginators`, stops receiving WS-driven updates and gets
19943
21153
  * its own `filterQueryResults` back. Its loaded items stay, and a query scheduled through
19944
- * `nextDebounced` is cancelled.
21154
+ * `toTailDebounced` or `toHeadDebounced` is cancelled.
19945
21155
  *
19946
21156
  * @param paginatorOrId - The paginator to remove, or its ID.
19947
21157
  * @returns The removed paginator, or `undefined` when this manager did not hold it.
@@ -21935,7 +23145,7 @@ var ChatApi = class {
21935
23145
  constructor(apiClient) {
21936
23146
  this.apiClient = apiClient;
21937
23147
  }
21938
- getApp(requestOptions) {
23148
+ getApp(_request, requestOptions) {
21939
23149
  return this.apiClient.sendRequest(
21940
23150
  "GET",
21941
23151
  "/api/v2/app",
@@ -21968,17 +23178,6 @@ var ChatApi = class {
21968
23178
  requestOptions
21969
23179
  );
21970
23180
  }
21971
- importBlockList(pathParams, request, requestOptions) {
21972
- return this.apiClient.sendRequest(
21973
- "POST",
21974
- "/api/v2/blocklists/{id}/import",
21975
- pathParams,
21976
- void 0,
21977
- request,
21978
- "application/json",
21979
- requestOptions
21980
- );
21981
- }
21982
23181
  deleteBlockList(pathParams, request, requestOptions) {
21983
23182
  return this.apiClient.sendRequest(
21984
23183
  "DELETE",
@@ -22374,7 +23573,7 @@ var ChatApi = class {
22374
23573
  requestOptions
22375
23574
  );
22376
23575
  }
22377
- getMessage(pathParams, requestOptions) {
23576
+ getMessage(pathParams, _request, requestOptions) {
22378
23577
  return this.apiClient.sendRequest(
22379
23578
  "GET",
22380
23579
  "/api/v2/chat/messages/{id}",
@@ -22429,7 +23628,7 @@ var ChatApi = class {
22429
23628
  requestOptions
22430
23629
  );
22431
23630
  }
22432
- deleteReaction(pathParams, requestOptions) {
23631
+ deleteReaction(pathParams, _request, requestOptions) {
22433
23632
  return this.apiClient.sendRequest(
22434
23633
  "DELETE",
22435
23634
  "/api/v2/chat/messages/{id}/reaction/{type}",
@@ -22484,7 +23683,7 @@ var ChatApi = class {
22484
23683
  requestOptions
22485
23684
  );
22486
23685
  }
22487
- deletePollVote(pathParams, requestOptions) {
23686
+ deletePollVote(pathParams, _request, requestOptions) {
22488
23687
  return this.apiClient.sendRequest(
22489
23688
  "DELETE",
22490
23689
  "/api/v2/chat/messages/{message_id}/polls/{poll_id}/vote/{vote_id}",
@@ -22495,7 +23694,7 @@ var ChatApi = class {
22495
23694
  requestOptions
22496
23695
  );
22497
23696
  }
22498
- deleteReminder(pathParams, requestOptions) {
23697
+ deleteReminder(pathParams, _request, requestOptions) {
22499
23698
  return this.apiClient.sendRequest(
22500
23699
  "DELETE",
22501
23700
  "/api/v2/chat/messages/{message_id}/reminders",
@@ -22616,7 +23815,7 @@ var ChatApi = class {
22616
23815
  requestOptions
22617
23816
  );
22618
23817
  }
22619
- deleteScheduledMessage(pathParams, requestOptions) {
23818
+ deleteScheduledMessage(pathParams, _request, requestOptions) {
22620
23819
  return this.apiClient.sendRequest(
22621
23820
  "DELETE",
22622
23821
  "/api/v2/chat/scheduled_messages/{id}",
@@ -22638,14 +23837,14 @@ var ChatApi = class {
22638
23837
  requestOptions
22639
23838
  );
22640
23839
  }
22641
- sendScheduledMessageNow(pathParams, request, requestOptions) {
23840
+ sendScheduledMessageNow(pathParams, _request, requestOptions) {
22642
23841
  return this.apiClient.sendRequest(
22643
23842
  "POST",
22644
23843
  "/api/v2/chat/scheduled_messages/{id}/send_now",
22645
23844
  pathParams,
22646
23845
  void 0,
22647
- request ?? {},
22648
- "application/json",
23846
+ void 0,
23847
+ void 0,
22649
23848
  requestOptions
22650
23849
  );
22651
23850
  }
@@ -22708,7 +23907,7 @@ var ChatApi = class {
22708
23907
  requestOptions
22709
23908
  );
22710
23909
  }
22711
- unreadCounts(requestOptions) {
23910
+ unreadCounts(_request, requestOptions) {
22712
23911
  return this.apiClient.sendRequest(
22713
23912
  "GET",
22714
23913
  "/api/v2/chat/unread",
@@ -22730,7 +23929,7 @@ var ChatApi = class {
22730
23929
  requestOptions
22731
23930
  );
22732
23931
  }
22733
- listDevices(requestOptions) {
23932
+ listDevices(_request, requestOptions) {
22734
23933
  return this.apiClient.sendRequest(
22735
23934
  "GET",
22736
23935
  "/api/v2/devices",
@@ -22818,7 +24017,7 @@ var ChatApi = class {
22818
24017
  requestOptions
22819
24018
  );
22820
24019
  }
22821
- deletePoll(pathParams, requestOptions) {
24020
+ deletePoll(pathParams, _request, requestOptions) {
22822
24021
  return this.apiClient.sendRequest(
22823
24022
  "DELETE",
22824
24023
  "/api/v2/polls/{poll_id}",
@@ -22829,7 +24028,7 @@ var ChatApi = class {
22829
24028
  requestOptions
22830
24029
  );
22831
24030
  }
22832
- getPoll(pathParams, requestOptions) {
24031
+ getPoll(pathParams, _request, requestOptions) {
22833
24032
  return this.apiClient.sendRequest(
22834
24033
  "GET",
22835
24034
  "/api/v2/polls/{poll_id}",
@@ -22873,7 +24072,7 @@ var ChatApi = class {
22873
24072
  requestOptions
22874
24073
  );
22875
24074
  }
22876
- deletePollOption(pathParams, requestOptions) {
24075
+ deletePollOption(pathParams, _request, requestOptions) {
22877
24076
  return this.apiClient.sendRequest(
22878
24077
  "DELETE",
22879
24078
  "/api/v2/polls/{poll_id}/options/{option_id}",
@@ -22884,7 +24083,7 @@ var ChatApi = class {
22884
24083
  requestOptions
22885
24084
  );
22886
24085
  }
22887
- getPollOption(pathParams, requestOptions) {
24086
+ getPollOption(pathParams, _request, requestOptions) {
22888
24087
  return this.apiClient.sendRequest(
22889
24088
  "GET",
22890
24089
  "/api/v2/polls/{poll_id}/options/{option_id}",
@@ -23093,7 +24292,7 @@ var ChatApi = class {
23093
24292
  requestOptions
23094
24293
  );
23095
24294
  }
23096
- getBlockedUsers(requestOptions) {
24295
+ getBlockedUsers(_request, requestOptions) {
23097
24296
  return this.apiClient.sendRequest(
23098
24297
  "GET",
23099
24298
  "/api/v2/users/block",
@@ -23115,7 +24314,7 @@ var ChatApi = class {
23115
24314
  requestOptions
23116
24315
  );
23117
24316
  }
23118
- getUserLiveLocations(requestOptions) {
24317
+ getUserLiveLocations(_request, requestOptions) {
23119
24318
  return this.apiClient.sendRequest(
23120
24319
  "GET",
23121
24320
  "/api/v2/users/live_locations",
@@ -23571,7 +24770,7 @@ var StreamChat = class _StreamChat extends ChatApi {
23571
24770
  return this.userAgent;
23572
24771
  }
23573
24772
  if (!this.cachedUserAgent) {
23574
- const version = "10.0.0-rc.23";
24773
+ const version = "10.0.0-rc.24";
23575
24774
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
23576
24775
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
23577
24776
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -23826,12 +25025,14 @@ var StreamChat = class _StreamChat extends ChatApi {
23826
25025
  /**
23827
25026
  * Retrieves application settings.
23828
25027
  *
25028
+ * @param _request - Unused. Holds the request position so `requestOptions` stays the
25029
+ * second argument, as on the generated methods; pass `undefined`.
23829
25030
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
23830
25031
  * into the request (optional).
23831
25032
  * @returns The application settings response.
23832
25033
  */
23833
- async getAppSettings(requestOptions) {
23834
- return await (this.appSettingsPromise = this.getApp(requestOptions));
25034
+ async getAppSettings(_request, requestOptions) {
25035
+ return await (this.appSettingsPromise = this.getApp(void 0, requestOptions));
23835
25036
  }
23836
25037
  /**
23837
25038
  * Creates a guest user.
@@ -24078,12 +25279,10 @@ var StreamChat = class _StreamChat extends ChatApi {
24078
25279
  return await super.queryChannels(payload, requestOptions);
24079
25280
  }
24080
25281
  async queryChannelsAndHydrate(options, stateOptions = {}, requestOptions) {
24081
- const candidateIdsByCid = /* @__PURE__ */ new Map();
25282
+ const headIntervalItemIdsAtRequestByCid = /* @__PURE__ */ new Map();
24082
25283
  for (const channel of this.channelManager.values()) {
24083
- const { cid } = channel;
24084
- const head = channel.messagePaginator?.headItems;
24085
- if (head?.length)
24086
- candidateIdsByCid.set(cid, new Set(head.map((message) => message.id)));
25284
+ const idsAtRequest = channel.messagePaginator?.getHeadIntervalItemIdsAtRequest();
25285
+ if (idsAtRequest) headIntervalItemIdsAtRequestByCid.set(channel.cid, idsAtRequest);
24087
25286
  }
24088
25287
  const queryChannelsResponse = await this.queryChannels(options, requestOptions);
24089
25288
  const channels = queryChannelsResponse.channels;
@@ -24104,7 +25303,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24104
25303
  channels,
24105
25304
  stateOptions,
24106
25305
  options,
24107
- candidateIdsByCid
25306
+ headIntervalItemIdsAtRequestByCid
24108
25307
  );
24109
25308
  if (stateOptions.withResponse) {
24110
25309
  return {
@@ -24147,7 +25346,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24147
25346
  }
24148
25347
  return await this.queryReactions(...args);
24149
25348
  }
24150
- hydrateChannels(channelsFromApi = [], stateOptions = {}, queryChannelsOptions, candidateIdsByCid) {
25349
+ hydrateChannels(channelsFromApi = [], stateOptions = {}, queryChannelsOptions, headIntervalItemIdsAtRequestByCid) {
24151
25350
  const { skipInitialization, offlineMode = false } = stateOptions;
24152
25351
  const channels = [];
24153
25352
  for (const channelState of channelsFromApi) {
@@ -24161,18 +25360,25 @@ var StreamChat = class _StreamChat extends ChatApi {
24161
25360
  c.state.partialNext(
24162
25361
  offlineMode ? { initialized: false, offlineMode: true } : { initialized: true, offlineMode: false }
24163
25362
  );
25363
+ const wasWatching = c.watchStatus === ChannelWatchStatus.Watching;
24164
25364
  if (!offlineMode && (queryChannelsOptions?.watch ?? this.wsConnection.isHealthy)) {
24165
25365
  c.watchStatus = ChannelWatchStatus.Watching;
24166
25366
  }
24167
25367
  c.push_preferences = channelState.push_preferences;
24168
25368
  const willInitialize = skipInitialization === void 0 || !skipInitialization.includes(channelState.channel.id);
24169
25369
  const requestedPageSize = queryChannelsOptions?.message_limit ?? DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE;
24170
- if (willInitialize && !c.active && (!c.messagePaginator.isInitialized || c.messagePaginator.isActiveIntervalAtHead)) {
24171
- c.messagePaginator.seedFirstPageSync(
25370
+ const placesNewestPage = willInitialize && !c.active;
25371
+ let placedFirstPage = false;
25372
+ if (placesNewestPage) {
25373
+ c.messagePaginator.setQueriedLatestMessageAt(
25374
+ channelState.channel?.last_message_at
25375
+ );
25376
+ placedFirstPage = c.messagePaginator.placeExternalNewestPage(
24172
25377
  channelState.messages.map(formatMessage),
24173
- requestedPageSize,
24174
- void 0,
24175
- { reconcile: true, candidateIds: candidateIdsByCid?.get(c.cid) }
25378
+ {
25379
+ headIntervalItemIdsAtRequest: headIntervalItemIdsAtRequestByCid?.get(c.cid),
25380
+ requestedLimit: requestedPageSize
25381
+ }
24176
25382
  );
24177
25383
  }
24178
25384
  if (skipInitialization === void 0) {
@@ -24180,6 +25386,10 @@ var StreamChat = class _StreamChat extends ChatApi {
24180
25386
  } else if (!skipInitialization.includes(channelState.channel.id)) {
24181
25387
  c._initializeState(channelState);
24182
25388
  }
25389
+ if (placedFirstPage) c.messagePaginator.seedUnreadSnapshot();
25390
+ if (willInitialize && !c.active && !wasWatching && !(placesNewestPage && channelState.messages.length)) {
25391
+ c.messagePaginator.unmarkStaleHead();
25392
+ }
24183
25393
  if (willInitialize) {
24184
25394
  this.polls.hydratePollCache(channelState.messages, true);
24185
25395
  this.reminders.hydrateState(channelState.messages);
@@ -24398,7 +25608,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24398
25608
  const parentMessages = response.threads.map((thread) => thread.parent_message);
24399
25609
  this.polls.hydratePollCache(parentMessages);
24400
25610
  const threads = response.threads.map(
24401
- (thread) => this.threads.resolveQueried(new Thread({ client: this, threadData: thread }))
25611
+ (threadData) => this.threads.resolveQueried(threadData)
24402
25612
  );
24403
25613
  if (optionsWithDefaults.watch) threads.forEach(markThreadChannelWatched);
24404
25614
  return { threads, next: response.next };
@@ -24422,7 +25632,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24422
25632
  throw new Error("Please specify the messageId when calling getThreadAndHydrate");
24423
25633
  }
24424
25634
  const optionsWithDefaults = {
24425
- participant_limit: 100,
25635
+ participant_limit: DEFAULT_THREAD_PARTICIPANT_LIMIT,
24426
25636
  reply_limit: 3,
24427
25637
  watch: true,
24428
25638
  ...options
@@ -24432,9 +25642,7 @@ var StreamChat = class _StreamChat extends ChatApi {
24432
25642
  optionsWithDefaults,
24433
25643
  requestOptions
24434
25644
  );
24435
- const thread = this.threads.resolveQueried(
24436
- new Thread({ client: this, threadData: response.thread })
24437
- );
25645
+ const thread = this.threads.resolveQueried(response.thread);
24438
25646
  if (optionsWithDefaults.watch) markThreadChannelWatched(thread);
24439
25647
  return thread;
24440
25648
  }
@@ -25320,7 +26528,10 @@ var OfflineDBSyncManager = class {
25320
26528
  );
25321
26529
  } else {
25322
26530
  const queryPromises = result.events.map(
25323
- (event) => this.offlineDb.handleEvent({ event, execute: false })
26531
+ (event) => (
26532
+ // `Event` leaves out the spec's never-sent `'*'` placeholder member of `WSEvent`.
26533
+ this.offlineDb.handleEvent({ event, execute: false })
26534
+ )
25324
26535
  );
25325
26536
  const queriesArray = await Promise.all(queryPromises);
25326
26537
  const queries = queriesArray.flat();
@@ -25513,7 +26724,7 @@ var AbstractOfflineDB = class {
25513
26724
  }) => {
25514
26725
  const client = this.client;
25515
26726
  const { cid, message, user } = event;
25516
- if (!message || message.parent_id && !message.show_in_channel) {
26727
+ if (!message || isThreadOnlyReply(message)) {
25517
26728
  return [];
25518
26729
  }
25519
26730
  return await this.queriesWithChannelGuard(
@@ -25680,8 +26891,9 @@ var AbstractOfflineDB = class {
25680
26891
  return queries;
25681
26892
  };
25682
26893
  /**
25683
- * The channel's persisted messages with a local `failed` status, which `Channel.reload`
25684
- * re-ingests. Built on {@link getChannels}, so a custom offline DB implements nothing extra.
26894
+ * The channel's persisted messages with a local `failed` status, which `Channel.reload` and
26895
+ * `Thread.reload` re-ingest. Built on {@link getChannels}, so a custom offline DB implements
26896
+ * nothing extra.
25685
26897
  *
25686
26898
  * @param payload.cid - The channel whose failed messages to read.
25687
26899
  * @returns The failed messages, formatted.