@devanachat/sdk 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,6 +52,7 @@ __webpack_require__.d(__webpack_exports__, {
52
52
  PermissionDefinition: () => (/* reexport */ PermissionDefinition),
53
53
  Permissions: () => (/* reexport */ Permissions),
54
54
  RoleFlag: () => (/* reexport */ RoleFlag),
55
+ STATE_SNAPSHOT_VERSION: () => (/* reexport */ STATE_SNAPSHOT_VERSION),
55
56
  STORAGE_UNIT_BYTES: () => (/* reexport */ STORAGE_UNIT_BYTES),
56
57
  SearchRange: () => (/* reexport */ SearchRange),
57
58
  SpaceFeature: () => (/* reexport */ SpaceFeature),
@@ -481,7 +482,8 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
481
482
  retainRatio: 1,
482
483
  fetchLimit: 50,
483
484
  lastFetchCount: 0,
484
- oldestId: null
485
+ oldestId: null,
486
+ gaps: []
485
487
  };
486
488
 
487
489
  /**
@@ -536,6 +538,16 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
536
538
  get hasLatest() {
537
539
  return [WindowState.LATEST, WindowState.LIVE].includes(this.state);
538
540
  }
541
+
542
+ /**
543
+ * IDs of the items with a gap in front of them: the item right above in the window is not the real predecessor,
544
+ * an unknown number of items in between was never fetched. Such a seam appears when {@link resyncToLatest} gets
545
+ * a full page that does not reach the loaded items. A marker lives as long as its item stays in the window and
546
+ * is closed once the items right before it are fetched.
547
+ */
548
+ get gaps() {
549
+ return this.internalState.gaps;
550
+ }
539
551
  get hasOldest() {
540
552
  return this.state === WindowState.OLDEST || this.state === WindowState.LATEST && this.length < this.fetchLimit || this.internalState.oldestId !== null && this.has(this.internalState.oldestId);
541
553
  }
@@ -545,15 +557,51 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
545
557
  }
546
558
  let result;
547
559
  const originalState = this.state;
548
- this.internalState.ongoing = WindowState.LATEST;
560
+ this.beginFetch(WindowState.LATEST);
549
561
  try {
550
562
  result = await this.fetchLatestItems();
551
563
  this.internalState.lastFetchCount = result.length;
552
564
  } finally {
553
- this.internalState.ongoing = undefined;
565
+ this.endFetch();
566
+ }
567
+ this.replaceItems(result);
568
+ this.internalState.current = WindowState.LATEST;
569
+ this.emitChangeWithDiff(true, originalState);
570
+ }
571
+
572
+ /**
573
+ * Refresh the window with the latest page, keeping the already loaded items instead of replacing them - the
574
+ * reconnect-friendly variant of {@link resetToLatest}. The page is merged on top of the loaded items (an item in
575
+ * both is taken from the page) and only the window size limit pushes the oldest ones out. When the page is full
576
+ * and does not reach the newest loaded item, both parts are still kept and the seam is recorded in {@link gaps}.
577
+ */
578
+ async resyncToLatest() {
579
+ if (this.internalState.ongoing) {
580
+ return;
581
+ }
582
+ let result;
583
+ const originalState = this.state;
584
+ this.beginFetch(WindowState.LATEST);
585
+ try {
586
+ result = await this.fetchLatestItems();
587
+ this.internalState.lastFetchCount = result.length;
588
+ } finally {
589
+ this.endFetch();
590
+ }
591
+ const loaded = this.items;
592
+ const fetchedIds = new Set(result.map(item => this.getId(item)));
593
+ const retained = loaded.filter(item => !fetchedIds.has(this.getId(item)));
594
+
595
+ // A page shorter than the limit is everything the remote side has, so nothing can be missing in between.
596
+ const isContinuous = !retained.length || result.length < this.internalState.fetchLimit || fetchedIds.has(this.getId(loaded[loaded.length - 1]));
597
+
598
+ // The page is continuous, so only its first item can have a gap in front of it.
599
+ this.forgetGapsOf(result.slice(1).map(item => this.getId(item)));
600
+ if (!isContinuous && !this.internalState.gaps.includes(this.getId(result[0]))) {
601
+ this.internalState.gaps = [...this.internalState.gaps, this.getId(result[0])];
554
602
  }
555
603
  this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
556
- this.addItems(result, 'tail');
604
+ this.addItems([...retained, ...result], 'tail');
557
605
  this.internalState.current = WindowState.LATEST;
558
606
  this.emitChangeWithDiff(true, originalState);
559
607
  }
@@ -563,18 +611,18 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
563
611
  }
564
612
  let result;
565
613
  const originalState = this.state;
566
- this.internalState.ongoing = WindowState.PAST;
614
+ const firstItem = this.getAt(0);
615
+ this.beginFetch(WindowState.PAST);
567
616
  try {
568
617
  result = await this.fetchItemsBefore();
569
618
  this.internalState.lastFetchCount = result ? result.length : 0;
570
619
  } finally {
571
- this.internalState.ongoing = undefined;
620
+ this.endFetch();
572
621
  }
573
622
  if (!result) {
574
623
  return this.resetToLatest();
575
624
  }
576
625
  if (!result.length) {
577
- const firstItem = this.getAt(0);
578
626
  this.internalState.oldestId = firstItem ? this.getId(firstItem) : null;
579
627
  await this.refreshFetchedState();
580
628
 
@@ -585,6 +633,10 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
585
633
  this.emitChangeWithDiff(false, originalState);
586
634
  return;
587
635
  }
636
+ if (firstItem) {
637
+ // The page was fetched as the direct predecessors of the first item, so a gap in front of it is closed.
638
+ this.forgetGapsOf([this.getId(firstItem)]);
639
+ }
588
640
  this.addItems(result, 'head');
589
641
  await this.refreshFetchedState();
590
642
  this.emitChangeWithDiff(true, originalState);
@@ -605,12 +657,12 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
605
657
  }
606
658
  let result;
607
659
  const originalState = this.state;
