stream-chat 10.0.2 → 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.
@@ -17,8 +17,11 @@ export type ScheduledLiveLocationSharing = SharedLiveLocationResponse & {
17
17
  stopSharingTimeout: ReturnType<typeof setTimeout> | null;
18
18
  };
19
19
  export type LiveLocationManagerState = {
20
+ /** Whether the user's active live locations have been loaded from the server. */
20
21
  ready: boolean;
21
22
  messages: Map<MessageId, ScheduledLiveLocationSharing>;
23
+ /** Error of the last failed load of the active live locations. Cleared by a successful load. */
24
+ lastQueryError?: Error;
22
25
  };
23
26
  export type LiveLocationManagerConstructorParameters = {
24
27
  client: StreamChat;
@@ -41,6 +44,14 @@ export declare class LiveLocationManager extends WithSubscriptions {
41
44
  private getDeviceId;
42
45
  private _deviceId;
43
46
  private watchLocation;
47
+ /** The in-flight load of the active live locations, shared by concurrent callers. */
48
+ private stateInitPromise?;
49
+ /**
50
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
51
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
52
+ * for these ids are skipped instead of being tracked again.
53
+ */
54
+ private unregisteredDuringLoad;
44
55
  private readonly configController;
45
56
  private unsubscribeConfiguration?;
46
57
  get configState(): StateStore<LiveLocationManagerConfig>;
@@ -61,6 +72,15 @@ export declare class LiveLocationManager extends WithSubscriptions {
61
72
  * @param config - The declarative slice. Leave it out to rebuild from the defaults.
62
73
  */
63
74
  initializeConfig(config?: Partial<LiveLocationManagerConfig>): void;
75
+ /**
76
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
77
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
78
+ * whether or not the load has finished.
79
+ *
80
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
81
+ * registered, so shares started later are still tracked. The next `init()`, position update or
82
+ * `connection.recovered` event retries the load.
83
+ */
64
84
  init(): Promise<void>;
65
85
  registerSubscriptions: () => void;
66
86
  /**
@@ -77,7 +97,9 @@ export declare class LiveLocationManager extends WithSubscriptions {
77
97
  get messages(): Map<string, ScheduledLiveLocationSharing>;
78
98
  get stateIsReady(): boolean;
79
99
  get deviceId(): string;
100
+ /** Loads the active live locations unless already loaded. Never rejects. */
80
101
  private assureStateInit;
102
+ private loadState;
81
103
  private subscribeTargetMessagesChange;
82
104
  private subscribeWatchLocation;
83
105
  private subscribeLiveLocationSharingUpdates;
@@ -522,11 +522,16 @@ export declare class Channel extends ChannelApi {
522
522
  get offlineMode(): boolean;
523
523
  set offlineMode(offlineMode: boolean);
524
524
  /**
525
- * Reads `state.data`. Assigning publishes `data`, `memberCount` and `ownCapabilities` in one update.
526
- * If the object omits `member_count` or `own_capabilities`, the last known values are carried onto
527
- * a copy (the assigned object is not changed). Editing `channel.data.x` in place does not reach
528
- * the state. `ownCapabilities` keeps its array while the capabilities stay the same (in any
529
- * order), so a subscriber to it is notified only when they change.
525
+ * Reads `state.data`. Assigning publishes `data`, `memberCount`, `activeMemberCount` and
526
+ * `ownCapabilities` in one update. If the object omits `member_count`, `active_member_count` or
527
+ * `own_capabilities`, the last known values are carried onto a copy (the assigned object is not
528
+ * changed). A carried `active_member_count` moves with `member_count` (shifted by the change in
529
+ * membership, clamped to `member_count`), since only Query Channels returns it; treat it as a
530
+ * last-known estimate, refreshed on the next query — it can lag a (de)activation or an
531
+ * already-deactivated member being added or removed. Editing
532
+ * `channel.data.x` in place does not reach the state. `ownCapabilities` keeps its array while the
533
+ * capabilities stay the same (in any order), so a subscriber to it is notified only when they
534
+ * change.
530
535
  */
531
536
  get data(): Partial<ChannelResponse> | undefined;
532
537
  set data(next: Partial<ChannelResponse> | undefined);
@@ -54,6 +54,7 @@ export type MembersState = {
54
54
  * member change and is authoritative, while counting per member event double-counts.
55
55
  */
56
56
  memberCount: number;
57
+ activeMemberCount?: number;
57
58
  };
58
59
  export type MembershipState = {
59
60
  membership: ChannelMemberResponse;
@@ -536,6 +536,7 @@ export declare class StreamChat extends ChatApi {
536
536
  unbanUser(targetUserId: string, options?: UnBanUserOptions): Promise<APIResponse>;
537
537
  blockUser(blockedUserId: string, requestOptions?: StreamRequestOptions): Promise<StreamResponse<import(".").BlockUsersResponse>>;
538
538
  getBlockedUsers(...args: Parameters<ChatApi['getBlockedUsers']>): Promise<StreamResponse<import(".").GetBlockedUsersResponse>>;
539
+ updatePushNotificationPreferences(...args: Parameters<ChatApi['updatePushNotificationPreferences']>): Promise<StreamResponse<import(".").UpsertPushPreferencesResponse>>;
539
540
  unblockUser(blockedUserId: string, requestOptions?: StreamRequestOptions): Promise<StreamResponse<import(".").UnblockUsersResponse>>;
540
541
  /**
541
542
  * Checks whether a user is muted.
@@ -1,5 +1,5 @@
1
1
  import * as scopedLogger from '@stream-io/logger';
2
- export type ChatLoggerScope = 'api-client' | 'channel' | 'channel-manager' | 'client' | 'connection' | 'instance-configuration' | 'message-composer' | 'offline-db' | 'state-store' | 'text-composer' | 'thread' | 'thread-manager' | 'token-manager' | 'upload-manager' | 'utils';
2
+ export type ChatLoggerScope = 'api-client' | 'channel' | 'channel-manager' | 'client' | 'connection' | 'instance-configuration' | 'live-location-manager' | 'message-composer' | 'offline-db' | 'state-store' | 'text-composer' | 'thread' | 'thread-manager' | 'token-manager' | 'upload-manager' | 'utils';
3
3
  /** @internal */
4
4
  export type ScopedLogger = scopedLogger.Logger<ChatLoggerScope>;
5
5
  export { LogLevelEnum } from '@stream-io/logger';
@@ -128,8 +128,10 @@ export type PaginationQueryParams<Q> = {
128
128
  silent?: boolean;
129
129
  /**
130
130
  * Whether the page's interval becomes the active one and the state is published. Default: true.
131
- * Otherwise the page is only stored; one landing in the active interval is still published. Even
132
- * with it, the paginator's own page can be only stored (see `BasePaginator.isPageOnlyStored`).
131
+ * With `false` the page is only stored. It is still published when it lands in the active
132
+ * interval, or when it is an empty first page of a list without items (not at a caller's
133
+ * `queryShape`, not superseded by a later claim). With `true` the paginator's own page can still
134
+ * be only stored (see `BasePaginator.isPageOnlyStored`).
133
135
  */
134
136
  updateState?: boolean;
135
137
  };
@@ -402,6 +404,8 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
402
404
  /** Canonical, ID-addressable item storage: the single source of truth outside the paginator. */
403
405
  protected _itemIndex: ItemIndexApi<T>;
404
406
  protected _executeQueryDebounced: DebouncedExecQueryFunction<Q>;
407
+ /** How many times `resetState()` ran, which tells the work started before a reset apart. */
408
+ private _stateResetCount;
405
409
  /** Last effective query shape produced by the subclass for the most recent request. */
406
410
  protected _lastQueryShape?: Q;
407
411
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
@@ -572,7 +576,8 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
572
576
  /**
573
577
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
574
578
  * besides its page, once the page is placed with `placeParams`. Runs once for every response that
575
- * arrived, also when extracting or placing its page failed. Does nothing by default.
579
+ * arrived, also when placing its page failed or a reset made it ignored (see
580
+ * {@link executeQuery}). Does nothing by default.
576
581
  */
577
582
  protected applyQueryResponseRest(_response: R, _placeParams: QueryPagePlacement<Q>): void;
578
583
  /**
@@ -945,11 +950,18 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
945
950
  }) => Promise<T[] | undefined> | T[] | undefined;
946
951
  /**
947
952
  * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
948
- * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
949
- * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
950
- * caller to end the query.
953
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
954
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
951
955
  */
952
- protected fetchQueryResponseWithRetries(params?: PaginationQueryParams<Q>): Promise<R | null>;
956
+ protected fetchQueryResponseWithRetries(params?: PaginationQueryParams<Q>, { checkWasStateResetDuringQuery, }?: {
957
+ checkWasStateResetDuringQuery?: () => boolean;
958
+ }): Promise<R | null>;
959
+ /**
960
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
961
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
962
+ * and the caller ends the query.
963
+ */
964
+ private reportFailedFetch;
953
965
  /**
954
966
  * Runs one query through the query pipeline, step by step:
955
967
  *
@@ -966,9 +978,13 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
966
978
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
967
979
  * rejects the call only with `throwErrors` set.
968
980
  *
969
- * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
970
- * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
971
- * placed, with `isSuperseded`.
981
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
982
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
983
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
984
+ *
985
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
986
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
987
+ * is `null` when no page was placed, with `isSuperseded`.
972
988
  *
973
989
  * @param params - Query parameters.
974
990
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -987,12 +1003,22 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
987
1003
  executeQuery(params?: PaginationQueryParams<Q>): Promise<ExecuteQueryReturnValue<T> | void>;
988
1004
  /** The steps after {@link prepareQuery} of the query pipeline (see {@link executeQuery}). */
989
1005
  private runPreparedQuery;
1006
+ /**
1007
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
1008
+ * An ignored query reports nothing, so an error here is swallowed.
1009
+ */
1010
+ private applyResponseRestOfIgnoredQuery;
990
1011
  /**
991
1012
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
992
1013
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
993
1014
  * placed with the error in its state, so a caller committing that state keeps the error.
994
1015
  */
995
1016
  private reportQueryError;
1017
+ /**
1018
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
1019
+ * reset uses it to ignore its results instead of writing them into the reset state.
1020
+ */
1021
+ protected makeStateResetWatcher(): () => boolean;
996
1022
  /**
997
1023
  * Whether a query claims the active interval by default (see
998
1024
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -1025,6 +1051,27 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
1025
1051
  * the page with no known place relative to the active interval.
1026
1052
  */
1027
1053
  private continuedIntervalIsInactive;
1054
+ /**
1055
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
1056
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
1057
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
1058
+ */
1059
+ private emptyPageKeepsLoadedItems;
1060
+ /**
1061
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
1062
+ * own `updateState: false` query settles a list without items
1063
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
1064
+ * what the stored page changed.
1065
+ */
1066
+ private commitsPlacedState;
1067
+ /**
1068
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
1069
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
1070
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
1071
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
1072
+ * owns the list.
1073
+ */
1074
+ private emptyPageSettlesListWithoutItems;
1028
1075
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
1029
1076
  private claimIsSuperseded;
1030
1077
  /**
@@ -1042,7 +1089,7 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
1042
1089
  * database. A page from a query the paginator did not run is placed without any of that, as one
1043
1090
  * of the paginator's own queries may still be running.
1044
1091
  */
1045
- protected placePage({ startsSeparateInterval, direction, isFirstPage, keepPreviousItems, queryShape, requestedPageSize, results, updateState, }: QueryPagePlacement<Q> & {
1092
+ protected placePage(placement: QueryPagePlacement<Q> & {
1046
1093
  results: PaginationQueryReturnValue<T>;
1047
1094
  }, { endsQuery }: {
1048
1095
  endsQuery: boolean;
@@ -1053,6 +1100,10 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
1053
1100
  */
1054
1101
  private publishStoredPage;
1055
1102
  cancelScheduledQuery(): void;
1103
+ /**
1104
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
1105
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
1106
+ */
1056
1107
  resetState(): void;
1057
1108
  /**
1058
1109
  * Releases this paginator's hold on its item content (unlinks every member ID from the shared
@@ -121,10 +121,31 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
121
121
  get effectiveSort(): SortParamRequest[];
122
122
  get options(): ChannelOptions | undefined;
123
123
  get channelStateOptions(): ChannelStateOptions | undefined;
124
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
124
125
  set staticFilters(filters: ChannelFilters | undefined);
126
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
125
127
  set sort(sort: SortParamRequest[] | undefined);
128
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
126
129
  set options(options: ChannelPaginatorRequestOptions | undefined);
127
130
  set channelStateOptions(options: ChannelStateOptions | undefined);
131
+ /**
132
+ * Applies a change to a query input (filters, sort, options) and resets the list with
133
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
134
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
135
+ * loaded pages.
136
+ *
137
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
138
+ * query's first page. A query still running for the old query is ignored; a debounced query
139
+ * stays scheduled and runs with the new query.
140
+ */
141
+ private changeQuery;
142
+ /**
143
+ * Whether the next query has another identity than `queryBefore`
144
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
145
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
146
+ * and `member_limit` and `message_limit` (how much of each channel loads).
147
+ */
148
+ private queryChangeDiscardsPages;
128
149
  get sortComparatorFactory(): ChannelSortComparatorFactory | undefined;
129
150
  /**
130
151
  * Rebuilds the comparator immediately; later rebuilds consult the factory again, so a sort change
@@ -140,6 +161,17 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
140
161
  buildQueryFilters: () => ChannelFilters;
141
162
  /** Filters items are matched against locally (`matchesFilter`), built from `effectiveFilters`. */
142
163
  buildMatchFilters: () => ChannelFilters;
164
+ /**
165
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
166
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
167
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
168
+ * cache stored without it) matches by `staticFilters`.
169
+ */
170
+ private get awaitsPredefinedFilter();
171
+ /**
172
+ * Whether `channel` belongs to the list. Nothing does while a list with
173
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
174
+ */
143
175
  matchesFilter(channel: Channel): boolean;
144
176
  /** Commits the response's `predefined_filter` metadata, or clears it when there is none. */
145
177
  protected applyPredefinedFilterResponse(predefinedFilter: ParsedPredefinedFilterResponse | undefined): void;
@@ -221,6 +253,11 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
221
253
  onEntitiesChanged(): void;
222
254
  /** Entity-store subscriber: the store removed a channel this list holds (e.g. logout). */
223
255
  onEntityRemoved(id: string, channel: unknown): void;
256
+ /**
257
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
258
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
259
+ * stays scheduled.
260
+ */
224
261
  resetState(): void;
225
262
  removeItem(params: {
226
263
  id?: string;
@@ -0,0 +1,5 @@
1
+ import type { ChannelResponse } from '../gen/models';
2
+ export declare const getCarriedActiveMemberCount: ({ next, previous, }: {
3
+ next: Partial<ChannelResponse>;
4
+ previous: Partial<ChannelResponse> | undefined;
5
+ }) => number | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stream-chat",
3
- "version": "10.0.2",
3
+ "version": "10.1.1",
4
4
  "description": "JS SDK for the Stream Chat API",
5
5
  "homepage": "https://getstream.io/chat/",
6
6
  "author": {
@@ -11,6 +11,7 @@ import { StateStore } from '@stream-io/state-store';
11
11
  import { ConfigController } from './configuration/ConfigController';
12
12
  import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
13
13
  import { WithSubscriptions } from './utils/WithSubscriptions';
14
+ import { chatLoggerSystem } from './logger';
14
15
  import type { StreamChat } from './client';
15
16
  import type { Unsubscribe } from '@stream-io/state-store';
16
17
  import type {
@@ -26,13 +27,18 @@ export type WatchLocation = (handler: WatchLocationHandler) => Unsubscribe;
26
27
  type DeviceIdGenerator = () => string;
27
28
  type MessageId = string;
28
29
 
30
+ const logger = chatLoggerSystem.getLogger('live-location-manager');
31
+
29
32
  export type ScheduledLiveLocationSharing = SharedLiveLocationResponse & {
30
33
  stopSharingTimeout: ReturnType<typeof setTimeout> | null;
31
34
  };
32
35
 
33
36
  export type LiveLocationManagerState = {
37
+ /** Whether the user's active live locations have been loaded from the server. */
34
38
  ready: boolean;
35
39
  messages: Map<MessageId, ScheduledLiveLocationSharing>;
40
+ /** Error of the last failed load of the active live locations. Cleared by a successful load. */
41
+ lastQueryError?: Error;
36
42
  };
37
43
 
38
44
  /** `setTimeout` silently clamps a longer delay to 1 ms, so longer waits are armed in steps. */
@@ -94,6 +100,14 @@ export class LiveLocationManager extends WithSubscriptions {
94
100
  private getDeviceId: DeviceIdGenerator;
95
101
  private _deviceId: string;
96
102
  private watchLocation: WatchLocation;
103
+ /** The in-flight load of the active live locations, shared by concurrent callers. */
104
+ private stateInitPromise?: Promise<void>;
105
+ /**
106
+ * Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
107
+ * `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
108
+ * for these ids are skipped instead of being tracked again.
109
+ */
110
+ private unregisteredDuringLoad = new Set<MessageId>();
97
111
 
98
112
  private readonly configController: ConfigController<LiveLocationManagerConfig>;
99
113
  private unsubscribeConfiguration?: Unsubscribe;
@@ -171,9 +185,18 @@ export class LiveLocationManager extends WithSubscriptions {
171
185
  this.configController.initialize(config);
172
186
  }
173
187
 
188
+ /**
189
+ * Registers the event subscriptions, then loads the user's active live locations. Registration
190
+ * runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
191
+ * whether or not the load has finished.
192
+ *
193
+ * Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
194
+ * registered, so shares started later are still tracked. The next `init()`, position update or
195
+ * `connection.recovered` event retries the load.
196
+ */
174
197
  public async init() {
175
- await this.assureStateInit();
176
198
  this.registerSubscriptions();
199
+ await this.assureStateInit();
177
200
  }
178
201
 
179
202
  public registerSubscriptions = () => {
@@ -219,24 +242,44 @@ export class LiveLocationManager extends WithSubscriptions {
219
242
  return this._deviceId;
220
243
  }
221
244
 
222
- private async assureStateInit() {
223
- if (this.stateIsReady) return;
224
- const { active_live_locations } = await this.client.getUserLiveLocations();
225
- this.state.next({
226
- messages: new Map(
227
- active_live_locations.filter(isTrackableLocation).map((location) => [
228
- location.message_id,
229
- {
245
+ /** Loads the active live locations unless already loaded. Never rejects. */
246
+ private assureStateInit(): Promise<void> {
247
+ if (this.stateIsReady) return Promise.resolve();
248
+
249
+ this.stateInitPromise ??= this.loadState().finally(() => {
250
+ this.stateInitPromise = undefined;
251
+ this.unregisteredDuringLoad.clear();
252
+ });
253
+ return this.stateInitPromise;
254
+ }
255
+
256
+ private async loadState() {
257
+ try {
258
+ const { active_live_locations } = await this.client.getUserLiveLocations();
259
+ this.state.next((currentValue) => {
260
+ // Events received while the request was in flight are at least as recent as the snapshot:
261
+ // shares they registered are kept as they are, and shares they unregistered stay out.
262
+ const messages = new Map(currentValue.messages);
263
+ for (const location of active_live_locations.filter(isTrackableLocation)) {
264
+ if (
265
+ messages.has(location.message_id) ||
266
+ this.unregisteredDuringLoad.has(location.message_id)
267
+ )
268
+ continue;
269
+ messages.set(location.message_id, {
230
270
  ...location,
231
271
  stopSharingTimeout: this.scheduleStopSharing(
232
272
  location.message_id,
233
273
  location.end_at,
234
274
  ),
235
- },
236
- ]),
237
- ),
238
- ready: true,
239
- });
275
+ });
276
+ }
277
+ return { ...currentValue, messages, ready: true, lastQueryError: undefined };
278
+ });
279
+ } catch (error) {
280
+ logger.warn('Failed to load the active live locations', error);
281
+ this.state.partialNext({ lastQueryError: error as Error });
282
+ }
240
283
  }
241
284
 
242
285
  private subscribeTargetMessagesChange() {
@@ -319,11 +362,13 @@ export class LiveLocationManager extends WithSubscriptions {
319
362
  if (event.type === 'live_location_sharing.started') {
320
363
  this.registerMessage(event.message);
321
364
  } else if (event.type === 'message.updated') {
322
- const isRegistered = this.messages.has(event.message.id);
323
- if (isRegistered && !isValidLiveLocationMessage(event.message)) {
365
+ // A share stopped on another device arrives here with an `end_at` in the past.
366
+ // Unregistered even when not tracked yet, so a load in flight does not re-add it.
367
+ if (isValidLiveLocationMessage(event.message)) {
368
+ this.registerMessage(event.message);
369
+ } else {
324
370
  this.unregisterMessages([event.message.id]);
325
371
  }
326
- this.registerMessage(event.message);
327
372
  } else {
328
373
  this.unregisterMessages([event.message.id]);
329
374
  }
@@ -334,6 +379,10 @@ export class LiveLocationManager extends WithSubscriptions {
334
379
 
335
380
  this.unregisterMessages([event.live_location?.message_id]);
336
381
  }),
382
+ // Retries a failed load once the connection is back. No-op once the state is loaded.
383
+ this.client.on('connection.recovered', () => {
384
+ void this.assureStateInit();
385
+ }),
337
386
  ];
338
387
 
339
388
  return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
@@ -392,6 +441,9 @@ export class LiveLocationManager extends WithSubscriptions {
392
441
  }
393
442
 
394
443
  private unregisterMessages(messageIds: string[]) {
444
+ if (this.stateInitPromise) {
445
+ messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
446
+ }
395
447
  const messages = this.messages;
396
448
  const removedMessages = new Set(messageIds);
397
449
  const newMessages = new Map(
package/src/channel.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  logChatPromiseExecution,
20
20
  sanitizeOutgoingAttachments,
21
21
  } from './utils';
22
+ import { getCarriedActiveMemberCount } from './utils/activeMemberCount';
22
23
  import { asTimestampNS, nowNs } from './utils/time';
23
24
  import { abortError, waitUnlessAborted } from './utils/abort';
24
25
  import { normalizeUploadFile } from './upload-utils';
@@ -1185,11 +1186,16 @@ export class Channel extends ChannelApi {
1185
1186
  }
1186
1187
 
1187
1188
  /**
1188
- * Reads `state.data`. Assigning publishes `data`, `memberCount` and `ownCapabilities` in one update.
1189
- * If the object omits `member_count` or `own_capabilities`, the last known values are carried onto
1190
- * a copy (the assigned object is not changed). Editing `channel.data.x` in place does not reach
1191
- * the state. `ownCapabilities` keeps its array while the capabilities stay the same (in any
1192
- * order), so a subscriber to it is notified only when they change.
1189
+ * Reads `state.data`. Assigning publishes `data`, `memberCount`, `activeMemberCount` and
1190
+ * `ownCapabilities` in one update. If the object omits `member_count`, `active_member_count` or
1191
+ * `own_capabilities`, the last known values are carried onto a copy (the assigned object is not
1192
+ * changed). A carried `active_member_count` moves with `member_count` (shifted by the change in
1193
+ * membership, clamped to `member_count`), since only Query Channels returns it; treat it as a
1194
+ * last-known estimate, refreshed on the next query — it can lag a (de)activation or an
1195
+ * already-deactivated member being added or removed. Editing
1196
+ * `channel.data.x` in place does not reach the state. `ownCapabilities` keeps its array while the
1197
+ * capabilities stay the same (in any order), so a subscriber to it is notified only when they
1198
+ * change.
1193
1199
  */
1194
1200
  get data(): Partial<ChannelResponse> | undefined {
1195
1201
  return this.state.getLatestValue().data;
@@ -1197,6 +1203,7 @@ export class Channel extends ChannelApi {
1197
1203
 
1198
1204
  set data(next: Partial<ChannelResponse> | undefined) {
1199
1205
  const {
1206
+ activeMemberCount: previousActiveMemberCount,
1200
1207
  data: previous,
1201
1208
  memberCount: previousMemberCount,
1202
1209
  ownCapabilities: previousOwnCapabilities,
@@ -1205,27 +1212,40 @@ export class Channel extends ChannelApi {
1205
1212
  typeof next?.member_count !== 'number' && typeof previous?.member_count === 'number'
1206
1213
  ? previous.member_count
1207
1214
  : undefined;
1215
+ const carriedActiveMemberCount = next
1216
+ ? getCarriedActiveMemberCount({ next, previous })
1217
+ : undefined;
1208
1218
  // `own_capabilities` stays undefined until known, so "not loaded" isn't read as "none"
1209
1219
  const carriedCapabilities =
1210
1220
  !Array.isArray(next?.own_capabilities) && Array.isArray(previous?.own_capabilities)
1211
1221
  ? [...previous.own_capabilities]
1212
1222
  : undefined;
1213
1223
 
1224
+ const carriesMemberCount = carriedMemberCount !== undefined;
1225
+ const carriesActiveMemberCount = carriedActiveMemberCount !== undefined;
1226
+ const carriesValues =
1227
+ carriesMemberCount || carriesActiveMemberCount || !!carriedCapabilities;
1228
+
1214
1229
  const data =
1215
- next && (carriedMemberCount !== undefined || carriedCapabilities)
1230
+ next && carriesValues
1216
1231
  ? {
1217
1232
  ...next,
1218
- ...(carriedMemberCount !== undefined && { member_count: carriedMemberCount }),
1233
+ ...(carriesMemberCount && { member_count: carriedMemberCount }),
1234
+ ...(carriesActiveMemberCount && {
1235
+ active_member_count: carriedActiveMemberCount,
1236
+ }),
1219
1237
  ...(carriedCapabilities && { own_capabilities: carriedCapabilities }),
1220
1238
  }
1221
1239
  : next;
1222
1240
 
1223
1241
  const memberCount = data?.member_count ?? carriedMemberCount;
1242
+ const activeMemberCount = data ? data.active_member_count : previousActiveMemberCount;
1224
1243
  const ownCapabilities = data?.own_capabilities ?? carriedCapabilities ?? [];
1225
1244
  const toKey = (capabilities: readonly string[]) => [...capabilities].sort().join();
1226
1245
  const haveSameOwnCapabilities =
1227
1246
  toKey(previousOwnCapabilities) === toKey(ownCapabilities);
1228
1247
  this.state.partialNext({
1248
+ activeMemberCount,
1229
1249
  data,
1230
1250
  memberCount: memberCount ?? previousMemberCount,
1231
1251
  ownCapabilities: haveSameOwnCapabilities
@@ -78,6 +78,7 @@ export type MembersState = {
78
78
  * member change and is authoritative, while counting per member event double-counts.
79
79
  */
80
80
  memberCount: number;
81
+ activeMemberCount?: number;
81
82
  };
82
83
 
83
84
  export type MembershipState = {
package/src/client.ts CHANGED
@@ -1733,6 +1733,22 @@ export class StreamChat extends ChatApi {
1733
1733
  return result;
1734
1734
  }
1735
1735
 
1736
+ override async updatePushNotificationPreferences(
1737
+ ...args: Parameters<ChatApi['updatePushNotificationPreferences']>
1738
+ ) {
1739
+ const result = await super.updatePushNotificationPreferences(...args);
1740
+ const { user } = this;
1741
+ if (!user) return result;
1742
+
1743
+ // The full stored preferences after the update, or null when the request only had
1744
+ // channel-level items for this user.
1745
+ const updated = result.user_preferences[user.id];
1746
+ if (updated) {
1747
+ this.user = { ...user, push_preferences: updated };
1748
+ }
1749
+ return result;
1750
+ }
1751
+
1736
1752
  async unblockUser(blockedUserId: string, requestOptions?: StreamRequestOptions) {
1737
1753
  const result = await this.unblockUsers(
1738
1754
  {
package/src/logger.ts CHANGED
@@ -7,6 +7,7 @@ export type ChatLoggerScope =
7
7
  | 'client'
8
8
  | 'connection'
9
9
  | 'instance-configuration'
10
+ | 'live-location-manager'
10
11
  | 'message-composer'
11
12
  | 'offline-db'
12
13
  | 'state-store'