stream-chat 10.1.0 → 10.1.1

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.1.1";
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();
@@ -5287,7 +5289,8 @@ var BasePaginator = class {
5287
5289
  /**
5288
5290
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
5289
5291
  * 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.
5292
+ * arrived, also when placing its page failed or a reset made it ignored (see
5293
+ * {@link executeQuery}). Does nothing by default.
5291
5294
  */
5292
5295
  applyQueryResponseRest(_response, _placeParams) {
5293
5296
  }
@@ -6606,33 +6609,44 @@ var BasePaginator = class {
6606
6609
  }
6607
6610
  /**
6608
6611
  * {@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.
6612
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
6613
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
6612
6614
  */
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;
6615
+ async fetchQueryResponseWithRetries(params = {}, {
6616
+ checkWasStateResetDuringQuery = () => false
6617
+ } = {}) {
6618
+ let remainingRetries = params.retryCount ?? 0;
6619
+ while (true) {
6620
+ try {
6621
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
6622
+ } catch (e) {
6623
+ if (checkWasStateResetDuringQuery()) return null;
6624
+ if (remainingRetries > 0) {
6625
+ remainingRetries -= 1;
6626
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6627
+ if (checkWasStateResetDuringQuery()) return null;
6628
+ continue;
6629
+ }
6630
+ return this.reportFailedFetch(e);
6632
6631
  }
6633
- return null;
6634
6632
  }
6635
6633
  }
6634
+ /**
6635
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
6636
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
6637
+ * and the caller ends the query.
6638
+ */
6639
+ reportFailedFetch(e) {
6640
+ const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6641
+ if (!isOfflineSupportEnabledWithItems) {
6642
+ this.state.partialNext({ lastQueryError: e });
6643
+ }
6644
+ if (this.config.throwErrors) {
6645
+ this.state.partialNext({ isLoading: false });
6646
+ throw e;
6647
+ }
6648
+ return null;
6649
+ }
6636
6650
  /**
6637
6651
  * Runs one query through the query pipeline, step by step:
6638
6652
  *
@@ -6649,9 +6663,13 @@ var BasePaginator = class {
6649
6663
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
6650
6664
  * rejects the call only with `throwErrors` set.
6651
6665
  *
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`.
6666
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
6667
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
6668
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
6669
+ *
6670
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
6671
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
6672
+ * is `null` when no page was placed, with `isSuperseded`.
6655
6673
  *
6656
6674
  * @param params - Query parameters.
6657
6675
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -6678,10 +6696,18 @@ var BasePaginator = class {
6678
6696
  async runPreparedQuery({
6679
6697
  fetchParams,
6680
6698
  offlinePreloadPromise,
6681
- placeParams
6699
+ placeParams,
6700
+ checkWasStateResetDuringQuery
6682
6701
  }) {
6683
6702
  if (offlinePreloadPromise) await offlinePreloadPromise;
6684
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
6703
+ if (checkWasStateResetDuringQuery()) return void 0;
6704
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
6705
+ checkWasStateResetDuringQuery
6706
+ });
6707
+ if (checkWasStateResetDuringQuery()) {
6708
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
6709
+ return void 0;
6710
+ }
6685
6711
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
6686
6712
  const errors = [];
6687
6713
  const runStep = (step) => {
@@ -6698,6 +6724,16 @@ var BasePaginator = class {
6698
6724
  runStep(() => this.applyQueryResponseRest(response, placeParams));
6699
6725
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
6700
6726
  }
6727
+ /**
6728
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
6729
+ * An ignored query reports nothing, so an error here is swallowed.
6730
+ */
6731
+ applyResponseRestOfIgnoredQuery(response, placeParams) {
6732
+ try {
6733
+ this.applyQueryResponseRest(response, placeParams);
6734
+ } catch {
6735
+ }
6736
+ }
6701
6737
  /**
6702
6738
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
6703
6739
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -6712,6 +6748,14 @@ var BasePaginator = class {
6712
6748
  targetInterval: placed?.targetInterval ?? null
6713
6749
  };
6714
6750
  }
6751
+ /**
6752
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
6753
+ * reset uses it to ignore its results instead of writing them into the reset state.
6754
+ */
6755
+ makeStateResetWatcher() {
6756
+ const resetCount = this._stateResetCount;
6757
+ return () => resetCount !== this._stateResetCount;
6758
+ }
6715
6759
  /**
6716
6760
  * Whether a query claims the active interval by default (see
6717
6761
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -6746,6 +6790,7 @@ var BasePaginator = class {
6746
6790
  updateState = true
6747
6791
  }) {
6748
6792
  if (!this.canExecuteQuery({ direction, reset })) return void 0;
6793
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
6749
6794
  const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
6750
6795
  const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
6751
6796
  const isForcedReset = reset === "yes" && !keepPreviousItems;
@@ -6779,12 +6824,19 @@ var BasePaginator = class {
6779
6824
  publishStateBeforeFirstQuery(void 0);
6780
6825
  } else {
6781
6826
  offlinePreloadPromise = (async () => {
6782
- const items = await this.preloadFirstPageFromOfflineDb({
6783
- direction,
6784
- queryShape,
6785
- reset,
6786
- retryCount
6787
- });
6827
+ let items;
6828
+ try {
6829
+ items = await this.preloadFirstPageFromOfflineDb({
6830
+ direction,
6831
+ queryShape,
6832
+ reset,
6833
+ retryCount
6834
+ });
6835
+ } catch (error) {
6836
+ if (checkWasStateResetDuringQuery()) return;
6837
+ throw error;
6838
+ }
6839
+ if (checkWasStateResetDuringQuery()) return;
6788
6840
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
6789
6841
  })();
6790
6842
  }
@@ -6807,7 +6859,8 @@ var BasePaginator = class {
6807
6859
  queryShape,
6808
6860
  requestedPageSize: this.getRequestedPageSize(queryShape),
6809
6861
  updateState
6810
- }
6862
+ },
6863
+ checkWasStateResetDuringQuery
6811
6864
  };
6812
6865
  }
6813
6866
  /**
@@ -6851,6 +6904,36 @@ var BasePaginator = class {
6851
6904
  }) {
6852
6905
  return continuesIntervalId !== void 0 && continuesIntervalId !== this._activeIntervalId;
6853
6906
  }
6907
+ /**
6908
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
6909
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
6910
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
6911
+ */
6912
+ emptyPageKeepsLoadedItems({
6913
+ isFirstPage,
6914
+ keepPreviousItems
6915
+ }) {
6916
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
6917
+ }
6918
+ /**
6919
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
6920
+ * own `updateState: false` query settles a list without items
6921
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
6922
+ * what the stored page changed.
6923
+ */
6924
+ commitsPlacedState(placement, page, { endsQuery }) {
6925
+ return placement.updateState !== false || endsQuery && this.emptyPageSettlesListWithoutItems(placement, page);
6926
+ }
6927
+ /**
6928
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
6929
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
6930
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
6931
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
6932
+ * owns the list.
6933
+ */
6934
+ emptyPageSettlesListWithoutItems(placement, page) {
6935
+ return placement.isFirstPage && page.length === 0 && !this.hasResults && !placement.startsSeparateInterval && !this.claimIsSuperseded(placement);
6936
+ }
6854
6937
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
6855
6938
  claimIsSuperseded({ activeIntervalClaim }) {
6856
6939
  return activeIntervalClaim !== void 0 && !this.isLatestActiveIntervalClaim(activeIntervalClaim);
@@ -6870,16 +6953,17 @@ var BasePaginator = class {
6870
6953
  * database. A page from a query the paginator did not run is placed without any of that, as one
6871
6954
  * of the paginator's own queries may still be running.
6872
6955
  */
6873
- placePage({
6874
- startsSeparateInterval,
6875
- direction,
6876
- isFirstPage,
6877
- keepPreviousItems,
6878
- queryShape,
6879
- requestedPageSize,
6880
- results,
6881
- updateState = true
6882
- }, { endsQuery }) {
6956
+ placePage(placement, { endsQuery }) {
6957
+ const {
6958
+ startsSeparateInterval,
6959
+ direction,
6960
+ isFirstPage,
6961
+ keepPreviousItems,
6962
+ queryShape,
6963
+ requestedPageSize,
6964
+ results,
6965
+ updateState = true
6966
+ } = placement;
6883
6967
  const stateUpdate = endsQuery ? { isLoading: false, lastQueryError: void 0 } : {};
6884
6968
  const { items, headward, tailward } = results;
6885
6969
  const filteredItems = this.filterQueryResults(items);
@@ -6904,7 +6988,7 @@ var BasePaginator = class {
6904
6988
  if (interval && updateState) {
6905
6989
  this.setActiveInterval(interval, { updateState: false });
6906
6990
  stateUpdate.items = this.intervalToItems(interval);
6907
- } else if (updateState && !filteredItems.length && (keepPreviousItems || !isFirstPage)) {
6991
+ } else if (updateState && !filteredItems.length && this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })) {
6908
6992
  stateUpdate.items = this.items;
6909
6993
  }
6910
6994
  const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
@@ -6995,8 +7079,9 @@ var BasePaginator = class {
6995
7079
  }
6996
7080
  }
6997
7081
  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 });
7082
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
7083
+ this.state.next(state);
7084
+ } else this.publishStoredPage({ endsQuery, interval, state });
7000
7085
  if (endsQuery && isFirstPage) {
7001
7086
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7002
7087
  }
