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.
@@ -1669,7 +1669,7 @@ var parseVersion = (raw) => {
1669
1669
  };
1670
1670
  var readInjectedVersion = () => {
1671
1671
  try {
1672
- return "10.1.0";
1672
+ return "10.2.0";
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();
@@ -5248,6 +5250,11 @@ var BasePaginator = class {
5248
5250
  cursor: this.config.initialCursor,
5249
5251
  offset: this.config.initialOffset ?? 0
5250
5252
  });
5253
+ this.state.addPreprocessor((next) => {
5254
+ if (!next.isLoading && next.loadingDirection !== void 0) {
5255
+ next.loadingDirection = void 0;
5256
+ }
5257
+ });
5251
5258
  this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
5252
5259
  this.intervalViews = new import_state_store8.StateStore({
5253
5260
  logicalHead: [],
@@ -5294,6 +5301,10 @@ var BasePaginator = class {
5294
5301
  get isLoading() {
5295
5302
  return this.state.getLatestValue().isLoading;
5296
5303
  }
5304
+ /** See {@link PaginatorState.loadingDirection}. */
5305
+ get loadingDirection() {
5306
+ return this.state.getLatestValue().loadingDirection;
5307
+ }
5297
5308
  /**
5298
5309
  * True once a query has run or a non-empty interval was loaded without one (`setItems`, or a
5299
5310
  * subclass calling `recordLoadedIntervalQueryShape`). Cleared by `resetState`.
@@ -5323,6 +5334,7 @@ var BasePaginator = class {
5323
5334
  hasMoreHead: true,
5324
5335
  hasMoreTail: true,
5325
5336
  isLoading: false,
5337
+ loadingDirection: void 0,
5326
5338
  items: void 0,
5327
5339
  lastQueryError: void 0,
5328
5340
  cursor: this.config.initialCursor,
@@ -5565,7 +5577,8 @@ var BasePaginator = class {
5565
5577
  /**
5566
5578
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
5567
5579
  * 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.
5580
+ * arrived, also when placing its page failed or a reset made it ignored (see
5581
+ * {@link executeQuery}). Does nothing by default.
5569
5582
  */
5570
5583
  applyQueryResponseRest(_response, _placeParams) {
5571
5584
  }
@@ -6884,33 +6897,44 @@ var BasePaginator = class {
6884
6897
  }
6885
6898
  /**
6886
6899
  * {@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.
6900
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
6901
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
6890
6902
  */
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;
6903
+ async fetchQueryResponseWithRetries(params = {}, {
6904
+ checkWasStateResetDuringQuery = () => false
6905
+ } = {}) {
6906
+ let remainingRetries = params.retryCount ?? 0;
6907
+ while (true) {
6908
+ try {
6909
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
6910
+ } catch (e) {
6911
+ if (checkWasStateResetDuringQuery()) return null;
6912
+ if (remainingRetries > 0) {
6913
+ remainingRetries -= 1;
6914
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
6915
+ if (checkWasStateResetDuringQuery()) return null;
6916
+ continue;
6917
+ }
6918
+ return this.reportFailedFetch(e);
6910
6919
  }
6911
- return null;
6912
6920
  }
6913
6921
  }
6922
+ /**
6923
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
6924
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
6925
+ * and the caller ends the query.
6926
+ */
6927
+ reportFailedFetch(e) {
6928
+ const isOfflineSupportEnabledWithItems = this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
6929
+ if (!isOfflineSupportEnabledWithItems) {
6930
+ this.state.partialNext({ lastQueryError: e });
6931
+ }
6932
+ if (this.config.throwErrors) {
6933
+ this.state.partialNext({ isLoading: false });
6934
+ throw e;
6935
+ }
6936
+ return null;
6937
+ }
6914
6938
  /**
6915
6939
  * Runs one query through the query pipeline, step by step:
6916
6940
  *
@@ -6927,9 +6951,13 @@ var BasePaginator = class {
6927
6951
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
6928
6952
  * rejects the call only with `throwErrors` set.
6929
6953
  *
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`.
6954
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
6955
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
6956
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
6957
+ *
6958
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
6959
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
6960
+ * is `null` when no page was placed, with `isSuperseded`.
6933
6961
  *
6934
6962
  * @param params - Query parameters.
6935
6963
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -6956,10 +6984,18 @@ var BasePaginator = class {
6956
6984
  async runPreparedQuery({
6957
6985
  fetchParams,
6958
6986
  offlinePreloadPromise,
6959
- placeParams
6987
+ placeParams,
6988
+ checkWasStateResetDuringQuery
6960
6989
  }) {
6961
6990
  if (offlinePreloadPromise) await offlinePreloadPromise;
6962
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
6991
+ if (checkWasStateResetDuringQuery()) return void 0;
6992
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
6993
+ checkWasStateResetDuringQuery
6994
+ });
6995
+ if (checkWasStateResetDuringQuery()) {
6996
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
6997
+ return void 0;
6998
+ }
6963
6999
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
6964
7000
  const errors = [];
6965
7001
  const runStep = (step) => {
@@ -6976,6 +7012,16 @@ var BasePaginator = class {
6976
7012
  runStep(() => this.applyQueryResponseRest(response, placeParams));
6977
7013
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
6978
7014
  }
7015
+ /**
7016
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
7017
+ * An ignored query reports nothing, so an error here is swallowed.
7018
+ */
7019
+ applyResponseRestOfIgnoredQuery(response, placeParams) {
7020
+ try {
7021
+ this.applyQueryResponseRest(response, placeParams);
7022
+ } catch {
7023
+ }
7024
+ }
6979
7025
  /**
6980
7026
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
6981
7027
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -6990,6 +7036,14 @@ var BasePaginator = class {
6990
7036
  targetInterval: placed?.targetInterval ?? null
6991
7037
  };
6992
7038
  }
7039
+ /**
7040
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
7041
+ * reset uses it to ignore its results instead of writing them into the reset state.
7042
+ */
7043
+ makeStateResetWatcher() {
7044
+ const resetCount = this._stateResetCount;
7045
+ return () => resetCount !== this._stateResetCount;
7046
+ }
6993
7047
  /**
6994
7048
  * Whether a query claims the active interval by default (see
6995
7049
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -7024,6 +7078,7 @@ var BasePaginator = class {
7024
7078
  updateState = true
7025
7079
  }) {
7026
7080
  if (!this.canExecuteQuery({ direction, reset })) return void 0;
7081
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7027
7082
  const claims = claimsActiveInterval ?? this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
7028
7083
  const activeIntervalClaim = claims ? this.claimActiveInterval() : void 0;
7029
7084
  const isForcedReset = reset === "yes" && !keepPreviousItems;
@@ -7057,17 +7112,28 @@ var BasePaginator = class {
7057
7112
  publishStateBeforeFirstQuery(void 0);
7058
7113
  } else {
7059
7114
  offlinePreloadPromise = (async () => {
7060
- const items = await this.preloadFirstPageFromOfflineDb({
7061
- direction,
7062
- queryShape,
7063
- reset,
7064
- retryCount
7065
- });
7115
+ let items;
7116
+ try {
7117
+ items = await this.preloadFirstPageFromOfflineDb({
7118
+ direction,
7119
+ queryShape,
7120
+ reset,
7121
+ retryCount
7122
+ });
7123
+ } catch (error) {
7124
+ if (checkWasStateResetDuringQuery()) return;
7125
+ throw error;
7126
+ }
7127
+ if (checkWasStateResetDuringQuery()) return;
7066
7128
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
7067
7129
  })();
7068
7130
  }
7069
7131
  } else if (!silent) {
7070
- this.state.partialNext({ isLoading: true });
7132
+ const loadsAtEdge = !isFirstPage && !forcedQueryShape;
7133
+ this.state.partialNext({
7134
+ isLoading: true,
7135
+ loadingDirection: loadsAtEdge ? direction : void 0
7136
+ });
7071
7137
  }
7072
7138
  const isAtCallersShape = !!forcedQueryShape;
7073
7139
  const continuesOwnCursor = !isFirstPage && !isAtCallersShape;
@@ -7085,7 +7151,8 @@ var BasePaginator = class {
7085
7151
  queryShape,
7086
7152
  requestedPageSize: this.getRequestedPageSize(queryShape),
7087
7153
  updateState
7088
- }
7154
+ },
7155
+ checkWasStateResetDuringQuery
7089
7156
  };
7090
7157
  }
7091
7158
  /**
@@ -7129,6 +7196,36 @@ var BasePaginator = class {
7129
7196
  }) {
7130
7197
  return continuesIntervalId !== void 0 && continuesIntervalId !== this._activeIntervalId;
7131
7198
  }
7199
+ /**
7200
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
7201
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
7202
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
7203
+ */
7204
+ emptyPageKeepsLoadedItems({
7205
+ isFirstPage,
7206
+ keepPreviousItems
7207
+ }) {
7208
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
7209
+ }
7210
+ /**
7211
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
7212
+ * own `updateState: false` query settles a list without items
7213
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
7214
+ * what the stored page changed.
7215
+ */
7216
+ commitsPlacedState(placement, page, { endsQuery }) {
7217
+ return placement.updateState !== false || endsQuery && this.emptyPageSettlesListWithoutItems(placement, page);
7218
+ }
7219
+ /**
7220
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
7221
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
7222
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
7223
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
7224
+ * owns the list.
7225
+ */
7226
+ emptyPageSettlesListWithoutItems(placement, page) {
7227
+ return placement.isFirstPage && page.length === 0 && !this.hasResults && !placement.startsSeparateInterval && !this.claimIsSuperseded(placement);
7228
+ }
7132
7229
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
7133
7230
  claimIsSuperseded({ activeIntervalClaim }) {
7134
7231
  return activeIntervalClaim !== void 0 && !this.isLatestActiveIntervalClaim(activeIntervalClaim);
@@ -7148,16 +7245,17 @@ var BasePaginator = class {
7148
7245
  * database. A page from a query the paginator did not run is placed without any of that, as one
7149
7246
  * of the paginator's own queries may still be running.
7150
7247
  */
7151
- placePage({
7152
- startsSeparateInterval,
7153
- direction,
7154
- isFirstPage,
7155
- keepPreviousItems,
7156
- queryShape,
7157
- requestedPageSize,
7158
- results,
7159
- updateState = true
7160
- }, { endsQuery }) {
7248
+ placePage(placement, { endsQuery }) {
7249
+ const {
7250
+ startsSeparateInterval,
7251
+ direction,
7252
+ isFirstPage,
7253
+ keepPreviousItems,
7254
+ queryShape,
7255
+ requestedPageSize,
7256
+ results,
7257
+ updateState = true
7258
+ } = placement;
7161
7259
  const stateUpdate = endsQuery ? { isLoading: false, lastQueryError: void 0 } : {};
7162
7260
  const { items, headward, tailward } = results;
7163
7261
  const filteredItems = this.filterQueryResults(items);
@@ -7182,7 +7280,7 @@ var BasePaginator = class {
7182
7280
  if (interval && updateState) {
7183
7281
  this.setActiveInterval(interval, { updateState: false });
7184
7282
  stateUpdate.items = this.intervalToItems(interval);
7185
- } else if (updateState && !filteredItems.length && (keepPreviousItems || !isFirstPage)) {
7283
+ } else if (updateState && !filteredItems.length && this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })) {
7186
7284
  stateUpdate.items = this.items;
7187
7285
  }
7188
7286
  const continuesActiveIntervalFlags = !isSeparateInterval || !!interval && this.isActiveInterval(interval);
@@ -7273,8 +7371,9 @@ var BasePaginator = class {
7273
7371
  }
7274
7372
  }
7275
7373
  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 });
7374
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
7375
+ this.state.next(state);
7376
+ } else this.publishStoredPage({ endsQuery, interval, state });
7278
7377
  if (endsQuery && isFirstPage) {
7279
7378
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
7280
7379
  }
@@ -7304,7 +7403,12 @@ var BasePaginator = class {
7304
7403
  cancelScheduledQuery() {
7305
7404
  this._executeQueryDebounced.cancel();
7306
7405
  }
7406
+ /**
7407
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
7408
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
7409
+ */
7307
7410
  resetState() {
7411
+ this._stateResetCount++;
7308
7412
  this._lastQueryShape = void 0;
7309
7413
  this._pageSetWithoutQuery = false;
7310
7414
  this.state.next(this.initialState);
@@ -7392,6 +7496,13 @@ var DEFAULT_BACKEND_SORT = [
7392
7496
  { direction: -1, field: "last_message_at" },
7393
7497
  { direction: -1, field: "updated_at" }
7394
7498
  ];
7499
+ var withoutUndefinedValues = (value) => {
7500
+ if (Array.isArray(value)) return value.map(withoutUndefinedValues);
7501
+ if (!value || typeof value !== "object" || isClassInstance(value)) return value;
7502
+ return Object.fromEntries(
7503
+ Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, withoutUndefinedValues(entry)])
7504
+ );
7505
+ };
7395
7506
  var getQueryIdentity = (queryShape) => {
7396
7507
  if (!queryShape) return queryShape;
7397
7508
  const {
@@ -7401,7 +7512,9 @@ var getQueryIdentity = (queryShape) => {
7401
7512
  offset: ____,
7402
7513
  ...identity
7403
7514
  } = queryShape;
7404
- return identity;
7515
+ return Object.fromEntries(
7516
+ Object.entries(identity).map(([key, value]) => [key, withoutUndefinedValues(value)])
7517
+ );
7405
7518
  };
7406
7519
  var hasPaginationQueryShapeChanged = (prevQueryShape, nextQueryShape) => !isEqual(getQueryIdentity(prevQueryShape), getQueryIdentity(nextQueryShape));
7407
7520
  var archivedFilterResolver = {
@@ -7581,12 +7694,13 @@ var ChannelPaginator = class extends BasePaginator {
7581
7694
  if (!this.client.offlineDb?.getChannelsForQuery || !this.client.user?.id || !queryShape)
7582
7695
  return void 0;
7583
7696
  const { stateOptions: _, ...request } = queryShape;
7697
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7584
7698
  try {
7585
7699
  const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
7586
7700
  userId: this.client.user.id,
7587
7701
  options: request
7588
7702
  });
7589
- if (cachedQuery) {
7703
+ if (cachedQuery && !checkWasStateResetDuringQuery()) {
7590
7704
  if (cachedQuery.predefinedFilter) {
7591
7705
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
7592
7706
  }
@@ -7598,7 +7712,7 @@ var ChannelPaginator = class extends BasePaginator {
7598
7712
  }
7599
7713
  } catch (error) {
7600
7714
  chatLoggerSystem.getLogger("channel").error(error.message);
7601
- if (this.config.throwErrors) throw error;
7715
+ if (this.config.throwErrors && !checkWasStateResetDuringQuery()) throw error;
7602
7716
  }
7603
7717
  return;
7604
7718
  };
@@ -7620,6 +7734,7 @@ var ChannelPaginator = class extends BasePaginator {
7620
7734
  this._itemsLoadedFromOfflineDB = false;
7621
7735
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
7622
7736
  const { stateOptions, ...request } = queryShape;
7737
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7623
7738
  let items;
7624
7739
  if (this.config.doRequest) {
7625
7740
  items = (await this.config.doRequest(queryShape)).items;
@@ -7629,7 +7744,9 @@ var ChannelPaginator = class extends BasePaginator {
7629
7744
  withResponse: true
7630
7745
  });
7631
7746
  items = response.channels;
7632
- this._pendingPredefinedFilter = response.predefined_filter;
7747
+ if (!checkWasStateResetDuringQuery()) {
7748
+ this._pendingPredefinedFilter = response.predefined_filter;
7749
+ }
7633
7750
  }
7634
7751
  return { items };
7635
7752
  };
@@ -7825,19 +7942,55 @@ var ChannelPaginator = class extends BasePaginator {
7825
7942
  get channelStateOptions() {
7826
7943
  return this._channelStateOptions;
7827
7944
  }
7945
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
7828
7946
  set staticFilters(filters) {
7829
- this._staticFilters = filters;
7947
+ this.changeQuery(() => {
7948
+ this._staticFilters = filters;
7949
+ });
7830
7950
  }
7951
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
7831
7952
  set sort(sort) {
7832
- this._sort = sort;
7833
- this.sortComparator = this.buildSortComparator(this.effectiveSort);
7953
+ this.changeQuery(() => {
7954
+ this._sort = sort;
7955
+ this.sortComparator = this.buildSortComparator(this.effectiveSort);
7956
+ });
7834
7957
  }
7958
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
7835
7959
  set options(options) {
7836
- this._options = options;
7960
+ this.changeQuery(() => {
7961
+ this._options = options;
7962
+ });
7837
7963
  }
7838
7964
  set channelStateOptions(options) {
7839
7965
  this._channelStateOptions = options;
7840
7966
  }
7967
+ /**
7968
+ * Applies a change to a query input (filters, sort, options) and resets the list with
7969
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
7970
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
7971
+ * loaded pages.
7972
+ *
7973
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
7974
+ * query's first page. A query still running for the old query is ignored; a debounced query
7975
+ * stays scheduled and runs with the new query.
7976
+ */
7977
+ changeQuery(applyChange) {
7978
+ const queryBefore = this.getNextQueryShape();
7979
+ applyChange();
7980
+ if (this.queryChangeDiscardsPages(queryBefore)) this.resetState();
7981
+ }
7982
+ /**
7983
+ * Whether the next query has another identity than `queryBefore`
7984
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
7985
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
7986
+ * and `member_limit` and `message_limit` (how much of each channel loads).
7987
+ */
7988
+ queryChangeDiscardsPages(queryBefore) {
7989
+ return this.config.hasPaginationQueryShapeChanged(
7990
+ queryBefore,
7991
+ this.getNextQueryShape()
7992
+ );
7993
+ }
7841
7994
  get sortComparatorFactory() {
7842
7995
  return this._sortComparatorFactory;
7843
7996
  }
@@ -7852,7 +8005,21 @@ var ChannelPaginator = class extends BasePaginator {
7852
8005
  getItemId(item) {
7853
8006
  return item.cid;
7854
8007
  }
8008
+ /**
8009
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
8010
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
8011
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
8012
+ * cache stored without it) matches by `staticFilters`.
8013
+ */
8014
+ get awaitsPredefinedFilter() {
8015
+ return !!this._options?.predefined_filter && !this._predefinedFilter && !this.hasResults;
8016
+ }
8017
+ /**
8018
+ * Whether `channel` belongs to the list. Nothing does while a list with
8019
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
8020
+ */
7855
8021
  matchesFilter(channel) {
8022
+ if (this.awaitsPredefinedFilter) return false;
7856
8023
  const filters = this.buildMatchFilters();
7857
8024
  if (channel.data?.hidden && !filterConstrainsField(filters, "hidden")) return false;
7858
8025
  return itemMatchesFilter(channel, filters, {
@@ -7967,6 +8134,7 @@ var ChannelPaginator = class extends BasePaginator {
7967
8134
  return;
7968
8135
  }
7969
8136
  this._queryAwaitingSync = queryShape;
8137
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
7970
8138
  if (!this.isInitialized) {
7971
8139
  let cachedChannels;
7972
8140
  try {
@@ -7978,6 +8146,7 @@ var ChannelPaginator = class extends BasePaginator {
7978
8146
  this._queryAwaitingSync = void 0;
7979
8147
  throw error;
7980
8148
  }
8149
+ if (checkWasStateResetDuringQuery()) return;
7981
8150
  if (cachedChannels?.length) {
7982
8151
  this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
7983
8152
  this._itemsLoadedFromOfflineDB = true;
@@ -8031,11 +8200,20 @@ var ChannelPaginator = class extends BasePaginator {
8031
8200
  onEntityRemoved(id, channel) {
8032
8201
  this.removeItem({ id, item: channel });
8033
8202
  }
8203
+ /**
8204
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
8205
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
8206
+ * stays scheduled.
8207
+ */
8034
8208
  resetState() {
8035
- super.resetState();
8036
- this._itemIndex.clear();
8037
8209
  this._queryAwaitingSync = void 0;
8038
8210
  this._tailQueryAwaitingRecovery = false;
8211
+ this._itemsLoadedFromOfflineDB = false;
8212
+ this._replaceOfflineSeedOnResponse = false;
8213
+ this._pendingPredefinedFilter = void 0;
8214
+ if (this._predefinedFilter) this.applyPredefinedFilterResponse(void 0);
8215
+ super.resetState();
8216
+ this._itemIndex.clear();
8039
8217
  }
8040
8218
  removeItem(params) {
8041
8219
  const coordinates = super.removeItem(params);
@@ -8330,6 +8508,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8330
8508
  this.claimActiveInterval();
8331
8509
  this.showLoadedInterval(interval);
8332
8510
  } else {
8511
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8333
8512
  const result = await this.executeQuery({
8334
8513
  claimsActiveInterval: true,
8335
8514
  // Always send a limit: the replies endpoint ignores `id_around` without one.
@@ -8338,6 +8517,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8338
8517
  updateState: false
8339
8518
  });
8340
8519
  if (result?.isSuperseded) return false;
8520
+ if (checkWasStateResetDuringQuery()) return false;
8341
8521
  localMessage = this.getItem(messageId);
8342
8522
  if (!localMessage || !result || !result.targetInterval) {
8343
8523
  this.channel.getClient().notifications.addError({
@@ -8379,12 +8559,14 @@ var MessageIntervalPaginator = class extends BasePaginator {
8379
8559
  */
8380
8560
  this.jumpToTheLatestMessage = async (options) => {
8381
8561
  if (!this.latestHeadInterval) {
8562
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
8382
8563
  const result = await this.executeQuery({
8383
8564
  claimsActiveInterval: true,
8384
8565
  queryShape: { limit: this.pageSize },
8385
8566
  updateState: false
8386
8567
  });
8387
8568
  if (result?.isSuperseded) return false;
8569
+ if (checkWasStateResetDuringQuery()) return false;
8388
8570
  }
8389
8571
  const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
8390
8572
  if (!latestMessageId) {
@@ -9515,6 +9697,15 @@ var MessageIntervalPaginator = class extends BasePaginator {
9515
9697
  offlineDb.hardDeleteMessages({ ids }).catch(() => {
9516
9698
  });
9517
9699
  }
9700
+ /**
9701
+ * Also drops the focus signal of an earlier jump. Whatever claims the active interval decides what
9702
+ * is shown, so the earlier target must not be scrolled to or highlighted there. A jump claims
9703
+ * before it emits its own signal, so it keeps that one.
9704
+ */
9705
+ claimActiveInterval() {
9706
+ this.clearMessageFocusSignal();
9707
+ return super.claimActiveInterval();
9708
+ }
9518
9709
  clearStateAndCache() {
9519
9710
  this.resetState();
9520
9711
  this._itemIndex.clear();
@@ -9758,6 +9949,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9758
9949
  messages: this.state.getLatestValue().items ?? []
9759
9950
  });
9760
9951
  if (!inferredLastReadMessageId) {
9952
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
9761
9953
  const result = await this.executeQuery({
9762
9954
  claimsActiveInterval: true,
9763
9955
  queryShape: {
@@ -9768,6 +9960,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9768
9960
  updateState: false
9769
9961
  });
9770
9962
  if (result?.isSuperseded) return false;
9963
+ if (checkWasStateResetDuringQuery()) return false;
9771
9964
  if (result) {
9772
9965
  ({
9773
9966
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -27969,6 +28162,7 @@ var AbstractOfflineDB = class {
27969
28162
 
27970
28163
  // src/LiveLocationManager.ts
27971
28164
  var import_state_store31 = require("@stream-io/state-store");
28165
+ var logger22 = chatLoggerSystem.getLogger("live-location-manager");
27972
28166
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
27973
28167
  var canTrackLocation = (location) => typeof location.end_at === "number" && Number.isFinite(location.end_at) && location.end_at >= nowNs();
27974
28168
  var isTrackableLocation = (location) => canTrackLocation(location);
@@ -27991,6 +28185,12 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
27991
28185
  throw new Error("Live-location sharing is reserved for client-side use only");
27992
28186
  }
27993
28187
  super();
28188
+ /**
28189
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
28190
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
28191
+ * for these ids are skipped instead of being tracked again.
28192
+ */
28193
+ this.unregisteredDuringLoad = /* @__PURE__ */ new Set();
27994
28194
  /** Subscribes to the `'liveLocationManager'` configuration key. Idempotent. */
27995
28195
  this.subscribeConfiguration = () => {
27996
28196
  if (this.unsubscribeConfiguration) return;
@@ -28060,9 +28260,18 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28060
28260
  initializeConfig(config) {
28061
28261
  this.configController.initialize(config);
28062
28262
  }
28263
+ /**
28264
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
28265
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
28266
+ * whether or not the load has finished.
28267
+ *
28268
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
28269
+ * registered, so shares started later are still tracked. The next `init()`, position update or
28270
+ * `connection.recovered` event retries the load.
28271
+ */
28063
28272
  async init() {
28064
- await this.assureStateInit();
28065
28273
  this.registerSubscriptions();
28274
+ await this.assureStateInit();
28066
28275
  }
28067
28276
  get messages() {
28068
28277
  return this.state.getLatestValue().messages;
@@ -28076,24 +28285,37 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28076
28285
  }
28077
28286
  return this._deviceId;
28078
28287
  }
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
- {
28288
+ /** Loads the active live locations unless already loaded. Never rejects. */
28289
+ assureStateInit() {
28290
+ if (this.stateIsReady) return Promise.resolve();
28291
+ this.stateInitPromise ?? (this.stateInitPromise = this.loadState().finally(() => {
28292
+ this.stateInitPromise = void 0;
28293
+ this.unregisteredDuringLoad.clear();
28294
+ }));
28295
+ return this.stateInitPromise;
28296
+ }
28297
+ async loadState() {
28298
+ try {
28299
+ const { active_live_locations } = await this.client.getUserLiveLocations();
28300
+ this.state.next((currentValue) => {
28301
+ const messages = new Map(currentValue.messages);
28302
+ for (const location of active_live_locations.filter(isTrackableLocation)) {
28303
+ if (messages.has(location.message_id) || this.unregisteredDuringLoad.has(location.message_id))
28304
+ continue;
28305
+ messages.set(location.message_id, {
28087
28306
  ...location,
28088
28307
  stopSharingTimeout: this.scheduleStopSharing(
28089
28308
  location.message_id,
28090
28309
  location.end_at
28091
28310
  )
28092
- }
28093
- ])
28094
- ),
28095
- ready: true
28096
- });
28311
+ });
28312
+ }
28313
+ return { ...currentValue, messages, ready: true, lastQueryError: void 0 };
28314
+ });
28315
+ } catch (error) {
28316
+ logger22.warn("Failed to load the active live locations", error);
28317
+ this.state.partialNext({ lastQueryError: error });
28318
+ }
28097
28319
  }
28098
28320
  subscribeTargetMessagesChange() {
28099
28321
  let unsubscribeWatchLocation = null;
@@ -28156,11 +28378,11 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28156
28378
  if (event.type === "live_location_sharing.started") {
28157
28379
  this.registerMessage(event.message);
28158
28380
  } else if (event.type === "message.updated") {
28159
- const isRegistered = this.messages.has(event.message.id);
28160
- if (isRegistered && !isValidLiveLocationMessage(event.message)) {
28381
+ if (isValidLiveLocationMessage(event.message)) {
28382
+ this.registerMessage(event.message);
28383
+ } else {
28161
28384
  this.unregisterMessages([event.message.id]);
28162
28385
  }
28163
- this.registerMessage(event.message);
28164
28386
  } else {
28165
28387
  this.unregisterMessages([event.message.id]);
28166
28388
  }
@@ -28169,6 +28391,10 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28169
28391
  this.client.on("live_location_sharing.stopped", (event) => {
28170
28392
  if (!event.live_location) return;
28171
28393
  this.unregisterMessages([event.live_location?.message_id]);
28394
+ }),
28395
+ // Retries a failed load once the connection is back. No-op once the state is loaded.
28396
+ this.client.on("connection.recovered", () => {
28397
+ void this.assureStateInit();
28172
28398
  })
28173
28399
  ];
28174
28400
  return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
@@ -28214,6 +28440,9 @@ var _LiveLocationManager = class _LiveLocationManager extends WithSubscriptions
28214
28440
  });
28215
28441
  }
28216
28442
  unregisterMessages(messageIds) {
28443
+ if (this.stateInitPromise) {
28444
+ messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
28445
+ }
28217
28446
  const messages = this.messages;
28218
28447
  const removedMessages = new Set(messageIds);
28219
28448
  const newMessages = new Map(