@devanachat/sdk 0.8.0 → 0.9.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.
package/build/index.mjs CHANGED
@@ -439,7 +439,8 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
439
439
  retainRatio: 1,
440
440
  fetchLimit: 50,
441
441
  lastFetchCount: 0,
442
- oldestId: null
442
+ oldestId: null,
443
+ gaps: []
443
444
  };
444
445
 
445
446
  /**
@@ -494,6 +495,16 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
494
495
  get hasLatest() {
495
496
  return [WindowState.LATEST, WindowState.LIVE].includes(this.state);
496
497
  }
498
+
499
+ /**
500
+ * IDs of the items with a gap in front of them: the item right above in the window is not the real predecessor,
501
+ * an unknown number of items in between was never fetched. Such a seam appears when {@link resyncToLatest} gets
502
+ * a full page that does not reach the loaded items. A marker lives as long as its item stays in the window and
503
+ * is closed once the items right before it are fetched.
504
+ */
505
+ get gaps() {
506
+ return this.internalState.gaps;
507
+ }
497
508
  get hasOldest() {
498
509
  return this.state === WindowState.OLDEST || this.state === WindowState.LATEST && this.length < this.fetchLimit || this.internalState.oldestId !== null && this.has(this.internalState.oldestId);
499
510
  }
@@ -503,15 +514,51 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
503
514
  }
504
515
  let result;
505
516
  const originalState = this.state;
506
- this.internalState.ongoing = WindowState.LATEST;
517
+ this.beginFetch(WindowState.LATEST);
518
+ try {
519
+ result = await this.fetchLatestItems();
520
+ this.internalState.lastFetchCount = result.length;
521
+ } finally {
522
+ this.endFetch();
523
+ }
524
+ this.replaceItems(result);
525
+ this.internalState.current = WindowState.LATEST;
526
+ this.emitChangeWithDiff(true, originalState);
527
+ }
528
+
529
+ /**
530
+ * Refresh the window with the latest page, keeping the already loaded items instead of replacing them - the
531
+ * reconnect-friendly variant of {@link resetToLatest}. The page is merged on top of the loaded items (an item in
532
+ * both is taken from the page) and only the window size limit pushes the oldest ones out. When the page is full
533
+ * and does not reach the newest loaded item, both parts are still kept and the seam is recorded in {@link gaps}.
534
+ */
535
+ async resyncToLatest() {
536
+ if (this.internalState.ongoing) {
537
+ return;
538
+ }
539
+ let result;
540
+ const originalState = this.state;
541
+ this.beginFetch(WindowState.LATEST);
507
542
  try {
508
543
  result = await this.fetchLatestItems();
509
544
  this.internalState.lastFetchCount = result.length;
510
545
  } finally {
511
- this.internalState.ongoing = undefined;
546
+ this.endFetch();
547
+ }
548
+ const loaded = this.items;
549
+ const fetchedIds = new Set(result.map(item => this.getId(item)));
550
+ const retained = loaded.filter(item => !fetchedIds.has(this.getId(item)));
551
+
552
+ // A page shorter than the limit is everything the remote side has, so nothing can be missing in between.
553
+ const isContinuous = !retained.length || result.length < this.internalState.fetchLimit || fetchedIds.has(this.getId(loaded[loaded.length - 1]));
554
+
555
+ // The page is continuous, so only its first item can have a gap in front of it.
556
+ this.forgetGapsOf(result.slice(1).map(item => this.getId(item)));
557
+ if (!isContinuous && !this.internalState.gaps.includes(this.getId(result[0]))) {
558
+ this.internalState.gaps = [...this.internalState.gaps, this.getId(result[0])];
512
559
  }
513
560
  this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
514
- this.addItems(result, 'tail');
561
+ this.addItems([...retained, ...result], 'tail');
515
562
  this.internalState.current = WindowState.LATEST;
516
563
  this.emitChangeWithDiff(true, originalState);
517
564
  }
@@ -521,18 +568,18 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
521
568
  }
522
569
  let result;
523
570
  const originalState = this.state;
524
- this.internalState.ongoing = WindowState.PAST;
571
+ const firstItem = this.getAt(0);
572
+ this.beginFetch(WindowState.PAST);
525
573
  try {
526
574
  result = await this.fetchItemsBefore();
527
575
  this.internalState.lastFetchCount = result ? result.length : 0;
528
576
  } finally {
529
- this.internalState.ongoing = undefined;
577
+ this.endFetch();
530
578
  }
531
579
  if (!result) {
532
580
  return this.resetToLatest();
533
581
  }
