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.
@@ -1669,7 +1669,7 @@ var parseVersion = (raw) => {
1669
1669
  };
1670
1670
  var readInjectedVersion = () => {
1671
1671
  try {
1672
- return "10.1.0";
1672
+ return "10.1.1";
1673
1673
  } catch {
1674
1674
  return void 0;
1675
1675
  }
@@ -5158,6 +5158,8 @@ var BasePaginator = class {
5158
5158
  this._itemIntervals = /* @__PURE__ */ new Map();
5159
5159
  /** How many claims on the active interval were made; the latest one decides it. */
5160
5160
  this._activeIntervalClaimCount = 0;
5161
+ /** How many times `resetState()` ran, which tells the work started before a reset apart. */
5162
+ this._stateResetCount = 0;
5161
5163
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
5162
5164
  this._pageSetWithoutQuery = false;
5163
5165
  this.boosts = /* @__PURE__ */ new Map();
@@ -5565,7 +5567,8 @@ var BasePaginator = class {
5565
5567
  /**
5566
5568
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
5567
5569
  * besides its page, once the page is placed with `placeParams`. Runs once for every response that
5568
- * arrived, also when extracting or placing its page failed. Does nothing by default.
5570
+ * arrived, also when placing its page failed or a reset made it ignored (see
5571
+ * {@link executeQuery}). Does nothing by default.
5569
5572
  */
5570
5573
  applyQueryResponseRest(_response, _placeParams) {
5571
5574
  }
@@ -6884,33 +6887,44 @@ var BasePaginator = class {
6884
6887
  }
6885
6888
  /**
6886
6889
  * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
6887
- * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
6888
- * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
6889
- * caller to end the query.
6890
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
6891
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
6890
6892
  */
6891
- async fetchQueryResponseWithRetries(params = {}) {
6892
- const remainingRetries = params.retryCount ?? 0;
6893
- try {
6894
- return await this.fetchQueryResponse(params);
6895
- } catch (e) {
6896
- if (remainingRetries > 0) {
6897
- await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6898
- return await this.fetchQueryResponseWithRetries({
6899
- ...params,
6900
- retryCount: remainingRetries - 1
6901
- });
6902
- }
6903
- const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6904
- if (!isOfflineSupportEnabledWithItems) {
6905
- this.state.partialNext({ lastQueryError: e });
6906
- }
6907
- if (this.config.throwErrors) {
6908
- this.state.partialNext({ isLoading: false });
6909
- throw e;
6893
+ async fetchQueryResponseWithRetries(params = {}, {
6894
+ checkWasStateResetDuringQuery = () => false
6895
+ } = {}) {
6896
+ let remainingRetries = params.retryCount ?? 0;
6897
+ while (true) {
6898
+ try {
6899
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
6900
+ } catch (e) {
6901
+ if (checkWasStateResetDuringQuery()) return null;
6902
+ if (remainingRetries > 0) {
6903
+ remainingRetries -= 1;
6904
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6905
+ if (checkWasStateResetDuringQuery()) return null;
6906
+ continue;
6907
+ }
6908
+ return this.reportFailedFetch(e);
6910
6909
  }
6911
- return null;
6912
6910
  }
6913
6911
  }
6912
+ /**
6913
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
6914
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
6915
+ * and the caller ends the query.
6916
+ */
6917
+ reportFailedFetch(e) {
6918
+ const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6919
+ if (!isOfflineSupportEnabledWithItems) {
6920
+ this.state.partialNext({ lastQueryError: e });
6921
+ }
6922
+ if (this.config.throwErrors) {
6923
+ this.state.partialNext({ isLoading: false });
6924
+ throw e;
6925
+ }
6926
+ return null;
6927
+ }
6914
6928
  /**
6915
6929
  * Runs one query through the query pipeline, step by step:
6916
6930
  *
@@ -6927,9 +6941,13 @@ var BasePaginator = class {
6927
6941
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
6928
6942
  * rejects the call only with `throwErrors` set.
6929
6943
  *
6930
- * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
6931
- * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
6932
- * placed, with `isSuperseded`.
6944
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
6945
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
6946
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
6947
+ *
6948
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
6949
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
6950
+ * is `null` when no page was placed, with `isSuperseded`.
6933
6951
  *
6934
6952
  * @param params - Query parameters.
6935
6953
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -6956,10 +6974,18 @@ var BasePaginator = class {
6956
6974
  async runPreparedQuery({
6957
6975
  fetchParams,
6958
6976
  offlinePreloadPromise,
6959
- placeParams
6977
+ placeParams,
6978
+ checkWasStateResetDuringQuery
6960
6979
  }) {
6961
6980
  if (offlinePreloadPromise) await offlinePreloadPromise;
6962
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
6981
+ if (checkWasStateResetDuringQuery()) return void 0;
6982
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
6983
+ checkWasStateResetDuringQuery
6984
+ });
6985
+ if (checkWasStateResetDuringQuery()) {
6986
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
6987
+ return void 0;
6988
+ }
6963
6989
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
6964
6990
  const errors = [];
6965
6991
  const runStep = (step) => {
@@ -6976,6 +7002,16 @@ var BasePaginator = class {
6976
7002
  runStep(() => this.applyQueryResponseRest(response, placeParams));
6977
7003
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
6978
7004
  }
7005
+ /**
7006
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
7007
+ * An ignored query reports nothing, so an error here is swallowed.
7008
+ */
7009
+ applyResponseRestOfIgnoredQuery(response, placeParams) {
7010
+ try {
7011
+ this.applyQueryResponseRest(response, placeParams);
7012
+ } catch {
7013
+ }
7014
+ }
6979
7015
  /**
6980
7016
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
6981
7017
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -6990,6 +7026,14 @@ var BasePaginator = class {
6990
7026
  targetInterval: placed?.targetInterval ?? null
6991
7027
  };
6992
7028
  }
7029
+ /**
7030
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
7031
+ * reset uses it to ignore its results instead of writing them into the reset state.
7032
+ */
7033
+ makeStateResetWatcher() {
7034
+ const resetCount = this._stateResetCount;
7035
+ return () => resetCount !== this._stateResetCount;
7036
+ }
6993
7037
  /**
6994
7038
  * Whether a query claims the active interval by default (see
6995
7039
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -7024,6 +7068,7 @@ var BasePaginator = class {
7024
7068
  updateState = true
7025
7069
  }) {
7026
7070
  if (!this.canExecuteQuery({ direction, reset })) return void 0;
7071
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7027
7072
  const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
7028
7073
  const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
7029
7074
  const isForcedReset = reset === "yes" && !keepPreviousItems;
@@ -7057,12 +7102,19 @@ var BasePaginator = class {
7057
7102
  publishStateBeforeFirstQuery(void 0);
7058
7103
  } else {
7059
7104
  offlinePreloadPromise = (async () => {
7060
- const items = await this.preloadFirstPageFromOfflineDb({
7061
- direction,
7062
- queryShape,
7063
- reset,
7064
- retryCount
7065
- });
7105
+ let items;
7106
+ try {
7107
+ items = await this.preloadFirstPageFromOfflineDb({
7108
+ direction,
7109
+ queryShape,
7110
+ reset,
7111
+ retryCount
7112
+ });
7113
+ } catch (error) {
7114
+ if (checkWasStateResetDuringQuery()) return;
7115
+ throw error;
7116
+ }
7117
+ if (checkWasStateResetDuringQuery()) return;
7066
7118
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
7067
7119
  })();
7068
7120
  }
@@ -7085,7 +7137,8 @@ var BasePaginator = class {
7085
7137
  queryShape,
7086
7138
  requestedPageSize: this.getRequestedPageSize(queryShape),
7087
7139
  updateState
7088
- }
7140
+ },
7141
+ checkWasStateResetDuringQuery
7089
7142
  };
7090
7143
  }
7091
7144
  /**
@@ -7129,6 +7182,36 @@ var BasePaginator = class {
7129
7182
  }) {
7130
7183
  return continuesIntervalId !== void 0 && continuesIntervalId !== this._activeIntervalId;
7131
7184
  }
7185
+ /**
7186
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
7187
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
7188
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
7189
+ */
7190
+ emptyPageKeepsLoadedItems({
7191
+ isFirstPage,
7192
+ keepPreviousItems
7193
+ }) {
7194
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
7195
+ }
7196
+ /**
7197
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
7198
+ * own `updateState: false` query settles a list without items
7199
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
7200
+ * what the stored page changed.
7201
+ */
7202
+ commitsPlacedState(placement, page, { endsQuery }) {
7203
+ return placement.updateState !== false || endsQuery && this.emptyPageSettlesListWithoutItems(placement, page);
7204
+ }
7205
+ /**
7206
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
7207
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
7208
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
7209
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
7210
+ * owns the list.
7211
+ */
7212
+ emptyPageSettlesListWithoutItems(placement, page) {
7213
+ return placement.isFirstPage && page.length === 0 && !this.hasResults && !placement.startsSeparateInterval && !this.claimIsSuperseded(placement);
7214
+ }
7132
7215
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
7133
7216
  claimIsSuperseded({ activeIntervalClaim }) {
7134
7217
  return activeIntervalClaim !== void 0 && !this.isLatestActiveIntervalClaim(activeIntervalClaim);
@@ -7148,16 +7231,17 @@ var BasePaginator = class {
7148
7231
  * database. A page from a query the paginator did not run is placed without any of that, as one
7149
7232
  * of the paginator's own queries may still be running.
7150
7233
  */
7151
- placePage({
7152
- startsSeparateInterval,
7153
- direction,
7154
- isFirstPage,
7155
- keepPreviousItems,
7156
- queryShape,
7157
- requestedPageSize,
7158
- results,
7159
- updateState = true
7160
- }, { endsQuery }) {
7234
+ placePage(placement, { endsQuery }) {
7235
+ const {
7236
+ startsSeparateInterval,
7237
+ direction,
7238
+ isFirstPage,
7239
+ keepPreviousItems,
7240
+ queryShape,
7241
+ requestedPageSize,
7242
+ results,
7243
+ updateState = true
7244
+ } = placement;
7161
7245
  const stateUpdate = endsQuery ? { isLoading: false, lastQueryError: void 0 } : {};
7162
7246
  const { items, headward, tailward } = results;
7163
7247
  const filteredItems = this.filterQueryResults(items);
@@ -7182,7 +7266,7 @@ var BasePaginator = class {
7182
7266
  if (interval && updateState) {
7183
7267
  this.setActiveInterval(interval, { updateState: false });
7184
7268
  stateUpdate.items = this.intervalToItems(interval);
7185
- } else if (updateState && !filteredItems.length && (keepPreviousItems || !isFirstPage)) {
7269
+ } else if (updateState && !filteredItems.length && this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })) {
7186
7270
  stateUpdate.items = this.items;
7187
7271
  }
7188
7272
  const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
@@ -7273,8 +7357,9 @@ var BasePaginator = class {
7273
7357
  }
7274
7358
  }
7275
7359
  const state = endsQuery ? this.getStateAfterQuery(stateUpdate, isFirstPage) : { ...this.state.getLatestValue(), ...stateUpdate };
7276
- if (updateState) this.state.next(state);
7277
- else this.publishStoredPage({ endsQuery, interval, state });
7360
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
7361
+ this.state.next(state);
7362
+ } else this.publishStoredPage({ endsQuery, interval, state });
7278
7363
  if (endsQuery && isFirstPage) {
7279
7364
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7280
7365
  }
@@ -7304,7 +7389,12 @@ var BasePaginator = class {
7304
7389
  cancelScheduledQuery() {
7305
7390
  this._executeQueryDebounced.cancel();
7306
7391
  }
7392
+ /**
7393
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
7394
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
7395
+ */
7307
7396
  resetState() {
7397
+ this._stateResetCount++;
7308
7398
  this._lastQueryShape = void 0;
7309
7399
  this._pageSetWithoutQuery = false;
7310
7400
  this.state.next(this.initialState);
@@ -7392,6 +7482,13 @@ var DEFAULT_BACKEND_SORT = [
7392
7482
  { direction: -1, field: "last_message_at" },
7393
7483
  { direction: -1, field: "updated_at" }
7394
7484
  ];
7485
+ var withoutUndefinedValues = (value) => {
7486
+ if (Array.isArray(value)) return value.map(withoutUndefinedValues);
7487
+ if (!value || typeof value !== "object" || isClassInstance(value)) return value;
7488
+ return Object.fromEntries(
7489
+ Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, withoutUndefinedValues(entry)])
7490
+ );
7491
+ };
7395
7492
  var getQueryIdentity = (queryShape) => {
7396
7493
  if (!queryShape) return queryShape;
7397
7494
  const {
@@ -7401,7 +7498,9 @@ var getQueryIdentity = (queryShape) => {
7401
7498
  offset: ____,
7402
7499
  ...identity
7403
7500
  } = queryShape;
7404
- return identity;
7501
+ return Object.fromEntries(
7502
+ Object.entries(identity).map(([key, value]) => [key, withoutUndefinedValues(value)])
7503
+ );
7405
7504
  };
7406
7505
  var hasPaginationQueryShapeChanged = (prevQueryShape, nextQueryShape) => !isEqual(getQueryIdentity(prevQueryShape), getQueryIdentity(nextQueryShape));
7407
7506
  var archivedFilterResolver = {
@@ -7581,12 +7680,13 @@ var ChannelPaginator = class extends BasePaginator {
7581
7680
  if (!this.client.offlineDb?.getChannelsForQuery || !this.client.user?.id || !queryShape)
7582
7681
  return void 0;
7583
7682
  const { stateOptions: _, ...request } = queryShape;
7683
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7584
7684
  try {
7585
7685
  const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
7586
7686
  userId: this.client.user.id,
7587
7687
  options: request
7588
7688
  });
7589
- if (cachedQuery) {
7689
+ if (cachedQuery && !checkWasStateResetDuringQuery()) {
7590
7690
  if (cachedQuery.predefinedFilter) {
7591
7691
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
7592
7692
  }
@@ -7598,7 +7698,7 @@ var ChannelPaginator = class extends BasePaginator {
7598
7698
  }
7599
7699
  } catch (error) {
7600
7700
  chatLoggerSystem.getLogger("channel").error(error.message);
7601
- if (this.config.throwErrors) throw error;
7701
+ if (this.config.throwErrors && !checkWasStateResetDuringQuery()) throw error;
7602
7702
  }
7603
7703
  return;
7604
7704
  };
@@ -7620,6 +7720,7 @@ var ChannelPaginator = class extends BasePaginator {
7620
7720
  this._itemsLoadedFromOfflineDB = false;
7621
7721
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
7622
7722
  const { stateOptions, ...request } = queryShape;
7723
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7623
7724
  let items;
7624
7725
  if (this.config.doRequest) {
7625
7726
  items = (await this.config.doRequest(queryShape)).items;
@@ -7629,7 +7730,9 @@ var ChannelPaginator = class extends BasePaginator {
7629
7730
  withResponse: true
7630
7731
  });
7631
7732
  items = response.channels;
7632
- this._pendingPredefinedFilter = response.predefined_filter;
7733
+ if (!checkWasStateResetDuringQuery()) {
7734
+ this._pendingPredefinedFilter = response.predefined_filter;
7735
+ }
7633
7736
  }
7634
7737
  return { items };
7635
7738
  };
@@ -7825,19 +7928,55 @@ var ChannelPaginator = class extends BasePaginator {
7825
7928
  get channelStateOptions() {
7826
7929
  return this._channelStateOptions;
7827
7930
  }
7931
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
7828
7932
  set staticFilters(filters) {
7829
- this._staticFilters = filters;
7933
+ this.changeQuery(() => {
7934
+ this._staticFilters = filters;
7935
+ });
7830
7936
  }
7937
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
7831
7938
  set sort(sort) {
7832
- this._sort = sort;
7833
- this.sortComparator = this.buildSortComparator(this.effectiveSort);
7939
+ this.changeQuery(() => {
7940
+ this._sort = sort;
7941
+ this.sortComparator = this.buildSortComparator(this.effectiveSort);
7942
+ });
7834
7943
  }
7944
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
7835
7945
  set options(options) {
7836
- this._options = options;
7946
+ this.changeQuery(() => {
7947
+ this._options = options;
7948
+ });
7837
7949
  }
7838
7950
  set channelStateOptions(options) {
7839
7951
  this._channelStateOptions = options;
7840
7952
  }
7953
+ /**
7954
+ * Applies a change to a query input (filters, sort, options) and resets the list with
7955
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
7956
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
7957
+ * loaded pages.
7958
+ *
7959
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
7960
+ * query's first page. A query still running for the old query is ignored; a debounced query
7961
+ * stays scheduled and runs with the new query.
7962
+ */
7963
+ changeQuery(applyChange) {
7964
+ const queryBefore = this.getNextQueryShape();
7965
+ applyChange();
7966
+ if (this.queryChangeDiscardsPages(queryBefore)) this.resetState();
7967
+ }
7968
+ /**
7969
+ * Whether the next query has another identity than `queryBefore`
7970
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
7971
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
7972
+ * and `member_limit` and `message_limit` (how much of each channel loads).
7973
+ */
7974
+ queryChangeDiscardsPages(queryBefore) {
7975
+ return this.config.hasPaginationQueryShapeChanged(
7976
+ queryBefore,
7977
+ this.getNextQueryShape()
7978
+ );
7979
+ }
7841
7980
  get sortComparatorFactory() {
7842
7981
  return this._sortComparatorFactory;
7843
7982
  }
@@ -7852,7 +7991,21 @@ var ChannelPaginator = class extends BasePaginator {
7852
7991
  getItemId(item) {
7853
7992
  return item.cid;
7854
7993
  }
7994
+ /**
7995
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
7996
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
7997
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
7998
+ * cache stored without it) matches by `staticFilters`.
7999
+ */
8000
+ get awaitsPredefinedFilter() {
8001
+ return !!this._options?.predefined_filter && !this._predefinedFilter && !this.hasResults;
8002
+ }
8003
+ /**
8004
+ * Whether `channel` belongs to the list. Nothing does while a list with
8005
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
8006
+ */
7855
8007
  matchesFilter(channel) {
8008
+ if (this.awaitsPredefinedFilter) return false;
7856
8009
  const filters = this.buildMatchFilters();
7857
8010
  if (channel.data?.hidden && !filterConstrainsField(filters, "hidden")) return false;
7858
8011
  return itemMatchesFilter(channel, filters, {
@@ -7967,6 +8120,7 @@ var ChannelPaginator = class extends BasePaginator {
7967
8120
  return;
7968
8121
  }
7969
8122
  this._queryAwaitingSync = queryShape;
8123
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7970
8124
  if (!this.isInitialized) {
7971
8125
  let cachedChannels;
7972
8126
  try {
@@ -7978,6 +8132,7 @@ var ChannelPaginator = class extends BasePaginator {
7978
8132
  this._queryAwaitingSync = void 0;
7979
8133
  throw error;
7980
8134
  }
8135
+ if (checkWasStateResetDuringQuery()) return;
7981
8136
  if (cachedChannels?.length) {
7982
8137
  this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
7983
8138
  this._itemsLoadedFromOfflineDB = true;
@@ -8031,11 +8186,20 @@ var ChannelPaginator = class extends BasePaginator {
8031
8186
  onEntityRemoved(id, channel) {
8032
8187
  this.removeItem({ id, item: channel });
8033
8188
  }
8189
+ /**
8190
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
8191
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
8192
+ * stays scheduled.
8193
+ */
8034
8194
  resetState() {
8035
- super.resetState();
8036
- this._itemIndex.clear();
8037
8195
  this._queryAwaitingSync = void 0;
8038
8196
  this._tailQueryAwaitingRecovery = false;
8197
+ this._itemsLoadedFromOfflineDB = false;
8198
+ this._replaceOfflineSeedOnResponse = false;
8199
+ this._pendingPredefinedFilter = void 0;
8200
+ if (this._predefinedFilter) this.applyPredefinedFilterResponse(void 0);
8201
+ super.resetState();
8202
+ this._itemIndex.clear();
8039
8203
  }
8040
8204
  removeItem(params) {
8041
8205
  const coordinates = super.removeItem(params);
@@ -8330,6 +8494,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8330
8494
  this.claimActiveInterval();
8331
8495
  this.showLoadedInterval(interval);
8332
8496
  } else {
8497
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8333
8498
  const result = await this.executeQuery({
8334
8499
  claimsActiveInterval: true,
8335
8500
  // Always send a limit: the replies endpoint ignores `id_around` without one.
@@ -8338,6 +8503,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8338
8503
  updateState: false
8339
8504
  });
8340
8505
  if (result?.isSuperseded) return false;
8506
+ if (checkWasStateResetDuringQuery()) return false;
8341
8507
  localMessage = this.getItem(messageId);
8342
8508
  if (!localMessage || !result || !result.targetInterval) {
8343
8509
  this.channel.getClient().notifications.addError({
@@ -8379,12 +8545,14 @@ var MessageIntervalPaginator = class extends BasePaginator {
8379
8545
  */
8380
8546
  this.jumpToTheLatestMessage = async (options) => {
8381
8547
  if (!this.latestHeadInterval) {
8548
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8382
8549
  const result = await this.executeQuery({
8383
8550
  claimsActiveInterval: true,
8384
8551
  queryShape: { limit: this.pageSize },
8385
8552
  updateState: false
8386
8553
  });
8387
8554
  if (result?.isSuperseded) return false;
8555
+ if (checkWasStateResetDuringQuery()) return false;
8388
8556
  }
8389
8557
  const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
8390
8558
  if (!latestMessageId) {
@@ -9758,6 +9926,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9758
9926
  messages: this.state.getLatestValue().items ?? []
9759
9927
  });
9760
9928
  if (!inferredLastReadMessageId) {
9929
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
9761
9930
  const result = await this.executeQuery({
9762
9931
  claimsActiveInterval: true,
9763
9932
  queryShape: {
@@ -9768,6 +9937,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9768
9937
  updateState: false
9769
9938
  });
9770
9939
  if (result?.isSuperseded) return false;
9940
+ if (checkWasStateResetDuringQuery()) return false;
9771
9941
  if (result) {
9772
9942
  ({
9773
9943
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -27969,6 +28139,7 @@ var AbstractOfflineDB = class {
27969
28139
 
27970
28140
  // src/LiveLocationManager.ts
27971
28141
  var import_state_store31 = require("@stream-io/state-store");
28142
+ var logger22 = chatLoggerSystem.getLogger("live-location-manager");
27972
28143
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
27973
28144
  var canTrackLocation = (location) => typeof location.end_at === "number" && Number.isFinite(location.end_at) && location.end_at >= nowNs();
27974
28145
  var isTrackableLocation = (location) => canTrackLocation(location);
@@ -27991,6 +28162,12 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27991
28162
  throw new Error("Live-location sharing is reserved for client-side use only");
27992
28163
  }
27993
28164
  super();
28165
+ /**
28166
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
28167
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
28168
+ * for these ids are skipped instead of being tracked again.
28169
+ */
28170
+ this.unregisteredDuringLoad = /* @__PURE__ */ new Set();
27994
28171
  /** Subscribes to the `'liveLocationManager'` configuration key. Idempotent. */
27995
28172
  this.subscribeConfiguration = () => {
27996
28173
  if (this.unsubscribeConfiguration) return;
@@ -28060,9 +28237,18 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28060
28237
  initializeConfig(config) {
28061
28238
  this.configController.initialize(config);
28062
28239
  }
28240
+ /**
28241
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
28242
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
28243
+ * whether or not the load has finished.
28244
+ *
28245
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
28246
+ * registered, so shares started later are still tracked. The next `init()`, position update or
28247
+ * `connection.recovered` event retries the load.
28248
+ */
28063
28249
  async init() {
28064
- await this.assureStateInit();
28065
28250
  this.registerSubscriptions();
28251
+ await this.assureStateInit();
28066
28252
  }
28067
28253
  get messages() {
28068
28254
  return this.state.getLatestValue().messages;
@@ -28076,24 +28262,37 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28076
28262
  }
28077
28263
  return this._deviceId;
28078
28264
  }
28079
- async assureStateInit() {
28080
- if (this.stateIsReady) return;
28081
- const { active_live_locations } = await this.client.getUserLiveLocations();
28082
- this.state.next({
28083
- messages: new Map(
28084
- active_live_locations.filter(isTrackableLocation).map((location) => [
28085
- location.message_id,
28086
- {
28265
+ /** Loads the active live locations unless already loaded. Never rejects. */
28266
+ assureStateInit() {
28267
+ if (this.stateIsReady) return Promise.resolve();
28268
+ this.stateInitPromise ?? (this.stateInitPromise = this.loadState().finally(() => {
28269
+ this.stateInitPromise = void 0;
28270
+ this.unregisteredDuringLoad.clear();
28271
+ }));
28272
+ return this.stateInitPromise;
28273
+ }
28274
+ async loadState() {
28275
+ try {
28276
+ const { active_live_locations } = await this.client.getUserLiveLocations();
28277
+ this.state.next((currentValue) => {
28278
+ const messages = new Map(currentValue.messages);
28279
+ for (const location of active_live_locations.filter(isTrackableLocation)) {
28280
+ if (messages.has(location.message_id) || this.unregisteredDuringLoad.has(location.message_id))
28281
+ continue;
28282
+ messages.set(location.message_id, {
28087
28283
  ...location,
28088
28284
  stopSharingTimeout: this.scheduleStopSharing(
28089
28285
  location.message_id,
28090
28286
  location.end_at
28091
28287
  )
28092
- }
28093
- ])
28094
- ),
28095
- ready: true
28096
- });
28288
+ });
28289
+ }
28290
+ return { ...currentValue, messages, ready: true, lastQueryError: void 0 };
28291
+ });
28292
+ } catch (error) {
28293
+ logger22.warn("Failed to load the active live locations", error);
28294
+ this.state.partialNext({ lastQueryError: error });
28295
+ }
28097
28296
  }
28098
28297
  subscribeTargetMessagesChange() {
28099
28298
  let unsubscribeWatchLocation = null;
@@ -28156,11 +28355,11 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28156
28355
  if (event.type === "live_location_sharing.started") {
28157
28356
  this.registerMessage(event.message);
28158
28357
  } else if (event.type === "message.updated") {
28159
- const isRegistered = this.messages.has(event.message.id);
28160
- if (isRegistered && !isValidLiveLocationMessage(event.message)) {
28358
+ if (isValidLiveLocationMessage(event.message)) {
28359
+ this.registerMessage(event.message);
28360
+ } else {
28161
28361
  this.unregisterMessages([event.message.id]);
28162
28362
  }
28163
- this.registerMessage(event.message);
28164
28363
  } else {
28165
28364
  this.unregisterMessages([event.message.id]);
28166
28365
  }
@@ -28169,6 +28368,10 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28169
28368
  this.client.on("live_location_sharing.stopped", (event) => {
28170
28369
  if (!event.live_location) return;
28171
28370
  this.unregisterMessages([event.live_location?.message_id]);
28371
+ }),
28372
+ // Retries a failed load once the connection is back. No-op once the state is loaded.
28373
+ this.client.on("connection.recovered", () => {
28374
+ void this.assureStateInit();
28172
28375
  })
28173
28376
  ];
28174
28377
  return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
@@ -28214,6 +28417,9 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28214
28417
  });
28215
28418
  }
28216
28419
  unregisterMessages(messageIds) {
28420
+ if (this.stateInitPromise) {
28421
+ messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
28422
+ }
28217
28423
  const messages = this.messages;
28218
28424
  const removedMessages = new Set(messageIds);
28219
28425
  const newMessages = new Map(