stream-chat 9.54.0 → 9.54.2

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.
@@ -1240,7 +1240,11 @@ var messagePaginationLinear = ({
1240
1240
  newPagination.hasNext = hasNext;
1241
1241
  return newPagination;
1242
1242
  };
1243
+ var hasMessagePaginationCursor = (options) => !!(options?.id_lt || options?.id_lte || options?.id_gt || options?.id_gte || options?.id_around || options?.created_at_before || options?.created_at_before_or_equal || options?.created_at_after || options?.created_at_after_or_equal || options?.created_at_around || options?.offset);
1243
1244
  var messageSetPagination = (params) => {
1245
+ if (params.requestedPageSize === 0 && params.parentSet.messages.length > 0) {
1246
+ return params.parentSet.pagination;
1247
+ }
1244
1248
  if (params.parentSet.messages.length + (params.returnedPage.length - params.filteredReturnedPage.length) < params.returnedPage.length) {
1245
1249
  params.logger?.(
1246
1250
  "error",
@@ -1416,6 +1420,7 @@ var aOverlapsB = (a, b) => {
1416
1420
  return oldestMessageA < oldestMessageB && oldestMessageB < newestMessageA && newestMessageA < newestMessageB;
1417
1421
  };
1418
1422
  var messageSetsOverlapByTimestamp = (a, b) => aContainsOrEqualsB(a, b) || aContainsOrEqualsB(b, a) || aOverlapsB(a, b) || aOverlapsB(b, a);
1423
+ var isLocalOnlyMessage = (message) => message.status === "sending" || message.status === "failed" || message.type === "error" || message.type === "ephemeral";
1419
1424
  var ChannelState = class {
1420
1425
  constructor(channel) {
1421
1426
  /**
@@ -2075,6 +2080,22 @@ var ChannelState = class {
2075
2080
  currentMessages.isCurrent = false;
2076
2081
  this.messageSets[index].isCurrent = true;
2077
2082
  }
2083
+ /**
2084
+ * Empties the latest message set if the newest page is newer than it and shares no messages
2085
+ * with it. Merging them would hide the messages in between from pagination.
2086
+ * Skipped while the set holds local-only messages, so they are not lost.
2087
+ */
2088
+ _dropLatestMessagesDisjointFrom(newestPage) {
2089
+ const latestSet = this.messageSets.find((s) => s.isLatest);
2090
+ const newestLoaded = latestSet?.messages.slice(-1)[0];
2091
+ const oldestReturned = newestPage.find((m) => !m.parent_id || m.show_in_channel);
2092
+ if (!latestSet || !newestLoaded || !oldestReturned?.created_at) return;
2093
+ if (new Date(oldestReturned.created_at).getTime() <= newestLoaded.created_at.getTime() || this.areMessageSetsOverlap(latestSet.messages, newestPage) || latestSet.messages.some(isLocalOnlyMessage)) {
2094
+ return;
2095
+ }
2096
+ latestSet.messages = [];
2097
+ latestSet.pagination = { ...DEFAULT_MESSAGE_SET_PAGINATION };
2098
+ }
2078
2099
  areMessageSetsOverlap(messages1, messages2) {
2079
2100
  return messages1.some((m1) => messages2.find((m2) => m1.id === m2.id));
2080
2101
  }
@@ -4057,13 +4078,14 @@ var localAttachmentToAttachment = (localAttachment) => {
4057
4078
  const { localMetadata, ...attachment } = localAttachment;
4058
4079
  return attachment;
4059
4080
  };
4081
+ var isSendable = (attachment) => isFinishedUpload(attachment) || !isLocalUploadAttachment(attachment);
4060
4082
  var composeWithPendingUploads = ({
4061
4083
  composer,
4062
4084
  state
4063
4085
  }) => {
4064
4086
  const composerIsKeptAsDraft = !!composer.pollId;
4065
4087
  const relevantAttachments = composer.attachmentManager.attachments.filter(
4066
- (attachment) => isFinishedUpload(attachment) || !composerIsKeptAsDraft && isPendingUpload(attachment)
4088
+ (attachment) => isSendable(attachment) || !composerIsKeptAsDraft && isPendingUpload(attachment)
4067
4089
  );
4068
4090
  const localAttachments = (state.localMessage.attachments ?? []).concat(
4069
4091
  relevantAttachments.map(
@@ -4071,7 +4093,7 @@ var composeWithPendingUploads = ({
4071
4093
  )
4072
4094
  );
4073
4095
  const messageAttachments = (state.message.attachments ?? []).concat(
4074
- relevantAttachments.filter(isFinishedUpload).map(localAttachmentToAttachment)
4096
+ relevantAttachments.filter(isSendable).map(localAttachmentToAttachment)
4075
4097
  );
4076
4098
  if (!localAttachments.length && !messageAttachments.length) return state;
4077
4099
  return {
@@ -4126,7 +4148,7 @@ var createAttachmentsCompositionMiddleware = (composer) => ({
4126
4148
  return discard();
4127
4149
  }
4128
4150
  const attachments = (state.message.attachments ?? []).concat(
4129
- attachmentManager.successfulUploads.map(localAttachmentToAttachment)
4151
+ attachmentManager.attachments.filter(isSendable).map(localAttachmentToAttachment)
4130
4152
  );
4131
4153
  if (!attachments.length) return forward();
4132
4154
  return next({
@@ -4153,9 +4175,9 @@ var createDraftAttachmentsCompositionMiddleware = (composer) => ({
4153
4175
  }) => {
4154
4176
  const { attachmentManager } = composer;
4155
4177
  if (!attachmentManager) return forward();
4156
- const successfulUploads = attachmentManager.successfulUploads;
4157
- const attachments = successfulUploads.length ? (state.draft.attachments ?? []).concat(
4158
- successfulUploads.map(localAttachmentToAttachment)
4178
+ const sendableAttachments = attachmentManager.attachments.filter(isSendable);
4179
+ const attachments = sendableAttachments.length ? (state.draft.attachments ?? []).concat(
4180
+ sendableAttachments.map(localAttachmentToAttachment)
4159
4181
  ) : void 0;
4160
4182
  return next({
4161
4183
  ...state,
@@ -8280,10 +8302,13 @@ var Thread = class extends WithSubscriptions {
8280
8302
  }));
8281
8303
  }
8282
8304
  };
8283
- const channel = client.channel(threadData.channel.type, threadData.channel.id, {
8284
- // @ts-expect-error name is a "custom" property
8285
- name: threadData.channel.name
8286
- });
8305
+ const channelResponse = threadData.channel;
8306
+ const channelData = { name: channelResponse.name };
8307
+ const channel = client.channel(
8308
+ threadData.channel.type,
8309
+ threadData.channel.id,
8310
+ channelData
8311
+ );
8287
8312
  channel._hydrateMembers({
8288
8313
  members: threadData.channel.members ?? [],
8289
8314
  overrideCurrentState: false
@@ -10790,7 +10815,8 @@ var Channel = class {
10790
10815
  }
10791
10816
  const { messageSet, filteredMessageIds } = this._initializeState(
10792
10817
  state,
10793
- messageSetToAddToIfDoesNotExist
10818
+ messageSetToAddToIfDoesNotExist,
10819
+ !hasMessagePaginationCursor(options?.messages)
10794
10820
  );
10795
10821
  messageSet.pagination = {
10796
10822
  ...messageSet.pagination,
@@ -11408,7 +11434,7 @@ var Channel = class {
11408
11434
  );
11409
11435
  }
11410
11436
  }
11411
- _initializeState(state, messageSetToAddToIfDoesNotExist = "latest") {
11437
+ _initializeState(state, messageSetToAddToIfDoesNotExist = "latest", isNewestPage = true) {
11412
11438
  const { state: clientState, user, userID } = this.getClient();
11413
11439
  if (state.members) {
11414
11440
  this._hydrateMembers({ members: state.members });
@@ -11423,6 +11449,9 @@ var Channel = class {
11423
11449
  if (!this.state.messages) {
11424
11450
  this.state.initMessages();
11425
11451
  }
11452
+ if (messageSetToAddToIfDoesNotExist === "latest" && isNewestPage) {
11453
+ this.state._dropLatestMessagesDisjointFrom(messages);
11454
+ }
11426
11455
  const { messageSet, filteredMessageIds } = this.state.addMessagesSorted(
11427
11456
  messages,
11428
11457
  false,
@@ -11683,6 +11712,10 @@ var StableWSConnection = class {
11683
11712
  if (data.type === "health.check") {
11684
11713
  this.scheduleNextPing();
11685
11714
  }
11715
+ if (data?.type === "connection.error" && data?.error?.code === chatCodes.TOKEN_EXPIRED) {
11716
+ this._log("onmessage() - server reported that the token expired", { wsID });
11717
+ this.tokenExpiredByServer = true;
11718
+ }
11686
11719
  this.client.dispatchEvent(data);
11687
11720
  this.scheduleConnectionCheck();
11688
11721
  };
@@ -11706,7 +11739,7 @@ var StableWSConnection = class {
11706
11739
  this.isConnecting = false;
11707
11740
  this.rejectPromise?.(this._errorFromWSEvent(event));
11708
11741
  this._log(`onclose() - WS connection closed. Calling reconnect ...`, { event });
11709
- this._reconnect();
11742
+ this._reconnectAfterFailure();
11710
11743
  }
11711
11744
  };
11712
11745
  this.onerror = (wsID, event) => {
@@ -11717,7 +11750,7 @@ var StableWSConnection = class {
11717
11750
  this.isConnecting = false;
11718
11751
  this.rejectPromise?.(this._errorFromWSEvent(event));
11719
11752
  this._log(`onerror() - WS connection resulted into error`, { event });
11720
- this._reconnect();
11753
+ this._reconnectAfterFailure();
11721
11754
  };
11722
11755
  /**
11723
11756
  * _setHealth - Sets the connection to healthy or unhealthy.
@@ -11770,6 +11803,7 @@ var StableWSConnection = class {
11770
11803
  */
11771
11804
  this._setupConnectionPromise = () => {
11772
11805
  this.isResolved = false;
11806
+ this.tokenExpiredByServer = false;
11773
11807
  this.connectionOpen = new Promise((resolve, reject) => {
11774
11808
  this.resolvePromise = resolve;
11775
11809
  this.rejectPromise = reject;
@@ -11817,6 +11851,7 @@ var StableWSConnection = class {
11817
11851
  this.isHealthy = false;
11818
11852
  this.wsID = 1;
11819
11853
  this.lastEvent = null;
11854
+ this.tokenExpiredByServer = false;
11820
11855
  this.pingInterval = 25 * 1e3;
11821
11856
  this.connectionCheckTimeout = this.pingInterval + 10 * 1e3;
11822
11857
  addConnectionEventListeners(this.onlineStatusChanged);
@@ -11915,6 +11950,7 @@ var StableWSConnection = class {
11915
11950
  this.wsID += 1;
11916
11951
  this.isConnecting = false;
11917
11952
  this.isDisconnected = true;
11953
+ this.tokenExpiredByServer = false;
11918
11954
  if (this.healthCheckTimeoutRef) {
11919
11955
  clearInterval(this.healthCheckTimeoutRef);
11920
11956
  }
@@ -12047,6 +12083,10 @@ var StableWSConnection = class {
12047
12083
  this._destroyCurrentWSConnection();
12048
12084
  if (options.refreshToken) {
12049
12085
  await this.client.tokenManager.loadToken();
12086
+ if (this.isConnecting || this.isHealthy) {
12087
+ this._log("_reconnect() - Abort (4) since already connecting or healthy");
12088
+ return;
12089
+ }
12050
12090
  }
12051
12091
  try {
12052
12092
  await this._connect();
@@ -12070,6 +12110,21 @@ var StableWSConnection = class {
12070
12110
  }
12071
12111
  this._log("_reconnect() - == END ==");
12072
12112
  }
12113
+ /**
12114
+ * _reconnectAfterFailure - Reconnects after the socket closed or failed. If the server
12115
+ * reported that the token expired, the token is refreshed before reconnecting.
12116
+ * Static tokens cannot be refreshed and reconnect as before.
12117
+ */
12118
+ _reconnectAfterFailure() {
12119
+ if (this.tokenExpiredByServer && !this.client.tokenManager.isStatic()) {
12120
+ this._log(
12121
+ "_reconnectAfterFailure() - token expired, so going to reload token and reconnect"
12122
+ );
12123
+ this._reconnect({ refreshToken: true });
12124
+ return;
12125
+ }
12126
+ this._reconnect();
12127
+ }
12073
12128
  /**
12074
12129
  * _destroyCurrentWSConnection - Removes the current WS connection
12075
12130
  *
@@ -13326,9 +13381,14 @@ function applyOwnVoteDelta(state, { add = [], remove = [] }) {
13326
13381
  }
13327
13382
  voteCount = Math.max(voteCount - 1, 0);
13328
13383
  if (latestVotesByOption?.[optionId]) {
13329
- latestVotesByOption[optionId] = latestVotesByOption[optionId].filter(
13384
+ const latestVotes = latestVotesByOption[optionId].filter(
13330
13385
  (latestVote) => latestVote.id !== vote.id
13331
13386
  );
13387
+ if (latestVotes.length) {
13388
+ latestVotesByOption[optionId] = latestVotes;
13389
+ } else {
13390
+ delete latestVotesByOption[optionId];
13391
+ }
13332
13392
  }
13333
13393
  }
13334
13394
  for (const vote of add) {
@@ -13432,7 +13492,15 @@ var Poll = class {
13432
13492
  if (!isPollUpdatedEvent(event)) return;
13433
13493
  const { id, ...pollData } = extractPollData(event.poll);
13434
13494
  if (pollData.is_closed) this.closeConfirmed = true;
13435
- this.state.partialNext({ ...pollData, lastActivityAt: new Date(event.created_at) });
13495
+ this.state.partialNext({
13496
+ ...pollData,
13497
+ // Server-owned translations, which `extractPollData` (an update request) leaves out. Copied
13498
+ // even when absent: the event carries the whole poll, and a change made under channel-only
13499
+ // translation drops the stale ones.
13500
+ description_i18n: event.poll.description_i18n,
13501
+ lastActivityAt: new Date(event.created_at),
13502
+ name_i18n: event.poll.name_i18n
13503
+ });
13436
13504
  this.upsertOfflineDb();
13437
13505
  };
13438
13506
  this.handlePollClosed = (event) => {
@@ -15425,7 +15493,7 @@ var StreamChat = class _StreamChat {
15425
15493
  return this.userAgent;
15426
15494
  }
15427
15495
  if (!this.cachedUserAgent) {
15428
- const version = "9.54.0";
15496
+ const version = "9.54.2";
15429
15497
  const { name: sdkName, version: sdkVersion } = this.sdkIdentifier ?? {};
15430
15498
  const { name: appName, version: appVersion } = this.appIdentifier ?? {};
15431
15499
  const { os, model: deviceModel } = this.deviceIdentifier ?? {};
@@ -16355,7 +16423,7 @@ var StreamChat = class _StreamChat {
16355
16423
  ...updatedMessagesSet.pagination,
16356
16424
  ...messageSetPagination({
16357
16425
  parentSet: updatedMessagesSet,
16358
- requestedPageSize: queryChannelsOptions?.message_limit || DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE,
16426
+ requestedPageSize: queryChannelsOptions?.message_limit ?? DEFAULT_QUERY_CHANNELS_MESSAGE_LIST_PAGE_SIZE,
16359
16427
  returnedPage: channelState.messages,
16360
16428
  filteredReturnedPage: channelState.messages.filter(
16361
16429
  (m) => !filteredMessageIds.includes(m.id)
@@ -17014,7 +17082,7 @@ var StreamChat = class _StreamChat {
17014
17082
  * @param {string} messageId
17015
17083
  * @param {string} language
17016
17084
  *
17017
- * @return {MessageResponse} Response that includes the message
17085
+ * @return {APIResponse & { message: MessageResponse }} Response that includes the translated message
17018
17086
  */
17019
17087
  async translateMessage(messageId, language) {
17020
17088
  return await this.post(