@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
package/build/index.mjs CHANGED
@@ -3503,6 +3503,10 @@ class Permissions {
3503
3503
  ManageCalls: {
3504
3504
  value: 2 ** 33,
3505
3505
  maxLayer: Layer.Room
3506
+ },
3507
+ StartCalls: {
3508
+ value: 2 ** 34,
3509
+ maxLayer: Layer.Room
3506
3510
  }
3507
3511
  };
3508
3512
 
@@ -3560,6 +3564,7 @@ class Permissions {
3560
3564
 
3561
3565
 
3562
3566
  const getOvId = (location, target) => [location.spaceId, location.roomId, location.topicId, target?.type, target?.userId, target?.roleId].filter(Boolean).join('/');
3567
+ const FETCH_CHUNK_SIZE = 50;
3563
3568
  const getOvIdByObject = overwrites => getOvId(overwrites.location, overwrites.target);
3564
3569
  class PermissionsManager extends EventTarget {
3565
3570
  overwrites = new IndexedCollection();
@@ -3579,23 +3584,18 @@ class PermissionsManager extends EventTarget {
3579
3584
  this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
3580
3585
  this.tracker.client.on('Session', ev => this.handleSession(ev));
3581
3586
  }
3587
+
3588
+ /**
3589
+ * Cached: kept up to date only for your own overwrites and those of your roles in the locations you belong to.
3590
+ * For live overwrites of another target send `GetPermissionOverwrites` yourself.
3591
+ */
3582
3592
  async getOverwrites(location, target) {
3583
3593
  this.validateLocation(location);
3584
- const id = getOvId(location, target);
3585
- if (this.overwritesPromises.notExist(id)) {
3586
- this.overwritesPromises.registerByFunction(async () => {
3587
- const result = await this.tracker.client.send('GetPermissionOverwrites', {
3588
- location,
3589
- target
3590
- });
3591
- if (result.error) {
3592
- throw result.error;
3593
- }
3594
- this.handlePermissionOverwrites(result.data);
3595
- }, id);
3596
- }
3597
- await this.overwritesPromises.get(id);
3598
- return this.overwrites.get(id);
3594
+ await this.fetchOverwrites([{
3595
+ location,
3596
+ target
3597
+ }]);
3598
+ return this.overwrites.get(getOvId(location, target));
3599
3599
  }
3600
3600
  async check(permissionNames, location) {
3601
3601
  if (!permissionNames.length) {
@@ -3630,54 +3630,111 @@ class PermissionsManager extends EventTarget {
3630
3630
  if (location.roomId && !room || location.spaceId && !(await this.tracker.spaces.get())?.has(location.spaceId)) {
3631
3631
  return this.fetchComputedPermissions(location);
3632
3632
  }
3633
- const userId = (await this.tracker.getMe()).id;
3633
+ const me = {
3634
+ type: 'User',
3635
+ userId: (await this.tracker.getMe()).id
3636
+ };
3634
3637
  const [spaceMember, roomMember] = await this.fetchMembersOrFail(location);
3635
3638
  const userRoles = [...(spaceMember?.roles ?? []), ...(roomMember?.roles ?? [])];
3636
- const promises = [
3637
- // Global user overwrites
3638
- this.getOverwrites({}, {
3639
- type: 'User',
3640
- userId
3641
- }).then(v => v.overwrites)];
3639
+ const layers = [{
3640
+ location: {},
3641
+ withRoles: false
3642
+ }];
3642
3643
  if (location.spaceId && (await this.tracker.spaces.get())?.has(location.spaceId)) {
3643
- const filterLocation = {
3644
- spaceId: location.spaceId
3645
- };
3646
- promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
3647
- promises.push(this.getOverwrites(filterLocation, {
3648
- type: 'User',
3649
- userId
3650
- }).then(v => v.overwrites));
3644
+ layers.push({
3645
+ location: {
3646
+ spaceId: location.spaceId
3647
+ },
3648
+ withRoles: true
3649
+ });
3651
3650
  }
3652
3651
  if (room) {
3653
- const filterLocation = {
3654
- spaceId: location.spaceId,
3655
- roomId: location.roomId
3656
- };
3657
- if (userRoles.length) {
3658
- promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
3659
- }
3660
- promises.push(this.getOverwrites(filterLocation, {
3661
- type: 'User',
3662
- userId
3663
- }).then(v => v.overwrites));
3652
+ layers.push({
3653
+ location: {
3654
+ spaceId: location.spaceId,
3655
+ roomId: location.roomId
3656
+ },
3657
+ withRoles: userRoles.length > 0
3658
+ });
3664
3659
  }
3665
3660
  if (location.topicId && (await this.tracker.rooms.getTopics(location.roomId))?.has(location.topicId)) {
3666
- if (userRoles.length) {
3667
- promises.push(this.collectRoleOverwrites(location, userRoles));
3661
+ layers.push({
3662
+ location,
3663
+ withRoles: userRoles.length > 0
3664
+ });
3665
+ }
3666
+ const queries = [];
3667
+ for (const layer of layers) {
3668
+ if (layer.withRoles) {
3669
+ queries.push(...userRoles.map(roleId => ({
3670
+ location: layer.location,
3671
+ target: {
3672
+ type: 'Role',
3673
+ roleId
3674
+ }
3675
+ })));
3668
3676
  }
3669
- promises.push(this.getOverwrites(location, {
3670
- type: 'User',
3671
- userId
3672
- }).then(v => v.overwrites));
3677
+ queries.push({
3678
+ location: layer.location,
3679
+ target: me
3680
+ });
3681
+ }
3682
+ await this.fetchOverwrites(queries);
3683
+ const values = [];
3684
+ for (const layer of layers) {
3685
+ if (layer.withRoles) {
3686
+ values.push(...this.collectRoleOverwrites(layer.location, userRoles));
3687
+ }
3688
+ values.push(this.getFetchedOverwrites(layer.location, me).overwrites);
3689
+ }
3690
+ return this.resolveOverwritesHierarchy(values);
3691
+ }
3692
+
3693
+ // Chunked by queries only: a calculation refers to at most 4 locations, the server limit for one request
3694
+ async fetchOverwrites(queries) {
3695
+ const missing = new Map();
3696
+ for (const query of queries) {
3697
+ const id = getOvId(query.location, query.target);
3698
+ if (this.overwritesPromises.notExist(id)) {
3699
+ missing.set(id, query);
3700
+ }
3701
+ }
3702
+ const pending = [...missing];
3703
+ for (let i = 0; i < pending.length; i += FETCH_CHUNK_SIZE) {
3704
+ const chunk = pending.slice(i, i + FETCH_CHUNK_SIZE);
3705
+ const request = this.requestOverwrites(chunk.map(([, query]) => query));
3706
+ for (const [id] of chunk) {
3707
+ this.overwritesPromises.register(request, id);
3708
+ }
3709
+ }
3710
+ await Promise.all(queries.map(query => this.overwritesPromises.get(getOvId(query.location, query.target))));
3711
+ }
3712
+ async requestOverwrites(queries) {
3713
+ const result = await this.tracker.client.send('GetPermissionOverwrites', {
3714
+ queries
3715
+ });
3716
+ if (result.error) {
3717
+ throw result.error;
3718
+ }
3719
+ const results = 'results' in result.data ? result.data.results : [];
3720
+ if (results.length !== queries.length) {
3721
+ throw new Error(`Expected ${queries.length} permission overwrites, received ${results.length}`);
3722
+ }
3723
+ for (const overwrites of results) {
3724
+ this.handlePermissionOverwrites(overwrites);
3725
+ }
3726
+ }
3727
+ getFetchedOverwrites(location, target) {
3728
+ const overwrites = this.overwrites.get(getOvId(location, target));
3729
+ if (!overwrites) {
3730
+ throw new Error(`Permission overwrites of ${getOvId(location, target)} are not fetched`);
3673
3731
  }
3674
- return this.resolveOverwritesHierarchy([].concat(...(await Promise.all(promises))));
3732
+ return overwrites;
3675
3733
  }
3676
3734
 
3677
3735
  /**
3678
3736
  * Arriving overwrites change the permissions only when they replace different ones. The first ones fetched for a
3679
- * key have not been part of any result yet - every calculation needing them awaits their fetch - and a fetch
3680
- * response arrives twice, as the command result and as an event.
3737
+ * key have not been part of any result yet - every calculation needing them awaits their fetch.
3681
3738
  */
3682
3739
  handlePermissionOverwrites(ev) {
3683
3740
  const id = getOvIdByObject(ev);
@@ -3743,11 +3800,11 @@ class PermissionsManager extends EventTarget {
3743
3800
  });
3744
3801
  return ids;
3745
3802
  }
3746
- async collectRoleOverwrites(location, userRoles) {
3747
- const roleOverwrites = await Promise.all(userRoles.map(roleId => this.getOverwrites(location, {
3803
+ collectRoleOverwrites(location, userRoles) {
3804
+ const roleOverwrites = userRoles.map(roleId => this.getFetchedOverwrites(location, {
3748
3805
  type: 'Role',
3749
3806
  roleId
3750
- })));
3807
+ }));
3751
3808
  // The space default role (everyone) has the space id; it is applied before the other roles, as on the server.
3752
3809
  const isDefaultRole = overwrites => overwrites.target.roleId === location.spaceId;
3753
3810
  return [this.mergeRolesOverwrites(roleOverwrites.filter(isDefaultRole)), this.mergeRolesOverwrites(roleOverwrites.filter(overwrites => !isDefaultRole(overwrites)))];
@@ -4270,6 +4327,395 @@ class CallsManager {
4270
4327
  this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4271
4328
  }
4272
4329
  }
4330
+ ;// ./src/state-tracker/ActivitiesManager.ts
4331
+
4332
+
4333
+
4334
+ // Mirror the server, so a live activity joins its group as the stored one did
4335
+ const VISIBLE_LIMIT = 20;
4336
+ const GROUP_SCAN = 5;
4337
+ const MAX_ACTORS = 3;
4338
+ const time = isoDate => isoDate ? Date.parse(isoDate) : 0;
4339
+ const newestFirst = (a, b) => time(b.createdAt) - time(a.createdAt);
4340
+
4341
+ // A reaction is to one's own message, so acknowledging it says nothing about the reaction
4342
+ const isReadWithAck = activity => activity.type !== 'Reaction' && activity.type !== 'Custom';
4343
+
4344
+ // Message ids are time-ordered and their base58 form has a fixed length, so they compare as strings
4345
+ const isAcknowledged = (activity, topicId, lastAckMessageId) => isReadWithAck(activity) && activity.location?.topicId === topicId && activity.messageId !== null && activity.messageId <= lastAckMessageId;
4346
+ class ActivitiesManager extends EventTarget {
4347
+ activities = new ObservableIndexedObjectCollection('id');
4348
+ messages = new ObservableIndexedObjectCollection('id');
4349
+ users = new ObservableIndexedObjectCollection('id');
4350
+ promises = new PromiseRegistry();
4351
+ acks = new Map();
4352
+ hiddenRoomIds = new Set();
4353
+ activitiesWanted = false;
4354
+ messagesWanted = false;
4355
+ refreshScheduled = false;
4356
+ seen = null;
4357
+ constructor(tracker) {
4358
+ super();
4359
+ this.tracker = tracker;
4360
+ this.tracker.client.on('NewActivity', ev => this.handleNewActivity(ev));
4361
+ this.tracker.client.on('ActivityUpdated', ev => this.handleActivityUpdated(ev));
4362
+ this.tracker.client.on('ActivityDeleted', ev => this.handleActivityDeleted(ev));
4363
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
4364
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4365
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4366
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4367
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4368
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4369
+ this.tracker.client.on('Session', () => this.handleSession());
4370
+ }
4371
+
4372
+ /**
4373
+ * Your latest activities, keyed by id; always the same collection. The first call fetches them, later ones resolve
4374
+ * with them. Once fetched, they are fetched again after every reconnect, also when the first fetch failed because
4375
+ * the connection was not ready yet. The collection keeps no meaningful order - sort by `createdAt`. Marking the list
4376
+ * as seen and clearing it is done with the `UpdateActivities` command.
4377
+ * @param fetchWithMessages Fetch the messages and the actors of the activities along, so {@link getMessages} and
4378
+ * {@link getUsers} need no request.
4379
+ */
4380
+ async get(fetchWithMessages = false) {
4381
+ if (fetchWithMessages) {
4382
+ await this.getMessages();
4383
+ }
4384
+ if (this.promises.notExist('activities')) {
4385
+ this.activitiesWanted = true;
4386
+ this.registerFetch(false);
4387
+ }
4388
+ await this.promises.get('activities');
4389
+ return this.activities;
4390
+ }
4391
+
4392
+ /**
4393
+ * The messages the activities point at, keyed by message id; always the same collection. The first call fetches
4394
+ * them together with the list of {@link get}, unless they were fetched already; afterwards they come with new
4395
+ * activities, follow the edits and are fetched again after every reconnect.
4396
+ */
4397
+ async getMessages() {
4398
+ if (this.promises.notExist('messages')) {
4399
+ this.activitiesWanted = true;
4400
+ this.messagesWanted = true;
4401
+ this.registerFetch(true);
4402
+ }
4403
+ await this.promises.get('messages');
4404
+ return this.messages;
4405
+ }
4406
+
4407
+ /**
4408
+ * The actors of the activities, keyed by user id; always the same collection, fetched and kept together with
4409
+ * {@link getMessages}.
4410
+ */
4411
+ async getUsers() {
4412
+ await this.getMessages();
4413
+ return this.users;
4414
+ }
4415
+
4416
+ /**
4417
+ * When the list was last seen, on any device; null until it is fetched or while it was never seen. A change emits
4418
+ * `seenAtChange`. Activities created later that are not {@link Activity.isRead} are the unread ones.
4419
+ */
4420
+ get seenAt() {
4421
+ return this.seen;
4422
+ }
4423
+ registerFetch(withMessages) {
4424
+ const fetching = this.fetch(withMessages);
4425
+ this.promises.register(fetching, 'activities');
4426
+ if (withMessages) {
4427
+ this.promises.register(fetching, 'messages');
4428
+ }
4429
+ }
4430
+ async fetch(withMessages) {
4431
+ const result = await this.tracker.client.send('GetActivities', {
4432
+ withMessages
4433
+ });
4434
+ if (result.error) {
4435
+ throw result.error;
4436
+ }
4437
+ this.apply(result.data, withMessages);
4438
+ }
4439
+ apply(ev, withMessages) {
4440
+ this.activities.reconcile(...ev.activities);
4441
+ if (withMessages) {
4442
+ this.messages.reconcile(...ev.messages);
4443
+ this.users.reconcile(...ev.users);
4444
+ }
4445
+ this.setSeen(ev.seenAt);
4446
+ }
4447
+ refresh() {
4448
+ if (this.messagesWanted) {
4449
+ this.registerFetch(true);
4450
+ } else if (this.activitiesWanted) {
4451
+ this.registerFetch(false);
4452
+ }
4453
+ this.promises.get('activities')?.catch(() => {});
4454
+ }
4455
+ setSeen(seenAt) {
4456
+ if (seenAt !== this.seen) {
4457
+ this.seen = seenAt;
4458
+ this.emit('seenAtChange', {});
4459
+ }
4460
+ }
4461
+ handleNewActivity(ev) {
4462
+ if (!this.activitiesWanted) {
4463
+ return;
4464
+ }
4465
+ const topicId = ev.activity.location?.topicId ?? '';
4466
+ const lastAck = this.acks.get(topicId);
4467
+ const added = lastAck && isAcknowledged(ev.activity, topicId, lastAck) ? {
4468
+ ...ev.activity,
4469
+ isRead: true
4470
+ } : ev.activity;
4471
+ const newest = this.activities.items.sort(newestFirst);
4472
+ const group = added.groupKey === null ? undefined : newest.slice(0, GROUP_SCAN).find(activity => activity.groupKey === added.groupKey);
4473
+ if (group && time(group.createdAt) > time(this.seen)) {
4474
+ this.activities.set({
4475
+ ...added,
4476
+ id: group.id,
4477
+ count: group.count + 1,
4478
+ actorIds: [...new Set([...added.actorIds, ...group.actorIds])].slice(0, MAX_ACTORS)
4479
+ });
4480
+ } else {
4481
+ this.activities.set(added);
4482
+ this.activities.delete(...newest.slice(VISIBLE_LIMIT - 1).map(activity => activity.id));
4483
+ }
4484
+ if (this.messagesWanted) {
4485
+ if (ev.message) {
4486
+ this.messages.set(ev.message);
4487
+ }
4488
+ this.users.set(...ev.users);
4489
+ }
4490
+ }
4491
+ handleActivityUpdated(ev) {
4492
+ if (time(ev.seenAt) > time(this.seen)) {
4493
+ this.setSeen(ev.seenAt);
4494
+ }
4495
+ if (ev.cleared) {
4496
+ this.activities.deleteAll();
4497
+ this.messages.deleteAll();
4498
+ this.users.deleteAll();
4499
+ }
4500
+ }
4501
+ handleActivityDeleted(ev) {
4502
+ if (this.activities.has(ev.id)) {
4503
+ this.activities.delete(ev.id);
4504
+ }
4505
+ }
4506
+ handleFollowedTopicUpdated(ev) {
4507
+ const {
4508
+ location,
4509
+ lastAckMessageId
4510
+ } = ev.followedTopic;
4511
+ if (!location.topicId || !lastAckMessageId) {
4512
+ return;
4513
+ }
4514
+
4515
+ // An acknowledgement may come before the activity of the same message
4516
+ this.acks.set(location.topicId, lastAckMessageId);
4517
+ const read = this.activities.items.filter(activity => !activity.isRead && isAcknowledged(activity, location.topicId, lastAckMessageId)).map(activity => ({
4518
+ ...activity,
4519
+ isRead: true
4520
+ }));
4521
+ this.activities.set(...read);
4522
+ }
4523
+ handleMessageUpdated(ev) {
4524
+ if (this.messages.has(ev.message.id)) {
4525
+ this.messages.set(ev.message);
4526
+ }
4527
+ }
4528
+ handleMessagesRedacted(ev) {
4529
+ const ids = new Set(ev.ids);
4530
+ this.deleteActivities(activity => activity.messageId !== null && ids.has(activity.messageId));
4531
+ }
4532
+ handleRoomDeleted(ev) {
4533
+ this.hiddenRoomIds.delete(ev.id);
4534
+ this.deleteActivities(activity => activity.location?.roomId === ev.id);
4535
+ }
4536
+ handleRoomLeft(ev) {
4537
+ // The server keeps them and hands them back once you rejoin
4538
+ if (this.deleteActivities(activity => activity.location?.roomId === ev.id)) {
4539
+ this.hiddenRoomIds.add(ev.id);
4540
+ }
4541
+ }
4542
+ handleRoomJoined(ev) {
4543
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4544
+ return;
4545
+ }
4546
+
4547
+ // Joining a space joins its rooms one by one; one request brings back the activities of all of them
4548
+ this.refreshScheduled = true;
4549
+ setTimeout(() => {
4550
+ this.refreshScheduled = false;
4551
+ this.refresh();
4552
+ }, 0);
4553
+ }
4554
+ deleteActivities(predicate) {
4555
+ const deleted = this.activities.items.filter(predicate);
4556
+ const messageIds = deleted.map(activity => activity.messageId).filter(id => id !== null && this.messages.has(id));
4557
+ this.activities.delete(...deleted.map(activity => activity.id));
4558
+ this.messages.delete(...messageIds);
4559
+ return deleted.length > 0;
4560
+ }
4561
+ handleSession() {
4562
+ this.acks.clear();
4563
+ this.promises.forgetAll();
4564
+ this.refresh();
4565
+ }
4566
+ }
4567
+ ;// ./src/state-tracker/SavedItemsManager.ts
4568
+
4569
+
4570
+ /**
4571
+ * The key of a saved item in the collection returned by {@link SavedItemsManager.get}.
4572
+ */
4573
+ const savedItemKey = (type, id) => `${type}:${id}`;
4574
+ const keyOf = item => savedItemKey(item.type, item.id);
4575
+ class SavedItemsManager {
4576
+ items = new ObservableIndexedObjectCollection(keyOf);
4577
+ messages = new ObservableIndexedObjectCollection('id');
4578
+ promises = new PromiseRegistry();
4579
+ hiddenRoomIds = new Set();
4580
+ itemsWanted = false;
4581
+ messagesWanted = false;
4582
+ refreshScheduled = false;
4583
+ constructor(tracker) {
4584
+ this.tracker = tracker;
4585
+ this.tracker.client.on('ItemSaved', ev => this.handleItemSaved(ev));
4586
+ this.tracker.client.on('ItemUnsaved', ev => this.handleItemUnsaved(ev));
4587
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4588
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4589
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4590
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4591
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4592
+ this.tracker.client.on('Session', () => this.handleSession());
4593
+ }
4594
+
4595
+ /**
4596
+ * The rooms and messages you saved, keyed by {@link savedItemKey}; always the same collection. The first call fetches
4597
+ * the list, later ones resolve with it. Items of rooms you are not a member of are left out until you rejoin. The
4598
+ * collection keeps no meaningful order - sort by `savedAt`. Once fetched, the list is fetched again after every
4599
+ * reconnect. Saving and unsaving is done with the `SaveItem` and `UnsaveItem` commands.
4600
+ * @param fetchWithMessages Fetch the contents of the saved messages along, so {@link getMessages} needs no request.
4601
+ */
4602
+ async get(fetchWithMessages = false) {
4603
+ if (fetchWithMessages) {
4604
+ await this.getMessages();
4605
+ }
4606
+ if (this.promises.notExist('items')) {
4607
+ this.itemsWanted = true;
4608
+ this.registerFetch(false);
4609
+ }
4610
+ await this.promises.get('items');
4611
+ return this.items;
4612
+ }
4613
+
4614
+ /**
4615
+ * The contents of the saved messages, keyed by message id; always the same collection. The first call fetches them
4616
+ * together with the list of {@link get}, unless they were fetched already; afterwards they follow the edits and are
4617
+ * fetched again after every reconnect.
4618
+ */
4619
+ async getMessages() {
4620
+ if (this.promises.notExist('messages')) {
4621
+ this.itemsWanted = true;
4622
+ this.messagesWanted = true;
4623
+ this.registerFetch(true);
4624
+ }
4625
+ await this.promises.get('messages');
4626
+ return this.messages;
4627
+ }
4628
+ async isSaved(type, id) {
4629
+ return (await this.get()).has(savedItemKey(type, id));
4630
+ }
4631
+ registerFetch(withMessages) {
4632
+ const fetching = this.fetch(withMessages);
4633
+ this.promises.register(fetching, 'items');
4634
+ if (withMessages) {
4635
+ this.promises.register(fetching, 'messages');
4636
+ }
4637
+ }
4638
+ async fetch(withMessages) {
4639
+ const result = await this.tracker.client.send('GetSavedItems', {
4640
+ withMessages
4641
+ });
4642
+ if (result.error) {
4643
+ throw result.error;
4644
+ }
4645
+ this.apply(result.data, withMessages);
4646
+ }
4647
+ apply(ev, withMessages) {
4648
+ this.items.reconcile(...ev.items);
4649
+ if (withMessages) {
4650
+ this.messages.reconcile(...ev.messages);
4651
+ }
4652
+ }
4653
+ refresh() {
4654
+ if (this.messagesWanted) {
4655
+ this.registerFetch(true);
4656
+ } else if (this.itemsWanted) {
4657
+ this.registerFetch(false);
4658
+ }
4659
+ this.promises.get('items')?.catch(() => {});
4660
+ }
4661
+ handleItemSaved(ev) {
4662
+ if (!this.itemsWanted) {
4663
+ return;
4664
+ }
4665
+ this.items.set(ev.item);
4666
+ if (this.messagesWanted && ev.message) {
4667
+ this.messages.set(ev.message);
4668
+ }
4669
+ }
4670
+ handleItemUnsaved(ev) {
4671
+ this.items.delete(savedItemKey(ev.type, ev.id));
4672
+ if (ev.type === 'Message') {
4673
+ this.messages.delete(ev.id);
4674
+ }
4675
+ }
4676
+ handleMessageUpdated(ev) {
4677
+ if (this.messages.has(ev.message.id)) {
4678
+ this.messages.set(ev.message);
4679
+ }
4680
+ }
4681
+ handleMessagesRedacted(ev) {
4682
+ const saved = ev.ids.filter(id => this.items.has(savedItemKey('Message', id)));
4683
+ this.items.delete(...saved.map(id => savedItemKey('Message', id)));
4684
+ this.messages.delete(...saved.filter(id => this.messages.has(id)));
4685
+ }
4686
+ handleRoomDeleted(ev) {
4687
+ this.hiddenRoomIds.delete(ev.id);
4688
+ this.deleteRoomItems(ev.id);
4689
+ }
4690
+ handleRoomLeft(ev) {
4691
+ // The server keeps them and hands them back once you rejoin
4692
+ if (this.deleteRoomItems(ev.id)) {
4693
+ this.hiddenRoomIds.add(ev.id);
4694
+ }
4695
+ }
4696
+ handleRoomJoined(ev) {
4697
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4698
+ return;
4699
+ }
4700
+
4701
+ // Joining a space joins its rooms one by one; one request brings back the items of all of them
4702
+ this.refreshScheduled = true;
4703
+ setTimeout(() => {
4704
+ this.refreshScheduled = false;
4705
+ this.refresh();
4706
+ }, 0);
4707
+ }
4708
+ deleteRoomItems(roomId) {
4709
+ const items = this.items.items.filter(item => item.roomId === roomId);
4710
+ this.items.delete(...items.map(keyOf));
4711
+ this.messages.delete(...items.filter(item => this.messages.has(item.id)).map(item => item.id));
4712
+ return items.length > 0;
4713
+ }
4714
+ handleSession() {
4715
+ this.promises.forgetAll();
4716
+ this.refresh();
4717
+ }
4718
+ }
4273
4719
  ;// ./src/state-tracker/ChatStateTracker.ts
4274
4720
 
4275
4721
 
@@ -4280,6 +4726,8 @@ class CallsManager {
4280
4726
 
4281
4727
 
4282
4728
 
4729
+
4730
+
4283
4731
  class ChatStateTracker {
4284
4732
  client;
4285
4733
 
@@ -4317,6 +4765,19 @@ class ChatStateTracker {
4317
4765
  * State of the calls in your rooms and of the calls ringing at you.
4318
4766
  */
4319
4767
  calls;
4768
+
4769
+ /**
4770
+ * Your latest personal events from all spaces (mentions, replies, reactions, followed threads, missed calls) and the
4771
+ * activities the server publishes. Private conversations keep their own unread state. Nothing is fetched until you
4772
+ * ask for it. Not part of the state snapshot.
4773
+ */
4774
+ activities;
4775
+
4776
+ /**
4777
+ * The rooms and messages you saved, from all spaces. Nothing is fetched until you ask for it. Not part of the state
4778
+ * snapshot.
4779
+ */
4780
+ savedItems;
4320
4781
  _me = null;
4321
4782
  deferredSession = new DeferredTask();
4322
4783
  sessionReceived = false;
@@ -4331,6 +4792,8 @@ class ChatStateTracker {
4331
4792
  this.users = new UsersManager(this);
4332
4793
  this.relationships = new RelationshipsManager(this);
4333
4794
  this.calls = new CallsManager(this);
4795
+ this.activities = new ActivitiesManager(this);
4796
+ this.savedItems = new SavedItemsManager(this);
4334
4797
 
4335
4798
  // Registered after the managers, so it runs once they have applied the session.
4336
4799
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -4967,10 +5430,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4967
5430
  ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4968
5431
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4969
5432
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
5433
+ ErrorCode["SavedItemsLimitReached"] = "SavedItemsLimitReachedException";
4970
5434
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
4971
5435
  ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
4972
5436
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4973
5437
  ErrorCode["UserNotFound"] = "UserNotFoundException";
5438
+ ErrorCode["UserType"] = "UserTypeException";
4974
5439
  return ErrorCode;
4975
5440
  }({});
4976
5441
  ;// ./src/protocol/schemes/MessageEmbed.ts
@@ -5113,6 +5578,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
5113
5578
 
5114
5579
 
5115
5580
 
5116
- export { AbstractRestClient, CallMemberFlag, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, MessageEmbedFlag, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
5581
+
5582
+ export { AbstractRestClient, CallMemberFlag, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, MessageEmbedFlag, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm, savedItemKey };
5117
5583
 
5118
5584
  //# sourceMappingURL=index.mjs.map