534
582
  if (!result.length) {
535
- const firstItem = this.getAt(0);
536
583
  this.internalState.oldestId = firstItem ? this.getId(firstItem) : null;
537
584
  await this.refreshFetchedState();
538
585
 
@@ -543,6 +590,10 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
543
590
  this.emitChangeWithDiff(false, originalState);
544
591
  return;
545
592
  }
593
+ if (firstItem) {
594
+ // The page was fetched as the direct predecessors of the first item, so a gap in front of it is closed.
595
+ this.forgetGapsOf([this.getId(firstItem)]);
596
+ }
546
597
  this.addItems(result, 'head');
547
598
  await this.refreshFetchedState();
548
599
  this.emitChangeWithDiff(true, originalState);
@@ -563,12 +614,12 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
563
614
  }
564
615
  let result;
565
616
  const originalState = this.state;
566
- this.internalState.ongoing = WindowState.PAST;
617
+ this.beginFetch(WindowState.PAST);
567
618
  try {
568
619
  result = await this.fetchItemsAfter();
569
620
  this.internalState.lastFetchCount = result ? result.length : 0;
570
621
  } finally {
571
- this.internalState.ongoing = undefined;
622
+ this.endFetch();
572
623
  }
573
624
  if (!result) {
574
625
  await this.resetToLatest(true);
@@ -581,26 +632,41 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
581
632
  return;
582
633
  }
583
634
  }
635
+
636
+ /**
637
+ * Load the items around the given one. Asked for while another fetch is running, it waits for that fetch to end
638
+ * instead of being dropped - when the call returns, the window either holds the item or it could not be loaded.
639
+ */
584
640
  async jumpTo(id) {
585
- if (this.internalState.ongoing || this.state !== WindowState.LIVE && this._items.has(id)) {
641
+ while (this.internalState.ongoing) {
642
+ await this.internalState.fetchSettled;
643
+ }
644
+ if (this.state !== WindowState.LIVE && this._items.has(id)) {
586
645
  return;
587
646
  }
588
647
  let result;
589
648
  const originalState = this.state;
590
- this.internalState.ongoing = WindowState.PAST;
649
+ this.beginFetch(WindowState.PAST);
591
650
  try {
592
651
  result = await this.fetchItemsAround(id);
593
652
  this.internalState.lastFetchCount = result ? result.length : 0;
594
653
  if (result) {
595
- this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
596
- this.addItems(result, 'tail');
654
+ this.replaceItems(result);
597
655
  await this.refreshFetchedState();
598
656
  }
599
657
  } finally {
600
- this.internalState.ongoing = undefined;
658
+ this.endFetch();
601
659
  }
602
660
  this.emitChangeWithDiff(!!result, originalState);
603
661
  }
662
+ delete(...ids) {
663
+ super.delete(...ids);
664
+ this.forgetGapsOf(ids);
665
+ }
666
+ deleteAll() {
667
+ super.deleteAll();
668
+ this.internalState.gaps = [];
669
+ }
604
670
  async refreshFetchedState() {
605
671
  this.internalState.current = (await this.isLatestItemLoaded()) ? WindowState.LATEST : WindowState.PAST;
606
672
  }
@@ -623,6 +689,29 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
623
689
  this._items.set(...entries, ...loaded);
624
690
  return this.trimTail(this.getLowWatermark(highWatermark));
625
691
  }
692
+ beginFetch(kind) {
693
+ this.internalState.ongoing = kind;
694
+ this.internalState.fetchSettled = new Promise(resolve => this.internalState.settleFetch = resolve);
695
+ }
696
+ endFetch() {
697
+ this.internalState.ongoing = undefined;
698
+ this.internalState.settleFetch?.();
699
+ }
700
+
701
+ /**
702
+ * Replace the whole content without emitting an event; the old gap markers mean nothing for the new content.
703
+ */
704
+ replaceItems(items) {
705
+ this._items.deleteAll();
706
+ this.internalState.gaps = [];
707
+ this.addItems(items, 'tail');
708
+ }
709
+ forgetGapsOf(ids) {
710
+ if (this.internalState.gaps.length && ids.length) {
711
+ const removed = new Set(ids);
712
+ this.internalState.gaps = this.internalState.gaps.filter(id => !removed.has(id));
713
+ }
714
+ }
626
715
  emitChangeWithDiff(itemChanged, originalState) {
627
716
  if (itemChanged || originalState !== this.state) {
628
717
  this.eventTarget.emit('change', {
@@ -649,6 +738,7 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
649
738
  deletedItems.push(id);
650
739
  }
651
740
  this._items.delete(...deletedItems);
741
+ this.forgetGapsOf(deletedItems);
652
742
  if (this.internalState.current === WindowState.OLDEST) {
653
743
  this.internalState.current = WindowState.PAST;
654
744
  }
@@ -660,6 +750,7 @@ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
660
750
  }
661
751
  const deletedItems = Array.from(this._items.items.keys()).slice(keep);
662
752
  this._items.delete(...deletedItems);
753
+ this.forgetGapsOf(deletedItems);
663
754
  return deletedItems;
664
755
  }
665
756
 
@@ -752,6 +843,12 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
752
843
  }
