@devanachat/sdk 0.11.0 → 0.13.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +15 -7
  3. package/build/index.cjs.js +436 -144
  4. package/build/index.cjs.js.map +1 -1
  5. package/build/index.mjs +436 -145
  6. package/build/index.mjs.map +1 -1
  7. package/build/index.umd.js +1 -1
  8. package/build/index.umd.js.map +1 -1
  9. package/build/types/AbstractChatClient.d.ts +18 -3
  10. package/build/types/Permissions.d.ts +5 -1
  11. package/build/types/WebSocketChatClient.d.ts +29 -2
  12. package/build/types/index.d.ts +2 -2
  13. package/build/types/protocol/index.d.ts +15 -3
  14. package/build/types/protocol/schemes/Message.d.ts +4 -0
  15. package/build/types/protocol/schemes/MessageEmbed.d.ts +83 -0
  16. package/build/types/protocol/schemes/commands/AckInteraction.d.ts +10 -0
  17. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +9 -0
  18. package/build/types/protocol/schemes/commands/GetGifCategories.d.ts +3 -0
  19. package/build/types/protocol/schemes/commands/GetMessages.d.ts +1 -0
  20. package/build/types/protocol/schemes/commands/Interact.d.ts +5 -0
  21. package/build/types/protocol/schemes/commands/SearchGifs.d.ts +5 -0
  22. package/build/types/protocol/schemes/commands/UpdateMessage.d.ts +8 -0
  23. package/build/types/protocol/schemes/events/Bye.d.ts +1 -0
  24. package/build/types/protocol/schemes/events/Error.d.ts +1 -0
  25. package/build/types/protocol/schemes/events/FoundGifs.d.ts +14 -0
  26. package/build/types/protocol/schemes/events/GifCategories.d.ts +8 -0
  27. package/build/types/protocol/schemes/events/Interacted.d.ts +4 -0
  28. package/build/types/protocol/schemes/events/InteractionResolved.d.ts +7 -0
  29. package/build/types/protocol/schemes/events/MessageUpdated.d.ts +6 -0
  30. package/build/types/protocol/schemes/events/Messages.d.ts +6 -2
  31. package/build/types/protocol/schemes/events/NewInteraction.d.ts +10 -0
  32. package/build/types/protocol/schemes/events/NewMessage.d.ts +3 -0
  33. package/build/types/state-tracker/RoomMessagesHistory.d.ts +7 -2
  34. package/build/types/state-tracker/RoomsManager.d.ts +12 -1
  35. package/build/types/state-tracker/StateSnapshot.d.ts +5 -1
  36. package/build/types/state-tracker/TopicHistoryWindow.d.ts +29 -2
  37. package/build/types/state-tracker/functions.d.ts +8 -1
  38. package/package.json +1 -1
@@ -46,6 +46,7 @@ __webpack_require__.d(__webpack_exports__, {
46
46
  IndexedCollection: () => (/* reexport */ IndexedCollection),
47
47
  IndexedObjectCollection: () => (/* reexport */ IndexedObjectCollection),
48
48
  Layer: () => (/* reexport */ Layer),
49
+ MessageEmbedFlag: () => (/* reexport */ MessageEmbedFlag),
49
50
  NO_LIMIT: () => (/* reexport */ NO_LIMIT),
50
51
  ObservableIndexedCollection: () => (/* reexport */ ObservableIndexedCollection),
51
52
  ObservableIndexedObjectCollection: () => (/* reexport */ ObservableIndexedObjectCollection),
@@ -450,8 +451,116 @@ class PromiseRegistry {
450
451
  this.promises.deleteAll();
451
452
  }
452
453
  }
454
+ ;// ./src/protocol/schemes/PmParticipant.ts
455
+ let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
456
+ PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
457
+ return PmParticipantFlag;
458
+ }({});
459
+ ;// ./src/state-tracker/functions.ts
460
+
461
+
462
+ /**
463
+ * @return New objects of the other roles whose priority has to move; the given roles are left intact.
464
+ */
465
+ function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
466
+ // If the priority has changed, adjust the rest of roles
467
+ const increased = updatedRole.priority - oldRole.priority > 0;
468
+ const decreased = !increased;
469
+ const changedRoles = [];
470
+ allRoles.forEach(role => {
471
+ if (role.id === updatedRole.id) {
472
+ // Skip the updated role
473
+ return;
474
+ }
475
+ if (increased && oldRole.priority <= role.priority) {
476
+ changedRoles.push({
477
+ ...role,
478
+ priority: role.priority - 1
479
+ });
480
+ }
481
+ if (decreased && updatedRole.priority <= role.priority) {
482
+ changedRoles.push({
483
+ ...role,
484
+ priority: role.priority + 1
485
+ });
486
+ }
487
+ });
488
+ return changedRoles;
489
+ }
490
+ function extractUserFromMember(member) {
491
+ return member.user ?? member.spaceMember?.user;
492
+ }
493
+
494
+ /**
495
+ * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
496
+ */
497
+ function isGroupPm(room) {
498
+ return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
499
+ }
500
+
501
+ /**
502
+ * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
503
+ * `meId`. Empty for notes and for rooms of spaces.
504
+ */
505
+ function getPmPeers(room, meId) {
506
+ return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
507
+ }
508
+ function getActivePmParticipants(room) {
509
+ return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
510
+ }
511
+ function isSameUser(a, b) {
512
+ const keys = Object.keys(a);
513
+ if (keys.length !== Object.keys(b).length) {
514
+ return false;
515
+ }
516
+ return keys.every(key => {
517
+ const valueA = a[key];
518
+ const valueB = b[key];
519
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
520
+ return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
521
+ }
522
+ return valueA === valueB;
523
+ });
524
+ }
525
+
526
+ /**
527
+ * The counter arrives as the global source of truth - only it is overwritten, and a reaction nobody holds any more
528
+ * (count 0) leaves the message.
529
+ * @return Null when the reactions stay as they are.
530
+ */
531
+ function applyReactionCounter(reactions, counter) {
532
+ const index = reactions.findIndex(reaction => reaction.type === counter.type && reaction.value === counter.value);
533
+ if (index === -1 && !counter.count) {
534
+ return null;
535
+ }
536
+ const next = [...reactions];
537
+ if (index === -1) {
538
+ next.push(counter);
539
+ } else if (counter.count) {
540
+ next[index] = counter; // In place - a pill must not jump around as its counter moves
541
+ } else {
542
+ next.splice(index, 1);
543
+ }
544
+ return next;
545
+ }
546
+ function applyToggledReaction(own, toggled) {
547
+ const {
548
+ type,
549
+ value,
550
+ isAdded
551
+ } = toggled;
552
+ const next = own.filter(reaction => reaction.type !== type || reaction.value !== value);
553
+ if (isAdded) {
554
+ next.push({
555
+ type,
556
+ value
557
+ });
558
+ }
559
+ return next;
560
+ }
453
561
  ;// ./src/state-tracker/TopicHistoryWindow.ts