@@ -7026,7 +7111,12 @@ var BasePaginator = class {
7026
7111
  cancelScheduledQuery() {
7027
7112
  this._executeQueryDebounced.cancel();
7028
7113
  }
7114
+ /**
7115
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
7116
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
7117
+ */
7029
7118
  resetState() {
7119
+ this._stateResetCount++;
7030
7120
  this._lastQueryShape = void 0;
7031
7121
  this._pageSetWithoutQuery = false;
7032
7122
  this.state.next(this.initialState);
@@ -7114,6 +7204,13 @@ var DEFAULT_BACKEND_SORT = [
7114
7204
  { direction: -1, field: "last_message_at" },
7115
7205
  { direction: -1, field: "updated_at" }
7116
7206
  ];
7207
+ var withoutUndefinedValues = (value) => {
7208
+ if (Array.isArray(value)) return value.map(withoutUndefinedValues);
7209
+ if (!value || typeof value !== "object" || isClassInstance(value)) return value;
7210
+ return Object.fromEntries(
7211
+ Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, withoutUndefinedValues(entry)])
7212
+ );
7213
+ };
7117
7214
  var getQueryIdentity = (queryShape) => {
7118
7215
  if (!queryShape) return queryShape;
7119
7216
  const {
@@ -7123,7 +7220,9 @@ var getQueryIdentity = (queryShape) => {
7123
7220
  offset: ____,
7124
7221
  ...identity
7125
7222
  } = queryShape;
7126
- return identity;
7223
+ return Object.fromEntries(
7224
+ Object.entries(identity).map(([key, value]) => [key, withoutUndefinedValues(value)])
7225
+ );
7127
7226
  };
7128
7227
  var hasPaginationQueryShapeChanged = (prevQueryShape, nextQueryShape) => !isEqual(getQueryIdentity(prevQueryShape), getQueryIdentity(nextQueryShape));
7129
7228
  var archivedFilterResolver = {
@@ -7303,12 +7402,13 @@ var ChannelPaginator = class extends BasePaginator {
7303
7402
  if (!this.client.offlineDb?.getChannelsForQuery || !this.client.user?.id || !queryShape)
7304
7403
  return void 0;
7305
7404
  const { stateOptions: _, ...request } = queryShape;
7405
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7306
7406
  try {
7307
7407
  const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
7308
7408
  userId: this.client.user.id,
7309
7409
  options: request
7310
7410
  });
7311
- if (cachedQuery) {
7411
+ if (cachedQuery && !checkWasStateResetDuringQuery()) {
7312
7412
  if (cachedQuery.predefinedFilter) {
7313
7413
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
7314
7414
  }
@@ -7320,7 +7420,7 @@ var ChannelPaginator = class extends BasePaginator {
7320
7420
  }
7321
7421
  } catch (error) {
7322
7422
  chatLoggerSystem.getLogger("channel").error(error.message);
7323
- if (this.config.throwErrors) throw error;
7423
+ if (this.config.throwErrors && !checkWasStateResetDuringQuery()) throw error;
7324
7424
  }
7325
7425
  return;
7326
7426
  };
@@ -7342,6 +7442,7 @@ var ChannelPaginator = class extends BasePaginator {
7342
7442
  this._itemsLoadedFromOfflineDB = false;
7343
7443
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
7344
7444
  const { stateOptions, ...request } = queryShape;
7445
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7345
7446
  let items;
7346
7447
  if (this.config.doRequest) {
7347
7448
  items = (await this.config.doRequest(queryShape)).items;
@@ -7351,7 +7452,9 @@ var ChannelPaginator = class extends BasePaginator {
7351
7452
  withResponse: true
7352
7453
  });
7353
7454
  items = response.channels;
7354
- this._pendingPredefinedFilter = response.predefined_filter;
7455
+ if (!checkWasStateResetDuringQuery()) {
7456
+ this._pendingPredefinedFilter = response.predefined_filter;
7457
+ }
7355
7458
  }
7356
7459
  return { items };
7357
7460
  };
@@ -7547,19 +7650,55 @@ var ChannelPaginator = class extends BasePaginator {
7547
7650
  get channelStateOptions() {
7548
7651
  return this._channelStateOptions;
7549
7652
  }
7653
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
7550
7654
  set staticFilters(filters) {
7551
- this._staticFilters = filters;
7655
+ this.changeQuery(() => {
7656
+ this._staticFilters = filters;
7657
+ });
7552
7658
  }
7659
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
7553
7660
  set sort(sort) {
7554
- this._sort = sort;
7555
- this.sortComparator = this.buildSortComparator(this.effectiveSort);
7661
+ this.changeQuery(() => {
7662
+ this._sort = sort;
7663
+ this.sortComparator = this.buildSortComparator(this.effectiveSort);
7664
+ });
7556
7665
  }
7666
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
7557
7667
  set options(options) {
7558
- this._options = options;
7668
+ this.changeQuery(() => {
7669
+ this._options = options;
7670
+ });
7559
7671
  }
7560
7672
  set channelStateOptions(options) {
7561
7673
  this._channelStateOptions = options;
7562
7674
  }
7675
+ /**
7676
+ * Applies a change to a query input (filters, sort, options) and resets the list with
7677
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
7678
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
7679
+ * loaded pages.
7680
+ *
7681
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
7682
+ * query's first page. A query still running for the old query is ignored; a debounced query
7683
+ * stays scheduled and runs with the new query.
7684
+ */
7685
+ changeQuery(applyChange) {
7686
+ const queryBefore = this.getNextQueryShape();
7687
+ applyChange();
7688
+ if (this.queryChangeDiscardsPages(queryBefore)) this.resetState();
7689
+ }
7690
+ /**
7691
+ * Whether the next query has another identity than `queryBefore`
7692
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
7693
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
7694
+ * and `member_limit` and `message_limit` (how much of each channel loads).
7695
+ */
7696
+ queryChangeDiscardsPages(queryBefore) {
7697
+ return this.config.hasPaginationQueryShapeChanged(
7698
+ queryBefore,
7699
+ this.getNextQueryShape()
7700
+ );
7701
+ }
7563
7702
  get sortComparatorFactory() {
7564
7703
  return this._sortComparatorFactory;
7565
7704
  }
@@ -7574,7 +7713,21 @@ var ChannelPaginator = class extends BasePaginator {
7574
7713
  getItemId(item) {
7575
7714
  return item.cid;
7576
7715
  }
7716
+ /**
7717
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
7718
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
7719
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
7720
+ * cache stored without it) matches by `staticFilters`.
7721
+ */
7722
+ get awaitsPredefinedFilter() {
7723
+ return !!this._options?.predefined_filter && !this._predefinedFilter && !this.hasResults;
7724
+ }
7725
+ /**
7726
+ * Whether `channel` belongs to the list. Nothing does while a list with
7727
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
7728
+ */
7577
7729
  matchesFilter(channel) {
7730
+ if (this.awaitsPredefinedFilter) return false;
7578
7731
  const filters = this.buildMatchFilters();
7579
7732
  if (channel.data?.hidden && !filterConstrainsField(filters, "hidden")) return false;
7580
7733
  return itemMatchesFilter(channel, filters, {
@@ -7689,6 +7842,7 @@ var ChannelPaginator = class extends BasePaginator {
7689
7842
  return;
7690
7843
  }
7691
7844
  this._queryAwaitingSync = queryShape;
7845
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7692
7846
  if (!this.isInitialized) {
7693
7847
  let cachedChannels;
7694
7848
  try {
@@ -7700,6 +7854,7 @@ var ChannelPaginator = class extends BasePaginator {
7700
7854
  this._queryAwaitingSync = void 0;
7701
7855
  throw error;
7702
7856
  }
7857
+ if (checkWasStateResetDuringQuery()) return;
7703
7858
  if (cachedChannels?.length) {
7704
7859
  this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
7705
7860
  this._itemsLoadedFromOfflineDB = true;
@@ -7753,11 +7908,20 @@ var ChannelPaginator = class extends BasePaginator {
7753
7908
  onEntityRemoved(id, channel) {
7754
7909
  this.removeItem({ id, item: channel });
7755
7910
  }
7911
+ /**
7912
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
7913
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
7914
+ * stays scheduled.
7915
+ */
7756
7916
  resetState() {
7757
- super.resetState();
7758
- this._itemIndex.clear();
7759
7917
  this._queryAwaitingSync = void 0;
7760
7918
  this._tailQueryAwaitingRecovery = false;
7919
+ this._itemsLoadedFromOfflineDB = false;
7920
+ this._replaceOfflineSeedOnResponse = false;
7921
+ this._pendingPredefinedFilter = void 0;
7922
+ if (this._predefinedFilter) this.applyPredefinedFilterResponse(void 0);
7923
+ super.resetState();
7924
+ this._itemIndex.clear();
7761
7925
  }
7762
7926
  removeItem(params) {
7763
7927
  const coordinates = super.removeItem(params);
@@ -8052,6 +8216,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8052
8216
  this.claimActiveInterval();
8053
8217
  this.showLoadedInterval(interval);
8054
8218
  } else {
8219
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8055
8220
  const result = await this.executeQuery({
8056
8221
  claimsActiveInterval: true,
8057
8222
  // Always send a limit: the replies endpoint ignores `id_around` without one.
@@ -8060,6 +8225,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8060
8225
  updateState: false
8061
8226
  });
8062
8227
  if (result?.isSuperseded) return false;
8228
+ if (checkWasStateResetDuringQuery()) return false;
8063
8229
  localMessage = this.getItem(messageId);
8064
8230
  if (!localMessage || !result || !result.targetInterval) {
8065
8231
  this.channel.getClient().notifications.addError({
@@ -8101,12 +8267,14 @@ var MessageIntervalPaginator = class extends BasePaginator {
8101
8267
  */
8102
8268
  this.jumpToTheLatestMessage = async (options) => {
8103
8269
  if (!this.latestHeadInterval) {
8270
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8104
8271
  const result = await this.executeQuery({
8105
8272
  claimsActiveInterval: true,
8106
8273
  queryShape: { limit: this.pageSize },
8107
8274
  updateState: false
8108
8275
  });
8109
8276
  if (result?.isSuperseded) return false;
8277
+ if (checkWasStateResetDuringQuery()) return false;
8110
8278
  }
8111
8279
  const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
8112
8280
  if (!latestMessageId) {
@@ -9480,6 +9648,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9480
9648
  messages: this.state.getLatestValue().items ?? []
9481
9649
  });
9482
9650
  if (!inferredLastReadMessageId) {
9651
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
9483
9652
  const result = await this.executeQuery({
9484
9653
  claimsActiveInterval: true,
9485
9654
  queryShape: {
@@ -9490,6 +9659,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9490
9659
  updateState: false
9491
9660
  });
9492
9661
  if (result?.isSuperseded) return false;
9662
+ if (checkWasStateResetDuringQuery()) return false;
9493
9663
  if (result) {
9494
9664
  ({
9495
9665
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -27691,6 +27861,7 @@ var AbstractOfflineDB = class {
27691
27861
 
27692
27862
  // src/LiveLocationManager.ts
27693
27863
  import { StateStore as StateStore31 } from "@stream-io/state-store";
27864
+ var logger22 = chatLoggerSystem.getLogger("live-location-manager");
27694
27865
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
27695
27866
  var canTrackLocation = (location) => typeof location.end_at === "number" && Number.isFinite(location.end_at) && location.end_at >= nowNs();
27696
27867
  var isTrackableLocation = (location) => canTrackLocation(location);
@@ -27713,6 +27884,12 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27713
27884
  throw new Error("Live-location sharing is reserved for client-side use only");
27714
27885
  }
27715
27886
  super();
27887
+ /**
27888
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
27889
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
27890
+ * for these ids are skipped instead of being tracked again.
27891
+ */
27892
+ this.unregisteredDuringLoad = /* @__PURE__ */ new Set();
27716
27893
  /** Subscribes to the `'liveLocationManager'` configuration key. Idempotent. */
27717
27894
  this.subscribeConfiguration = () => {
27718
27895
  if (this.unsubscribeConfiguration) return;
@@ -27782,9 +27959,18 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27782
27959
  initializeConfig(config) {
27783
27960
  this.configController.initialize(config);
27784
27961
  }
27962
+ /**
27963
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
27964
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
27965
+ * whether or not the load has finished.
27966
+ *
27967
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
27968
+ * registered, so shares started later are still tracked. The next `init()`, position update or
27969
+ * `connection.recovered` event retries the load.
27970
+ */
27785
27971
  async init() {
27786
- await this.assureStateInit();
27787
27972
  this.registerSubscriptions();
27973
+ await this.assureStateInit();
27788
27974
  }
27789
27975
  get messages() {
27790
27976
  return this.state.getLatestValue().messages;
@@ -27798,24 +27984,37 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27798
27984
  }
27799
27985
  return this._deviceId;
27800
27986
  }
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
- {
27987
+ /** Loads the active live locations unless already loaded. Never rejects. */
27988
+ assureStateInit() {
27989
+ if (this.stateIsReady) return Promise.resolve();
27990
+ this.stateInitPromise ?? (this.stateInitPromise = this.loadState().finally(() => {
27991
+ this.stateInitPromise = void 0;
27992
+ this.unregisteredDuringLoad.clear();
27993
+ }));
27994
+ return this.stateInitPromise;
27995
+ }
27996
+ async loadState() {
27997
+ try {
27998
+ const { active_live_locations } = await this.client.getUserLiveLocations();
27999
+ this.state.next((currentValue) => {
28000
+ const messages = new Map(currentValue.messages);
28001
+ for (const location of active_live_locations.filter(isTrackableLocation)) {
28002
+ if (messages.has(location.message_id) || this.unregisteredDuringLoad.has(location.message_id))
28003
+ continue;
28004
+ messages.set(location.message_id, {
27809
28005
  ...location,
27810
28006
  stopSharingTimeout: this.scheduleStopSharing(
27811
28007
  location.message_id,
27812
28008
  location.end_at
27813
28009
  )
27814
- }
27815
- ])
27816
- ),
27817
- ready: true
27818
- });
28010
+ });
28011
+ }
28012
+ return { ...currentValue, messages, ready: true, lastQueryError: void 0 };
28013
+ });
28014
+ } catch (error) {
28015
+ logger22.warn("Failed to load the active live locations", error);
28016
+ this.state.partialNext({ lastQueryError: error });
28017
+ }
27819
28018
  }
27820
28019
  subscribeTargetMessagesChange() {
27821
28020
  let unsubscribeWatchLocation = null;
@@ -27878,11 +28077,11 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27878
28077
  if (event.type === "live_location_sharing.started") {
27879
28078
  this.registerMessage(event.message);
27880
28079
  } else if (event.type === "message.updated") {
27881
- const isRegistered = this.messages.has(event.message.id);
27882
- if (isRegistered && !isValidLiveLocationMessage(event.message)) {
28080
+ if (isValidLiveLocationMessage(event.message)) {
28081
+ this.registerMessage(event.message);
28082
+ } else {
27883
28083
  this.unregisterMessages([event.message.id]);
27884
28084
  }
27885
- this.registerMessage(event.message);
27886
28085
  } else {
27887
28086
  this.unregisterMessages([event.message.id]);
27888
28087
  }
@@ -27891,6 +28090,10 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27891
28090
  this.client.on("live_location_sharing.stopped", (event) => {
27892
28091
  if (!event.live_location) return;
27893
28092
  this.unregisterMessages([event.live_location?.message_id]);
28093
+ }),
28094
+ // Retries a failed load once the connection is back. No-op once the state is loaded.
28095
+ this.client.on("connection.recovered", () => {
28096
+ void this.assureStateInit();
27894
28097
  })
27895
28098
  ];
27896
28099
  return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
@@ -27936,6 +28139,9 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27936
28139
  });
27937
28140
  }
27938
28141
  unregisterMessages(messageIds) {
28142
+ if (this.stateInitPromise) {
28143
+ messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
28144
+ }
27939
28145
  const messages = this.messages;
27940
28146
  const removedMessages = new Set(messageIds);
27941
28147
  const newMessages = new Map(