608
- this.internalState.ongoing = WindowState.PAST;
660
+ this.beginFetch(WindowState.PAST);
609
661
  try {
610
662
  result = await this.fetchItemsAfter();
611
663
  this.internalState.lastFetchCount = result ? result.length : 0;
612
664
  } finally {
613
- this.internalState.ongoing = undefined;
665
+ this.endFetch();
614
666
  }
615
667
  if (!result) {
616
668
  await this.resetToLatest(true);
@@ -623,26 +675,41 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
623
675
  return;
624
676
  }
625
677
  }
678
+
679
+ /**
680
+ * Load the items around the given one. Asked for while another fetch is running, it waits for that fetch to end
681
+ * instead of being dropped - when the call returns, the window either holds the item or it could not be loaded.
682
+ */
626
683
  async jumpTo(id) {
627
- if (this.internalState.ongoing || this.state !== WindowState.LIVE && this._items.has(id)) {
684
+ while (this.internalState.ongoing) {
685
+ await this.internalState.fetchSettled;
686
+ }
687
+ if (this.state !== WindowState.LIVE && this._items.has(id)) {
628
688
  return;
629
689
  }
630
690
  let result;
631
691
  const originalState = this.state;
632
- this.internalState.ongoing = WindowState.PAST;
692
+ this.beginFetch(WindowState.PAST);
633
693
  try {
634
694
  result = await this.fetchItemsAround(id);
635
695
  this.internalState.lastFetchCount = result ? result.length : 0;
636
696
  if (result) {
637
- this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
638
- this.addItems(result, 'tail');
697
+ this.replaceItems(result);
639
698
  await this.refreshFetchedState();
640
699
  }
641
700
  } finally {
642
- this.internalState.ongoing = undefined;
701
+ this.endFetch();
643
702
  }
644
703
  this.emitChangeWithDiff(!!result, originalState);
645
704
  }
705
+ delete(...ids) {
706
+ super.delete(...ids);
707
+ this.forgetGapsOf(ids);
708
+ }
709
+ deleteAll() {
710
+ super.deleteAll();
711
+ this.internalState.gaps = [];
712
+ }
646
713
  async refreshFetchedState() {
647
714
  this.internalState.current = (await this.isLatestItemLoaded()) ? WindowState.LATEST : WindowState.PAST;
648
715
  }
@@ -665,6 +732,29 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
665
732
  this._items.set(...entries, ...loaded);
666
733
  return this.trimTail(this.getLowWatermark(highWatermark));
667
734
  }
735
+ beginFetch(kind) {
736
+ this.internalState.ongoing = kind;
737
+ this.internalState.fetchSettled = new Promise(resolve => this.internalState.settleFetch = resolve);
738
+ }
739
+ endFetch() {
740
+ this.internalState.ongoing = undefined;
741
+ this.internalState.settleFetch?.();
742
+ }
743
+
744
+ /**
745
+ * Replace the whole content without emitting an event; the old gap markers mean nothing for the new content.
746
+ */
747
+ replaceItems(items) {
748
+ this._items.deleteAll();
749
+ this.internalState.gaps = [];
750
+ this.addItems(items, 'tail');
751
+ }
752
+ forgetGapsOf(ids) {
753
+ if (this.internalState.gaps.length && ids.length) {
754
+ const removed = new Set(ids);
755
+ this.internalState.gaps = this.internalState.gaps.filter(id => !removed.has(id));
756
+ }
757
+ }
668
758
  emitChangeWithDiff(itemChanged, originalState) {
669
759
  if (itemChanged || originalState !== this.state) {
670
760
  this.eventTarget.emit('change', {
@@ -691,6 +781,7 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
691
781
  deletedItems.push(id);
692
782
  }
693
783
  this._items.delete(...deletedItems);
784
+ this.forgetGapsOf(deletedItems);
694
785
  if (this.internalState.current === WindowState.OLDEST) {
695
786
  this.internalState.current = WindowState.PAST;
696
787
  }
@@ -702,6 +793,7 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
702
793
  }
703
794
  const deletedItems = Array.from(this._items.items.keys()).slice(keep);
704
795
  this._items.delete(...deletedItems);
796
+ this.forgetGapsOf(deletedItems);
705
797
  return deletedItems;
706
798
  }
707
799
 
@@ -794,6 +886,12 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
794
886
  }
795
887
  return super.resetToLatest(force);
796
888
  }