753
844
  return super.resetToLatest(force);
754
845
  }
846
+ async resyncToLatest() {
847
+ if (this.internalState.traverseLock) {
848
+ return;
849
+ }
850
+ return super.resyncToLatest();
851
+ }
755
852
  async fetchNext() {
756
853
  if (this.internalState.traverseLock) {
757
854
  return;
@@ -782,7 +879,10 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
782
879
  if (this.state !== WindowState.LATEST) {
783
880
  return null;
784
881
  }
785
- const messages = this.items.slice(-Math.max(limit, this.fetchLimit));
882
+ const items = this.items;
883
+ // A restored window is taken for continuous, so nothing above the newest gap goes into it.
884
+ const continuousFrom = Math.max(0, ...this.internalState.gaps.map(id => items.findIndex(item => item.id === id)));
885
+ const messages = items.slice(Math.max(continuousFrom, items.length - Math.max(limit, this.fetchLimit)));
786
886
  const myReactions = {};
787
887
  for (const message of messages) {
788
888
  if (this.internalState.myReactions[message.id]) {
@@ -802,8 +902,7 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
802
902
  */
803
903
  _restoreLatest(messages, myReactions) {
804
904
  const originalState = this.state;
805
- this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
806
- this.addItems(messages, 'tail');
905
+ this.replaceItems(messages);
807
906
  this.internalState.myReactions = {
808
907
  ...myReactions
809
908
  };
@@ -976,10 +1075,12 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
976
1075
  value
977
1076
  });
978
1077
  }
979
- const {
980
- [ev.messageId]: _previous,
981
- ...myReactions
982
- } = this.internalState.myReactions;
1078
+
1079
+ // Not `{[ev.messageId]: _, ...rest}` - Babel's loose object rest drops the key when the binding is unused (babel/babel#18196)
1080
+ const myReactions = {
1081
+ ...this.internalState.myReactions
1082
+ };
1083
+ delete myReactions[ev.messageId];
983
1084
  if (own.length) {
984
1085
  myReactions[ev.messageId] = own;
985
1086
  }
@@ -1017,6 +1118,7 @@ class RoomMessagesHistory {
1017
1118
  roomId;
1018
1119
  historyWindows = new IndexedCollection();
1019
1120
  traverseLock = false;
1121
+ timeLimitedHistory = false;
1020
1122
  room;
1021
1123
  constructor(room, tracker) {
1022
1124
  this.tracker = tracker;
@@ -1024,7 +1126,7 @@ class RoomMessagesHistory {
1024
1126
  this.room = typeof room === 'string' ? null : room;
1025
1127
  this.isPreview = this.room === null;
1026
1128
  if (this.room) {
1027
- this.updateTraverseLock(this.room);
1129
+ this.updateHistoryMode(this.room);
1028
1130
  }
1029
1131
  if (this.room?.defaultTopic) {
1030
1132
  this.createHistoryWindowForTopic(this.room.defaultTopic);
@@ -1057,13 +1159,19 @@ class RoomMessagesHistory {
1057
1159
  *
1058
1160
  * The window bindings are preserved; only windows that the application had
1059
1161
  * actually pulled to the latest page (state === LATEST) are refreshed, with
1060
- * a single resetToLatest instead of a chain of catch-up requests. Windows
1061
- * that were never pulled (LIVE) or belong to an ephemeral room are left
1162
+ * a single request instead of a chain of catch-up requests. Windows that
1163
+ * were never pulled (LIVE) or belong to an ephemeral room are left
1062
1164
  * untouched so their in-memory context survives the reconnect.
1165
+ *
1166
+ * Rooms keeping the full history are reset to the latest page (the rest can
1167
+ * always be traversed back), while the windows of rooms with a time-limited
1168
+ * history (MaxAge) keep what they had loaded and get the missed messages on
1169
+ * top - the server may no longer serve the older ones. If more messages were
1170
+ * missed than a single page holds, the seam is recorded in the window gaps.
1063
1171
  */
1064
1172
  async resync(room) {
1065
1173
  this.room = room;
1066
- this.updateTraverseLock(room);
1174
+ this.updateHistoryMode(room);
1067
1175
  if (this.room.defaultTopic) {
1068
1176
  this.createHistoryWindowForTopic(this.room.defaultTopic);
1069
1177
  }
@@ -1076,7 +1184,12 @@ class RoomMessagesHistory {
1076
1184
  if (this.traverseLock) {
1077
1185
  continue;
1078
1186
  }
1079
- if (window.state === WindowState.LATEST) {
1187
+ if (window.state !== WindowState.LATEST) {
1188
+ continue;
1189
+ }
1190
+ if (this.timeLimitedHistory) {
1191
+ await window.resyncToLatest();
1192
+ } else {
1080
1193
  await window.resetToLatest(true);
1081
1194
  }
1082
1195
  } catch (_e) {
@@ -1118,7 +1231,7 @@ class RoomMessagesHistory {
1118
1231
  */
1119
1232
  async _handleRoomUpdated(ev) {
1120
1233
  this.room = ev.room;
1121
- this.updateTraverseLock(ev.room);
1234
+ this.updateHistoryMode(ev.room);
1122
1235
  if (ev.room.defaultTopic) {
1123
1236
  this.createHistoryWindowForTopic(ev.room.defaultTopic);
1124
1237
  }
@@ -1204,8 +1317,9 @@ class RoomMessagesHistory {
1204
1317
  this.tracker.rooms._deleteTopicsFromRoom(this.roomId, ...deletedTopicIds);
1205
1318
  });
1206
1319
  }
1207
- updateTraverseLock(room) {
1320
+ updateHistoryMode(room) {
1208
1321
  this.traverseLock = room.history.mode === 'Ephemeral';
1322
+ this.timeLimitedHistory = room.history.mode === 'MaxAge';
1209
1323
  }
1210
1324
  }
1211
1325
  ;// ./src/state-tracker/MessagesManager.ts
@@ -1999,7 +2113,15 @@ class RoomsManager {
1999
2113
  const promise = this.tracker.client.send('GetTopics', {
2000
2114
  roomId,
2001
2115
  topicIds: idsToFetch
2002
- }).then(result => this.topics.get(result.data.location.roomId)?.set(...result.data.topics));
2116
+ }).then(result => {
2117
+ const topics = this.topics.get(roomId);
2118
+ if (topics) {
2119
+ topics.set(...result.data.topics);
2120
+ } else {
2121
+ // A room not joined yet has nowhere to keep them - let them be fetched again once it is.
2122
+ this.topicsPromises.forget(...idsToFetch.map(topicId => roomId + topicId));
2123
+ }
2124
+ });
2003
2125
  idsToFetch.forEach(topicId => this.topicsPromises.register(promise, roomId + topicId));
2004
2126
  }
2005
2127
  for (const topicId of tryToFetchTopicIds) {
@@ -2903,6 +3025,10 @@ class Permissions {
2903
3025
  SearchMessages: {
2904
3026
  value: 1 << 25,
2905
3027
  maxLayer: Layer.Room
3028
+ },
3029
+ UseExternalEmoticons: {
3030
+ value: 1 << 26,
3031
+ maxLayer: Layer.Room
2906
3032
  }
2907
3033
  };
2908
3034
  static getNames() {
@@ -3196,7 +3322,6 @@ class PermissionsManager extends EventTarget {
3196
3322
  ;// ./src/state-tracker/EmoticonsManager.ts
3197
3323
 
3198
3324
 
3199
- const GLOBAL_KEY = 'global';
3200
3325
  class EmoticonsManager {
3201
3326
  list = new IndexedCollection();
3202
3327
  emoticonsPromises = new PromiseRegistry();
@@ -3209,8 +3334,7 @@ class EmoticonsManager {
3209
3334
  this.tracker.client.on('Session', () => this.handleSession());
3210
3335
  }
3211
3336
  async get(spaceId) {
3212
- const key = spaceId ?? GLOBAL_KEY;
3213
- if (this.emoticonsPromises.notExist(key)) {
3337
+ if (this.emoticonsPromises.notExist(spaceId)) {
3214
3338
  this.emoticonsPromises.registerByFunction(async () => {
3215
3339
  const result = await this.tracker.client.send('GetEmoticons', {
3216
3340
  spaceId
@@ -3219,10 +3343,10 @@ class EmoticonsManager {
3219
3343
  throw result.error;
3220
3344
  }
3221
3345
  this.handleEmoticons(result.data);
3222
- }, key);
3346
+ }, spaceId);
3223
3347
  }
3224
- await this.emoticonsPromises.get(key);
3225
- return this.list.get(key);
3348
+ await this.emoticonsPromises.get(spaceId);
3349
+ return this.list.get(spaceId);
3226
3350
  }
3227
3351
 
3228
3352
  /**
@@ -3230,8 +3354,8 @@ class EmoticonsManager {
3230
3354
  * @internal
3231
3355
  */
3232
3356
  _exportEmoticons() {
3233
- return Array.from(this.list.items).map(([key, emoticons]) => ({
3234
- spaceId: key === GLOBAL_KEY ? null : key,
3357
+ return Array.from(this.list.items).map(([spaceId, emoticons]) => ({
3358
+ spaceId,
3235
3359
  emoticons: emoticons.items
3236
3360
  }));
3237
3361
  }
@@ -3246,17 +3370,19 @@ class EmoticonsManager {
3246
3370
  spaceId,
3247
3371
  emoticons
3248
3372
  } of snapshots) {
3249
- if (spaceId !== null && !joinedSpaceIds.has(spaceId)) {
3373
+ // TODO(emoticons-compat): snapshots written before the global emoticons were gone still hold them under
3374
+ // null - drop the comment once no such snapshot can be left on a device (the check itself stays).
3375
+ if (!joinedSpaceIds.has(spaceId)) {
3250
3376
  continue;
3251
3377
  }
3252
3378
  this.handleEmoticons({
3253
3379
  location: {
3254
- spaceId: spaceId ?? undefined
3380
+ spaceId
3255
3381
  },
3256
3382
  emoticons
3257
3383
  });
3258
3384
  // Served from the snapshot until the session invalidates it.
3259
- this.emoticonsPromises.register(Promise.resolve(), spaceId ?? GLOBAL_KEY);
3385
+ this.emoticonsPromises.register(Promise.resolve(), spaceId);
3260
3386
  }
3261
3387
  }
3262
3388
 
@@ -3265,13 +3391,19 @@ class EmoticonsManager {
3265
3391
  * @internal
3266
3392
  */
3267
3393
  _forgetSpacesExcept(spaceIds) {
3268
- const keptKeys = new Set([GLOBAL_KEY, ...spaceIds]);
3394
+ const keptKeys = new Set(spaceIds);
3269
3395
  const removedKeys = Array.from(this.list.items.keys()).filter(key => !keptKeys.has(key));
3270
3396
  this.list.delete(...removedKeys);
3271
3397
  this.emoticonsPromises.forget(...removedKeys);
3272
3398
  }
3273
3399
  handleEmoticons(event) {
3274
- const spaceId = event.location.spaceId ?? GLOBAL_KEY;
3400
+ // A selection by ids has no location.
3401
+ // TODO(emoticons-compat): one without a space is the always empty list of the gone global emoticons, sent
3402
+ // until the server stops answering old clients that way.
3403
+ const spaceId = event.location?.spaceId;
3404
+ if (!spaceId) {
3405
+ return;
3406
+ }
3275
3407
  if (!this.list.has(spaceId)) {
3276
3408
  this.list.set([spaceId, new ObservableIndexedObjectCollection('id')]);
3277
3409
  }
@@ -3282,11 +3414,11 @@ class EmoticonsManager {
3282
3414
  this.list.get(spaceId).reconcile(...event.emoticons);
3283
3415
  }
3284
3416
  handleNewEmoticon(ev) {
3285
- const collection = this.list.get(ev.emoticon.spaceId ?? GLOBAL_KEY);
3417
+ const collection = this.list.get(ev.emoticon.spaceId);
3286
3418
  collection?.set(ev.emoticon);
3287
3419
  }
3288
3420
  handleEmoticonDeleted(ev) {
3289
- const collection = this.list.get(ev.spaceId ?? GLOBAL_KEY);
3421
+ const collection = this.list.get(ev.spaceId);
3290
3422
  collection?.delete(ev.emoticonId);
3291
3423
  }
3292
3424
  handleSpaceDeleted(event) {
@@ -4169,6 +4301,7 @@ let UserFeature = /*#__PURE__*/function (UserFeature) {
4169
4301
  UserFeature["MessageLength"] = "user.message.length";
4170
4302
  UserFeature["StorageLimit"] = "user.storage.limit";
4171
4303
  UserFeature["StorageSingleFileLimit"] = "user.storage.single_file_limit";
4304
+ UserFeature["ExternalEmoticons"] = "user.external_emoticons";
4172
4305
  return UserFeature;
4173
4306
  }({});
4174
4307