stream-chat 10.1.0 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1391,7 +1391,7 @@ var parseVersion = (raw) => {
1391
1391
  };
1392
1392
  var readInjectedVersion = () => {
1393
1393
  try {
1394
- return "10.1.0";
1394
+ return "10.2.0";
1395
1395
  } catch {
1396
1396
  return void 0;
1397
1397
  }
@@ -4880,6 +4880,8 @@ var BasePaginator = class {
4880
4880
  this._itemIntervals = /* @__PURE__ */ new Map();
4881
4881
  /** How many claims on the active interval were made; the latest one decides it. */
4882
4882
  this._activeIntervalClaimCount = 0;
4883
+ /** How many times `resetState()` ran, which tells the work started before a reset apart. */
4884
+ this._stateResetCount = 0;
4883
4885
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
4884
4886
  this._pageSetWithoutQuery = false;
4885
4887
  this.boosts = /* @__PURE__ */ new Map();
@@ -4970,6 +4972,11 @@ var BasePaginator = class {
4970
4972
  cursor: this.config.initialCursor,
4971
4973
  offset: this.config.initialOffset ?? 0
4972
4974
  });
4975
+ this.state.addPreprocessor((next) => {
4976
+ if (!next.isLoading && next.loadingDirection !== void 0) {
4977
+ next.loadingDirection = void 0;
4978
+ }
4979
+ });
4973
4980
  this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
4974
4981
  this.intervalViews = new StateStore8({
4975
4982
  logicalHead: [],
@@ -5016,6 +5023,10 @@ var BasePaginator = class {
5016
5023
  get isLoading() {
5017
5024
  return this.state.getLatestValue().isLoading;
5018
5025
  }
5026
+ /** See {@link PaginatorState.loadingDirection}. */
5027
+ get loadingDirection() {
5028
+ return this.state.getLatestValue().loadingDirection;
5029
+ }
5019
5030
  /**
5020
5031
  * True once a query has run or a non-empty interval was loaded without one (`setItems`, or a
5021
5032
  * subclass calling `recordLoadedIntervalQueryShape`). Cleared by `resetState`.
@@ -5045,6 +5056,7 @@ var BasePaginator = class {
5045
5056
  hasMoreHead: true,
5046
5057
  hasMoreTail: true,
5047
5058
  isLoading: false,
5059
+ loadingDirection: void 0,
5048
5060
  items: void 0,
5049
5061
  lastQueryError: void 0,
5050
5062
  cursor: this.config.initialCursor,
@@ -5287,7 +5299,8 @@ var BasePaginator = class {
5287
5299
  /**
5288
5300
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
5289
5301
  * besides its page, once the page is placed with `placeParams`. Runs once for every response that
5290
- * arrived, also when extracting or placing its page failed. Does nothing by default.
5302
+ * arrived, also when placing its page failed or a reset made it ignored (see
5303
+ * {@link executeQuery}). Does nothing by default.
5291
5304
  */
5292
5305
  applyQueryResponseRest(_response, _placeParams) {
5293
5306
  }
@@ -6606,33 +6619,44 @@ var BasePaginator = class {
6606
6619
  }
6607
6620
  /**
6608
6621
  * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
6609
- * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
6610
- * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
6611
- * caller to end the query.
6622
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
6623
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
6612
6624
  */
6613
- async fetchQueryResponseWithRetries(params = {}) {
6614
- const remainingRetries = params.retryCount ?? 0;
6615
- try {
6616
- return await this.fetchQueryResponse(params);
6617
- } catch (e) {
6618
- if (remainingRetries > 0) {
6619
- await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6620
- return await this.fetchQueryResponseWithRetries({
6621
- ...params,
6622
- retryCount: remainingRetries - 1
6623
- });
6624
- }
6625
- const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6626
- if (!isOfflineSupportEnabledWithItems) {
6627
- this.state.partialNext({ lastQueryError: e });
6628
- }
6629
- if (this.config.throwErrors) {
6630
- this.state.partialNext({ isLoading: false });
6631
- throw e;
6625
+ async fetchQueryResponseWithRetries(params = {}, {
6626
+ checkWasStateResetDuringQuery = () => false
6627
+ } = {}) {
6628
+ let remainingRetries = params.retryCount ?? 0;
6629
+ while (true) {
6630
+ try {
6631
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
6632
+ } catch (e) {
6633
+ if (checkWasStateResetDuringQuery()) return null;
6634
+ if (remainingRetries > 0) {
6635
+ remainingRetries -= 1;
6636
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6637
+ if (checkWasStateResetDuringQuery()) return null;
6638
+ continue;
6639
+ }
6640
+ return this.reportFailedFetch(e);
6632
6641
  }
6633
- return null;
6634
6642
  }
6635
6643
  }
6644
+ /**
6645
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
6646
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
6647
+ * and the caller ends the query.
6648
+ */
6649
+ reportFailedFetch(e) {
6650
+ const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6651
+ if (!isOfflineSupportEnabledWithItems) {
6652
+ this.state.partialNext({ lastQueryError: e });
6653
+ }
6654
+ if (this.config.throwErrors) {
6655
+ this.state.partialNext({ isLoading: false });
6656
+ throw e;
6657
+ }
6658
+ return null;
6659
+ }
6636
6660
  /**
6637
6661
  * Runs one query through the query pipeline, step by step:
6638
6662
  *
@@ -6649,9 +6673,13 @@ var BasePaginator = class {
6649
6673
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
6650
6674
  * rejects the call only with `throwErrors` set.
6651
6675
  *
6652
- * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
6653
- * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
6654
- * placed, with `isSuperseded`.
6676
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
6677
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
6678
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
6679
+ *
6680
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
6681
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
6682
+ * is `null` when no page was placed, with `isSuperseded`.
6655
6683
  *
6656
6684
  * @param params - Query parameters.
6657
6685
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -6678,10 +6706,18 @@ var BasePaginator = class {
6678
6706
  async runPreparedQuery({
6679
6707
  fetchParams,
6680
6708
  offlinePreloadPromise,
6681
- placeParams
6709
+ placeParams,
6710
+ checkWasStateResetDuringQuery
6682
6711
  }) {
6683
6712
  if (offlinePreloadPromise) await offlinePreloadPromise;
6684
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
6713
+ if (checkWasStateResetDuringQuery()) return void 0;
6714
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
6715
+ checkWasStateResetDuringQuery
6716
+ });
6717
+ if (checkWasStateResetDuringQuery()) {
6718
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
6719
+ return void 0;
6720
+ }
6685
6721
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
6686
6722
  const errors = [];
6687
6723
  const runStep = (step) => {
@@ -6698,6 +6734,16 @@ var BasePaginator = class {
6698
6734
  runStep(() => this.applyQueryResponseRest(response, placeParams));
6699
6735
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
6700
6736
  }
6737
+ /**
6738
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
6739
+ * An ignored query reports nothing, so an error here is swallowed.
6740
+ */
6741
+ applyResponseRestOfIgnoredQuery(response, placeParams) {
6742
+ try {
6743
+ this.applyQueryResponseRest(response, placeParams);
6744
+ } catch {
6745
+ }
6746
+ }
6701
6747
  /**
6702
6748
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
6703
6749
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -6712,6 +6758,14 @@ var BasePaginator = class {
6712
6758
  targetInterval: placed?.targetInterval ?? null
6713
6759
  };
6714
6760
  }
6761
+ /**
6762
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
6763
+ * reset uses it to ignore its results instead of writing them into the reset state.
6764
+ */
6765
+ makeStateResetWatcher() {
6766
+ const resetCount = this._stateResetCount;
6767
+ return () => resetCount !== this._stateResetCount;
6768
+ }
6715
6769
  /**
6716
6770
  * Whether a query claims the active interval by default (see
6717
6771
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -6746,6 +6800,7 @@ var BasePaginator = class {
6746
6800
  updateState = true
6747
6801
  }) {
6748
6802
  if (!this.canExecuteQuery({ direction, reset })) return void 0;
6803
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
6749
6804
  const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
6750
6805
  const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
6751
6806
  const isForcedReset = reset === "yes" && !keepPreviousItems;
@@ -6779,17 +6834,28 @@ var BasePaginator = class {
6779
6834
  publishStateBeforeFirstQuery(void 0);
6780
6835
  } else {
6781
6836
  offlinePreloadPromise = (async () => {
6782
- const items = await this.preloadFirstPageFromOfflineDb({
6783
- direction,
6784
- queryShape,
6785
- reset,
6786
- retryCount
6787
- });
6837
+ let items;
6838
+ try {
6839
+ items = await this.preloadFirstPageFromOfflineDb({
6840
+ direction,
6841
+ queryShape,
6842
+ reset,
6843
+ retryCount
6844
+ });
6845
+ } catch (error) {
6846
+ if (checkWasStateResetDuringQuery()) return;
6847
+ throw error;
6848
+ }
6849
+ if (checkWasStateResetDuringQuery()) return;
6788
6850
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
6789
6851
  })();
6790
6852
  }
6791
6853
  } else if (!silent) {
6792
- this.state.partialNext({ isLoading: true });
6854
+ const loadsAtEdge = !isFirstPage && !forcedQueryShape;
6855
+ this.state.partialNext({
6856
+ isLoading: true,
6857
+ loadingDirection: loadsAtEdge ? direction : void 0
6858
+ });
6793
6859
  }
6794
6860
  const isAtCallersShape = !!forcedQueryShape;
6795
6861
  const continuesOwnCursor = !isFirstPage && !isAtCallersShape;
@@ -6807,7 +6873,8 @@ var BasePaginator = class {
6807
6873
  queryShape,
6808
6874
  requestedPageSize: this.getRequestedPageSize(queryShape),
6809
6875
  updateState
6810
- }
6876
+ },
6877
+ checkWasStateResetDuringQuery
6811
6878
  };
6812
6879
  }
6813
6880
  /**
@@ -6851,6 +6918,36 @@ var BasePaginator = class {
6851
6918
  }) {
6852
6919
  return continuesIntervalId !== void 0 && continuesIntervalId !== this._activeIntervalId;
6853
6920
  }
6921
+ /**
6922
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
6923
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
6924
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
6925
+ */
6926
+ emptyPageKeepsLoadedItems({
6927
+ isFirstPage,
6928
+ keepPreviousItems
6929
+ }) {
6930
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
6931
+ }
6932
+ /**
6933
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
6934
+ * own `updateState: false` query settles a list without items
6935
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
6936
+ * what the stored page changed.
6937
+ */
6938
+ commitsPlacedState(placement, page, { endsQuery }) {
6939
+ return placement.updateState !== false || endsQuery && this.emptyPageSettlesListWithoutItems(placement, page);
6940
+ }
6941
+ /**
6942
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
6943
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
6944
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
6945
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
6946
+ * owns the list.
6947
+ */
6948
+ emptyPageSettlesListWithoutItems(placement, page) {
6949
+ return placement.isFirstPage && page.length === 0 && !this.hasResults && !placement.startsSeparateInterval && !this.claimIsSuperseded(placement);
6950
+ }
6854
6951
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
6855
6952
  claimIsSuperseded({ activeIntervalClaim }) {
6856
6953
  return activeIntervalClaim !== void 0 && !this.isLatestActiveIntervalClaim(activeIntervalClaim);
@@ -6870,16 +6967,17 @@ var BasePaginator = class {
6870
6967
  * database. A page from a query the paginator did not run is placed without any of that, as one
6871
6968
  * of the paginator's own queries may still be running.
6872
6969
  */
6873
- placePage({
6874
- startsSeparateInterval,
6875
- direction,
6876
- isFirstPage,
6877
- keepPreviousItems,
6878
- queryShape,
6879
- requestedPageSize,
6880
- results,
6881
- updateState = true
6882
- }, { endsQuery }) {
6970
+ placePage(placement, { endsQuery }) {
6971
+ const {
6972
+ startsSeparateInterval,
6973
+ direction,
6974
+ isFirstPage,
6975
+ keepPreviousItems,
6976
+ queryShape,
6977
+ requestedPageSize,
6978
+ results,
6979
+ updateState = true
6980
+ } = placement;
6883
6981
  const stateUpdate = endsQuery ? { isLoading: false, lastQueryError: void 0 } : {};
6884
6982
  const { items, headward, tailward } = results;
6885
6983
  const filteredItems = this.filterQueryResults(items);
@@ -6904,7 +7002,7 @@ var BasePaginator = class {
6904
7002
  if (interval && updateState) {
6905
7003
  this.setActiveInterval(interval, { updateState: false });
6906
7004
  stateUpdate.items = this.intervalToItems(interval);
6907
- } else if (updateState && !filteredItems.length && (keepPreviousItems || !isFirstPage)) {
7005
+ } else if (updateState && !filteredItems.length && this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })) {
6908
7006
  stateUpdate.items = this.items;
6909
7007
  }
6910
7008
  const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
@@ -6995,8 +7093,9 @@ var BasePaginator = class {
6995
7093
  }
6996
7094
  }
6997
7095
  const state = endsQuery ? this.getStateAfterQuery(stateUpdate, isFirstPage) : { ...this.state.getLatestValue(), ...stateUpdate };
6998
- if (updateState) this.state.next(state);
6999
- else this.publishStoredPage({ endsQuery, interval, state });
7096
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
7097
+ this.state.next(state);
7098
+ } else this.publishStoredPage({ endsQuery, interval, state });
7000
7099
  if (endsQuery && isFirstPage) {
7001
7100
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7002
7101
  }
@@ -7026,7 +7125,12 @@ var BasePaginator = class {
7026
7125
  cancelScheduledQuery() {
7027
7126
  this._executeQueryDebounced.cancel();
7028
7127
  }
7128
+ /**
7129
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
7130
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
7131
+ */
7029
7132
  resetState() {
7133
+ this._stateResetCount++;
7030
7134
  this._lastQueryShape = void 0;
7031
7135
  this._pageSetWithoutQuery = false;
7032
7136
  this.state.next(this.initialState);
@@ -7114,6 +7218,13 @@ var DEFAULT_BACKEND_SORT = [
7114
7218
  { direction: -1, field: "last_message_at" },
7115
7219
  { direction: -1, field: "updated_at" }
7116
7220
  ];
7221
+ var withoutUndefinedValues = (value) => {
7222
+ if (Array.isArray(value)) return value.map(withoutUndefinedValues);
7223
+ if (!value || typeof value !== "object" || isClassInstance(value)) return value;
7224
+ return Object.fromEntries(
7225
+ Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, withoutUndefinedValues(entry)])
7226
+ );
7227
+ };
7117
7228
  var getQueryIdentity = (queryShape) => {
7118
7229
  if (!queryShape) return queryShape;
7119
7230
  const {
@@ -7123,7 +7234,9 @@ var getQueryIdentity = (queryShape) => {
7123
7234
  offset: ____,
7124
7235
  ...identity
7125
7236
  } = queryShape;
7126
- return identity;
7237
+ return Object.fromEntries(
7238
+ Object.entries(identity).map(([key, value]) => [key, withoutUndefinedValues(value)])
7239
+ );
7127
7240
  };
7128
7241
  var hasPaginationQueryShapeChanged = (prevQueryShape, nextQueryShape) => !isEqual(getQueryIdentity(prevQueryShape), getQueryIdentity(nextQueryShape));
7129
7242
  var archivedFilterResolver = {
@@ -7303,12 +7416,13 @@ var ChannelPaginator = class extends BasePaginator {
7303
7416
  if (!this.client.offlineDb?.getChannelsForQuery || !this.client.user?.id || !queryShape)
7304
7417
  return void 0;
7305
7418
  const { stateOptions: _, ...request } = queryShape;
7419
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7306
7420
  try {
7307
7421
  const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
7308
7422
  userId: this.client.user.id,
7309
7423
  options: request
7310
7424
  });
7311
- if (cachedQuery) {
7425
+ if (cachedQuery && !checkWasStateResetDuringQuery()) {
7312
7426
  if (cachedQuery.predefinedFilter) {
7313
7427
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
7314
7428
  }
@@ -7320,7 +7434,7 @@ var ChannelPaginator = class extends BasePaginator {
7320
7434
  }
7321
7435
  } catch (error) {
7322
7436
  chatLoggerSystem.getLogger("channel").error(error.message);
7323
- if (this.config.throwErrors) throw error;
7437
+ if (this.config.throwErrors && !checkWasStateResetDuringQuery()) throw error;
7324
7438
  }
7325
7439
  return;
7326
7440
  };
@@ -7342,6 +7456,7 @@ var ChannelPaginator = class extends BasePaginator {
7342
7456
  this._itemsLoadedFromOfflineDB = false;
7343
7457
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
7344
7458
  const { stateOptions, ...request } = queryShape;
7459
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7345
7460
  let items;
7346
7461
  if (this.config.doRequest) {
7347
7462
  items = (await this.config.doRequest(queryShape)).items;
@@ -7351,7 +7466,9 @@ var ChannelPaginator = class extends BasePaginator {
7351
7466
  withResponse: true
7352
7467
  });
7353
7468
  items = response.channels;
7354
- this._pendingPredefinedFilter = response.predefined_filter;
7469
+ if (!checkWasStateResetDuringQuery()) {
7470
+ this._pendingPredefinedFilter = response.predefined_filter;
7471
+ }
7355
7472
  }
7356
7473
  return { items };
7357
7474
  };
@@ -7547,19 +7664,55 @@ var ChannelPaginator = class extends BasePaginator {
7547
7664
  get channelStateOptions() {
7548
7665
  return this._channelStateOptions;
7549
7666
  }
7667
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
7550
7668
  set staticFilters(filters) {
7551
- this._staticFilters = filters;
7669
+ this.changeQuery(() => {
7670
+ this._staticFilters = filters;
7671
+ });
7552
7672
  }
7673
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
7553
7674
  set sort(sort) {
7554
- this._sort = sort;
7555
- this.sortComparator = this.buildSortComparator(this.effectiveSort);
7675
+ this.changeQuery(() => {
7676
+ this._sort = sort;
7677
+ this.sortComparator = this.buildSortComparator(this.effectiveSort);
7678
+ });
7556
7679
  }
7680
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
7557
7681
  set options(options) {
7558
- this._options = options;
7682
+ this.changeQuery(() => {
7683
+ this._options = options;
7684
+ });
7559
7685
  }
7560
7686
  set channelStateOptions(options) {
7561
7687
  this._channelStateOptions = options;
7562
7688
  }
7689
+ /**
7690
+ * Applies a change to a query input (filters, sort, options) and resets the list with
7691
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
7692
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
7693
+ * loaded pages.
7694
+ *
7695
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
7696
+ * query's first page. A query still running for the old query is ignored; a debounced query
7697
+ * stays scheduled and runs with the new query.
7698
+ */
7699
+ changeQuery(applyChange) {
7700
+ const queryBefore = this.getNextQueryShape();
7701
+ applyChange();
7702
+ if (this.queryChangeDiscardsPages(queryBefore)) this.resetState();
7703
+ }
7704
+ /**
7705
+ * Whether the next query has another identity than `queryBefore`
7706
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
7707
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
7708
+ * and `member_limit` and `message_limit` (how much of each channel loads).
7709
+ */
7710
+ queryChangeDiscardsPages(queryBefore) {
7711
+ return this.config.hasPaginationQueryShapeChanged(
7712
+ queryBefore,
7713
+ this.getNextQueryShape()
7714
+ );
7715
+ }
7563
7716
  get sortComparatorFactory() {
7564
7717
  return this._sortComparatorFactory;
7565
7718
  }
@@ -7574,7 +7727,21 @@ var ChannelPaginator = class extends BasePaginator {
7574
7727
  getItemId(item) {
7575
7728
  return item.cid;
7576
7729
  }
7730
+ /**
7731
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
7732
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
7733
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
7734
+ * cache stored without it) matches by `staticFilters`.
7735
+ */
7736
+ get awaitsPredefinedFilter() {
7737
+ return !!this._options?.predefined_filter && !this._predefinedFilter && !this.hasResults;
7738
+ }
7739
+ /**
7740
+ * Whether `channel` belongs to the list. Nothing does while a list with
7741
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
7742
+ */
7577
7743
  matchesFilter(channel) {
7744
+ if (this.awaitsPredefinedFilter) return false;
7578
7745
  const filters = this.buildMatchFilters();
7579
7746
  if (channel.data?.hidden && !filterConstrainsField(filters, "hidden")) return false;
7580
7747
  return itemMatchesFilter(channel, filters, {
@@ -7689,6 +7856,7 @@ var ChannelPaginator = class extends BasePaginator {
7689
7856
  return;
7690
7857
  }
7691
7858
  this._queryAwaitingSync = queryShape;
7859
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7692
7860
  if (!this.isInitialized) {
7693
7861
  let cachedChannels;
7694
7862
  try {
@@ -7700,6 +7868,7 @@ var ChannelPaginator = class extends BasePaginator {
7700
7868
  this._queryAwaitingSync = void 0;
7701
7869
  throw error;
7702
7870
  }
7871
+ if (checkWasStateResetDuringQuery()) return;
7703
7872
  if (cachedChannels?.length) {
7704
7873
  this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
7705
7874
  this._itemsLoadedFromOfflineDB = true;
@@ -7753,11 +7922,20 @@ var ChannelPaginator = class extends BasePaginator {
7753
7922
  onEntityRemoved(id, channel) {
7754
7923
  this.removeItem({ id, item: channel });
7755
7924
  }
7925
+ /**
7926
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
7927
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
7928
+ * stays scheduled.
7929
+ */
7756
7930
  resetState() {
7757
- super.resetState();
7758
- this._itemIndex.clear();
7759
7931
  this._queryAwaitingSync = void 0;
7760
7932
  this._tailQueryAwaitingRecovery = false;
7933
+ this._itemsLoadedFromOfflineDB = false;
7934
+ this._replaceOfflineSeedOnResponse = false;
7935
+ this._pendingPredefinedFilter = void 0;
7936
+ if (this._predefinedFilter) this.applyPredefinedFilterResponse(void 0);
7937
+ super.resetState();
7938
+ this._itemIndex.clear();
7761
7939
  }
7762
7940
  removeItem(params) {
7763
7941
  const coordinates = super.removeItem(params);
@@ -8052,6 +8230,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8052
8230
  this.claimActiveInterval();
8053
8231
  this.showLoadedInterval(interval);
8054
8232
  } else {
8233
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8055
8234
  const result = await this.executeQuery({
8056
8235
  claimsActiveInterval: true,
8057
8236
  // Always send a limit: the replies endpoint ignores `id_around` without one.
@@ -8060,6 +8239,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8060
8239
  updateState: false
8061
8240
  });
8062
8241
  if (result?.isSuperseded) return false;
8242
+ if (checkWasStateResetDuringQuery()) return false;
8063
8243
  localMessage = this.getItem(messageId);
8064
8244
  if (!localMessage || !result || !result.targetInterval) {
8065
8245
  this.channel.getClient().notifications.addError({
@@ -8101,12 +8281,14 @@ var MessageIntervalPaginator = class extends BasePaginator {
8101
8281
  */
8102
8282
  this.jumpToTheLatestMessage = async (options) => {
8103
8283
  if (!this.latestHeadInterval) {
8284
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8104
8285
  const result = await this.executeQuery({
8105
8286
  claimsActiveInterval: true,
8106
8287
  queryShape: { limit: this.pageSize },
8107
8288
  updateState: false
8108
8289
  });
8109
8290
  if (result?.isSuperseded) return false;
8291
+ if (checkWasStateResetDuringQuery()) return false;
8110
8292
  }
8111
8293
  const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
8112
8294
  if (!latestMessageId) {
@@ -9237,6 +9419,15 @@ var MessageIntervalPaginator = class extends BasePaginator {
9237
9419
  offlineDb.hardDeleteMessages({ ids }).catch(() => {
9238
9420
  });
9239
9421
  }
9422
+ /**
9423
+ * Also drops the focus signal of an earlier jump. Whatever claims the active interval decides what
9424
+ * is shown, so the earlier target must not be scrolled to or highlighted there. A jump claims
9425
+ * before it emits its own signal, so it keeps that one.
9426
+ */
9427
+ claimActiveInterval() {
9428
+ this.clearMessageFocusSignal();
9429
+ return super.claimActiveInterval();
9430
+ }
9240
9431
  clearStateAndCache() {
9241
9432
  this.resetState();
9242
9433
  this._itemIndex.clear();
@@ -9480,6 +9671,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9480
9671
  messages: this.state.getLatestValue().items ?? []
9481
9672
  });
9482
9673
  if (!inferredLastReadMessageId) {
9674
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
9483
9675
  const result = await this.executeQuery({
9484
9676
  claimsActiveInterval: true,
9485
9677
  queryShape: {
@@ -9490,6 +9682,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9490
9682
  updateState: false
9491
9683
  });
9492
9684
  if (result?.isSuperseded) return false;
9685
+ if (checkWasStateResetDuringQuery()) return false;
9493
9686
  if (result) {
9494
9687
  ({
9495
9688
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -27691,6 +27884,7 @@ var AbstractOfflineDB = class {
27691
27884
 
27692
27885
  // src/LiveLocationManager.ts
27693
27886
  import { StateStore as StateStore31 } from "@stream-io/state-store";
27887
+ var logger22 = chatLoggerSystem.getLogger("live-location-manager");
27694
27888
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
27695
27889
  var canTrackLocation = (location) => typeof location.end_at === "number" && Number.isFinite(location.end_at) && location.end_at >= nowNs();
27696
27890
  var isTrackableLocation = (location) => canTrackLocation(location);
@@ -27713,6 +27907,12 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27713
27907
  throw new Error("Live-location sharing is reserved for client-side use only");
27714
27908
  }
27715
27909
  super();
27910
+ /**
27911
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
27912
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
27913
+ * for these ids are skipped instead of being tracked again.
27914
+ */
27915
+ this.unregisteredDuringLoad = /* @__PURE__ */ new Set();
27716
27916
  /** Subscribes to the `'liveLocationManager'` configuration key. Idempotent. */
27717
27917
  this.subscribeConfiguration = () => {
27718
27918
  if (this.unsubscribeConfiguration) return;
@@ -27782,9 +27982,18 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27782
27982
  initializeConfig(config) {
27783
27983
  this.configController.initialize(config);
27784
27984
  }
27985
+ /**
27986
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
27987
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
27988
+ * whether or not the load has finished.
27989
+ *
27990
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
27991
+ * registered, so shares started later are still tracked. The next `init()`, position update or
27992
+ * `connection.recovered` event retries the load.
27993
+ */
27785
27994
  async init() {
27786
- await this.assureStateInit();
27787
27995
  this.registerSubscriptions();
27996
+ await this.assureStateInit();
27788
27997
  }
27789
27998
  get messages() {
27790
27999
  return this.state.getLatestValue().messages;
@@ -27798,24 +28007,37 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27798
28007
  }
27799
28008
  return this._deviceId;
27800
28009
  }
27801
- async assureStateInit() {
27802
- if (this.stateIsReady) return;
27803
- const { active_live_locations } = await this.client.getUserLiveLocations();
27804
- this.state.next({
27805
- messages: new Map(
27806
- active_live_locations.filter(isTrackableLocation).map((location) => [
27807
- location.message_id,
27808
- {
28010
+ /** Loads the active live locations unless already loaded. Never rejects. */
28011
+ assureStateInit() {
28012
+ if (this.stateIsReady) return Promise.resolve();
28013
+ this.stateInitPromise ?? (this.stateInitPromise = this.loadState().finally(() => {
28014
+ this.stateInitPromise = void 0;
28015
+ this.unregisteredDuringLoad.clear();
28016
+ }));
28017
+ return this.stateInitPromise;
28018
+ }
28019
+ async loadState() {
28020
+ try {
28021
+ const { active_live_locations } = await this.client.getUserLiveLocations();
28022
+ this.state.next((currentValue) => {
28023
+ const messages = new Map(currentValue.messages);
28024
+ for (const location of active_live_locations.filter(isTrackableLocation)) {
28025
+ if (messages.has(location.message_id) || this.unregisteredDuringLoad.has(location.message_id))
28026
+ continue;
28027
+ messages.set(location.message_id, {
27809
28028
  ...location,
27810
28029
  stopSharingTimeout: this.scheduleStopSharing(
27811
28030
  location.message_id,
27812
28031
  location.end_at
27813
28032
  )
27814
- }
27815
- ])
27816
- ),
27817
- ready: true
27818
- });
28033
+ });
28034
+ }
28035
+ return { ...currentValue, messages, ready: true, lastQueryError: void 0 };
28036
+ });
28037
+ } catch (error) {
28038
+ logger22.warn("Failed to load the active live locations", error);
28039
+ this.state.partialNext({ lastQueryError: error });
28040
+ }
27819
28041
  }
27820
28042
  subscribeTargetMessagesChange() {
27821
28043
  let unsubscribeWatchLocation = null;
@@ -27878,11 +28100,11 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27878
28100
  if (event.type === "live_location_sharing.started") {
27879
28101
  this.registerMessage(event.message);
27880
28102
  } else if (event.type === "message.updated") {
27881
- const isRegistered = this.messages.has(event.message.id);
27882
- if (isRegistered && !isValidLiveLocationMessage(event.message)) {
28103
+ if (isValidLiveLocationMessage(event.message)) {
28104
+ this.registerMessage(event.message);
28105
+ } else {
27883
28106
  this.unregisterMessages([event.message.id]);
27884
28107
  }
27885
- this.registerMessage(event.message);
27886
28108
  } else {
27887
28109
  this.unregisterMessages([event.message.id]);
27888
28110
  }
@@ -27891,6 +28113,10 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27891
28113
  this.client.on("live_location_sharing.stopped", (event) => {
27892
28114
  if (!event.live_location) return;
27893
28115
  this.unregisterMessages([event.live_location?.message_id]);
28116
+ }),
28117
+ // Retries a failed load once the connection is back. No-op once the state is loaded.
28118
+ this.client.on("connection.recovered", () => {
28119
+ void this.assureStateInit();
27894
28120
  })
27895
28121
  ];
27896
28122
  return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
@@ -27936,6 +28162,9 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27936
28162
  });
27937
28163
  }
27938
28164
  unregisterMessages(messageIds) {
28165
+ if (this.stateInitPromise) {
28166
+ messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
28167
+ }
27939
28168
  const messages = this.messages;
27940
28169
  const removedMessages = new Set(messageIds);
27941
28170
  const newMessages = new Map(