stream-chat 10.0.0-rc.32 → 10.0.0-rc.34

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.
Files changed (35) hide show
  1. package/dist/cjs/index.browser.js +204 -87
  2. package/dist/cjs/index.browser.js.map +2 -2
  3. package/dist/cjs/index.node.js +207 -87
  4. package/dist/cjs/index.node.js.map +2 -2
  5. package/dist/esm/index.mjs +204 -87
  6. package/dist/esm/index.mjs.map +2 -2
  7. package/dist/types/channel.d.ts +9 -0
  8. package/dist/types/client.d.ts +2 -1
  9. package/dist/types/connection/ConnectionRecoveryManager.d.ts +13 -1
  10. package/dist/types/custom_types.d.ts +0 -2
  11. package/dist/types/gen/models/index.d.ts +93 -11
  12. package/dist/types/index.d.ts +1 -1
  13. package/dist/types/messageComposer/attachmentIdentity.d.ts +18 -0
  14. package/dist/types/messageComposer/attachmentManager.d.ts +16 -2
  15. package/dist/types/messageComposer/types.d.ts +19 -1
  16. package/dist/types/pagination/paginators/BasePaginator.d.ts +11 -0
  17. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +5 -1
  18. package/dist/types/pagination/paginators/MessagePaginator.d.ts +29 -16
  19. package/package.json +1 -1
  20. package/src/channel.ts +37 -1
  21. package/src/client.ts +13 -3
  22. package/src/connection/ConnectionRecoveryManager.ts +29 -14
  23. package/src/custom_types.ts +0 -1
  24. package/src/gen/models/index.ts +94 -11
  25. package/src/index.ts +0 -1
  26. package/src/messageComposer/attachmentIdentity.ts +26 -0
  27. package/src/messageComposer/attachmentManager.ts +46 -27
  28. package/src/messageComposer/messageComposer.ts +8 -9
  29. package/src/messageComposer/middleware/messageComposer/attachments.ts +12 -21
  30. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +4 -3
  31. package/src/messageComposer/types.ts +27 -1
  32. package/src/messageOperations/settlePendingAttachmentUploads.ts +2 -3
  33. package/src/pagination/paginators/BasePaginator.ts +21 -3
  34. package/src/pagination/paginators/MessageIntervalPaginator.ts +8 -1
  35. package/src/pagination/paginators/MessagePaginator.ts +104 -50
