@devanachat/sdk 0.14.0 → 0.16.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 (33) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/build/index.cjs.js +521 -54
  3. package/build/index.cjs.js.map +1 -1
  4. package/build/index.mjs +520 -54
  5. package/build/index.mjs.map +1 -1
  6. package/build/index.umd.js +1 -1
  7. package/build/index.umd.js.map +1 -1
  8. package/build/types/AbstractChatClient.d.ts +15 -2
  9. package/build/types/Permissions.d.ts +4 -0
  10. package/build/types/index.d.ts +4 -2
  11. package/build/types/protocol/index.d.ts +17 -2
  12. package/build/types/protocol/schemes/Activity.d.ts +16 -0
  13. package/build/types/protocol/schemes/SavedItem.d.ts +7 -0
  14. package/build/types/protocol/schemes/commands/GetActivities.d.ts +3 -0
  15. package/build/types/protocol/schemes/commands/GetPermissionOverwrites.d.ts +17 -1
  16. package/build/types/protocol/schemes/commands/GetSavedItems.d.ts +3 -0
  17. package/build/types/protocol/schemes/commands/SaveItem.d.ts +5 -0
  18. package/build/types/protocol/schemes/commands/UnsaveItem.d.ts +5 -0
  19. package/build/types/protocol/schemes/commands/UpdateActivities.d.ts +4 -0
  20. package/build/types/protocol/schemes/events/Activities.d.ts +9 -0
  21. package/build/types/protocol/schemes/events/ActivityDeleted.d.ts +3 -0
  22. package/build/types/protocol/schemes/events/ActivityUpdated.d.ts +4 -0
  23. package/build/types/protocol/schemes/events/Error.d.ts +3 -1
  24. package/build/types/protocol/schemes/events/ItemSaved.d.ts +6 -0
  25. package/build/types/protocol/schemes/events/ItemUnsaved.d.ts +5 -0
  26. package/build/types/protocol/schemes/events/NewActivity.d.ts +8 -0
  27. package/build/types/protocol/schemes/events/PermissionOverwritesList.d.ts +4 -0
  28. package/build/types/protocol/schemes/events/SavedItems.d.ts +6 -0
  29. package/build/types/state-tracker/ActivitiesManager.d.ts +63 -0
  30. package/build/types/state-tracker/ChatStateTracker.d.ts +13 -0
  31. package/build/types/state-tracker/PermissionsManager.d.ts +8 -2
  32. package/build/types/state-tracker/SavedItemsManager.d.ts +46 -0
  33. package/package.json +1 -1
@@ -69,7 +69,8 @@ __webpack_require__.d(__webpack_exports__, {
69
69
  WebSocketChatClient: () => (/* reexport */ WebSocketChatClient),
70
70
  extractUserFromMember: () => (/* reexport */ extractUserFromMember),
71
71
  getPmPeers: () => (/* reexport */ getPmPeers),
72
- isGroupPm: () => (/* reexport */ isGroupPm)
72
+ isGroupPm: () => (/* reexport */ isGroupPm),
73
+ savedItemKey: () => (/* reexport */ savedItemKey)
73
74
  });
74
75
 
75
76
  ;// ./src/EventTarget.ts
@@ -3553,6 +3554,10 @@ class Permissions {
3553
3554
  ManageCalls: {
3554
3555
  value: 2 ** 33,
3555
3556
  maxLayer: Layer.Room
3557
+ },
3558
+ StartCalls: {
3559
+ value: 2 ** 34,
3560
+ maxLayer: Layer.Room
3556
3561
  }
3557
3562
  };
3558
3563
 