889
+ async resyncToLatest() {
890
+ if (this.internalState.traverseLock) {
891
+ return;
892
+ }
893
+ return super.resyncToLatest();
894
+ }
797
895
  async fetchNext() {
798
896
  if (this.internalState.traverseLock) {
799
897
  return;
@@ -816,6 +914,45 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
816
914
  return super.jumpTo(id);
817
915
  }
818
916
 
917
+ /**
918
+ * The latest messages (oldest first) with the reactions of the user, or null if the window does not hold them.
919
+ * @internal
920
+ */
921
+ _exportLatest(limit) {
922
+ if (this.state !== WindowState.LATEST) {
923
+ return null;
924
+ }
925
+ const items = this.items;
926
+ // A restored window is taken for continuous, so nothing above the newest gap goes into it.
927
+ const continuousFrom = Math.max(0, ...this.internalState.gaps.map(id => items.findIndex(item => item.id === id)));
928
+ const messages = items.slice(Math.max(continuousFrom, items.length - Math.max(limit, this.fetchLimit)));
929
+ const myReactions = {};
930
+ for (const message of messages) {
931
+ if (this.internalState.myReactions[message.id]) {
932
+ myReactions[message.id] = this.internalState.myReactions[message.id];
933
+ }
934
+ }
935
+ return {
936
+ messages,
937
+ myReactions
938
+ };
939
+ }
940
+
941
+ /**
942
+ * Fill the window with saved latest messages, as if they were just fetched; the next reset to the latest replaces
943
+ * them.
944
+ * @internal
945
+ */
946
+ _restoreLatest(messages, myReactions) {
947
+ const originalState = this.state;
948
+ this.replaceItems(messages);
949
+ this.internalState.myReactions = {
950
+ ...myReactions
951
+ };
952
+ this.internalState.current = WindowState.LATEST;
953
+ this.emitChangeWithDiff(true, originalState);
954
+ }
955
+
819
956
  /**
820
957
  * For internal use.
821
958
  * @internal
@@ -1022,6 +1159,7 @@ class RoomMessagesHistory {
1022
1159
  roomId;
1023
1160
  historyWindows = new IndexedCollection();
1024
1161
  traverseLock = false;
1162
+ timeLimitedHistory = false;
1025
1163
  room;
1026
1164
  constructor(room, tracker) {
1027
1165
  this.tracker = tracker;
@@ -1029,7 +1167,7 @@ class RoomMessagesHistory {
1029
1167
  this.room = typeof room === 'string' ? null : room;
1030
1168
  this.isPreview = this.room === null;
1031
1169
  if (this.room) {
1032
- this.updateTraverseLock(this.room);
1170
+ this.updateHistoryMode(this.room);
1033
1171
  }
1034
1172
  if (this.room?.defaultTopic) {
1035
1173
  this.createHistoryWindowForTopic(this.room.defaultTopic);
@@ -1062,13 +1200,19 @@ class RoomMessagesHistory {
1062
1200
  *
1063
1201
  * The window bindings are preserved; only windows that the application had
1064
1202
  * actually pulled to the latest page (state === LATEST) are refreshed, with
1065
- * a single resetToLatest instead of a chain of catch-up requests. Windows
1066
- * that were never pulled (LIVE) or belong to an ephemeral room are left
1203
+ * a single request instead of a chain of catch-up requests. Windows that
1204
+ * were never pulled (LIVE) or belong to an ephemeral room are left
1067
1205
  * untouched so their in-memory context survives the reconnect.
1206
+ *
1207
+ * Rooms keeping the full history are reset to the latest page (the rest can
1208
+ * always be traversed back), while the windows of rooms with a time-limited
1209
+ * history (MaxAge) keep what they had loaded and get the missed messages on
1210
+ * top - the server may no longer serve the older ones. If more messages were
1211
+ * missed than a single page holds, the seam is recorded in the window gaps.
1068
1212
  */
1069
1213
  async resync(room) {
1070
1214
  this.room = room;
1071
- this.updateTraverseLock(room);
1215
+ this.updateHistoryMode(room);
1072
1216
  if (this.room.defaultTopic) {
1073
1217
  this.createHistoryWindowForTopic(this.room.defaultTopic);
1074
1218
  }
@@ -1081,7 +1225,12 @@ class RoomMessagesHistory {
1081
1225
  if (this.traverseLock) {
1082
1226
  continue;
1083
1227
  }
1084
- if (window.state === WindowState.LATEST) {
1228
+ if (window.state !== WindowState.LATEST) {
1229
+ continue;
1230
+ }
1231
+ if (this.timeLimitedHistory) {
1232
+ await window.resyncToLatest();
1233
+ } else {
1085
1234
  await window.resetToLatest(true);
1086
1235
  }
1087
1236
  } catch (_e) {
@@ -1092,13 +1241,38 @@ class RoomMessagesHistory {
1092
1241
  }
1093
1242
  }
1094
1243
 
1244
+ /**
1245
+ * For internal use.
1246
+ * @internal
1247
+ */
1248
+ get _isEphemeral() {
1249
+ return this.traverseLock;
1250
+ }
1251
+
1252
+ /**
1253
+ * The window of the topic, if created; unlike getMessagesWindow(), never creates nor fetches one.
1254
+ * @internal
1255
+ */
1256
+ _peekWindow(topicId) {
1257
+ return this.historyWindows.get(topicId);
1258
+ }
1259
+
1260
+ /**
1261
+ * For internal use.
1262
+ * @internal
1263
+ */
1264
+ _restoreWindow(topic, messages, myReactions) {
1265
+ this.createHistoryWindowForTopic(topic);
1266
+ this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions);
1267
+ }
1268
+
1095
1269
  /**
1096
1270
  * For internal use.
1097
1271
  * @internal
1098
1272
  */
1099
1273
  async _handleRoomUpdated(ev) {
1100
1274
  this.room = ev.room;
1101
- this.updateTraverseLock(ev.room);
1275
+ this.updateHistoryMode(ev.room);
1102
1276
  if (ev.room.defaultTopic) {
1103
1277
  this.createHistoryWindowForTopic(ev.room.defaultTopic);
1104
1278
  }
@@ -1184,8 +1358,9 @@ class RoomMessagesHistory {
1184
1358
  this.tracker.rooms._deleteTopicsFromRoom(this.roomId, ...deletedTopicIds);
1185
1359
  });
1186
1360
  }
1187
- updateTraverseLock(room) {
1361
+ updateHistoryMode(room) {
1188
1362
  this.traverseLock = room.history.mode === 'Ephemeral';
1363
+ this.timeLimitedHistory = room.history.mode === 'MaxAge';
1189
1364
  }
1190
1365
  }
1191
1366
  ;// ./src/state-tracker/MessagesManager.ts
@@ -1250,6 +1425,43 @@ class MessagesManager {
1250
1425
  }
1251
1426
  return message || null;
1252
1427
  }