@@ -229,10 +229,13 @@ __export(src_exports, {
229
229
  isLocalVideoAttachment: () => isLocalVideoAttachment,
230
230
  isLocalVoiceRecordingAttachment: () => isLocalVoiceRecordingAttachment,
231
231
  isLogicalInterval: () => isLogicalInterval,
232
+ isNonUploadAttachment: () => isNonUploadAttachment,
232
233
  isOwnUser: () => isOwnUser,
233
234
  isPendingUpload: () => isPendingUpload,
234
235
  isPollComposerValidationError: () => isPollComposerValidationError,
236
+ isResolvableUpload: () => isResolvableUpload,
235
237
  isScrapedContent: () => isScrapedContent,
238
+ isSendableAttachment: () => isSendableAttachment,
236
239
  isSharedLocationResponseData: () => isSharedLocationResponseData,
237
240
  isTargetedOptionTextUpdate: () => isTargetedOptionTextUpdate,
238
241
  isUploadCancellation: () => isUploadCancellation,
@@ -1754,6 +1757,9 @@ var PENDING_UPLOAD_STATES = [
1754
1757
  var isPendingUpload = (attachment) => isLocalUploadAttachment(attachment) && PENDING_UPLOAD_STATES.includes(attachment.localMetadata.uploadState);
1755
1758
  var isFinishedUpload = (attachment) => isLocalUploadAttachment(attachment) && attachment.localMetadata.uploadState === "finished";
1756
1759
  var isFailedUpload = (attachment) => isLocalUploadAttachment(attachment) && attachment.localMetadata.uploadState === "failed";
1760
+ var isResolvableUpload = (attachment) => isPendingUpload(attachment) || isFailedUpload(attachment);
1761
+ var isNonUploadAttachment = (attachment) => isLocalAttachment(attachment) && !isLocalUploadAttachment(attachment) && !attachment.localMetadata.file;
1762
+ var isSendableAttachment = (attachment) => isFinishedUpload(attachment) || isNonUploadAttachment(attachment);
1757
1763
  var isFileAttachment = (attachment, supportedVideoFormat = []) => attachment.type === "file" || !!(attachment.custom?.mime_type && supportedVideoFormat.indexOf(
1758
1764
  attachment.custom?.mime_type
1759
1765
  ) === -1 && attachment.type !== "video");
@@ -2913,24 +2919,29 @@ var _AttachmentManager = class _AttachmentManager {
2913
2919
  const attachmentsById = this.attachmentsById;
2914
2920
  return this.attachments.indexOf(attachmentsById[localId]);
2915
2921
  };
2916
- this.prepareAttachmentUpdate = (attachmentToUpdate) => {
2917
- const stateAttachments = this.attachments;
2918
- const attachments = [...this.attachments];
2919
- const attachmentIndex = this.getAttachmentIndex(attachmentToUpdate.localMetadata.id);
2922
+ /**
2923
+ * `attachments` with `attachmentToUpdate` merged in place of the one with its `localMetadata.id`:
2924
+ * `null` when none has it, `attachments` itself when the merge changes nothing.
2925
+ */
2926
+ this.prepareAttachmentUpdate = (attachmentToUpdate, attachments = this.attachments) => {
2927
+ const attachmentIndex = attachments.findIndex(
2928
+ ({ localMetadata }) => localMetadata?.id === attachmentToUpdate.localMetadata.id
2929
+ );
2920
2930
  if (attachmentIndex === -1) return null;
2921
2931
  const merged = mergeWithDiff(
2922
- stateAttachments[attachmentIndex],
2932
+ attachments[attachmentIndex],
2923
2933
  attachmentToUpdate
2924
2934
  );
2925
2935
  const updatesOnMerge = merged.diff && Object.keys(merged.diff.children).length;
2926
2936
  if (updatesOnMerge) {
2927
2937
  const localAttachment = ensureIsLocalAttachment(merged.result);
2928
2938
  if (localAttachment) {
2929
- attachments.splice(attachmentIndex, 1, localAttachment);
2930
- return attachments;
2939
+ const updatedAttachments = [...attachments];
2940
+ updatedAttachments.splice(attachmentIndex, 1, localAttachment);
2941
+ return updatedAttachments;
2931
2942
  }
2932
2943
  }
2933
- return stateAttachments;
2944
+ return attachments;
2934
2945
  };
2935
2946
  this.updateAttachment = (attachmentToUpdate) => {
2936
2947
  const updatedAttachments = this.prepareAttachmentUpdate(attachmentToUpdate);
@@ -2938,24 +2949,24 @@ var _AttachmentManager = class _AttachmentManager {
2938
2949
  this.state.partialNext({ attachments: updatedAttachments });
2939
2950
  }
2940
2951
  };
2952
+ /**
2953
+ * Merges each attachment into the one with its `localMetadata.id`, or appends it. An attachment
2954
+ * without a local id (e.g. a custom-type one the app builds) is appended with a new one, on every
2955
+ * call: to update or remove it later, pass `{ ...attachment, localMetadata: { id } }` with your own
2956
+ * id instead.
2957
+ */
2941
2958
  this.upsertAttachments = (attachmentsToUpsert) => {
2942
2959
  if (!attachmentsToUpsert.length) return;
2943
- let attachments = [...this.attachments];
2944
- let hasUpdates = false;
2960
+ let attachments = this.attachments;
2945
2961
  attachmentsToUpsert.forEach((attachment) => {
2946
- const updatedAttachments = this.prepareAttachmentUpdate(attachment);
2947
- if (updatedAttachments === null) {
2948
- const localAttachment = ensureIsLocalAttachment(attachment);
2949
- if (localAttachment) {
2950
- attachments.push(localAttachment);
2951
- hasUpdates = true;
2952
- }
2953
- } else if (updatedAttachments !== this.attachments) {
2954
- attachments = updatedAttachments;
2955
- hasUpdates = true;
2956
- }
2962
+ const localAttachment = ensureIsLocalAttachment(attachment);
2963
+ if (!localAttachment) return;
2964
+ attachments = this.prepareAttachmentUpdate(localAttachment, attachments) ?? [
2965
+ ...attachments,
2966
+ localAttachment
2967
+ ];
2957
2968
  });
2958
- if (hasUpdates) {
2969
+ if (attachments !== this.attachments) {
2959
2970
  this.state.partialNext({ attachments });
2960
2971
  }
2961
2972
  };
@@ -2982,10 +2993,11 @@ var _AttachmentManager = class _AttachmentManager {
2982
2993
  this.getUploadConfigCheck = async (fileLike) => {
2983
2994
  const client = this.channel.getClient();
2984
2995
  let appSettings;
2985
- if (!client.appSettingsPromise) {
2986
- appSettings = await client.getAppSettings();
2987
- } else {
2988
- appSettings = await client.appSettingsPromise;
2996
+ try {
2997
+ appSettings = await (client.appSettingsPromise ?? client.getAppSettings());
2998
+ } catch (error) {
2999
+ appSettings = client.userId ? await client.offlineDb?.getAppSettings({ userId: client.userId }).catch(() => null) : null;
3000
+ if (!appSettings) throw error;
2989
3001
  }
2990
3002
  const uploadConfig = isImageFile(fileLike) ? appSettings?.app?.image_upload_config : appSettings?.app?.file_upload_config;
2991
3003
  if (!uploadConfig) return { uploadBlocked: false };
@@ -3277,6 +3289,10 @@ var _AttachmentManager = class _AttachmentManager {
3277
3289
  get pendingUploadsCount() {
3278
3290
  return this.getUploadsByState("pending").length;
3279
3291
  }
3292
+ /**
3293
+ * Slots left for files. Each finished or uploading attachment takes one. Pending, failed and blocked
3294
+ * uploads, and attachments with nothing to upload, take none.
3295
+ */
3280
3296
  get availableUploadSlots() {
3281
3297
  return this.config.maxNumberOfFilesPerMessage - this.successfulUploadsCount - this.uploadsInProgressCount;
3282
3298
  }
@@ -3364,24 +3380,23 @@ var localAttachmentToAttachment = (localAttachment) => {
3364
3380
  const { localMetadata: _localMetadata, ...attachment } = localAttachment;
3365
3381
  return attachment;
3366
3382
  };
3367
- var isSendable = (attachment) => isFinishedUpload(attachment) || !isLocalUploadAttachment(attachment);
3368
3383
  var composeWithPendingUploads = ({
3369
3384
  composer,
3370
3385
  state
3371
3386
  }) => {
3372
3387
  const composerIsKeptAsDraft = composer.retainsCompositionOnSubmit;
3373
3388
  const relevantAttachments = composer.attachmentManager.attachments.filter(
3374
- (attachment) => isSendable(attachment) || !composerIsKeptAsDraft && (isPendingUpload(attachment) || isFailedUpload(attachment))
3389
+ (attachment) => isSendableAttachment(attachment) || !composerIsKeptAsDraft && isResolvableUpload(attachment)
3375
3390
  );
3376
3391
  const localAttachments = (state.localMessage.attachments ?? []).concat(
3377
3392
  // A finished upload or a non-upload is final; the rest keep `localMetadata` (joined to the upload
3378
3393
  // record).
3379
3394
  relevantAttachments.map(
3380
- (attachment) => isSendable(attachment) ? localAttachmentToAttachment(attachment) : attachment
3395
+ (attachment) => isSendableAttachment(attachment) ? localAttachmentToAttachment(attachment) : attachment
3381
3396
  )
3382
3397
  );
3383
3398
  const messageAttachments = (state.message.attachments ?? []).concat(
3384
- relevantAttachments.filter(isSendable).map(localAttachmentToAttachment)
3399
+ relevantAttachments.filter(isSendableAttachment).map(localAttachmentToAttachment)
3385
3400
  );
3386
3401
  if (!localAttachments.length && !messageAttachments.length) return state;
3387
3402
  return {
@@ -3424,7 +3439,7 @@ var createAttachmentsCompositionMiddleware = (composer) => ({
3424
3439
  return discard();
3425
3440
  }
3426
3441
  const attachments = (state.message.attachments ?? []).concat(
3427
- attachmentManager.attachments.filter(isSendable).map(localAttachmentToAttachment)
3442
+ attachmentManager.attachments.filter(isSendableAttachment).map(localAttachmentToAttachment)
3428
3443
  );
3429
3444
  if (!attachments.length) return forward();
3430
3445
  return next({
@@ -3451,7 +3466,7 @@ var createDraftAttachmentsCompositionMiddleware = (composer) => ({
3451
3466
  }) => {
3452
3467
  const { attachmentManager } = composer;
3453
3468
  if (!attachmentManager) return forward();
3454
- const sendableAttachments = attachmentManager.attachments.filter(isSendable);
3469
+ const sendableAttachments = attachmentManager.attachments.filter(isSendableAttachment);
3455
3470
  const attachments = sendableAttachments.length ? (state.draft.attachments ?? []).concat(
3456
3471
  sendableAttachments.map(localAttachmentToAttachment)
3457
3472
  ) : void 0;
@@ -5110,6 +5125,8 @@ var BasePaginator = class {
5110
5125
  this._itemIntervals = /* @__PURE__ */ new Map();
5111
5126
  /** How many claims on the active interval were made; the latest one decides it. */
5112
5127
  this._activeIntervalClaimCount = 0;
5128
+ /** Set by `setItems`, which loads a page (even an empty one) without a query. */
5129
+ this._pageSetWithoutQuery = false;
5113
5130
  this.boosts = /* @__PURE__ */ new Map();
5114
5131
  this._maxBoostSeq = 0;
5115
5132
  /** Boosted items first (higher `seq` first), then `itemOrderComparator`. */
@@ -5251,6 +5268,17 @@ var BasePaginator = class {
5251
5268
  get isInitialized() {
5252
5269
  return typeof this._lastQueryShape !== "undefined";
5253
5270
  }
5271
+ /**
5272
+ * True once a page was loaded: by a query, or by `setItems`, including an empty page (e.g. a
5273
+ * catch-all list seeded so it never runs its own query). Items that live events ingested into a
5274
+ * never-queried list are not a loaded page, although they make `items` defined: a UI deciding
5275
+ * whether to run the first query reads this, not `items === undefined`. Unlike `isInitialized`,
5276
+ * an empty `setItems` page counts, so connection recovery (which re-runs initialized lists'
5277
+ * queries) still skips such a list. Cleared by `resetState`.
5278
+ */
5279
+ get hasLoadedPage() {
5280
+ return this._pageSetWithoutQuery || this.isInitialized;
5281
+ }
5254
5282
  get isOfflineSupportEnabled() {
5255
5283
  return false;
5256
5284
  }
@@ -6709,6 +6737,7 @@ var BasePaginator = class {
6709
6737
  newState.hasMoreHead = interval.hasMoreHead;
6710
6738
  newState.hasMoreTail = interval.hasMoreTail;
6711
6739
  }
6740
+ this._pageSetWithoutQuery = true;
6712
6741
  return newState;
6713
6742
  });
6714
6743
  this.recordLoadedIntervalQueryShape();
@@ -7243,11 +7272,12 @@ var BasePaginator = class {
7243
7272
  this._executeQueryDebounced.cancel();
7244
7273
  }
7245
7274
  resetState() {
7275
+ this._lastQueryShape = void 0;
7276
+ this._pageSetWithoutQuery = false;
7246
7277
  this.state.next(this.initialState);
7247
7278
  this.setIntervals([]);
7248
7279
  this.setActiveInterval(void 0);
7249
7280
  this.clearIntervalViews();
7250
- this._lastQueryShape = void 0;
7251
7281
  }
7252
7282
  /**
7253
7283
  * Releases this paginator's hold on its item content (unlinks every member ID from the shared
@@ -8529,16 +8559,22 @@ var MessageIntervalPaginator = class extends BasePaginator {
8529
8559
  }
8530
8560
  this.messageFocusSignal.next({ signal: null });
8531
8561
  };
8562
+ /**
8563
+ * Deletes `userId`'s loaded messages (removes them on a hard delete) and marks the quotes of them
8564
+ * as deleted. Returns the messages it deleted, as they were before.
8565
+ */
8532
8566
  this.applyMessageDeletionForUser = ({
8533
8567
  userId,
8534
8568
  hardDelete = false,
8535
8569
  deletedAt
8536
8570
  }) => {
8537
8571
  const loadedMessages = this._itemIndex.values();
8572
+ const deletedMessages = [];
8538
8573
  this.batch(
8539
8574
  () => {
8540
8575
  for (const message of loadedMessages) {
8541
8576
  if (message.user?.id === userId) {
8577
+ deletedMessages.push(message);
8542
8578
  if (hardDelete) {
8543
8579
  this.removeItem({ id: message.id });
8544
8580
  } else {
@@ -8566,6 +8602,7 @@ var MessageIntervalPaginator = class extends BasePaginator {
8566
8602
  },
8567
8603
  { coalesce: true }
8568
8604
  );
8605
+ return deletedMessages;
8569
8606
  };
8570
8607
  /** Updates the quoted-message snapshot of every cached message that quotes `message`. */
8571
8608
  this.reflectQuotedMessageUpdate = (message) => {
@@ -9621,6 +9658,8 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9621
9658
  stateThrottleMs: 500,
9622
9659
  ...builtInDefaults
9623
9660
  });
9661
+ /** Whether `message` counts for {@link latestMessageAt}. */
9662
+ this.movesLastMessageAt = (message) => this.shouldAdvanceLatestMessage(message) && !this.isSkippedSystemMessage(message);
9624
9663
  /**
9625
9664
  * (Re)seeds the unread snapshot from the own read state. Runs once a first page and the rest of
9626
9665
  * its response are in (the paginator's own first-page queries, `watch()` and the channel-list
@@ -9765,10 +9804,17 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9765
9804
  * {@link latestMessage}'s `created_at` and the `last_message_at` of the latest response (see
9766
9805
  * {@link setQueriedLatestMessageAt}). Later than {@link latestMessage} when the server has newer
9767
9806
  * messages the client does not hold. The channel-list sort key. **Derived** (never stored) so it
9768
- * cannot drift from {@link latestMessage}. `null` until a query sets it or a message is ingested.
9807
+ * cannot drift from {@link latestMessage}. A system message that does not move `last_message_at`
9808
+ * (see {@link isSkippedSystemMessage}) does not count: the newest loaded message that does is
9809
+ * used instead. `null` until a query sets it or a message is ingested.
9769
9810
  */
9770
9811
  get latestMessageAt() {
9771
- return this.latestMessageAtIncluding(this.latestMessage);
9812
+ return this.latestMessageAtIncluding(this.latestMessageAtSource);
9813
+ }
9814
+ /** The newest loaded message that moves `last_message_at`, which {@link latestMessageAt} reads. */
9815
+ get latestMessageAtSource() {
9816
+ const { latestMessage } = this.aggregateState.getLatestValue();
9817
+ return this.isSkippedSystemMessage(latestMessage) ? this.recomputeLatestMessage({ counts: this.movesLastMessageAt }) : latestMessage;
9772
9818
  }
9773
9819
  /**
9774
9820
  * {@link latestMessageAt} as the server knows it (see {@link pageReachesHead}): an unsent latest
@@ -9778,7 +9824,10 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9778
9824
  const { latestMessage } = this.aggregateState.getLatestValue();
9779
9825
  const isUnsent = !!latestMessage && !this.isServerConfirmedMessage(latestMessage);
9780
9826
  return this.latestMessageAtIncluding(
9781
- isUnsent ? this.recomputeLatestMessage({ serverConfirmedOnly: true }) : latestMessage
9827
+ isUnsent || this.isSkippedSystemMessage(latestMessage) ? this.recomputeLatestMessage({
9828
+ counts: this.movesLastMessageAt,
9829
+ serverConfirmedOnly: true
9830
+ }) : latestMessage
9782
9831
  );
9783
9832
  }
9784
9833
  /** The later of `message`'s `created_at` and the queried `last_message_at`. */
@@ -9800,8 +9849,8 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9800
9849
  *
9801
9850
  * It differs from {@link anchoredHeadItem}, the newest message of the interval known to reach the
9802
9851
  * server's latest message, in two ways:
9803
- * - It skips messages that do not count. With system messages skipped, a system message can be
9804
- * `anchoredHeadItem` but never `latestMessage`.
9852
+ * - It skips messages that do not count: an `error` message can be `anchoredHeadItem` but never
9853
+ * `latestMessage`.
9805
9854
  * - It does not need that interval. A channel opened at its first unread message loads m40–m60
9806
9855
  * while the server's newest is m95: `latestMessage` is m60, `latestMessageAt` is m95's time and
9807
9856
  * `anchoredHeadItem` is `undefined`.
@@ -9822,17 +9871,24 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9822
9871
  return head ? this.getServerKnownEdges(head).head : void 0;
9823
9872
  }
9824
9873
  /**
9825
- * Whether `message` counts as the channel's latest message: not shadowed and, in the main list,
9826
- * not a thread-only reply nor (with `skip_last_msg_update_for_system_msgs`, which the server also
9827
- * applies to `last_message_at`) a system message. A reply list (`parentMessageId` set) holds only
9828
- * thread replies, so only the shadow rule applies there.
9874
+ * Whether `message` counts as the channel's latest message: not shadowed, not an `error` or
9875
+ * `ephemeral` message (only the current user sees those, e.g. a failed command or a giphy preview)
9876
+ * and, in the main list, not a thread-only reply. A reply list (`parentMessageId` set) holds only
9877
+ * thread replies, so the thread-only rule does not apply there.
9829
9878
  */
9830
9879
  shouldAdvanceLatestMessage(message) {
9831
9880
  if (message.shadowed) return false;
9881
+ if (message.type === "error" || message.type === "ephemeral") return false;
9832
9882
  if (this.parentMessageId) return true;
9833
- if (isThreadOnlyReply(message)) return false;
9834
- const skipSystemMessage = !!this.channel.serverConfig?.skip_last_msg_update_for_system_msgs && message.type === "system";
9835
- return !skipSystemMessage;
9883
+ return !isThreadOnlyReply(message);
9884
+ }
9885
+ /**
9886
+ * Whether `message` is a main-list system message that, with
9887
+ * `skip_last_msg_update_for_system_msgs`, does not move the channel's `last_message_at` on the
9888
+ * server. It is still shown as the {@link latestMessage}, but {@link latestMessageAt} skips it.
9889
+ */
9890
+ isSkippedSystemMessage(message) {
9891
+ return !!message && !this.parentMessageId && message.type === "system" && !!this.channel.serverConfig?.skip_last_msg_update_for_system_msgs;
9836
9892
  }
9837
9893
  /**
9838
9894
  * Advances {@link latestMessage} (and so {@link latestMessageAt}) to `message` when it is newer
@@ -9841,10 +9897,16 @@ var MessagePaginator = class extends MessageIntervalPaginator {
9841
9897
  * for callers that advance it without an in-interval ingest, e.g. offline pending-message replay.
9842
9898
  */
9843
9899
  trackLatestMessage(message) {
9844
- if (!this.shouldAdvanceLatestMessage(message)) return false;
9900
+ const current = this.aggregateState.getLatestValue().latestMessage;
9901
+ if (!this.shouldAdvanceLatestMessage(message)) {
9902
+ if (current?.id !== message.id) return false;
9903
+ this.aggregateState.partialNext({
9904
+ latestMessage: this.recomputeLatestMessage({ excludeId: message.id })
9905
+ });
9906
+ return true;
9907
+ }
9845
9908
  const incoming = getMessageCreatedAtTimestamp(message);
9846
9909
  if (incoming === null) return false;
9847
- const current = this.aggregateState.getLatestValue().latestMessage;
9848
9910
  if (current && current.id === message.id) {
9849
9911
  this.aggregateState.partialNext({ latestMessage: message });
9850
9912
  return true;
@@ -10038,7 +10100,10 @@ var MessagePaginator = class extends MessageIntervalPaginator {
10038
10100
  const { latestMessage } = this.aggregateState.getLatestValue();
10039
10101
  if (!latestMessage || !batch.changedIds.has(latestMessage.id)) return;
10040
10102
  const stored = this.getItem(latestMessage.id);
10041
- if (stored) this.aggregateState.partialNext({ latestMessage: stored });
10103
+ if (!stored) return;
10104
+ this.aggregateState.partialNext({
10105
+ latestMessage: this.shouldAdvanceLatestMessage(stored) ? stored : this.recomputeLatestMessage({ excludeId: stored.id })
10106
+ });
10042
10107
  }
10043
10108
  reflectUserUpdate(user) {
10044
10109
  super.reflectUserUpdate(user);
@@ -10050,17 +10115,19 @@ var MessagePaginator = class extends MessageIntervalPaginator {
10050
10115
  const removedId = params.id ?? (params.item ? this.getItemId(params.item) : void 0);
10051
10116
  const { latestMessage, queriedLatestMessageAt } = this.aggregateState.getLatestValue();
10052
10117
  const wasLatest = !!removedId && latestMessage?.id === removedId;
10118
+ const latestMessageAtSource = removedId ? this.latestMessageAtSource : null;
10119
+ const wasLatestMessageAtSource = !!removedId && latestMessageAtSource?.id === removedId;
10053
10120
  const result = super.removeItem(params);
10054
- if (wasLatest) {
10055
- const previous = this.recomputeLatestMessage();
10056
- const previousAt = getMessageCreatedAtTimestamp(previous);
10057
- const removedAt = getMessageCreatedAtTimestamp(latestMessage);
10058
- const isQueriedFromRemovedMessage = queriedLatestMessageAt !== null && removedAt !== null && queriedLatestMessageAt <= removedAt;
10059
- this.aggregateState.partialNext({
10060
- latestMessage: previous,
10061
- queriedLatestMessageAt: isQueriedFromRemovedMessage && previousAt !== null ? previousAt : queriedLatestMessageAt
10062
- });
10063
- }
10121
+ if (!wasLatest && !wasLatestMessageAtSource) return result;
10122
+ const previousAt = wasLatestMessageAtSource ? getMessageCreatedAtTimestamp(
10123
+ this.recomputeLatestMessage({ counts: this.movesLastMessageAt })
10124
+ ) : null;
10125
+ const removedAt = getMessageCreatedAtTimestamp(latestMessageAtSource);
10126
+ const isQueriedFromRemovedMessage = wasLatestMessageAtSource && queriedLatestMessageAt !== null && removedAt !== null && queriedLatestMessageAt <= removedAt;
10127
+ this.aggregateState.partialNext({
10128
+ latestMessage: wasLatest ? this.recomputeLatestMessage() : latestMessage,
10129
+ queriedLatestMessageAt: isQueriedFromRemovedMessage && previousAt !== null ? previousAt : queriedLatestMessageAt
10130
+ });
10064
10131
  return result;
10065
10132
  }
10066
10133
  truncate(params) {
@@ -10078,15 +10145,18 @@ var MessagePaginator = class extends MessageIntervalPaginator {
10078
10145
  });
10079
10146
  }
10080
10147
  /**
10081
- * The still-loaded message with the greatest `created_at` that passes
10082
- * {@link shouldAdvanceLatestMessage} (skips system / thread-only per config), from the interval
10083
- * that reaches the newest message and the {@link logicalHeadItemsSinceQueriedLatestMessageAt}.
10084
- * An interval reached by a jump is not searched, nor an out-of-order older message: neither is the
10085
- * channel's previous message. Used to recompute the tracked latest after the current one is
10086
- * removed; `serverConfirmedOnly` skips unsent messages. `null` when nothing loaded qualifies.
10087
- * It compares timestamps rather than positions, so it holds for any `itemOrder` / `requestSort`.
10148
+ * The still-loaded message with the greatest `created_at` that `counts` (by default
10149
+ * {@link shouldAdvanceLatestMessage}), from the interval that reaches the newest message and the
10150
+ * {@link logicalHeadItemsSinceQueriedLatestMessageAt}. An interval reached by a jump is not
10151
+ * searched, nor an out-of-order older message: neither is the channel's previous message. Used to
10152
+ * recompute the tracked latest after the current one is removed or stops counting;
10153
+ * `serverConfirmedOnly` skips unsent messages and `excludeId` skips that message. `null` when
10154
+ * nothing loaded qualifies. It compares timestamps rather than positions, so it holds for any
10155
+ * `itemOrder` / `requestSort`.
10088
10156
  */
10089
10157
  recomputeLatestMessage({
10158
+ counts = (message) => this.shouldAdvanceLatestMessage(message),
10159
+ excludeId,
10090
10160
  serverConfirmedOnly = false
10091
10161
  } = {}) {
10092
10162
  let latest = null;
@@ -10095,7 +10165,7 @@ var MessagePaginator = class extends MessageIntervalPaginator {
10095
10165
  ...this.anchoredHeadItems,
10096
10166
  ...this.logicalHeadItemsSinceQueriedLatestMessageAt
10097
10167
  ]) {
10098
- if (!this.shouldAdvanceLatestMessage(item)) continue;
10168
+ if (item.id === excludeId || !counts(item)) continue;
10099
10169
  if (serverConfirmedOnly && !this.isServerConfirmedMessage(item)) continue;
10100
10170
  const timestamp = getMessageCreatedAtTimestamp(item);
10101
10171
  if (timestamp === null || timestamp <= latestTimestamp) continue;
@@ -11327,12 +11397,14 @@ var createLinkPreviewsCompositionMiddleware = (composer) => ({
11327
11397
  linkPreviews
11328
11398
  );
11329
11399
  const localAttachments = (state.localMessage.attachments ?? []).concat(linkPreviews);
11330
- if (!messageAttachments.length && !localAttachments.length) return forward();
11331
11400
  const sendOptions = { ...state.sendOptions };
11332
11401
  const skip_enrich_url = !someLinkPreviewsLoading && linkPreviews.length > 0 || someLinkPreviewsDismissed;
11333
11402
  if (skip_enrich_url) {
11334
11403
  sendOptions.skip_enrich_url = true;
11335
11404
  }
11405
+ if (!messageAttachments.length && !localAttachments.length) {
11406
+ return skip_enrich_url ? next({ ...state, sendOptions }) : forward();
11407
+ }
11336
11408
  return next({
11337
11409
  ...state,
11338
11410
  message: messageAttachments.length ? {
@@ -15107,7 +15179,7 @@ var settlePendingAttachmentUploads = async ({
15107
15179
  client
15108
15180
  }) => {
15109
15181
  const unsettledIndexes = attachments.reduce((indexes, attachment, index) => {
15110
- if (isPendingUpload(attachment) || isFailedUpload(attachment)) indexes.push(index);
15182
+ if (isResolvableUpload(attachment)) indexes.push(index);
15111
15183
  return indexes;
15112
15184
  }, []);
15113
15185
  if (!unsettledIndexes.length) return { attachments };
@@ -16859,6 +16931,24 @@ var Channel = class extends ChannelApi {
16859
16931
  const paginator = this.messagePaginator;
16860
16932
  return paginator.anchoredHeadItem !== void 0 ? paginator.anchoredHeadItems : paginator.logicalHeadItems;
16861
16933
  }
16934
+ /**
16935
+ * Lowers the own unread count by the unread ones among `deletedMessages`, as they were before the
16936
+ * delete. The server lowers it for every unread message deleted, except in a soft bulk delete
16937
+ * (`user.messages.deleted`), and does not send the new count. Unread messages that are not loaded
16938
+ * cannot be counted; the next query brings the server's count.
16939
+ *
16940
+ * @internal
16941
+ */
16942
+ _lowerUnreadCountForDeletedMessages(deletedMessages) {
16943
+ const lastRead = this.lastRead();
16944
+ if (lastRead == null || this.state.unreadCount === 0) return;
16945
+ const deletedUnread = deletedMessages.filter(
16946
+ (message) => message.type !== "deleted" && message.created_at > lastRead && this._countMessageAsUnread(message)
16947
+ ).length;
16948
+ if (deletedUnread > 0) {
16949
+ this._setOwnUnreadCount(Math.max(0, this.state.unreadCount - deletedUnread));
16950
+ }
16951
+ }
16862
16952
  /**
16863
16953
  * Counts the unread messages that mention the current user, within the channel's newest messages
16864
16954
  * that are loaded (see {@link newestKnownMessages}).
@@ -17342,6 +17432,8 @@ var Channel = class extends ChannelApi {
17342
17432
  if (event.message) {
17343
17433
  this._extendEventWithOwnReactions(event);
17344
17434
  const formattedMessage = formatMessage(event.message);
17435
+ const deletedMessage = this.getClient().messageStore.get(event.message.id);
17436
+ if (deletedMessage) this._lowerUnreadCountForDeletedMessages([deletedMessage]);
17345
17437
  if (!isThreadOnlyReply(event.message)) {
17346
17438
  if (event.hard_delete) {
17347
17439
  this.messagePaginator.removeItem({ id: event.message.id });
@@ -17359,11 +17451,12 @@ var Channel = class extends ChannelApi {
17359
17451
  if (event.user) {
17360
17452
  const deletedAt = event.created_at ?? nowNs();
17361
17453
  const hardDelete = !!event.hard_delete;
17362
- this.messagePaginator.applyMessageDeletionForUser({
17454
+ const deletedMessages = this.messagePaginator.applyMessageDeletionForUser({
17363
17455
  userId: event.user.id,
17364
17456
  hardDelete,
17365
17457
  deletedAt
17366
17458
  });
17459
+ if (hardDelete) this._lowerUnreadCountForDeletedMessages(deletedMessages);
17367
17460
  this.pinnedMessagesPaginator.applyMessageDeletionForUser({
17368
17461
  userId: event.user.id,
17369
17462
  hardDelete,
@@ -17509,6 +17602,14 @@ var Channel = class extends ChannelApi {
17509
17602
  if (removedUserId === this.getClient().userId) {
17510
17603
  channelState.membership = {};
17511
17604
  }
17605
+ this._patchReadState(
17606
+ (currentReadState) => {
17607
+ if (!currentReadState[removedUserId]) return currentReadState;
17608
+ const { [removedUserId]: _removed, ...nextReadState } = currentReadState;
17609
+ return nextReadState;
17610
+ },
17611
+ { removedUserIds: [removedUserId] }
17612
+ );
17512
17613
  }
17513
17614
  break;
17514
17615
  }
@@ -18547,12 +18648,12 @@ var _MessageComposer = class _MessageComposer extends WithSubscriptions {
18547
18648
  get hasSendableData() {
18548
18649
  if (!this.isCommandSendable) return false;
18549
18650
  if (this.allowsPendingUploads) {
18550
- const hasSendableAttachment = this.attachmentManager.attachments.some(
18551
- (attachment) => isFinishedUpload(attachment) || isPendingUpload(attachment) || isFailedUpload(attachment)
18651
+ const hasAttachmentContent = this.attachmentManager.attachments.some(
18652
+ (attachment) => isSendableAttachment(attachment) || isResolvableUpload(attachment)
18552
18653
  );
18553
- return !!(!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || hasSendableAttachment || this.pollId || this.locationComposer.validLocation);
18654
+ return !!(!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || hasAttachmentContent || this.pollId || this.locationComposer.validLocation);
18554
18655
  }
18555
- return !!(!this.attachmentManager.uploadsInProgressCount && (!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || this.attachmentManager.successfulUploadsCount > 0) || this.pollId || !!this.locationComposer.validLocation);
18656
+ return !!(!this.attachmentManager.uploadsInProgressCount && (!this.textComposer.textIsEmpty || this.textComposer.activeCommandIsContent || this.attachmentManager.attachments.some(isSendableAttachment)) || this.pollId || !!this.locationComposer.validLocation);
18556
18657
  }
18557
18658
  get compositionIsEmpty() {
18558
18659
  return !this.quotedMessage && this.contentIsEmpty;
@@ -21679,14 +21780,8 @@ var ConnectionRecoveryManager = class extends WithSubscriptions {
21679
21780
  wasHealthy = isHealthy;
21680
21781
  if (previous === void 0 || !isHealthy) return;
21681
21782
  if (!lastUnhealthyAt) return;
21682
- if (!this.config.enabled) return;
21683
21783
  const syncEdgeDrivesRecovery = this.ensureSyncStatusSubscription();
21684
- if (!syncEdgeDrivesRecovery) {
21685
- runDetached(this.recoverChannelLists(), { context: "recoverChannelLists" });
21686
- runDetached(this.recoverActiveChannels(), {
21687
- context: "recoverActiveChannels"
21688
- });
21689
- }
21784
+ if (!syncEdgeDrivesRecovery) this.handleReconnect();
21690
21785
  }
21691
21786
  )
21692
21787
  );
@@ -21708,9 +21803,7 @@ var ConnectionRecoveryManager = class extends WithSubscriptions {
21708
21803
  const { offlineDb } = this.client;
21709
21804
  if (!offlineDb?.state.getLatestValue().initialized) return false;
21710
21805
  const { unsubscribe } = offlineDb.syncManager.onSyncStatusChange((status) => {
21711
- if (!status || !this.config.enabled) return;
21712
- runDetached(this.recoverChannelLists(), { context: "recoverChannelLists" });
21713
- runDetached(this.recoverActiveChannels(), { context: "recoverActiveChannels" });
21806
+ if (status) this.handleReconnect();
21714
21807
  });
21715
21808
  this.unsubscribeSyncStatus = unsubscribe;
21716
21809
  return true;
@@ -21783,6 +21876,21 @@ var ConnectionRecoveryManager = class extends WithSubscriptions {
21783
21876
  initializeConfig(config) {
21784
21877
  this.configController.initialize(config);
21785
21878
  }
21879
+ /**
21880
+ * Recovers the lists, and the active channels and threads (that pass dispatches `connection.recovered`
21881
+ * when done). With recovery disabled it skips the refresh and only dispatches the event, so an app that
21882
+ * refreshes its own data knows when to do it.
21883
+ */
21884
+ handleReconnect() {
21885
+ if (this.config.enabled) {
21886
+ runDetached(this.recoverChannelLists(), { context: "recoverChannelLists" });
21887
+ runDetached(this.recoverActiveChannels(), { context: "recoverActiveChannels" });
21888
+ return;
21889
+ }
21890
+ if (this.client.wsConnection.isHealthy) {
21891
+ this.client.dispatchEvent({ type: "connection.recovered" });
21892
+ }
21893
+ }
21786
21894
  /**
21787
21895
  * Channels a consumer is reading. Not filtered on `watchStatus`: a channel opened while offline never
21788
21896
  * reached `Watching`, and `Channel.reload()` has its own `initialized || offlineMode` guard.
@@ -25079,11 +25187,12 @@ var StreamChat = class _StreamChat extends ChatApi {
25079
25187
  this._deleteUserMessageReference = (user, hardDelete = false, deletedAt) => {
25080
25188
  for (const channel of this.channelManager.values()) {
25081
25189
  if (channel) {
25082
- channel.messagePaginator.applyMessageDeletionForUser({
25190
+ const deletedMessages = channel.messagePaginator.applyMessageDeletionForUser({
25083
25191
  userId: user.id,
25084
25192
  hardDelete,
25085
25193
  deletedAt: deletedAt ?? nowNs()
25086
25194
  });
25195
+ if (hardDelete) channel._lowerUnreadCountForDeletedMessages(deletedMessages);
25087
25196
  channel.pinnedMessagesPaginator.applyMessageDeletionForUser({
25088
25197
  userId: user.id,
25089
25198
  hardDelete,
@@ -25165,7 +25274,7 @@ var StreamChat = class _StreamChat extends ChatApi {
25165
25274
  return this.userAgent;
25166
25275
  }
25167
25276
  if (!this.cachedUserAgent) {
25168
- const version = "10.0.0-rc.32";
25277
+ const version = "10.0.0-rc.34";
25169
25278
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
25170
25279
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
25171
25280
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -25424,10 +25533,18 @@ var StreamChat = class _StreamChat extends ChatApi {
25424
25533
  * second argument, as on the generated methods; pass `undefined`.
25425
25534
  * @param requestOptions - Per-request options such as an abort `signal`. Never serialized
25426
25535
  * into the request (optional).
25427
- * @returns The application settings response.
25536
+ * @returns The application settings response. A failed request is not kept in
25537
+ * {@link appSettingsPromise}, so the next call fetches again.
25428
25538
  */
25429
25539
  async getAppSettings(_request, requestOptions) {
25430
- return await (this.appSettingsPromise = this.getApp(void 0, requestOptions));
25540
+ const promise = this.getApp(void 0, requestOptions);
25541
+ this.appSettingsPromise = promise;
25542
+ try {
25543
+ return await promise;
25544
+ } catch (error) {
25545
+ if (this.appSettingsPromise === promise) this.appSettingsPromise = void 0;
25546
+ throw error;
25547
+ }
25431
25548
  }
25432
25549
  /**
25433
25550
  * Creates a guest user.