454
562
 
563
+
455
564
  let WindowState = /*#__PURE__*/function (WindowState) {
456
565
  /**
457
566
  * The latest messages (those received live) are available in the history window, history has not been fetched.
@@ -829,6 +938,8 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
829
938
  this.internalState.traverseLock = false;
830
939
  this.internalState.includeMyReactions = !preview;
831
940
  this.internalState.myReactions = {};
941
+ this.internalState.includeRepliedMessages = true;
942
+ this.internalState.repliedMessages = new Map();
832
943
  this.internalState.liveLimit = 50;
833
944
  }
834
945
  createMirror() {
@@ -868,6 +979,32 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
868
979
  this.internalState.includeMyReactions = value;
869
980
  }
870
981
 
982
+ /**
983
+ * Whether the history is fetched together with the messages its messages reply to.
984
+ * Turn it off only where replies are never shown with what they reply to.
985
+ */
986
+ get includeRepliedMessages() {
987
+ return this.internalState.includeRepliedMessages;
988
+ }
989
+ set includeRepliedMessages(value) {
990
+ this.internalState.includeRepliedMessages = value;
991
+ }
992
+
993
+ /**
994
+ * The message the given one replies to: null when it replies to nothing or the replied message is gone,
995
+ * undefined when the window does not know it (replied messages are not fetched).
996
+ */
997
+ getRepliedMessage(message) {
998
+ if (!message.replyTo) {
999
+ return null;
1000
+ }
1001
+ const replied = this.get(message.replyTo) ?? this.internalState.repliedMessages.get(message.replyTo);
1002
+ if (replied) {
1003
+ return replied;
1004
+ }
1005
+ return this.internalState.includeRepliedMessages ? null : undefined;
1006
+ }
1007
+
871
1008
  /**
872
1009
  * Maximum number of items a window that has not been fetched yet (LIVE state) collects from the incoming
873
1010
  * messages. Null for the same as {@link limit}. It keeps the windows of topics nobody looks at small;
@@ -932,14 +1069,21 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
932
1069
  const continuousFrom = Math.max(0, ...this.internalState.gaps.map(id => items.findIndex(item => item.id === id)));
933
1070
  const messages = items.slice(Math.max(continuousFrom, items.length - Math.max(limit, this.fetchLimit)));
934
1071
  const myReactions = {};
1072
+ const exportedIds = new Set(messages.map(message => message.id));
1073
+ const repliedMessages = new Map();
935
1074
  for (const message of messages) {
936
1075
  if (this.internalState.myReactions[message.id]) {
937
1076
  myReactions[message.id] = this.internalState.myReactions[message.id];
938
1077
  }
1078
+ const replied = this.getRepliedMessage(message);
1079
+ if (replied && !exportedIds.has(replied.id)) {
1080
+ repliedMessages.set(replied.id, replied);
1081
+ }
939
1082
  }
940
1083
  return {
941
1084
  messages,
942
- myReactions
1085
+ myReactions,
1086
+ repliedMessages: [...repliedMessages.values()]
943
1087
  };
944
1088
  }
945
1089
 
@@ -948,12 +1092,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
948
1092
  * them.
949
1093
  * @internal
950
1094
  */
951
- _restoreLatest(messages, myReactions) {
1095
+ _restoreLatest(messages, myReactions, repliedMessages) {
952
1096
  const originalState = this.state;
953
1097
  this.replaceItems(messages);
954
1098
  this.internalState.myReactions = {
955
1099
  ...myReactions
956
1100
  };
1101
+ this.storeRepliedMessages(messages, repliedMessages);
957
1102
  this.internalState.current = WindowState.LATEST;
958
1103
  this.emitChangeWithDiff(true, originalState);
959
1104
  }
@@ -1004,12 +1149,14 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1004
1149
  },
1005
1150
  limit: this.internalState.fetchLimit,
1006
1151
  includeMyReactions: this.internalState.includeMyReactions,
1152
+ includeRepliedMessages: this.internalState.includeRepliedMessages,
1007
1153
  ...criteria
1008
1154
  });