@@ -3610,6 +3615,7 @@ class Permissions {
3610
3615
 
3611
3616
 
3612
3617
  const getOvId = (location, target) => [location.spaceId, location.roomId, location.topicId, target?.type, target?.userId, target?.roleId].filter(Boolean).join('/');
3618
+ const FETCH_CHUNK_SIZE = 50;
3613
3619
  const getOvIdByObject = overwrites => getOvId(overwrites.location, overwrites.target);
3614
3620
  class PermissionsManager extends EventTarget {
3615
3621
  overwrites = new IndexedCollection();
@@ -3629,23 +3635,18 @@ class PermissionsManager extends EventTarget {
3629
3635
  this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
3630
3636
  this.tracker.client.on('Session', ev => this.handleSession(ev));
3631
3637
  }
3638
+
3639
+ /**
3640
+ * Cached: kept up to date only for your own overwrites and those of your roles in the locations you belong to.
3641
+ * For live overwrites of another target send `GetPermissionOverwrites` yourself.
3642
+ */
3632
3643
  async getOverwrites(location, target) {
3633
3644
  this.validateLocation(location);
3634
- const id = getOvId(location, target);
3635
- if (this.overwritesPromises.notExist(id)) {
3636
- this.overwritesPromises.registerByFunction(async () => {
3637
- const result = await this.tracker.client.send('GetPermissionOverwrites', {
3638
- location,
3639
- target
3640
- });
3641
- if (result.error) {
3642
- throw result.error;
3643
- }
3644
- this.handlePermissionOverwrites(result.data);
3645
- }, id);
3646
- }
3647
- await this.overwritesPromises.get(id);
3648
- return this.overwrites.get(id);
3645
+ await this.fetchOverwrites([{
3646
+ location,
3647
+ target
3648
+ }]);
3649
+ return this.overwrites.get(getOvId(location, target));
3649
3650
  }
3650
3651
  async check(permissionNames, location) {
3651
3652
  if (!permissionNames.length) {
@@ -3680,54 +3681,111 @@ class PermissionsManager extends EventTarget {
3680
3681
  if (location.roomId && !room || location.spaceId && !(await this.tracker.spaces.get())?.has(location.spaceId)) {
3681
3682
  return this.fetchComputedPermissions(location);
3682
3683
  }
3683
- const userId = (await this.tracker.getMe()).id;
3684
+ const me = {
3685
+ type: 'User',
3686
+ userId: (await this.tracker.getMe()).id
3687
+ };
3684
3688
  const [spaceMember, roomMember] = await this.fetchMembersOrFail(location);
3685
3689
  const userRoles = [...(spaceMember?.roles ?? []), ...(roomMember?.roles ?? [])];
3686
- const promises = [
3687
- // Global user overwrites
3688
- this.getOverwrites({}, {
3689
- type: 'User',
3690
- userId
3691
- }).then(v => v.overwrites)];
3690
+ const layers = [{
3691
+ location: {},
3692
+ withRoles: false
3693
+ }];
3692
3694
  if (location.spaceId && (await this.tracker.spaces.get())?.has(location.spaceId)) {
3693
- const filterLocation = {
3694
- spaceId: location.spaceId
3695
- };
3696
- promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
3697
- promises.push(this.getOverwrites(filterLocation, {
3698
- type: 'User',
3699
- userId
3700
- }).then(v => v.overwrites));
3695
+ layers.push({
3696
+ location: {
3697
+ spaceId: location.spaceId
3698
+ },
3699
+ withRoles: true
3700
+ });
3701
3701
  }
3702
3702
  if (room) {
3703
- const filterLocation = {
3704
- spaceId: location.spaceId,
3705
- roomId: location.roomId
3706
- };
3707
- if (userRoles.length) {
3708
- promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
3709
- }
3710
- promises.push(this.getOverwrites(filterLocation, {
3711
- type: 'User',
3712
- userId
3713
- }).then(v => v.overwrites));
3703
+ layers.push({
3704
+ location: {
3705
+ spaceId: location.spaceId,
3706
+ roomId: location.roomId
3707
+ },
3708
+ withRoles: userRoles.length > 0
3709
+ });
3714
3710
  }
3715
3711
  if (location.topicId && (await this.tracker.rooms.getTopics(location.roomId))?.has(location.topicId)) {
3716
- if (userRoles.length) {
3717
- promises.push(this.collectRoleOverwrites(location, userRoles));
3712
+ layers.push({
3713
+ location,
3714
+ withRoles: userRoles.length > 0
3715
+ });
3716
+ }
3717
+ const queries = [];
3718
+ for (const layer of layers) {
3719
+ if (layer.withRoles) {
3720
+ queries.push(...userRoles.map(roleId => ({
3721
+ location: layer.location,
3722
+ target: {
3723
+ type: 'Role',
3724
+ roleId
3725
+ }
3726
+ })));
3718
3727
  }
3719
- promises.push(this.getOverwrites(location, {
3720
- type: 'User',
3721
- userId
3722
- }).then(v => v.overwrites));
3728
+ queries.push({
3729
+ location: layer.location,
3730
+ target: me
3731
+ });
3732
+ }
3733
+ await this.fetchOverwrites(queries);
3734
+ const values = [];
3735
+ for (const layer of layers) {
3736
+ if (layer.withRoles) {
3737
+ values.push(...this.collectRoleOverwrites(layer.location, userRoles));
3738
+ }
3739
+ values.push(this.getFetchedOverwrites(layer.location, me).overwrites);
3740
+ }
3741
+ return this.resolveOverwritesHierarchy(values);
3742
+ }
3743
+
3744
+ // Chunked by queries only: a calculation refers to at most 4 locations, the server limit for one request
3745
+ async fetchOverwrites(queries) {
3746
+ const missing = new Map();
3747
+ for (const query of queries) {
3748
+ const id = getOvId(query.location, query.target);
3749
+ if (this.overwritesPromises.notExist(id)) {
3750
+ missing.set(id, query);
3751
+ }
3752
+ }
3753
+ const pending = [...missing];
3754
+ for (let i = 0; i < pending.length; i += FETCH_CHUNK_SIZE) {
3755
+ const chunk = pending.slice(i, i + FETCH_CHUNK_SIZE);
3756
+ const request = this.requestOverwrites(chunk.map(([, query]) => query));
3757
+ for (const [id] of chunk) {
3758
+ this.overwritesPromises.register(request, id);
3759
+ }
3760
+ }
3761
+ await Promise.all(queries.map(query => this.overwritesPromises.get(getOvId(query.location, query.target))));
3762
+ }
3763
+ async requestOverwrites(queries) {
3764
+ const result = await this.tracker.client.send('GetPermissionOverwrites', {
3765
+ queries
3766
+ });
3767
+ if (result.error) {
3768
+ throw result.error;
3769
+ }
3770
+ const results = 'results' in result.data ? result.data.results : [];
3771
+ if (results.length !== queries.length) {
3772
+ throw new Error(`Expected ${queries.length} permission overwrites, received ${results.length}`);
3773
+ }
3774
+ for (const overwrites of results) {
3775
+ this.handlePermissionOverwrites(overwrites);
3776
+ }
3777
+ }
3778
+ getFetchedOverwrites(location, target) {
3779
+ const overwrites = this.overwrites.get(getOvId(location, target));
3780
+ if (!overwrites) {
3781
+ throw new Error(`Permission overwrites of ${getOvId(location, target)} are not fetched`);
3723
3782
  }
3724
- return this.resolveOverwritesHierarchy([].concat(...(await Promise.all(promises))));
3783
+ return overwrites;
3725
3784
  }
3726
3785
 
3727
3786
  /**
3728
3787
  * Arriving overwrites change the permissions only when they replace different ones. The first ones fetched for a
3729
- * key have not been part of any result yet - every calculation needing them awaits their fetch - and a fetch
3730
- * response arrives twice, as the command result and as an event.
3788
+ * key have not been part of any result yet - every calculation needing them awaits their fetch.
3731
3789
  */
3732
3790
  handlePermissionOverwrites(ev) {
3733
3791
  const id = getOvIdByObject(ev);
@@ -3793,11 +3851,11 @@ class PermissionsManager extends EventTarget {
3793
3851
  });
3794
3852
  return ids;
3795
3853
  }
3796
- async collectRoleOverwrites(location, userRoles) {
3797
- const roleOverwrites = await Promise.all(userRoles.map(roleId => this.getOverwrites(location, {
3854
+ collectRoleOverwrites(location, userRoles) {
3855
+ const roleOverwrites = userRoles.map(roleId => this.getFetchedOverwrites(location, {
3798
3856
  type: 'Role',
3799
3857
  roleId
3800
- })));
3858
+ }));
3801
3859
  // The space default role (everyone) has the space id; it is applied before the other roles, as on the server.
3802
3860
  const isDefaultRole = overwrites => overwrites.target.roleId === location.spaceId;
3803
3861
  return [this.mergeRolesOverwrites(roleOverwrites.filter(isDefaultRole)), this.mergeRolesOverwrites(roleOverwrites.filter(overwrites => !isDefaultRole(overwrites)))];
@@ -4320,6 +4378,395 @@ class CallsManager {
4320
4378
  this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4321
4379
  }
4322
4380
  }
4381
+ ;// ./src/state-tracker/ActivitiesManager.ts
4382
+
4383
+
4384
+
4385
+ // Mirror the server, so a live activity joins its group as the stored one did
4386
+ const VISIBLE_LIMIT = 20;
4387
+ const GROUP_SCAN = 5;
4388
+ const MAX_ACTORS = 3;
4389
+ const time = isoDate => isoDate ? Date.parse(isoDate) : 0;
4390
+ const newestFirst = (a, b) => time(b.createdAt) - time(a.createdAt);
4391
+
4392
+ // A reaction is to one's own message, so acknowledging it says nothing about the reaction
4393
+ const isReadWithAck = activity => activity.type !== 'Reaction' && activity.type !== 'Custom';
4394
+
4395
+ // Message ids are time-ordered and their base58 form has a fixed length, so they compare as strings
4396
+ const isAcknowledged = (activity, topicId, lastAckMessageId) => isReadWithAck(activity) && activity.location?.topicId === topicId && activity.messageId !== null && activity.messageId <= lastAckMessageId;
4397
+ class ActivitiesManager extends EventTarget {
4398
+ activities = new ObservableIndexedObjectCollection('id');
4399
+ messages = new ObservableIndexedObjectCollection('id');
4400
+ users = new ObservableIndexedObjectCollection('id');
4401
+ promises = new PromiseRegistry();
4402
+ acks = new Map();
4403
+ hiddenRoomIds = new Set();
4404
+ activitiesWanted = false;
4405
+ messagesWanted = false;
4406
+ refreshScheduled = false;
4407
+ seen = null;
4408
+ constructor(tracker) {
4409
+ super();
4410
+ this.tracker = tracker;
4411
+ this.tracker.client.on('NewActivity', ev => this.handleNewActivity(ev));
4412
+ this.tracker.client.on('ActivityUpdated', ev => this.handleActivityUpdated(ev));
4413
+ this.tracker.client.on('ActivityDeleted', ev => this.handleActivityDeleted(ev));
4414
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
4415
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4416
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4417
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4418
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4419
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4420
+ this.tracker.client.on('Session', () => this.handleSession());
4421
+ }
4422
+
4423
+ /**
4424
+ * Your latest activities, keyed by id; always the same collection. The first call fetches them, later ones resolve
4425
+ * with them. Once fetched, they are fetched again after every reconnect, also when the first fetch failed because
4426
+ * the connection was not ready yet. The collection keeps no meaningful order - sort by `createdAt`. Marking the list
4427
+ * as seen and clearing it is done with the `UpdateActivities` command.
4428
+ * @param fetchWithMessages Fetch the messages and the actors of the activities along, so {@link getMessages} and
4429
+ * {@link getUsers} need no request.
4430
+ */
4431
+ async get(fetchWithMessages = false) {
4432
+ if (fetchWithMessages) {
4433
+ await this.getMessages();
4434
+ }
4435
+ if (this.promises.notExist('activities')) {
4436
+ this.activitiesWanted = true;
4437
+ this.registerFetch(false);
4438
+ }
4439
+ await this.promises.get('activities');
4440
+ return this.activities;
4441
+ }
4442
+
4443
+ /**
4444
+ * The messages the activities point at, keyed by message id; always the same collection. The first call fetches
4445
+ * them together with the list of {@link get}, unless they were fetched already; afterwards they come with new
4446
+ * activities, follow the edits and are fetched again after every reconnect.
4447
+ */
4448
+ async getMessages() {
4449
+ if (this.promises.notExist('messages')) {
4450
+ this.activitiesWanted = true;
4451
+ this.messagesWanted = true;
4452
+ this.registerFetch(true);
4453
+ }
4454
+ await this.promises.get('messages');
4455
+ return this.messages;
4456
+ }
4457
+
4458
+ /**
4459
+ * The actors of the activities, keyed by user id; always the same collection, fetched and kept together with
4460
+ * {@link getMessages}.
4461
+ */
4462
+ async getUsers() {
4463
+ await this.getMessages();
4464
+ return this.users;
4465
+ }
4466
+
4467
+ /**
4468
+ * When the list was last seen, on any device; null until it is fetched or while it was never seen. A change emits
4469
+ * `seenAtChange`. Activities created later that are not {@link Activity.isRead} are the unread ones.
4470
+ */
4471
+ get seenAt() {
4472
+ return this.seen;
4473
+ }
4474
+ registerFetch(withMessages) {
4475
+ const fetching = this.fetch(withMessages);
4476
+ this.promises.register(fetching, 'activities');
4477
+ if (withMessages) {
4478
+ this.promises.register(fetching, 'messages');
4479
+ }
4480
+ }
4481
+ async fetch(withMessages) {
4482
+ const result = await this.tracker.client.send('GetActivities', {
4483
+ withMessages
4484
+ });
4485
+ if (result.error) {
4486
+ throw result.error;
4487
+ }
4488
+ this.apply(result.data, withMessages);
4489
+ }
4490
+ apply(ev, withMessages) {
4491
+ this.activities.reconcile(...ev.activities);
4492
+ if (withMessages) {
4493
+ this.messages.reconcile(...ev.messages);
4494
+ this.users.reconcile(...ev.users);
4495
+ }
4496
+ this.setSeen(ev.seenAt);
4497
+ }
4498
+ refresh() {
4499
+ if (this.messagesWanted) {
4500
+ this.registerFetch(true);
4501
+ } else if (this.activitiesWanted) {
4502
+ this.registerFetch(false);
4503
+ }
4504
+ this.promises.get('activities')?.catch(() => {});
4505
+ }
4506
+ setSeen(seenAt) {
4507
+ if (seenAt !== this.seen) {
4508
+ this.seen = seenAt;
4509
+ this.emit('seenAtChange', {});
4510
+ }
4511
+ }
4512
+ handleNewActivity(ev) {
4513
+ if (!this.activitiesWanted) {
4514
+ return;
4515
+ }
4516
+ const topicId = ev.activity.location?.topicId ?? '';
4517
+ const lastAck = this.acks.get(topicId);
4518
+ const added = lastAck && isAcknowledged(ev.activity, topicId, lastAck) ? {
4519
+ ...ev.activity,
4520
+ isRead: true
4521
+ } : ev.activity;
4522
+ const newest = this.activities.items.sort(newestFirst);
4523
+ const group = added.groupKey === null ? undefined : newest.slice(0, GROUP_SCAN).find(activity => activity.groupKey === added.groupKey);
4524
+ if (group && time(group.createdAt) > time(this.seen)) {
4525
+ this.activities.set({
4526
+ ...added,
4527
+ id: group.id,
4528
+ count: group.count + 1,
4529
+ actorIds: [...new Set([...added.actorIds, ...group.actorIds])].slice(0, MAX_ACTORS)
4530
+ });
4531
+ } else {
4532
+ this.activities.set(added);
4533
+ this.activities.delete(...newest.slice(VISIBLE_LIMIT - 1).map(activity => activity.id));
4534
+ }
4535
+ if (this.messagesWanted) {
4536
+ if (ev.message) {
4537
+ this.messages.set(ev.message);
4538
+ }
4539
+ this.users.set(...ev.users);
4540
+ }
4541
+ }
4542
+ handleActivityUpdated(ev) {
4543
+ if (time(ev.seenAt) > time(this.seen)) {
4544
+ this.setSeen(ev.seenAt);
4545
+ }
4546
+ if (ev.cleared) {
4547
+ this.activities.deleteAll();
4548
+ this.messages.deleteAll();
4549
+ this.users.deleteAll();
4550
+ }
4551
+ }
4552
+ handleActivityDeleted(ev) {
4553
+ if (this.activities.has(ev.id)) {
4554
+ this.activities.delete(ev.id);
4555
+ }
4556
+ }
4557
+ handleFollowedTopicUpdated(ev) {
4558
+ const {
4559
+ location,
4560
+ lastAckMessageId
4561
+ } = ev.followedTopic;
4562
+ if (!location.topicId || !lastAckMessageId) {
4563
+ return;
4564
+ }
4565
+
4566
+ // An acknowledgement may come before the activity of the same message
4567
+ this.acks.set(location.topicId, lastAckMessageId);
4568
+ const read = this.activities.items.filter(activity => !activity.isRead && isAcknowledged(activity, location.topicId, lastAckMessageId)).map(activity => ({
4569
+ ...activity,
4570
+ isRead: true
4571
+ }));
4572
+ this.activities.set(...read);
4573
+ }
4574
+ handleMessageUpdated(ev) {
4575
+ if (this.messages.has(ev.message.id)) {
4576
+ this.messages.set(ev.message);
4577
+ }
4578
+ }
4579
+ handleMessagesRedacted(ev) {
4580
+ const ids = new Set(ev.ids);
4581
+ this.deleteActivities(activity => activity.messageId !== null && ids.has(activity.messageId));
4582
+ }
4583
+ handleRoomDeleted(ev) {
4584
+ this.hiddenRoomIds.delete(ev.id);
4585
+ this.deleteActivities(activity => activity.location?.roomId === ev.id);
4586
+ }
4587
+ handleRoomLeft(ev) {
4588
+ // The server keeps them and hands them back once you rejoin
4589
+ if (this.deleteActivities(activity => activity.location?.roomId === ev.id)) {
4590
+ this.hiddenRoomIds.add(ev.id);
4591
+ }
4592
+ }
4593
+ handleRoomJoined(ev) {
4594
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4595
+ return;
4596
+ }
4597
+
4598
+ // Joining a space joins its rooms one by one; one request brings back the activities of all of them
4599
+ this.refreshScheduled = true;
4600
+ setTimeout(() => {
4601
+ this.refreshScheduled = false;
4602
+ this.refresh();
4603
+ }, 0);
4604
+ }
4605
+ deleteActivities(predicate) {
4606
+ const deleted = this.activities.items.filter(predicate);
4607
+ const messageIds = deleted.map(activity => activity.messageId).filter(id => id !== null && this.messages.has(id));
4608
+ this.activities.delete(...deleted.map(activity => activity.id));
4609
+ this.messages.delete(...messageIds);
4610
+ return deleted.length > 0;
4611
+ }
4612
+ handleSession() {
4613
+ this.acks.clear();
4614
+ this.promises.forgetAll();
4615
+ this.refresh();
4616
+ }
4617
+ }
4618
+ ;// ./src/state-tracker/SavedItemsManager.ts
4619
+
4620
+
4621
+ /**
4622
+ * The key of a saved item in the collection returned by {@link SavedItemsManager.get}.
4623
+ */
4624
+ const savedItemKey = (type, id) => `${type}:${id}`;
4625
+ const keyOf = item => savedItemKey(item.type, item.id);
4626
+ class SavedItemsManager {
4627
+ items = new ObservableIndexedObjectCollection(keyOf);
4628
+ messages = new ObservableIndexedObjectCollection('id');
4629
+ promises = new PromiseRegistry();
4630
+ hiddenRoomIds = new Set();
4631
+ itemsWanted = false;
4632
+ messagesWanted = false;
4633
+ refreshScheduled = false;
4634
+ constructor(tracker) {
4635
+ this.tracker = tracker;
4636
+ this.tracker.client.on('ItemSaved', ev => this.handleItemSaved(ev));
4637
+ this.tracker.client.on('ItemUnsaved', ev => this.handleItemUnsaved(ev));
4638
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4639
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4640
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4641
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4642
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4643
+ this.tracker.client.on('Session', () => this.handleSession());
4644
+ }
4645
+
4646
+ /**
4647
+ * The rooms and messages you saved, keyed by {@link savedItemKey}; always the same collection. The first call fetches
4648
+ * the list, later ones resolve with it. Items of rooms you are not a member of are left out until you rejoin. The
4649
+ * collection keeps no meaningful order - sort by `savedAt`. Once fetched, the list is fetched again after every
4650
+ * reconnect. Saving and unsaving is done with the `SaveItem` and `UnsaveItem` commands.
4651
+ * @param fetchWithMessages Fetch the contents of the saved messages along, so {@link getMessages} needs no request.
4652
+ */
4653
+ async get(fetchWithMessages = false) {
4654
+ if (fetchWithMessages) {
4655
+ await this.getMessages();
4656
+ }
4657
+ if (this.promises.notExist('items')) {
4658
+ this.itemsWanted = true;
4659
+ this.registerFetch(false);
4660
+ }
4661
+ await this.promises.get('items');
4662
+ return this.items;
4663
+ }
4664
+
4665
+ /**
4666
+ * The contents of the saved messages, keyed by message id; always the same collection. The first call fetches them
4667
+ * together with the list of {@link get}, unless they were fetched already; afterwards they follow the edits and are
4668
+ * fetched again after every reconnect.
4669
+ */
4670
+ async getMessages() {
4671
+ if (this.promises.notExist('messages')) {
4672
+ this.itemsWanted = true;
4673
+ this.messagesWanted = true;
4674
+ this.registerFetch(true);
4675
+ }
4676
+ await this.promises.get('messages');
4677
+ return this.messages;
4678
+ }
4679
+ async isSaved(type, id) {
4680
+ return (await this.get()).has(savedItemKey(type, id));
4681
+ }
4682
+ registerFetch(withMessages) {
4683
+ const fetching = this.fetch(withMessages);
4684
+ this.promises.register(fetching, 'items');
4685
+ if (withMessages) {
4686
+ this.promises.register(fetching, 'messages');
4687
+ }
4688
+ }
4689
+ async fetch(withMessages) {
4690
+ const result = await this.tracker.client.send('GetSavedItems', {
4691
+ withMessages
4692
+ });
4693
+ if (result.error) {
4694
+ throw result.error;
4695
+ }
4696
+ this.apply(result.data, withMessages);
4697
+ }
4698
+ apply(ev, withMessages) {
4699
+ this.items.reconcile(...ev.items);
4700
+ if (withMessages) {
4701
+ this.messages.reconcile(...ev.messages);
4702
+ }
4703
+ }
4704
+ refresh() {
4705
+ if (this.messagesWanted) {
4706
+ this.registerFetch(true);
4707
+ } else if (this.itemsWanted) {
4708
+ this.registerFetch(false);
4709
+ }
4710
+ this.promises.get('items')?.catch(() => {});
4711
+ }
4712
+ handleItemSaved(ev) {
4713
+ if (!this.itemsWanted) {
4714
+ return;
4715
+ }
4716
+ this.items.set(ev.item);
4717
+ if (this.messagesWanted && ev.message) {
4718
+ this.messages.set(ev.message);
4719
+ }
4720
+ }
4721
+ handleItemUnsaved(ev) {
4722
+ this.items.delete(savedItemKey(ev.type, ev.id));
4723
+ if (ev.type === 'Message') {
4724
+ this.messages.delete(ev.id);
4725
+ }
4726
+ }
4727
+ handleMessageUpdated(ev) {
4728
+ if (this.messages.has(ev.message.id)) {
4729
+ this.messages.set(ev.message);
4730
+ }
4731
+ }
4732
+ handleMessagesRedacted(ev) {
4733
+ const saved = ev.ids.filter(id => this.items.has(savedItemKey('Message', id)));
4734
+ this.items.delete(...saved.map(id => savedItemKey('Message', id)));
4735
+ this.messages.delete(...saved.filter(id => this.messages.has(id)));
4736
+ }
4737
+ handleRoomDeleted(ev) {
4738
+ this.hiddenRoomIds.delete(ev.id);
4739
+ this.deleteRoomItems(ev.id);
4740
+ }
4741
+ handleRoomLeft(ev) {
4742
+ // The server keeps them and hands them back once you rejoin
4743
+ if (this.deleteRoomItems(ev.id)) {
4744
+ this.hiddenRoomIds.add(ev.id);
4745
+ }
4746
+ }
4747
+ handleRoomJoined(ev) {
4748
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4749
+ return;
4750
+ }
4751
+
4752
+ // Joining a space joins its rooms one by one; one request brings back the items of all of them
4753
+ this.refreshScheduled = true;
4754
+ setTimeout(() => {
4755
+ this.refreshScheduled = false;
4756
+ this.refresh();
4757
+ }, 0);
4758
+ }
4759
+ deleteRoomItems(roomId) {
4760
+ const items = this.items.items.filter(item => item.roomId === roomId);
4761
+ this.items.delete(...items.map(keyOf));
4762
+ this.messages.delete(...items.filter(item => this.messages.has(item.id)).map(item => item.id));
4763
+ return items.length > 0;
4764
+ }
4765
+ handleSession() {
4766
+ this.promises.forgetAll();
4767
+ this.refresh();
4768
+ }
4769
+ }
4323
4770
  ;// ./src/state-tracker/ChatStateTracker.ts
4324
4771
 
4325
4772
 
@@ -4330,6 +4777,8 @@ class CallsManager {
4330
4777
 
4331
4778
 
4332
4779
 
4780
+
4781
+
4333
4782
  class ChatStateTracker {
4334
4783
  client;
4335
4784
 
@@ -4367,6 +4816,19 @@ class ChatStateTracker {
4367
4816
  * State of the calls in your rooms and of the calls ringing at you.
4368
4817
  */
4369
4818
  calls;
4819
+
4820
+ /**
4821
+ * Your latest personal events from all spaces (mentions, replies, reactions, followed threads, missed calls) and the
4822
+ * activities the server publishes. Private conversations keep their own unread state. Nothing is fetched until you
4823
+ * ask for it. Not part of the state snapshot.
4824
+ */
4825
+ activities;
4826
+
4827
+ /**
4828
+ * The rooms and messages you saved, from all spaces. Nothing is fetched until you ask for it. Not part of the state
4829
+ * snapshot.
4830
+ */
4831
+ savedItems;
4370
4832
  _me = null;
4371
4833
  deferredSession = new DeferredTask();
4372
4834
  sessionReceived = false;
@@ -4381,6 +4843,8 @@ class ChatStateTracker {
4381
4843
  this.users = new UsersManager(this);
4382
4844
  this.relationships = new RelationshipsManager(this);
4383
4845
  this.calls = new CallsManager(this);
4846
+ this.activities = new ActivitiesManager(this);
4847
+ this.savedItems = new SavedItemsManager(this);
4384
4848
 
4385
4849
  // Registered after the managers, so it runs once they have applied the session.
4386
4850
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -5017,10 +5481,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
5017
5481
  ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
5018
5482
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
5019
5483
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
5484
+ ErrorCode["SavedItemsLimitReached"] = "SavedItemsLimitReachedException";
5020
5485
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
5021
5486
  ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
5022
5487
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
5023
5488
  ErrorCode["UserNotFound"] = "UserNotFoundException";
5489
+ ErrorCode["UserType"] = "UserTypeException";
5024
5490
  return ErrorCode;
5025
5491
  }({});
5026
5492
  ;// ./src/protocol/schemes/MessageEmbed.ts
@@ -5163,6 +5629,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
5163
5629
 
5164
5630
 
5165
5631
 
5632
+
5166
5633
  module.exports = __webpack_exports__;
5167
5634
  /******/ })()
5168
5635
  ;