1428
+
1429
+ /**
1430
+ * For internal use.
1431
+ * @internal
1432
+ */
1433
+ _importRooms(rooms) {
1434
+ for (const room of rooms) {
1435
+ this.createHistoryForNewRoom(room);
1436
+ }
1437
+ this.deferredSession.resolve();
1438
+ }
1439
+
1440
+ /**
1441
+ * For internal use.
1442
+ * @internal
1443
+ */
1444
+ _exportLatest(roomId, topicId, limit) {
1445
+ const history = this.roomHistories.get(roomId);
1446
+
1447
+ // Ephemeral history lives only in the memory of the session.
1448
+ if (!history || history._isEphemeral) {
1449
+ return null;
1450
+ }
1451
+ return history._peekWindow(topicId)?._exportLatest(limit) ?? null;
1452
+ }
1453
+
1454
+ /**
1455
+ * For internal use.
1456
+ * @internal
1457
+ */
1458
+ _importHistory(roomId, topic, snapshot) {
1459
+ const history = this.roomHistories.get(roomId);
1460
+ if (history && !history._isEphemeral) {
1461
+ const messages = snapshot.messages.filter(message => message.location.roomId === roomId && message.location.topicId === topic.id);
1462
+ history._restoreWindow(topic, messages, snapshot.myReactions);
1463
+ }
1464
+ }
1253
1465
  forEachRoomHistory(callback) {
1254
1466
  for (const history of this.roomHistories.items.values()) {
1255
1467
  callback(history);
@@ -1470,6 +1682,47 @@ class FollowedTopicsManager extends EventTarget {
1470
1682
  this.followedTopics.get(roomId)?.delete(...topicIds);
1471
1683
  topicIds.forEach(topicId => this.invalidateUnreadSummaries(roomId, topicId));
1472
1684
  }
1685
+
1686
+ /**
1687
+ * For internal use.
1688
+ * @internal
1689
+ */
1690
+ _exportFollowedTopics() {
1691
+ return Array.from(this.followedTopics.items).filter(([roomId]) => this.tracker.rooms._getRoom(roomId)).map(([roomId, followedTopics]) => ({
1692
+ roomId,
1693
+ followedTopics: followedTopics.items
1694
+ }));
1695
+ }
1696
+
1697
+ /**
1698
+ * Expects the rooms to be imported already - followed topics of other rooms are skipped.
1699
+ * @internal
1700
+ */
1701
+ _importFollowedTopics(snapshots) {
1702
+ for (const {
1703
+ roomId,
1704
+ followedTopics
1705
+ } of snapshots) {
1706
+ if (this.tracker.rooms._getRoom(roomId)) {
1707
+ this.applyRoomFollowedTopics(roomId, followedTopics);
1708
+ }
1709
+ }
1710
+ this.invalidateUnreadSummaries();
1711
+ this.deferredSession.resolve();
1712
+ }
1713
+
1714
+ /**
1715
+ * For internal use.
1716
+ * @internal
1717
+ */
1718
+ _forgetRoomsExcept(roomIds) {
1719
+ const keptRoomIds = new Set(roomIds);
1720
+ for (const roomId of Array.from(this.followedTopics.items.keys())) {
1721
+ if (!keptRoomIds.has(roomId)) {
1722
+ this.clearRoomFollowedTopicsStructures(roomId);
1723
+ }
1724
+ }
1725
+ }
1473
1726
  handleSession(ev) {
1474
1727
  // Keep cached followed-topic collections (they drive unread indicators
1475
1728
  // that would otherwise blank on reconnect), but mark them stale and drop
@@ -1670,11 +1923,148 @@ class FollowedTopicsManager extends EventTarget {
1670
1923
  this.invalidateUnreadSummaries(roomId);
1671
1924
  }
1672
1925
  }
1926
+ ;// ./src/protocol/schemes/User.ts
1927
+ /**
1928
+ * Availability of a user, aggregated over all of their sessions.
1929
+ *
1930
+ * - `Offline` - no session is connected and none can be reached asynchronously.
1931
+ * - `Online` - at least one session holds a live connection.
1932
+ * - `OnlineAsync` - no live connection, but a push-registered device was active
1933
+ * recently, so a message will still reach the user.
1934
+ */
1935
+ let UserStatus = /*#__PURE__*/function (UserStatus) {
1936
+ UserStatus[UserStatus["Offline"] = 0] = "Offline";
1937
+ UserStatus[UserStatus["Online"] = 1] = "Online";
1938
+ UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
1939
+ return UserStatus;
1940
+ }({});
1941
+ ;// ./src/state-tracker/StateSnapshot.ts
1942
+
1943
+
1944
+ /**
1945
+ * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
1946
+ */
1947
+ const STATE_SNAPSHOT_VERSION = 1;
1948
+
1949
+ /**
1950
+ * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
1951
+ * application start (before the connection is established) - see {@link ChatStateTracker.exportSnapshot}.
1952
+ *
1953
+ * Only the data that lasts is included: the current user, the joined spaces (with roles) and rooms (with the default
1954
+ * topics), and the lazily loaded lists already fetched - rooms of spaces, followed topics, emoticons and relationships.
1955
+ * The message histories of the topics named in the {@link StateSnapshotIntent} are included too, with what their
1956
+ * display needs: the topics referenced by the messages and, optionally, the members of the rooms.
1957
+ * Left out on purpose:
1958
+ * - presence - every user status is saved as `Offline`, a status from the past would show people online who are not;
1959
+ * - members of spaces, and of rooms not asked for - large, made mostly of presence, and refetched cheaply on demand;
1960
+ * - other message histories and topics, histories of ephemeral rooms (they live only in the memory of the session),
1961
+ * permission overwrites and room previews - loaded on demand once the connection is up, as on a reconnect.
1962
+ */
1963
+
1964
+ /**
1965
+ * What {@link ChatStateTracker.exportSnapshot} should include beyond the state that is always exported.
1966
+ */
1967
+
1968
+ function withoutPresence(user) {
1969
+ return {
1970
+ ...user,
1971
+ status: UserStatus.Offline,
1972
+ online: false
1973
+ };
1974
+ }
1975
+ function messageWithoutPresence(message) {
1976
+ return {
1977
+ ...message,
1978
+ author: {
1979
+ ...message.author,
1980
+ user: withoutPresence(message.author.user)
1981
+ }
1982
+ };
1983
+ }
1984
+ function memberWithoutPresence(member) {
1985
+ return {
1986
+ ...member,
1987
+ user: member.user ? withoutPresence(member.user) : member.user,
1988
+ spaceMember: member.spaceMember ? {
1989
+ ...member.spaceMember,
1990
+ user: withoutPresence(member.spaceMember.user)
1991
+ } : member.spaceMember
1992
+ };
1993
+ }
1994
+
1995
+ /**
1996
+ * Structural check of the data restored from a storage - deep enough that importing it cannot throw, as the state
1997
+ * handlers dereference these fields without checking them.
1998
+ */
1999
+ function isValidStateSnapshot(value) {
2000
+ return isObject(value) && value.version === STATE_SNAPSHOT_VERSION && typeof value.createdAt === 'number' && isUser(value.user) && isArrayOf(value.spaces, isSpace) && isArrayOf(value.rooms, isRoom) && isArrayOf(value.spaceRooms, isSpaceRooms) && isArrayOf(value.followedTopics, isRoomFollowedTopics) && isArrayOf(value.emoticons, isEmoticons) && (value.relationships === null || isArrayOf(value.relationships, isRelationship)) && isArrayOf(value.histories, isTopicHistory) && isArrayOf(value.roomMembers, isRoomMembers);
2001
+ }
2002
+ function isObject(value) {
2003
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
2004
+ }
2005
+ function isArrayOf(value, isItem) {
2006
+ return Array.isArray(value) && value.every(isItem);
2007
+ }
2008
+ function isString(value) {
2009
+ return typeof value === 'string';
2010
+ }
2011
+ function hasId(value) {
2012
+ return isObject(value) && isString(value.id);
2013
+ }
2014
+ function isUser(value) {
2015
+ return hasId(value);
2016
+ }
2017
+ function isRole(value) {
2018
+ return hasId(value) && typeof value.priority === 'number';
2019
+ }
2020
+ function isSpace(value) {
2021
+ return hasId(value) && isArrayOf(value.roles, isRole) && isArrayOf(value.defaultRooms, isString) && (value.systemRoom === null || isString(value.systemRoom));
2022
+ }
2023
+ function isTopic(value) {
2024
+ return hasId(value) && (value.refMessage === undefined || value.refMessage === null || isMessage(value.refMessage));
2025
+ }
2026
+ function isMessage(value) {
2027
+ return hasId(value) && isObject(value.location) && isString(value.location.topicId);
2028
+ }
2029
+ function isFullMessage(value) {
2030
+ return hasId(value) && isObject(value.location) && isString(value.location.roomId) && isString(value.location.topicId) && isObject(value.author) && isUser(value.author.user) && Array.isArray(value.reactions);
2031
+ }
2032
+ function isRoom(value) {
2033
+ return hasId(value) && isString(value.type) && (value.spaceId === null || isString(value.spaceId)) && (value.defaultTopic === null || isTopic(value.defaultTopic)) && (value.recipients === null || isArrayOf(value.recipients, isUser)) && isObject(value.history) && isString(value.history.mode);
2034
+ }
2035
+ function isSpaceRooms(value) {
2036
+ return isObject(value) && isString(value.spaceId) && isArrayOf(value.summaries, hasId);
2037
+ }
2038
+ function isFollowedTopic(value) {
2039
+ return isObject(value) && isObject(value.location) && isString(value.location.roomId) && isString(value.location.topicId);
2040
+ }
2041
+ function isRoomFollowedTopics(value) {
2042
+ return isObject(value) && isString(value.roomId) && isArrayOf(value.followedTopics, isFollowedTopic);
2043
+ }
2044
+ function isEmoticons(value) {
2045
+ return isObject(value) && (value.spaceId === null || isString(value.spaceId)) && isArrayOf(value.emoticons, hasId);
2046
+ }
2047
+ function isRelationship(value) {
2048
+ return isObject(value) && isUser(value.refUser) && isString(value.type);
2049
+ }
2050
+ function isUserReactions(value) {
2051
+ return isObject(value) && Object.values(value).every(reactions => isArrayOf(reactions, isObject));
2052
+ }
2053
+ function isTopicHistory(value) {
2054
+ return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.topics, isTopic);
2055
+ }
2056
+ function isRoomMember(value) {
2057
+ return isObject(value) && (isUser(value.user) || isObject(value.spaceMember) && isUser(value.spaceMember.user));
2058
+ }
2059
+ function isRoomMembers(value) {
2060
+ return isObject(value) && isString(value.roomId) && isArrayOf(value.members, isRoomMember);
2061
+ }
1673
2062
  ;// ./src/state-tracker/RoomsManager.ts
1674
2063
 
1675
2064
 
1676
2065
 
1677
2066
 
2067
+
1678
2068
  class RoomsManager {
1679
2069
  messages;
1680
2070
  followedTopics;
@@ -1684,6 +2074,7 @@ class RoomsManager {
1684
2074
  deferredSession = new DeferredTask();
1685
2075
  membersPromises = new PromiseRegistry();
1686
2076
  topicsPromises = new PromiseRegistry();
2077
+ importedTopicIds = new Map();
1687
2078
  constructor(tracker) {
1688
2079
  this.tracker = tracker;
1689
2080
  this.messages = new MessagesManager(tracker);
@@ -1788,6 +2179,148 @@ class RoomsManager {
1788
2179
  _deleteTopicsFromRoom(roomId, ...topicIds) {
1789
2180
  this.topics.get(roomId)?.delete(...topicIds);
1790
2181
  }
2182
+
2183
+ /**
2184
+ * For internal use.
2185
+ * @internal
2186
+ */
2187
+ _exportRooms() {
2188
+ return this.list.items.map(room => room.recipients ? {
2189
+ ...room,
2190
+ recipients: room.recipients.map(withoutPresence)
2191
+ } : room);
2192
+ }
2193
+
2194
+ /**
2195
+ * For internal use.
2196
+ * @internal
2197
+ */
2198
+ _importRooms(rooms) {
2199
+ this.messages._importRooms(rooms);
2200
+ this.addJoinedRooms(...rooms);
2201
+ this.deferredSession.resolve();
2202
+ }
2203
+
2204
+ /**
2205
+ * For internal use.
2206
+ * @internal
2207
+ */
2208
+ _exportHistories(intent) {
2209
+ const histories = [];
2210
+ const exported = new Set();
2211
+ for (const {
2212
+ roomId,
2213
+ topicId: requestedTopicId
2214
+ } of intent.histories ?? []) {
2215
+ const room = this.list.get(roomId);
2216
+ const topicId = requestedTopicId ?? room?.defaultTopic?.id;
2217
+ if (!room || !topicId || exported.has(`${roomId}/${topicId}`)) {
2218
+ continue;
2219
+ }
2220
+ const latest = this.messages._exportLatest(roomId, topicId, intent.historyLimit ?? 0);
2221
+ const topics = this.topics.get(roomId);
2222
+
2223
+ // A topic other than the default one is restored from the snapshot, so it has to be known.
2224
+ if (!latest || topicId !== room.defaultTopic?.id && !topics?.has(topicId)) {
2225
+ continue;
2226
+ }
2227
+ const topicIds = new Set([topicId, ...latest.messages.map(message => message.topicRef)]);
2228
+ topicIds.delete(room.defaultTopic?.id);
2229
+ exported.add(`${roomId}/${topicId}`);
2230
+ histories.push({
2231
+ roomId,
2232
+ topicId,
2233
+ messages: latest.messages.map(messageWithoutPresence),
2234
+ myReactions: latest.myReactions,
2235
+ topics: Array.from(topicIds).filter(id => topics?.has(id)).map(id => topics.get(id))
2236
+ });
2237
+ }
2238
+ return histories;
2239
+ }
2240
+
2241
+ /**
2242
+ * Members of private conversations are not exported - they are made of the recipients of the room.
2243
+ * @internal
2244
+ */
2245
+ _exportMembers(roomIds, limit) {
2246
+ const snapshots = [];
2247
+ if (!limit) {
2248
+ return snapshots;
2249
+ }
2250
+ for (const roomId of new Set(roomIds)) {
2251
+ const members = this.members.get(roomId);
2252
+ if (members && members.length <= limit && this.list.get(roomId)?.type !== 'Pm') {
2253
+ snapshots.push({
2254
+ roomId,
2255
+ members: members.items.map(memberWithoutPresence)
2256
+ });
2257
+ }
2258
+ }
2259
+ return snapshots;
2260
+ }
2261
+
2262
+ /**
2263
+ * Expects the rooms to be imported already - histories and members of other rooms are skipped.
2264
+ * @internal
2265
+ */
2266
+ _importHistories(histories, roomMembers) {
2267
+ for (const {
2268
+ roomId,
2269
+ members
2270
+ } of roomMembers) {
2271
+ if (this.list.has(roomId) && this.list.get(roomId).type !== 'Pm') {
2272
+ this.handleRoomMembers({
2273
+ id: roomId,
2274
+ members
2275
+ });
2276
+ // Served from the snapshot until the session invalidates it.
2277
+ this.membersPromises.register(Promise.resolve(), roomId);
2278
+ }
2279
+ }
2280
+ for (const history of histories) {
2281
+ const room = this.list.get(history.roomId);
2282
+ if (!room) {
2283
+ continue;
2284
+ }
2285
+ const topics = history.topics.filter(topic => topic.id !== room.defaultTopic?.id);
2286
+ if (topics.length) {
2287
+ this.addJoinedRoomTopics(room.id, ...topics);
2288
+ const importedTopicIds = this.importedTopicIds.get(room.id) ?? new Set();
2289
+ topics.forEach(topic => importedTopicIds.add(topic.id));
2290
+ this.importedTopicIds.set(room.id, importedTopicIds);
2291
+ }
2292
+ const topic = history.topicId === room.defaultTopic?.id ? room.defaultTopic : this.topics.get(room.id)?.get(history.topicId);
2293
+ if (topic) {
2294
+ this.messages._importHistory(room.id, topic, history);
2295
+ }
2296
+ }
2297
+ }
2298
+
2299
+ /**
2300
+ * The session carries only the default topics, so the other restored ones are fetched anew.
2301
+ * @internal
2302
+ */
2303
+ _refreshImportedTopics() {
2304
+ const importedTopicIds = Array.from(this.importedTopicIds);
2305
+ this.importedTopicIds.clear();
2306
+ for (const [roomId, ids] of importedTopicIds) {
2307
+ if (!this.list.has(roomId)) {
2308
+ continue;
2309
+ }
2310
+ const topicIds = Array.from(ids);
2311
+ const promise = this.tracker.client.send('GetTopics', {
2312
+ roomId,
2313
+ topicIds
2314
+ }).then(result => {
2315
+ if (!result.error) {
2316
+ this.topics.get(roomId)?.set(...result.data.topics);
2317
+ }
2318
+ });
2319
+ topicIds.forEach(topicId => this.topicsPromises.register(promise, roomId + topicId));
2320
+ // Best effort: on a failure the restored topics stay, as after a reconnect.
2321
+ promise.catch(() => undefined);
2322
+ }
2323
+ }
1791
2324
  deleteRoom(...roomIds) {
1792
2325
  this.list.delete(...roomIds);
1793
2326
  this.members.delete(...roomIds);
@@ -2184,6 +2717,47 @@ class SpacesManager {
2184
2717
  const members = await this.getMembers(spaceId);
2185
2718
  return members?.items.find(member => member.user.id === userId);
2186
2719
  }
2720
+
2721
+ /**
2722
+ * For internal use.
2723
+ * @internal
2724
+ */
2725
+ _exportSpaces() {
2726
+ return this.list.items;
2727
+ }
2728
+
2729
+ /**
2730
+ * Room listings of the joined spaces only - of other spaces they are fetched for a moment's look.
2731
+ * @internal
2732
+ */
2733
+ _exportSpaceRooms() {
2734
+ return Array.from(this.rooms.items).filter(([spaceId]) => this.list.has(spaceId)).map(([spaceId, summaries]) => ({
2735
+ spaceId,
2736
+ summaries: summaries.items
2737
+ }));
2738
+ }
2739
+
2740
+ /**
2741
+ * For internal use.
2742
+ * @internal
2743
+ */
2744
+ _importSpaces(spaces, spaceRooms) {
2745
+ this.addJoinedSpaces(...spaces);
2746
+ for (const {
2747
+ spaceId,
2748
+ summaries
2749
+ } of spaceRooms) {
2750
+ if (this.list.has(spaceId)) {
2751
+ this.handleSpaceRooms({
2752
+ id: spaceId,
2753
+ summaries
2754
+ });
2755
+ // Served from the snapshot until the session invalidates it.
2756
+ this.roomsPromises.register(Promise.resolve(), spaceId);
2757
+ }
2758
+ }
2759
+ this.deferredSession.resolve();
2760
+ }
2187
2761
  handleNewRole(ev) {
2188
2762
  this.roles.get(ev.spaceId).set(ev.role);
2189
2763
  this.syncSpaceRoles(ev.spaceId);
@@ -2805,6 +3379,52 @@ class EmoticonsManager {
2805
3379
  await this.emoticonsPromises.get(key);
2806
3380
  return this.list.get(key);
2807
3381
  }
3382
+
3383
+ /**
3384
+ * For internal use.
3385
+ * @internal
3386
+ */
3387
+ _exportEmoticons() {
3388
+ return Array.from(this.list.items).map(([key, emoticons]) => ({
3389
+ spaceId: key === GLOBAL_KEY ? null : key,
3390
+ emoticons: emoticons.items
3391
+ }));
3392
+ }
3393
+
3394
+ /**
3395
+ * Emoticons of spaces other than the given ones are skipped.
3396
+ * @internal
3397
+ */
3398
+ _importEmoticons(snapshots, spaceIds) {
3399
+ const joinedSpaceIds = new Set(spaceIds);
3400
+ for (const {
3401
+ spaceId,
3402
+ emoticons
3403
+ } of snapshots) {
3404
+ if (spaceId !== null && !joinedSpaceIds.has(spaceId)) {
3405
+ continue;
3406
+ }
3407
+ this.handleEmoticons({
3408
+ location: {
3409
+ spaceId: spaceId ?? undefined
3410
+ },
3411
+ emoticons
3412
+ });
3413
+ // Served from the snapshot until the session invalidates it.
3414
+ this.emoticonsPromises.register(Promise.resolve(), spaceId ?? GLOBAL_KEY);
3415
+ }
3416
+ }
3417
+
3418
+ /**
3419
+ * For internal use.
3420
+ * @internal
3421
+ */
3422
+ _forgetSpacesExcept(spaceIds) {
3423
+ const keptKeys = new Set([GLOBAL_KEY, ...spaceIds]);
3424
+ const removedKeys = Array.from(this.list.items.keys()).filter(key => !keptKeys.has(key));
3425
+ this.list.delete(...removedKeys);
3426
+ this.emoticonsPromises.forget(...removedKeys);
3427
+ }
2808
3428
  handleEmoticons(event) {
2809
3429
  const spaceId = event.location.spaceId ?? GLOBAL_KEY;
2810
3430
  if (!this.list.has(spaceId)) {
@@ -2860,6 +3480,14 @@ class UsersManager {
2860
3480
  async getAvailable() {
2861
3481
  return this.users;
2862
3482
  }
3483
+
3484
+ /**
3485
+ * For internal use.
3486
+ * @internal
3487
+ */
3488
+ _importUser(user) {
3489
+ this.handleUsers([user]);
3490
+ }
2863
3491
  handleMembers(members) {
2864
3492
  this.handleUsers(members.map(extractUserFromMember));
2865
3493
  }
@@ -2906,11 +3534,13 @@ function isSameUser(a, b) {
2906
3534
  ;// ./src/state-tracker/RelationshipsManager.ts
2907
3535
 
2908
3536
 
3537
+
2909
3538
  const getId = (refUserId, type) => `${refUserId}-${type}`;
2910
3539
  const getIdFromRelationship = relationship => getId(relationship.refUser.id, relationship.type);
2911
3540
  class RelationshipsManager {
2912
3541
  relationships = new ObservableIndexedObjectCollection(getIdFromRelationship);
2913
3542
  promises = new PromiseRegistry();
3543
+ loaded = false;
2914
3544
  constructor(tracker) {
2915
3545
  this.tracker = tracker;
2916
3546
  this.tracker.client.on('Relationships', ev => this.handleRelationships(ev));
@@ -2934,7 +3564,33 @@ class RelationshipsManager {
2934
3564
  await this.get();
2935
3565
  return this.relationships.has(getId(refUserId, type));
2936
3566
  }
3567
+
3568
+ /**
3569
+ * For internal use.
3570
+ * @internal
3571
+ */
3572
+ _exportRelationships() {
3573
+ return this.loaded ? this.relationships.items.map(relationship => ({
3574
+ ...relationship,
3575
+ refUser: withoutPresence(relationship.refUser)
3576
+ })) : null;
3577
+ }
3578
+
3579
+ /**
3580
+ * For internal use.
3581
+ * @internal
3582
+ */
3583
+ _importRelationships(relationships) {
3584
+ if (relationships) {
3585
+ this.handleRelationships({
3586
+ relationships
3587
+ });
3588
+ // Served from the snapshot until the session invalidates it.
3589
+ this.promises.register(Promise.resolve(), 'all');
3590
+ }
3591
+ }
2937
3592
  handleRelationships(ev) {
3593
+ this.loaded = true;
2938
3594
  // Full list from the server: reconcile in place so a reconnect refetch
2939
3595
  // updates a bound (visible) list without an intermediate empty state.
2940
3596
  this.relationships.reconcile(...ev.relationships);
@@ -2963,6 +3619,7 @@ class RelationshipsManager {
2963
3619
 
2964
3620
 
2965
3621
 
3622
+
2966
3623
  class ChatStateTracker {
2967
3624
  client;
2968
3625
 
@@ -2997,6 +3654,8 @@ class ChatStateTracker {
2997
3654
  relationships;
2998
3655
  _me = null;
2999
3656
  deferredSession = new DeferredTask();
3657
+ sessionReceived = false;
3658
+ snapshotImported = false;
3000
3659
  constructor(client) {
3001
3660
  this.client = client;
3002
3661
  this.client.on('Session', ev => this.handleSession(ev));
@@ -3006,6 +3665,9 @@ class ChatStateTracker {
3006
3665
  this.emoticons = new EmoticonsManager(this);
3007
3666
  this.users = new UsersManager(this);
3008
3667
  this.relationships = new RelationshipsManager(this);
3668
+
3669
+ // Registered after the managers, so it runs once they have applied the session.
3670
+ this.client.on('Session', ev => this.handleSessionAfterImport(ev));
3009
3671
  }
3010
3672
  get me() {
3011
3673
  return this._me;
@@ -3014,10 +3676,88 @@ class ChatStateTracker {
3014
3676
  await this.deferredSession.promise;
3015
3677
  return this._me;
3016
3678
  }
3679
+
3680
+ /**
3681
+ * Export the tracked state to a plain, JSON-serializable object, to be saved and restored with
3682
+ * {@link importSnapshot} at the next start of the application, before the connection is established.
3683
+ * See {@link StateSnapshot} for what is included.
3684
+ * @param intent What to include beyond the state that is always exported, e.g. the message histories.
3685
+ * @return Null if there is no state yet (no session has been received or imported).
3686
+ */
3687
+ exportSnapshot(intent = {}) {
3688
+ if (!this._me) {
3689
+ return null;
3690
+ }
3691
+ const snapshot = {
3692
+ version: STATE_SNAPSHOT_VERSION,
3693
+ createdAt: Date.now(),
3694
+ user: withoutPresence(this._me),
3695
+ spaces: this.spaces._exportSpaces(),
3696
+ rooms: this.rooms._exportRooms(),
3697
+ spaceRooms: this.spaces._exportSpaceRooms(),
3698
+ followedTopics: this.rooms.followedTopics._exportFollowedTopics(),
3699
+ emoticons: this.emoticons._exportEmoticons(),
3700
+ relationships: this.relationships._exportRelationships(),
3701
+ histories: this.rooms._exportHistories(intent),
3702
+ roomMembers: this.rooms._exportMembers((intent.histories ?? []).map(history => history.roomId), intent.roomMembersLimit ?? 0)
3703
+ };
3704
+
3705
+ // Detaches the snapshot from the live state objects and leaves nothing a JSON round trip would change.
3706
+ return JSON.parse(JSON.stringify(snapshot));
3707
+ }
3708
+
3709
+ /**
3710
+ * Restore the state exported with {@link exportSnapshot}, so it is available before the connection is
3711
+ * established. The collections emit their usual change events and the getters waiting for the session resolve.
3712
+ * The first `Session` from the server then replaces the restored state the same way it does on a reconnect:
3713
+ * removed spaces and rooms are dropped, the rest is updated in place, the restored message histories and topics
3714
+ * other than the default ones are fetched anew (as a window holding the latest messages is on a reconnect), and
3715
+ * the lazily loaded lists are refetched on their next access.
3716
+ *
3717
+ * Allowed only once and only before the first `Session`.
3718
+ * @return False if the snapshot was rejected (another version, malformed data, or a session already received) -
3719
+ * the state is not changed then.
3720
+ */
3721
+ importSnapshot(snapshot) {
3722
+ if (this.sessionReceived || this.snapshotImported || !isValidStateSnapshot(snapshot)) {
3723
+ return false;
3724
+ }
3725
+ this.snapshotImported = true;
3726
+ try {
3727
+ this._me = snapshot.user;
3728
+ this.users._importUser(snapshot.user);
3729
+ this.rooms._importRooms(snapshot.rooms);
3730
+ this.spaces._importSpaces(snapshot.spaces, snapshot.spaceRooms);
3731
+ this.rooms.followedTopics._importFollowedTopics(snapshot.followedTopics);
3732
+ this.emoticons._importEmoticons(snapshot.emoticons, snapshot.spaces.map(space => space.id));
3733
+ this.relationships._importRelationships(snapshot.relationships);
3734
+ this.rooms._importHistories(snapshot.histories, snapshot.roomMembers);
3735
+ } catch {
3736
+ // Not expected after the validation; whatever got restored is replaced by the first session anyway.
3737
+ return false;
3738
+ }
3739
+ this.deferredSession.resolve();
3740
+ return true;
3741
+ }
3017
3742
  handleSession(ev) {
3018
3743
  this._me = ev.user;
3744
+ this.sessionReceived = true;
3019
3745
  this.deferredSession.resolve();
3020
3746
  }
3747
+
3748
+ /**
3749
+ * A reconnect keeps the followed topics and emoticons of rooms and spaces that are gone; for the restored ones
3750
+ * the first session is the only chance to tell they are gone.
3751
+ */
3752
+ handleSessionAfterImport(ev) {
3753
+ if (!this.snapshotImported) {
3754
+ return;
3755
+ }
3756
+ this.snapshotImported = false;
3757
+ this.rooms.followedTopics._forgetRoomsExcept(ev.state.rooms.map(room => room.id));
3758
+ this.emoticons._forgetSpacesExcept(ev.state.spaces.map(space => space.id));
3759
+ this.rooms._refreshImportedTopics();
3760
+ }
3021
3761
  }
3022
3762
  ;// ./src/WebSocketChatClient.ts
3023
3763
 
@@ -3504,21 +4244,6 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
3504
4244
  ErrorCode["UserNotFound"] = "UserNotFoundException";
3505
4245
  return ErrorCode;
3506
4246
  }({});
3507
- ;// ./src/protocol/schemes/User.ts
3508
- /**
3509
- * Availability of a user, aggregated over all of their sessions.
3510
- *
3511
- * - `Offline` - no session is connected and none can be reached asynchronously.
3512
- * - `Online` - at least one session holds a live connection.
3513
- * - `OnlineAsync` - no live connection, but a push-registered device was active
3514
- * recently, so a message will still reach the user.
3515
- */
3516
- let UserStatus = /*#__PURE__*/function (UserStatus) {
3517
- UserStatus[UserStatus["Offline"] = 0] = "Offline";
3518
- UserStatus[UserStatus["Online"] = 1] = "Online";
3519
- UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
3520
- return UserStatus;
3521
- }({});
3522
4247
  ;// ./src/protocol/schemes/Role.ts
3523
4248
  /**
3524
4249
  * Bit flags of a role, stored in {@link Role.flags}.
@@ -3650,6 +4375,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
3650
4375
 
3651
4376
 
3652
4377
 
4378
+
3653
4379
  module.exports = __webpack_exports__;
3654
4380
  /******/ })()
3655
4381
  ;