1009
1155
  if (result.error) {
1010
1156
  throw new Error(`Cannot fetch messages: ${result.error.message}`);
1011
1157
  }
1012
- this.storeMyReactions(result.data.messages, result.data.myReactions);
1158
+ this.storeMyReactions(result.data.messages, result.data.myReactions ?? []);
1159
+ this.storeRepliedMessages(result.data.messages, result.data.repliedMessages ?? []);
1013
1160
  return result.data.messages;
1014
1161
  }
1015
1162
 
@@ -1025,15 +1172,63 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1025
1172
  ...this.internalState.myReactions
1026
1173
  };
1027
1174
  for (const message of messages) {
1028
- const own = myReactions?.[message.id];
1029
- if (own?.length) {
1030
- next[message.id] = own;
1031
- } else {
1032
- delete next[message.id];
1175
+ delete next[message.id];
1176
+ }
1177
+ for (const own of myReactions) {
1178
+ if (own.reactions.length) {
1179
+ next[own.messageId] = own.reactions;
1033
1180
  }
1034
1181
  }
1035
1182
  this.internalState.myReactions = next;
1036
1183
  }
1184
+
1185
+ /**
1186
+ * The response is the truth for its replies: an original it leaves out is gone. The originals the page holds
1187
+ * itself are kept too, as the window may drop them while their replies stay.
1188
+ */
1189
+ storeRepliedMessages(incoming, repliedMessages) {
1190
+ if (!this.internalState.includeRepliedMessages) {
1191
+ return;
1192
+ }
1193
+ const fromResponse = new Map();
1194
+ for (const message of [...incoming, ...repliedMessages]) {
1195
+ fromResponse.set(message.id, message);
1196
+ }
1197
+ const stored = this.internalState.repliedMessages;
1198
+ const kept = new Map();
1199
+ for (const message of incoming) {
1200
+ const replied = message.replyTo ? fromResponse.get(message.replyTo) : undefined;
1201
+ if (replied) {
1202
+ kept.set(replied.id, replied);
1203
+ }
1204
+ }
1205
+ for (const message of this.items) {
1206
+ if (!message.replyTo || fromResponse.has(message.id) || kept.has(message.replyTo)) {
1207
+ continue;
1208
+ }
1209
+ const replied = stored.get(message.replyTo) ?? this.get(message.replyTo);
1210
+ if (replied) {
1211
+ kept.set(replied.id, replied);
1212
+ }
1213
+ }
1214
+ this.internalState.repliedMessages = kept;
1215
+ }
1216
+ emitChange(setItems) {
1217
+ if (setItems.length) {
1218
+ this.eventTarget.emit('change', {
1219
+ setItems
1220
+ });
1221
+ }
1222
+ }
1223
+ repliesTo(repliedIds) {
1224
+ const replyIds = [];
1225
+ for (const message of this.items) {
1226
+ if (message.replyTo && repliedIds.has(message.replyTo)) {
1227
+ replyIds.push(message.id);
1228
+ }
1229
+ }
1230
+ return replyIds;
1231
+ }
1037
1232
  async getTopic() {
1038
1233
  if (this.preview) {
1039
1234
  // The tracker holds the topics of the joined rooms only
@@ -1065,7 +1260,15 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1065
1260
  return;
1066
1261
  }
1067
1262
  const limit = this.state === WindowState.LIVE && !this.internalState.traverseLock ? this.internalState.liveLimit ?? this.limit : this.limit;
1263
+ if (ev.repliedMessage && this.internalState.includeRepliedMessages) {
1264
+ this.internalState.repliedMessages.set(ev.repliedMessage.id, ev.repliedMessage);
1265
+ }
1068
1266
  const deletedItems = this.addItems([ev.message], 'tail', limit);
1267
+
1268
+ // Pruned only once the store outgrows the window, not on every message that pushes one out
1269
+ if (deletedItems.length && this.internalState.repliedMessages.size > this.length) {
1270
+ this.storeRepliedMessages([], []);
1271
+ }
1069
1272
  this.eventTarget.emit('change', deletedItems.length ? {
1070
1273
  setItems: [ev.message.id],
1071
1274
  deletedItems
@@ -1082,25 +1285,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1082
1285
  */
1083
1286
  _handleReactionUpdated(ev) {
1084
1287
  const message = this.get(ev.messageId);
1085
- if (!message) {
1086
- return;
1087
- }
1088
- const index = message.reactions.findIndex(reaction => reaction.type === ev.reaction.type && reaction.value === ev.reaction.value);
1089
- if (index === -1 && !ev.reaction.count) {
1090
- return;
1091
- }
1092
- const reactions = [...message.reactions];
1093
- if (index === -1) {
1094
- reactions.push(ev.reaction);
1095
- } else if (ev.reaction.count) {
1096
- reactions[index] = ev.reaction; // In place - a pill must not jump around as its counter moves
1097
- } else {
1098
- reactions.splice(index, 1);
1288
+ const reactions = message ? applyReactionCounter(message.reactions, ev.reaction) : null;
1289
+ if (reactions) {
1290
+ this.set({
1291
+ ...message,
1292
+ reactions
1293
+ });
1099
1294
  }
1100
- this.set({
1101
- ...message,
1102
- reactions
1103
- });
1104
1295
  }
1105
1296
 
1106
1297
  /**
@@ -1111,18 +1302,7 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1111
1302
  if (!this.has(ev.messageId)) {
1112
1303
  return;
1113
1304
  }
1114
- const {
1115
- type,
1116
- value,
1117
- isAdded
1118
- } = ev.reaction;
1119
- const own = (this.internalState.myReactions[ev.messageId] ?? []).filter(reaction => reaction.type !== type || reaction.value !== value);
1120
- if (isAdded) {
1121
- own.push({
1122
- type,
1123
- value
1124
- });
1125
- }
1305
+ const own = applyToggledReaction(this.internalState.myReactions[ev.messageId] ?? [], ev.reaction);
1126
1306
 
1127
1307
  // Not `{[ev.messageId]: _, ...rest}` - Babel's loose object rest drops the key when the binding is unused (babel/babel#18196)
1128
1308
  const myReactions = {
@@ -1138,13 +1318,39 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1138
1318
  });
1139
1319
  }
1140
1320
 
1321
+ /**
1322
+ * Replaces a loaded message, also where it is kept as a replied one.
1323
+ * For internal use.
1324
+ * @internal
1325
+ */
1326
+ _handleMessageUpdated(ev) {
1327
+ const {
1328
+ message
1329
+ } = ev;
1330
+ const loaded = this.has(message.id);
1331
+ const kept = this.internalState.repliedMessages.has(message.id);
1332
+ if (loaded) {
1333
+ this.set(message);
1334
+ }
1335
+ if (kept) {
1336
+ this.internalState.repliedMessages.set(message.id, message);
1337
+ }
1338
+ if (loaded || kept) {
1339
+ this.emitChange(this.repliesTo(new Set([message.id])));
1340
+ }
1341
+ }
1342
+
1141
1343
  /**
1142
1344
  * For internal use.
1143
1345
  * @internal
1144
1346
  */
1145
1347
  async _handleMessagesRedacted(ev) {
1146
1348
  const refTopicIds = this.items.filter(msg => msg.topicRef && ev.ids.includes(msg.id)).map(msg => msg.topicRef);
1349
+ const redactedOriginals = new Set(ev.ids.filter(id => this.internalState.repliedMessages.delete(id) || this.has(id)));
1147
1350
  this.delete(...ev.ids);
1351
+ if (redactedOriginals.size) {
1352
+ this.emitChange(this.repliesTo(redactedOriginals));
1353
+ }
1148
1354
  if (this.length === 0) {
1149
1355
  await this.resetToLatest();
1150
1356
  }
@@ -1268,9 +1474,9 @@ class RoomMessagesHistory {
1268
1474
  * For internal use.
1269
1475
  * @internal
1270
1476
  */
1271
- _restoreWindow(topic, messages, myReactions) {
1477
+ _restoreWindow(topic, messages, myReactions, repliedMessages) {
1272
1478
  this.createHistoryWindowForTopic(topic);
1273
- this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions);
1479
+ this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions, repliedMessages);
1274
1480
  }
1275
1481
 
1276
1482
  /**
@@ -1320,6 +1526,14 @@ class RoomMessagesHistory {
1320
1526
  void this.historyWindows.get(ev.location.topicId)?._handleMessagesRedacted(ev);
1321
1527
  }
1322
1528
 
1529
+ /**
1530
+ * For internal use.
1531
+ * @internal
1532
+ */
1533
+ _handleMessageUpdated(ev) {
1534
+ this.historyWindows.get(ev.message.location.topicId)?._handleMessageUpdated(ev);
1535
+ }
1536
+
1323
1537
  /**
1324
1538
  * For internal use.
1325
1539
  * @internal
@@ -1391,6 +1605,7 @@ class MessagesManager {
1391
1605
  this.tracker.client.on('NewTopic', ev => this.roomHistories.get(ev.roomId)?._handleNewTopic(ev));
1392
1606
  this.tracker.client.on('TopicDeleted', ev => this.roomHistories.get(ev.location.roomId)?._handleTopicDeleted(ev));
1393
1607
  this.tracker.client.on('NewMessage', ev => this.roomHistories.get(ev.message.location.roomId)?._handleNewMessage(ev));
1608
+ this.tracker.client.on('MessageUpdated', ev => this.roomHistories.get(ev.message.location.roomId)?._handleMessageUpdated(ev));
1394
1609
  this.tracker.client.on('MessagesRedacted', ev => this.roomHistories.get(ev.location.roomId)?._handleMessagesRedacted(ev));
1395
1610
  this.tracker.client.on('ReactionUpdated', ev => this.forEachRoomHistory(history => history._handleReactionUpdated(ev)));
1396
1611
  this.tracker.client.on('Reacted', ev => this.forEachRoomHistory(history => history._handleReacted(ev)));
@@ -1466,7 +1681,7 @@ class MessagesManager {
1466
1681
  const history = this.roomHistories.get(roomId);
1467
1682
  if (history && !history._isEphemeral) {
1468
1683
  const messages = snapshot.messages.filter(message => message.location.roomId === roomId && message.location.topicId === topic.id);
1469
- history._restoreWindow(topic, messages, snapshot.myReactions);
1684
+ history._restoreWindow(topic, messages, snapshot.myReactions, snapshot.repliedMessages);
1470
1685
  }
1471
1686
  }
1472
1687
  forEachRoomHistory(callback) {
@@ -2074,7 +2289,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2074
2289
  /**
2075
2290
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2076
2291
  */
2077
- const STATE_SNAPSHOT_VERSION = 2;
2292
+ const STATE_SNAPSHOT_VERSION = 3;
2078
2293
 
2079
2294
  /**
2080
2295
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -2184,7 +2399,7 @@ function isUserReactions(value) {
2184
2399
  return isObject(value) && Object.values(value).every(reactions => isArrayOf(reactions, isObject));
2185
2400
  }
2186
2401
  function isTopicHistory(value) {
2187
- return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.topics, isTopic);
2402
+ return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.repliedMessages, isFullMessage) && isArrayOf(value.topics, isTopic);
2188
2403
  }
2189
2404
  function isRoomMember(value) {
2190
2405
  return isObject(value) && (isUser(value.user) || isObject(value.spaceMember) && isUser(value.spaceMember.user));
@@ -2192,77 +2407,6 @@ function isRoomMember(value) {
2192
2407
  function isRoomMembers(value) {
2193
2408
  return isObject(value) && isString(value.roomId) && isArrayOf(value.members, isRoomMember);
2194
2409
  }
2195
- ;// ./src/protocol/schemes/PmParticipant.ts
2196
- let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
2197
- PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
2198
- return PmParticipantFlag;
2199
- }({});
2200
- ;// ./src/state-tracker/functions.ts
2201
-
2202
-
2203
- /**
2204
- * @return New objects of the other roles whose priority has to move; the given roles are left intact.
2205
- */
2206
- function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
2207
- // If the priority has changed, adjust the rest of roles
2208
- const increased = updatedRole.priority - oldRole.priority > 0;
2209
- const decreased = !increased;
2210
- const changedRoles = [];
2211
- allRoles.forEach(role => {
2212
- if (role.id === updatedRole.id) {
2213
- // Skip the updated role
2214
- return;
2215
- }
2216
- if (increased && oldRole.priority <= role.priority) {
2217
- changedRoles.push({
2218
- ...role,
2219
- priority: role.priority - 1
2220
- });
2221
- }
2222
- if (decreased && updatedRole.priority <= role.priority) {
2223
- changedRoles.push({
2224
- ...role,
2225
- priority: role.priority + 1
2226
- });
2227
- }
2228
- });
2229
- return changedRoles;
2230
- }
2231
- function extractUserFromMember(member) {
2232
- return member.user ?? member.spaceMember?.user;
2233
- }
2234
-
2235
- /**
2236
- * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
2237
- */
2238
- function isGroupPm(room) {
2239
- return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
2240
- }
2241
-
2242
- /**
2243
- * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
2244
- * `meId`. Empty for notes and for rooms of spaces.
2245
- */
2246
- function getPmPeers(room, meId) {
2247
- return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
2248
- }
2249
- function getActivePmParticipants(room) {
2250
- return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
2251
- }
2252
- function isSameUser(a, b) {
2253
- const keys = Object.keys(a);
2254
- if (keys.length !== Object.keys(b).length) {
2255
- return false;
2256
- }
2257
- return keys.every(key => {
2258
- const valueA = a[key];
2259
- const valueB = b[key];
2260
- if (Array.isArray(valueA) && Array.isArray(valueB)) {
2261
- return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
2262
- }
2263
- return valueA === valueB;
2264
- });
2265
- }
2266
2410
  ;// ./src/state-tracker/RoomsManager.ts
2267
2411
 
2268
2412
 
@@ -2282,6 +2426,8 @@ class RoomsManager {
2282
2426
  membersPromises = new PromiseRegistry();
2283
2427
  topicsPromises = new PromiseRegistry();
2284
2428
  importedTopicIds = new Map();
2429
+ stickyMyReactions = new ObservableIndexedObjectCollection('messageId');
2430
+ stickyMyReactionsPromises = new PromiseRegistry();
2285
2431
  constructor(tracker) {
2286
2432
  this.tracker = tracker;
2287
2433
  this.messages = new MessagesManager(tracker);
@@ -2289,6 +2435,9 @@ class RoomsManager {
2289
2435
  this.typing = new TypingManager(tracker);
2290
2436
  this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
2291
2437
  this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
2438
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
2439
+ this.tracker.client.on('ReactionUpdated', ev => this.handleReactionUpdated(ev));
2440
+ this.tracker.client.on('Reacted', ev => this.handleReacted(ev));
2292
2441
  this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
2293
2442
  this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
2294
2443
  this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
@@ -2327,6 +2476,34 @@ class RoomsManager {
2327
2476
  return this.members.get(roomId);
2328
2477
  }
2329
2478
 
2479
+ /**
2480
+ * Get the reactions of the connected user on sticky messages, keyed by message id. A sticky message comes with its
2481
+ * topic, outside of the message history, so the reactions of the given one are fetched once and then follow
2482
+ * the reactions of the user.
2483
+ */
2484
+ async getStickyMyReactions(location, messageId) {
2485
+ if (this.stickyMyReactionsPromises.notExist(messageId)) {
2486
+ this.stickyMyReactionsPromises.registerByFunction(async () => {
2487
+ const result = await this.tracker.client.send('GetMessages', {
2488
+ location,
2489
+ around: messageId,
2490
+ limit: 1,
2491
+ includeMyReactions: true
2492
+ });
2493
+ if (result.error) {
2494
+ throw result.error;
2495
+ }
2496
+ const own = result.data.myReactions?.find(item => item.messageId === messageId);
2497
+ this.stickyMyReactions.set({
2498
+ messageId,
2499
+ reactions: own?.reactions ?? []
2500
+ });
2501
+ }, messageId);
2502
+ }
2503
+ await this.stickyMyReactionsPromises.get(messageId);
2504
+ return this.stickyMyReactions;
2505
+ }
2506
+
2330
2507
  /**
2331
2508
  * Get a room member representing the current user.
2332
2509
  */
@@ -2452,6 +2629,7 @@ class RoomsManager {
2452
2629
  topicId,
2453
2630
  messages: latest.messages.map(messageWithoutPresence),
2454
2631
  myReactions: latest.myReactions,
2632
+ repliedMessages: latest.repliedMessages.map(messageWithoutPresence),
2455
2633
  topics: Array.from(topicIds).filter(id => topics?.has(id)).map(id => topics.get(id))
2456
2634
  });
2457
2635
  }
@@ -2728,6 +2906,8 @@ class RoomsManager {
2728
2906
  // so bound views refresh in place without blanking.
2729
2907
  this.membersPromises.forgetAll();
2730
2908
  this.topicsPromises.forgetAll();
2909
+ // Reactions could change meanwhile, and missed changes never arrive
2910
+ this.stickyMyReactionsPromises.forgetAll();
2731
2911
 
2732
2912
  // Upsert surviving/new rooms from the authoritative snapshot.
2733
2913
  this.addJoinedRooms(...ev.state.rooms);
@@ -2770,6 +2950,10 @@ class RoomsManager {
2770
2950
  this.list.set(...newRooms);
2771
2951
  }
2772
2952
  handleNewMessage(ev) {
2953
+ // Shown to one user and never stored, so it is neither counted nor the last message of the topic
2954
+ if (ev.message.type === 'Ephemeral') {
2955
+ return;
2956
+ }
2773
2957
  const topics = this.topics.get(ev.message.location.roomId);
2774
2958
  const topic = topics?.get(ev.message.location.topicId);
2775
2959
  if (!topic) {
@@ -2784,7 +2968,59 @@ class RoomsManager {
2784
2968
  topics.set(newTopic);
2785
2969
  this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2786
2970
  }
2971
+ handleMessageUpdated(ev) {
2972
+ const topics = this.topics.get(ev.message.location.roomId);
2973
+ const refTopic = ev.message.topicRef ? topics?.get(ev.message.topicRef) : undefined;
2974
+ if (refTopic?.refMessage?.id === ev.message.id) {
2975
+ topics.set({
2976
+ ...refTopic,
2977
+ refMessage: ev.message
2978
+ });
2979
+ }
2980
+ const topic = topics?.get(ev.message.location.topicId);
2981
+ const isLast = topic?.lastMessage?.id === ev.message.id;
2982
+ const isSticky = topic?.stickyMessage?.id === ev.message.id;
2983
+ if (!topic || !isLast && !isSticky) {
2984
+ return;
2985
+ }
2986
+ const newTopic = {
2987
+ ...topic,
2988
+ lastMessage: isLast ? ev.message : topic.lastMessage,
2989
+ stickyMessage: isSticky ? ev.message : topic.stickyMessage
2990
+ };
2991
+ topics.set(newTopic);
2992
+ this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2993
+ }
2994
+ handleReactionUpdated(ev) {
2995
+ for (const [roomId, topics] of this.topics.items) {
2996
+ for (const topic of topics.items) {
2997
+ const reactions = topic.stickyMessage?.id === ev.messageId ? applyReactionCounter(topic.stickyMessage.reactions, ev.reaction) : null;
2998
+ if (reactions) {
2999
+ const newTopic = {
3000
+ ...topic,
3001
+ stickyMessage: {
3002
+ ...topic.stickyMessage,
3003
+ reactions
3004
+ }
3005
+ };
3006
+ topics.set(newTopic);
3007
+ this.updatePmDefaultTopic(roomId, newTopic);
3008
+ }
3009
+ }
3010
+ }
3011
+ }
3012
+ handleReacted(ev) {
3013
+ const own = this.stickyMyReactions.get(ev.messageId);
3014
+ if (own) {
3015
+ this.stickyMyReactions.set({
3016
+ messageId: own.messageId,
3017
+ reactions: applyToggledReaction(own.reactions, ev.reaction)
3018
+ });
3019
+ }
3020
+ }
2787
3021
  async handleMessagesRedacted(ev) {
3022
+ this.stickyMyReactions.delete(...ev.ids);
3023
+
2788
3024
  // Remove redacted messages from topic and update metadata
2789
3025
  const topics = this.topics.get(ev.location.roomId);
2790
3026
  const topic = topics?.get(ev.location.topicId);
@@ -3252,7 +3488,7 @@ class Permissions {
3252
3488
  value: 1 << 18,
3253
3489
  maxLayer: Layer.Room
3254
3490
  },
3255
- RedactMessages: {
3491
+ ManageMessages: {
3256
3492
  value: 1 << 19,
3257
3493
  maxLayer: Layer.Topic
3258
3494
  },
@@ -3291,6 +3527,10 @@ class Permissions {
3291
3527
  SendAttachments: {
3292
3528
  value: 1 << 28,
3293
3529
  maxLayer: Layer.Topic
3530
+ },
3531
+ EditMessages: {
3532
+ value: 1 << 29,
3533
+ maxLayer: Layer.Topic
3294
3534
  }
3295
3535
  };
3296
3536
  static getNames() {
@@ -3996,6 +4236,12 @@ class ChatStateTracker {
3996
4236
  ;// ./src/WebSocketChatClient.ts
3997
4237
 
3998
4238
 
4239
+ const MAX_RETRY_AFTER_MS = 60000;
4240
+ // Going Away, Service Restart, Try Again Later
4241
+ const SERVER_CLOSE_CODES = [1001, 1012, 1013];
4242
+ function normalizeRetryAfter(retryAfterMs) {
4243
+ return typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : undefined;
4244
+ }
3999
4245
  var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
4000
4246
  WebSocketChatClientEvent["connect"] = "connect";
4001
4247
  WebSocketChatClientEvent["disconnect"] = "disconnect";
@@ -4018,6 +4264,10 @@ class WebSocketChatClient extends AbstractChatClient {
4018
4264
  reconnectEnabled = false;
4019
4265
  reconnectTimeoutId;
4020
4266
  reconnectAttempts = 0;
4267
+ serverClosedSinceStable = false;
4268
+ byeReceived = false;
4269
+ byeRetryAfterMs;
4270
+ stableConnectionTimeoutId;
4021
4271
  constructor(options) {
4022
4272
  super();
4023
4273
  this.options = options;
@@ -4054,7 +4304,7 @@ class WebSocketChatClient extends AbstractChatClient {
4054
4304
  disconnect() {
4055
4305
  const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
4056
4306
  this.reconnectEnabled = false;
4057
- this.reconnectAttempts = 0;
4307
+ this.resetBackoff();
4058
4308
  this.cancelScheduledReconnect();
4059
4309
  this.releaseSocket(1000); // Normal closure
4060
4310
  this.failPendingCommands(new Error('Client disconnected before the command was answered'));
@@ -4096,9 +4346,16 @@ class WebSocketChatClient extends AbstractChatClient {
4096
4346
  // Not every implementation follows a failed handshake with a close
4097
4347
  // event (e.g. Node.js), so an error alone means the connection is lost.
4098
4348
  ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
4349
+ ws.onopen = () => ws === this.ws && this.startConnectingTimeout(this.options.sessionTimeoutMs ?? 60000);
4099
4350
  this.ws = ws;
4100
4351
  this.authenticated = false;
4101
- this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
4352
+ this.byeReceived = false;
4353
+ this.byeRetryAfterMs = undefined;
4354
+ this.startConnectingTimeout(this.options.connectingTimeoutMs ?? 10000);
4355
+ }
4356
+ startConnectingTimeout(timeoutMs) {
4357
+ clearTimeout(this.connectingTimeoutId);
4358
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), timeoutMs);
4102
4359
  }
4103
4360
  sendEnvelope(envelope) {
4104
4361
  if (this.isReady) {
@@ -4110,34 +4367,52 @@ class WebSocketChatClient extends AbstractChatClient {
4110
4367
  onMessage(event) {
4111
4368
  this.lastReceivedMessageAt = Date.now();
4112
4369
  const envelope = JSON.parse(event.data);
4370
+ const ws = this.ws;
4113
4371
  this.handleIncomingEnvelope(envelope);
4114
4372
  this.emit(envelope.type, envelope.data);
4115
4373
  this.emit(this.Event.message, envelope);
4116
4374
 
4375
+ // A listener has called disconnect() or connect(), which settled this socket already.
4376
+ if (ws !== this.ws) {
4377
+ return;
4378
+ }
4379
+ if (envelope.type === 'Bye') {
4380
+ this.onBye(envelope.data);
4381
+ return;
4382
+ }
4383
+
4117
4384
  // Login successfully
4118
4385
  if (!this.authenticated) {
4119
- const isAuthenticated = envelope.type !== 'Bye';
4120
- this.authenticated = isAuthenticated;
4121
- if (isAuthenticated) {
4122
- this.reconnectAttempts = 0;
4123
- this.startConnectionMonitor();
4124
- this.settleConnect();
4125
- this.emit(this.Event.connect);
4126
- this.sendFromQueue();
4127
- } else {
4128
- this.settleConnect(envelope.data);
4129
- const error = envelope.data?.reason?.error;
4130
- if (error?.code === 'AuthenticationException') {
4131
- // Invalid token - retrying would be rejected the same way.
4132
- this.handleConnectionLoss(false);
4133
- this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4134
- }
4135
- }
4386
+ this.authenticated = true;
4387
+ this.stableConnectionTimeoutId = setTimeout(() => this.resetBackoff(), this.options.reconnect?.stableConnectionMs ?? 30000);
4388
+ this.startConnectionMonitor();
4389
+ this.settleConnect();
4390
+ this.emit(this.Event.connect);
4391
+ this.sendFromQueue();
4392
+ }
4393
+ }
4394
+ onBye(bye) {
4395
+ this.byeReceived = true;
4396
+ this.byeRetryAfterMs = normalizeRetryAfter(bye?.retryAfterMs);
4397
+ if (bye?.reason?.type === 'Service' || bye?.reason?.error?.code === 'ServiceUnavailableException') {
4398
+ // Not left to the close code: the server may close with 1000 and some platforms rewrite the code.
4399
+ this.handleConnectionLoss(true, true);
4400
+ return;
4401
+ }
4402
+ if (this.authenticated) {
4403
+ return;
4404
+ }
4405
+ this.settleConnect(bye);
4406
+ const error = bye?.reason?.error;
4407
+ if (error?.code === 'AuthenticationException') {
4408
+ // Invalid token - retrying would be rejected the same way.
4409
+ this.handleConnectionLoss(false);
4410
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4136
4411
  }
4137
4412
  }
4138
4413
  onClose(event) {
4139
4414
  // Connection was closed because of error
4140
- this.handleConnectionLoss(event.code !== 1000);
4415
+ this.handleConnectionLoss(event.code !== 1000, this.byeReceived || SERVER_CLOSE_CODES.includes(event.code));
4141
4416
  }
4142
4417
 
4143
4418
  /**
@@ -4145,7 +4420,7 @@ class WebSocketChatClient extends AbstractChatClient {
4145
4420
  * may never come, or take minutes on a dead TCP connection), settle
4146
4421
  * everything that depended on it and schedule a retry when requested.
4147
4422
  */
4148
- handleConnectionLoss(reconnect) {
4423
+ handleConnectionLoss(reconnect, closedByServer = false) {
4149
4424
  this.releaseSocket(reconnect ? 3000 : 1000);
4150
4425
 
4151
4426
  // The server can no longer answer anything that was queued or in
@@ -4155,7 +4430,7 @@ class WebSocketChatClient extends AbstractChatClient {
4155
4430
  if (reconnect) {
4156
4431
  // Keep a pending connect() promise unsettled - the retry below is
4157
4432
  // expected to authenticate and will resolve it.
4158
- this.scheduleReconnect();
4433
+ this.scheduleReconnect(closedByServer);
4159
4434
  } else {
4160
4435
  this.reconnectEnabled = false;
4161
4436
  this.settleConnect(new Error('Connection closed before authentication'));
@@ -4171,13 +4446,15 @@ class WebSocketChatClient extends AbstractChatClient {
4171
4446
  this.stopConnectionMonitor();
4172
4447
  clearTimeout(this.connectingTimeoutId);
4173
4448
  this.connectingTimeoutId = undefined;
4449
+ clearTimeout(this.stableConnectionTimeoutId);
4450
+ this.stableConnectionTimeoutId = undefined;
4174
4451
  this.authenticated = false;
4175
4452
  const ws = this.ws;
4176
4453
  this.ws = null;
4177
4454
  if (!ws) {
4178
4455
  return;
4179
4456
  }
4180
- ws.onmessage = ws.onclose = ws.onerror = null;
4457
+ ws.onmessage = ws.onclose = ws.onerror = ws.onopen = null;
4181
4458
  if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
4182
4459
  try {
4183
4460
  ws.close(closeCode);
@@ -4186,19 +4463,27 @@ class WebSocketChatClient extends AbstractChatClient {
4186
4463
  }
4187
4464
  }
4188
4465
  }
4189
- scheduleReconnect() {
4466
+ scheduleReconnect(closedByServer) {
4190
4467
  this.cancelScheduledReconnect();
4191
- const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
4192
- const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
4468
+
4469
+ // Once the server has closed a connection, the attempts that fail while it is still down
4470
+ // keep the longer backoff.
4471
+ this.serverClosedSinceStable ||= closedByServer;
4472
+ const reconnectOptions = this.options.reconnect;
4473
+ const minDelay = Math.max(0, this.serverClosedSinceStable ? reconnectOptions?.serverCloseMinDelayMs ?? 5000 : reconnectOptions?.minDelayMs ?? 1000);
4474
+ const maxDelay = Math.max(minDelay, reconnectOptions?.maxDelayMs ?? 30000);
4193
4475
  const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
4194
4476
  this.reconnectAttempts++;
4195
4477
 
4196
- // Random jitter (50-100% of the delay) keeps clients from reconnecting
4197
- // in lockstep after a server restart.
4478
+ // Full jitter spreads the clients dropped together over the whole delay; the server jitters its own hint.
4198
4479
  this.reconnectTimeoutId = setTimeout(() => {
4199
4480
  this.reconnectTimeoutId = undefined;
4200
4481
  this.connect().catch(() => undefined);
4201
- }, delay / 2 + Math.random() * delay / 2);
4482
+ }, this.byeRetryAfterMs ?? Math.random() * delay);
4483
+ }
4484
+ resetBackoff() {
4485
+ this.reconnectAttempts = 0;
4486
+ this.serverClosedSinceStable = false;
4202
4487
  }
4203
4488
  cancelScheduledReconnect() {
4204
4489
  clearTimeout(this.reconnectTimeoutId);
@@ -4473,6 +4758,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4473
4758
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4474
4759
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
4475
4760
  ErrorCode["MessageNotFound"] = "MessageNotFoundException";
4761
+ ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4476
4762
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4477
4763
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4478
4764
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
@@ -4480,6 +4766,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4480
4766
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4481
4767
  return ErrorCode;
4482
4768
  }({});
4769
+ ;// ./src/protocol/schemes/MessageEmbed.ts
4770
+ let MessageEmbedFlag = /*#__PURE__*/function (MessageEmbedFlag) {
4771
+ MessageEmbedFlag[MessageEmbedFlag["HideContent"] = 1] = "HideContent";
4772
+ MessageEmbedFlag[MessageEmbedFlag["Suppressed"] = 2] = "Suppressed";
4773
+ return MessageEmbedFlag;
4774
+ }({});
4483
4775
  ;// ./src/protocol/schemes/Role.ts
4484
4776
  /**
4485
4777
  * Bit flags of a role, stored in {@link Role.flags}.