@devanachat/sdk 0.13.0 → 0.15.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 (59) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/build/index.cjs.js +686 -15
  3. package/build/index.cjs.js.map +1 -1
  4. package/build/index.mjs +684 -15
  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 +28 -1
  9. package/build/types/Permissions.d.ts +38 -0
  10. package/build/types/index.d.ts +6 -3
  11. package/build/types/protocol/index.d.ts +35 -2
  12. package/build/types/protocol/schemes/Activity.d.ts +16 -0
  13. package/build/types/protocol/schemes/Call.d.ts +35 -0
  14. package/build/types/protocol/schemes/IncomingCall.d.ts +6 -0
  15. package/build/types/protocol/schemes/Message.d.ts +3 -1
  16. package/build/types/protocol/schemes/MessageCall.d.ts +9 -0
  17. package/build/types/protocol/schemes/Room.d.ts +2 -0
  18. package/build/types/protocol/schemes/RoomCall.d.ts +6 -0
  19. package/build/types/protocol/schemes/SavedItem.d.ts +7 -0
  20. package/build/types/protocol/schemes/UserData.d.ts +1 -0
  21. package/build/types/protocol/schemes/UserState.d.ts +4 -0
  22. package/build/types/protocol/schemes/commands/DeclineCall.d.ts +3 -0
  23. package/build/types/protocol/schemes/commands/GetActivities.d.ts +3 -0
  24. package/build/types/protocol/schemes/commands/GetCallMembers.d.ts +5 -0
  25. package/build/types/protocol/schemes/commands/GetSavedItems.d.ts +3 -0
  26. package/build/types/protocol/schemes/commands/InviteToCall.d.ts +5 -0
  27. package/build/types/protocol/schemes/commands/JoinCall.d.ts +4 -0
  28. package/build/types/protocol/schemes/commands/KickCallMember.d.ts +4 -0
  29. package/build/types/protocol/schemes/commands/MuteCallMember.d.ts +4 -0
  30. package/build/types/protocol/schemes/commands/SaveItem.d.ts +5 -0
  31. package/build/types/protocol/schemes/commands/SetPermissionOverwrites.d.ts +1 -0
  32. package/build/types/protocol/schemes/commands/SetSessionData.d.ts +1 -0
  33. package/build/types/protocol/schemes/commands/SetUserData.d.ts +1 -0
  34. package/build/types/protocol/schemes/commands/UnsaveItem.d.ts +5 -0
  35. package/build/types/protocol/schemes/commands/UpdateActivities.d.ts +4 -0
  36. package/build/types/protocol/schemes/commands/UpdateCallMember.d.ts +7 -0
  37. package/build/types/protocol/schemes/commands/UpdateRoom.d.ts +2 -0
  38. package/build/types/protocol/schemes/events/Activities.d.ts +9 -0
  39. package/build/types/protocol/schemes/events/ActivityDeleted.d.ts +3 -0
  40. package/build/types/protocol/schemes/events/ActivityUpdated.d.ts +4 -0
  41. package/build/types/protocol/schemes/events/CallJoined.d.ts +7 -0
  42. package/build/types/protocol/schemes/events/CallMemberJoined.d.ts +5 -0
  43. package/build/types/protocol/schemes/events/CallMemberLeft.d.ts +4 -0
  44. package/build/types/protocol/schemes/events/CallMemberUpdated.d.ts +6 -0
  45. package/build/types/protocol/schemes/events/CallMembers.d.ts +5 -0
  46. package/build/types/protocol/schemes/events/CallUpdated.d.ts +5 -0
  47. package/build/types/protocol/schemes/events/CallVideoLimitReached.d.ts +4 -0
  48. package/build/types/protocol/schemes/events/Error.d.ts +9 -1
  49. package/build/types/protocol/schemes/events/IncomingCallUpdated.d.ts +5 -0
  50. package/build/types/protocol/schemes/events/ItemSaved.d.ts +6 -0
  51. package/build/types/protocol/schemes/events/ItemUnsaved.d.ts +5 -0
  52. package/build/types/protocol/schemes/events/NewActivity.d.ts +8 -0
  53. package/build/types/protocol/schemes/events/SavedItems.d.ts +6 -0
  54. package/build/types/state-tracker/ActivitiesManager.d.ts +63 -0
  55. package/build/types/state-tracker/CallsManager.d.ts +74 -0
  56. package/build/types/state-tracker/ChatStateTracker.d.ts +18 -0
  57. package/build/types/state-tracker/SavedItemsManager.d.ts +46 -0
  58. package/build/types/state-tracker/StateSnapshot.d.ts +1 -1
  59. package/package.json +1 -1
package/build/index.mjs CHANGED
@@ -2240,7 +2240,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2240
2240
  /**
2241
2241
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2242
2242
  */
2243
- const STATE_SNAPSHOT_VERSION = 3;
2243
+ const STATE_SNAPSHOT_VERSION = 4;
2244
2244
 
2245
2245
  /**
2246
2246
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -3364,6 +3364,12 @@ class PermissionDefinition {
3364
3364
  value;
3365
3365
  maxLayer;
3366
3366
  }
3367
+ const WORD = 2 ** 32;
3368
+ function combineWords(a, b, operation) {
3369
+ const high = operation(Math.floor(a / WORD), Math.floor(b / WORD)) >>> 0;
3370
+ const low = operation(a % WORD, b % WORD) >>> 0;
3371
+ return high * WORD + low;
3372
+ }
3367
3373
  class Permissions {
3368
3374
  static list = {
3369
3375
  Root: {
@@ -3382,7 +3388,6 @@ class Permissions {
3382
3388
  value: 1 << 3,
3383
3389
  maxLayer: Layer.Space
3384
3390
  },
3385
- //ManageRoom: {value: 1 << 4, maxLayer: Layer.Room},
3386
3391
  CreateTopics: {
3387
3392
  value: 1 << 5,
3388
3393
  maxLayer: Layer.Room
@@ -3482,8 +3487,63 @@ class Permissions {
3482
3487
  EditMessages: {
3483
3488
  value: 1 << 29,
3484
3489
  maxLayer: Layer.Topic
3490
+ },
3491
+ JoinCalls: {
3492
+ value: 2 ** 30,
3493
+ maxLayer: Layer.Room
3494
+ },
3495
+ ShareVideo: {
3496
+ value: 2 ** 31,
3497
+ maxLayer: Layer.Room
3498
+ },
3499
+ InviteToCall: {
3500
+ value: 2 ** 32,
3501
+ maxLayer: Layer.Room
3502
+ },
3503
+ ManageCalls: {
3504
+ value: 2 ** 33,
3505
+ maxLayer: Layer.Room
3506
+ },
3507
+ StartCalls: {
3508
+ value: 2 ** 34,
3509
+ maxLayer: Layer.Room
3485
3510
  }
3486
3511
  };
3512
+
3513
+ /**
3514
+ * Whether the permission mask (e.g. from {@link PermissionsManager.calculatePermissions}) grants the permission.
3515
+ * Use it and {@link union} / {@link subtract} instead of `&` and `|`: JavaScript bitwise operators keep only
3516
+ * 32 bits, and permissions go beyond them.
3517
+ */
3518
+ static has(mask, name) {
3519
+ const value = this.list[name].value;
3520
+ return combineWords(mask, value, (a, b) => a & b) === value;
3521
+ }
3522
+
3523
+ /**
3524
+ * The permission masks combined (`a | b`), safe for permissions beyond 32 bits.
3525
+ */
3526
+ static union(...masks) {
3527
+ let result = 0;
3528
+ for (const mask of masks) {
3529
+ result = combineWords(result, mask, (a, b) => a | b);
3530
+ }
3531
+ return result;
3532
+ }
3533
+
3534
+ /**
3535
+ * The mask without the permissions of `removed` (`mask & ~removed`), safe for permissions beyond 32 bits.
3536
+ */
3537
+ static subtract(mask, removed) {
3538
+ return combineWords(mask, removed, (a, b) => a & ~b);
3539
+ }
3540
+
3541
+ /**
3542
+ * Mask of all the permissions this version of the SDK knows - for `SetPermissionOverwrites.knownPermissions`.
3543
+ */
3544
+ static getKnownMask() {
3545
+ return this.union(...Object.values(this.list).map(permission => permission.value));
3546
+ }
3487
3547
  static getNames() {
3488
3548
  return Object.keys(this.list);
3489
3549
  }
@@ -3547,11 +3607,11 @@ class PermissionsManager extends EventTarget {
3547
3607
  }
3548
3608
  const ownedPermissions = await this.calculatePermissions(location);
3549
3609
  const missing = [];
3550
- permissionNames.forEach(name => {
3551
- if (~ownedPermissions & Permissions.getByName(name).value) {
3610
+ for (const name of permissionNames) {
3611
+ if (!Permissions.has(ownedPermissions, name)) {
3552
3612
  missing.push(name);
3553
3613
  }
3554
- });
3614
+ }
3555
3615
  return {
3556
3616
  ok: missing.length === 0,
3557
3617
  hasAll: missing.length === 0,
@@ -3702,8 +3762,8 @@ class PermissionsManager extends EventTarget {
3702
3762
  for (const {
3703
3763
  overwrites
3704
3764
  } of rolesOverwrites) {
3705
- allow |= overwrites.allow ?? 0;
3706
- deny |= overwrites.deny ?? 0;
3765
+ allow = Permissions.union(allow, overwrites.allow ?? 0);
3766
+ deny = Permissions.union(deny, overwrites.deny ?? 0);
3707
3767
  }
3708
3768
  return {
3709
3769
  allow,
@@ -3713,19 +3773,15 @@ class PermissionsManager extends EventTarget {
3713
3773
  resolveOverwritesHierarchy(permissionOverwritesValues) {
3714
3774
  let result = 0;
3715
3775
  for (const value of permissionOverwritesValues) {
3716
- if (value.allow & Permissions.getByName('Root').value) {
3776
+ if (Permissions.has(value.allow ?? 0, 'Root')) {
3717
3777
  return this.getRootAccessValue();
3718
3778
  }
3719
- result = result & ~value.deny | value.allow;
3779
+ result = Permissions.union(Permissions.subtract(result, value.deny ?? 0), value.allow ?? 0);
3720
3780
  }
3721
3781
  return result;
3722
3782
  }
3723
3783
  getRootAccessValue() {
3724
- let result = 0;
3725
- for (const name of Permissions.getNames()) {
3726
- result |= Permissions.getByName(name).value;
3727
- }
3728
- return result;
3784
+ return Permissions.union(...Permissions.getNames().map(name => Permissions.getByName(name).value));
3729
3785
  }
3730
3786
  async fetchComputedPermissions(location) {
3731
3787
  const result = await this.tracker.client.send('GetComputedPermissions', {
@@ -4035,6 +4091,578 @@ class RelationshipsManager {
4035
4091
  this.promises.forgetAll();
4036
4092
  }
4037
4093
  }
4094
+ ;// ./src/state-tracker/CallsManager.ts
4095
+
4096
+ class CallsManager {
4097
+ list = new ObservableIndexedObjectCollection(call => call.location.roomId);
4098
+ ringing = new ObservableIndexedObjectCollection(incoming => incoming.call.location.roomId);
4099
+ constructor(tracker) {
4100
+ this.tracker = tracker;
4101
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
4102
+ this.tracker.client.on('CallUpdated', ev => this.handleCallUpdated(ev));
4103
+ this.tracker.client.on('CallMemberJoined', ev => this.handleMemberChanged(ev.roomId, ev.member.user.id, ev.member));
4104
+ this.tracker.client.on('CallMemberUpdated', ev => this.handleMemberChanged(ev.roomId, ev.userId, ev.member));
4105
+ this.tracker.client.on('CallMemberLeft', ev => this.handleMemberChanged(ev.roomId, ev.userId));
4106
+ this.tracker.client.on('IncomingCallUpdated', ev => this.handleIncomingCallUpdated(ev));
4107
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomGone(ev));
4108
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomGone(ev));
4109
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceGone(ev));
4110
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceGone(ev));
4111
+ }
4112
+
4113
+ /**
4114
+ * Ongoing calls in the rooms you are a member of, keyed by room id - at most one per room. Filled with the
4115
+ * session and kept current by the server; a call leaves the collection when its last member leaves.
4116
+ * Not part of the state snapshot, so it stays empty until the first session.
4117
+ */
4118
+ async get() {
4119
+ await this.tracker.getMe();
4120
+ return this.list;
4121
+ }
4122
+
4123
+ /**
4124
+ * Calls ringing at you, keyed by room id. A call leaves the collection when it is answered or declined on any of
4125
+ * your devices, or when it ends. Filled with the session, like the ongoing calls.
4126
+ */
4127
+ async getRinging() {
4128
+ await this.tracker.getMe();
4129
+ return this.ringing;
4130
+ }
4131
+
4132
+ /**
4133
+ * Members of the call with a raised hand, in the order they raised it - the queue in the `Queue` mode.
4134
+ */
4135
+ getQueue(call) {
4136
+ return call.members.filter(member => member.handRaisedAt)
4137
+ // Whole seconds; the server breaks ties by comparing user ids as plain strings.
4138
+ .sort((a, b) => Date.parse(a.handRaisedAt) - Date.parse(b.handRaisedAt) || (a.user.id < b.user.id ? -1 : Number(a.user.id > b.user.id)));
4139
+ }
4140
+
4141
+ /**
4142
+ * A page of the members of the call the call message stands for, in the order they joined. The message itself
4143
+ * carries only some of them (`MessageCall.partialMembers`) and their count.
4144
+ */
4145
+ async getMembers(messageId, page = {}) {
4146
+ return (await this.send('GetCallMembers', {
4147
+ messageId,
4148
+ ...page
4149
+ })).members;
4150
+ }
4151
+
4152
+ /**
4153
+ * Join the call in the room, starting it if there is none. Connect to the media server with the returned access
4154
+ * yourself; leaving the call is disconnecting from it. Joining another call makes the server end your
4155
+ * participation in the previous one. In the `Stage` and `Queue` modes you join as a listener (a moderator as a
4156
+ * speaker), and the title given when starting the call names its topic.
4157
+ */
4158
+ join(roomId, title) {
4159
+ return this.send('JoinCall', {
4160
+ roomId,
4161
+ title
4162
+ });
4163
+ }
4164
+
4165
+ /**
4166
+ * Stop the call ringing at you, on all of your devices. In a one-to-one private room it also ends the call.
4167
+ */
4168
+ async decline(roomId) {
4169
+ await this.send('DeclineCall', {
4170
+ roomId
4171
+ });
4172
+ }
4173
+
4174
+ /**
4175
+ * Invite the given members of the room, or the room members having one of the roles, to the call - it rings at
4176
+ * them. Members already in the call and you are skipped.
4177
+ */
4178
+ async invite(roomId, target) {
4179
+ await this.send('InviteToCall', {
4180
+ roomId,
4181
+ ...target
4182
+ });
4183
+ }
4184
+
4185
+ /**
4186
+ * Turn off the microphone of a call member. Only they can turn it on again.
4187
+ */
4188
+ async muteMember(roomId, userId) {
4189
+ await this.send('MuteCallMember', {
4190
+ roomId,
4191
+ userId
4192
+ });
4193
+ }
4194
+ async kickMember(roomId, userId) {
4195
+ await this.send('KickCallMember', {
4196
+ roomId,
4197
+ userId
4198
+ });
4199
+ }
4200
+
4201
+ /**
4202
+ * Raise or lower your hand (in the `Queue` mode: enter or leave the queue) and leave the stage, which in the
4203
+ * `Queue` mode ends your turn. A moderator also moves a member to the stage and off it (skipping their turn),
4204
+ * lowers their hand and blocks them from raising it until the call ends.
4205
+ */
4206
+ async updateMember(roomId, userId, change) {
4207
+ await this.send('UpdateCallMember', {
4208
+ roomId,
4209
+ userId,
4210
+ ...change
4211
+ });
4212
+ }
4213
+ async send(type, data) {
4214
+ const result = await this.tracker.client.send(type, data);
4215
+ if (result.error) {
4216
+ throw result.error;
4217
+ }
4218
+ return result.data;
4219
+ }
4220
+ handleSession(ev) {
4221
+ this.list.reconcile(...ev.state.calls);
4222
+ this.ringing.reconcile(...ev.state.incomingCalls);
4223
+ }
4224
+ handleCallUpdated(ev) {
4225
+ if (ev.call) {
4226
+ // An update sent before the server learned you left the room
4227
+ if (this.tracker.rooms._getRoom(ev.roomId)) {
4228
+ this.setCall(ev.call);
4229
+ }
4230
+ } else {
4231
+ this.list.delete(ev.roomId);
4232
+ this.ringing.delete(ev.roomId);
4233
+ }
4234
+ }
4235
+ handleIncomingCallUpdated(ev) {
4236
+ if (ev.incomingCall) {
4237
+ this.ringing.set(ev.incomingCall);
4238
+ } else {
4239
+ this.ringing.delete(ev.roomId);
4240
+ }
4241
+ }
4242
+ handleMemberChanged(roomId, userId, member) {
4243
+ const call = this.list.get(roomId);
4244
+ if (!call) {
4245
+ return;
4246
+ }
4247
+ const members = call.members.filter(item => item.user.id !== userId);
4248
+ if (member) {
4249
+ const index = call.members.findIndex(item => item.user.id === userId);
4250
+ members.splice(index === -1 ? members.length : index, 0, member);
4251
+ }
4252
+ this.setCall({
4253
+ ...call,
4254
+ members
4255
+ });
4256
+ }
4257
+ setCall(call) {
4258
+ this.list.set(call);
4259
+ const incoming = this.ringing.get(call.location.roomId);
4260
+ if (incoming) {
4261
+ this.ringing.set({
4262
+ ...incoming,
4263
+ call
4264
+ });
4265
+ }
4266
+ }
4267
+ handleRoomGone(ev) {
4268
+ this.list.delete(ev.id);
4269
+ this.ringing.delete(ev.id);
4270
+ }
4271
+ handleSpaceGone(ev) {
4272
+ const roomIdsOf = calls => calls.filter(call => call.location.spaceId === ev.id).map(call => call.location.roomId);
4273
+ this.list.delete(...roomIdsOf(this.list.items));
4274
+ this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4275
+ }
4276
+ }
4277
+ ;// ./src/state-tracker/ActivitiesManager.ts
4278
+
4279
+
4280
+
4281
+ // Mirror the server, so a live activity joins its group as the stored one did
4282
+ const VISIBLE_LIMIT = 20;
4283
+ const GROUP_SCAN = 5;
4284
+ const MAX_ACTORS = 3;
4285
+ const time = isoDate => isoDate ? Date.parse(isoDate) : 0;
4286
+ const newestFirst = (a, b) => time(b.createdAt) - time(a.createdAt);
4287
+
4288
+ // A reaction is to one's own message, so acknowledging it says nothing about the reaction
4289
+ const isReadWithAck = activity => activity.type !== 'Reaction' && activity.type !== 'Custom';
4290
+
4291
+ // Message ids are time-ordered and their base58 form has a fixed length, so they compare as strings
4292
+ const isAcknowledged = (activity, topicId, lastAckMessageId) => isReadWithAck(activity) && activity.location?.topicId === topicId && activity.messageId !== null && activity.messageId <= lastAckMessageId;
4293
+ class ActivitiesManager extends EventTarget {
4294
+ activities = new ObservableIndexedObjectCollection('id');
4295
+ messages = new ObservableIndexedObjectCollection('id');
4296
+ users = new ObservableIndexedObjectCollection('id');
4297
+ promises = new PromiseRegistry();
4298
+ acks = new Map();
4299
+ hiddenRoomIds = new Set();
4300
+ activitiesWanted = false;
4301
+ messagesWanted = false;
4302
+ refreshScheduled = false;
4303
+ seen = null;
4304
+ constructor(tracker) {
4305
+ super();
4306
+ this.tracker = tracker;
4307
+ this.tracker.client.on('NewActivity', ev => this.handleNewActivity(ev));
4308
+ this.tracker.client.on('ActivityUpdated', ev => this.handleActivityUpdated(ev));
4309
+ this.tracker.client.on('ActivityDeleted', ev => this.handleActivityDeleted(ev));
4310
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
4311
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4312
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4313
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4314
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4315
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4316
+ this.tracker.client.on('Session', () => this.handleSession());
4317
+ }
4318
+
4319
+ /**
4320
+ * Your latest activities, keyed by id; always the same collection. The first call fetches them, later ones resolve
4321
+ * with them. Once fetched, they are fetched again after every reconnect, also when the first fetch failed because
4322
+ * the connection was not ready yet. The collection keeps no meaningful order - sort by `createdAt`. Marking the list
4323
+ * as seen and clearing it is done with the `UpdateActivities` command.
4324
+ * @param fetchWithMessages Fetch the messages and the actors of the activities along, so {@link getMessages} and
4325
+ * {@link getUsers} need no request.
4326
+ */
4327
+ async get(fetchWithMessages = false) {
4328
+ if (fetchWithMessages) {
4329
+ await this.getMessages();
4330
+ }
4331
+ if (this.promises.notExist('activities')) {
4332
+ this.activitiesWanted = true;
4333
+ this.registerFetch(false);
4334
+ }
4335
+ await this.promises.get('activities');
4336
+ return this.activities;
4337
+ }
4338
+
4339
+ /**
4340
+ * The messages the activities point at, keyed by message id; always the same collection. The first call fetches
4341
+ * them together with the list of {@link get}, unless they were fetched already; afterwards they come with new
4342
+ * activities, follow the edits and are fetched again after every reconnect.
4343
+ */
4344
+ async getMessages() {
4345
+ if (this.promises.notExist('messages')) {
4346
+ this.activitiesWanted = true;
4347
+ this.messagesWanted = true;
4348
+ this.registerFetch(true);
4349
+ }
4350
+ await this.promises.get('messages');
4351
+ return this.messages;
4352
+ }
4353
+
4354
+ /**
4355
+ * The actors of the activities, keyed by user id; always the same collection, fetched and kept together with
4356
+ * {@link getMessages}.
4357
+ */
4358
+ async getUsers() {
4359
+ await this.getMessages();
4360
+ return this.users;
4361
+ }
4362
+
4363
+ /**
4364
+ * When the list was last seen, on any device; null until it is fetched or while it was never seen. A change emits
4365
+ * `seenAtChange`. Activities created later that are not {@link Activity.isRead} are the unread ones.
4366
+ */
4367
+ get seenAt() {
4368
+ return this.seen;
4369
+ }
4370
+ registerFetch(withMessages) {
4371
+ const fetching = this.fetch(withMessages);
4372
+ this.promises.register(fetching, 'activities');
4373
+ if (withMessages) {
4374
+ this.promises.register(fetching, 'messages');
4375
+ }
4376
+ }
4377
+ async fetch(withMessages) {
4378
+ const result = await this.tracker.client.send('GetActivities', {
4379
+ withMessages
4380
+ });
4381
+ if (result.error) {
4382
+ throw result.error;
4383
+ }
4384
+ this.apply(result.data, withMessages);
4385
+ }
4386
+ apply(ev, withMessages) {
4387
+ this.activities.reconcile(...ev.activities);
4388
+ if (withMessages) {
4389
+ this.messages.reconcile(...ev.messages);
4390
+ this.users.reconcile(...ev.users);
4391
+ }
4392
+ this.setSeen(ev.seenAt);
4393
+ }
4394
+ refresh() {
4395
+ if (this.messagesWanted) {
4396
+ this.registerFetch(true);
4397
+ } else if (this.activitiesWanted) {
4398
+ this.registerFetch(false);
4399
+ }
4400
+ this.promises.get('activities')?.catch(() => {});
4401
+ }
4402
+ setSeen(seenAt) {
4403
+ if (seenAt !== this.seen) {
4404
+ this.seen = seenAt;
4405
+ this.emit('seenAtChange', {});
4406
+ }
4407
+ }
4408
+ handleNewActivity(ev) {
4409
+ if (!this.activitiesWanted) {
4410
+ return;
4411
+ }
4412
+ const topicId = ev.activity.location?.topicId ?? '';
4413
+ const lastAck = this.acks.get(topicId);
4414
+ const added = lastAck && isAcknowledged(ev.activity, topicId, lastAck) ? {
4415
+ ...ev.activity,
4416
+ isRead: true
4417
+ } : ev.activity;
4418
+ const newest = this.activities.items.sort(newestFirst);
4419
+ const group = added.groupKey === null ? undefined : newest.slice(0, GROUP_SCAN).find(activity => activity.groupKey === added.groupKey);
4420
+ if (group && time(group.createdAt) > time(this.seen)) {
4421
+ this.activities.set({
4422
+ ...added,
4423
+ id: group.id,
4424
+ count: group.count + 1,
4425
+ actorIds: [...new Set([...added.actorIds, ...group.actorIds])].slice(0, MAX_ACTORS)
4426
+ });
4427
+ } else {
4428
+ this.activities.set(added);
4429
+ this.activities.delete(...newest.slice(VISIBLE_LIMIT - 1).map(activity => activity.id));
4430
+ }
4431
+ if (this.messagesWanted) {
4432
+ if (ev.message) {
4433
+ this.messages.set(ev.message);
4434
+ }
4435
+ this.users.set(...ev.users);
4436
+ }
4437
+ }
4438
+ handleActivityUpdated(ev) {
4439
+ if (time(ev.seenAt) > time(this.seen)) {
4440
+ this.setSeen(ev.seenAt);
4441
+ }
4442
+ if (ev.cleared) {
4443
+ this.activities.deleteAll();
4444
+ this.messages.deleteAll();
4445
+ this.users.deleteAll();
4446
+ }
4447
+ }
4448
+ handleActivityDeleted(ev) {
4449
+ if (this.activities.has(ev.id)) {
4450
+ this.activities.delete(ev.id);
4451
+ }
4452
+ }
4453
+ handleFollowedTopicUpdated(ev) {
4454
+ const {
4455
+ location,
4456
+ lastAckMessageId
4457
+ } = ev.followedTopic;
4458
+ if (!location.topicId || !lastAckMessageId) {
4459
+ return;
4460
+ }
4461
+
4462
+ // An acknowledgement may come before the activity of the same message
4463
+ this.acks.set(location.topicId, lastAckMessageId);
4464
+ const read = this.activities.items.filter(activity => !activity.isRead && isAcknowledged(activity, location.topicId, lastAckMessageId)).map(activity => ({
4465
+ ...activity,
4466
+ isRead: true
4467
+ }));
4468
+ this.activities.set(...read);
4469
+ }
4470
+ handleMessageUpdated(ev) {
4471
+ if (this.messages.has(ev.message.id)) {
4472
+ this.messages.set(ev.message);
4473
+ }
4474
+ }
4475
+ handleMessagesRedacted(ev) {
4476
+ const ids = new Set(ev.ids);
4477
+ this.deleteActivities(activity => activity.messageId !== null && ids.has(activity.messageId));
4478
+ }
4479
+ handleRoomDeleted(ev) {
4480
+ this.hiddenRoomIds.delete(ev.id);
4481
+ this.deleteActivities(activity => activity.location?.roomId === ev.id);
4482
+ }
4483
+ handleRoomLeft(ev) {
4484
+ // The server keeps them and hands them back once you rejoin
4485
+ if (this.deleteActivities(activity => activity.location?.roomId === ev.id)) {
4486
+ this.hiddenRoomIds.add(ev.id);
4487
+ }
4488
+ }
4489
+ handleRoomJoined(ev) {
4490
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4491
+ return;
4492
+ }
4493
+
4494
+ // Joining a space joins its rooms one by one; one request brings back the activities of all of them
4495
+ this.refreshScheduled = true;
4496
+ setTimeout(() => {
4497
+ this.refreshScheduled = false;
4498
+ this.refresh();
4499
+ }, 0);
4500
+ }
4501
+ deleteActivities(predicate) {
4502
+ const deleted = this.activities.items.filter(predicate);
4503
+ const messageIds = deleted.map(activity => activity.messageId).filter(id => id !== null && this.messages.has(id));
4504
+ this.activities.delete(...deleted.map(activity => activity.id));
4505
+ this.messages.delete(...messageIds);
4506
+ return deleted.length > 0;
4507
+ }
4508
+ handleSession() {
4509
+ this.acks.clear();
4510
+ this.promises.forgetAll();
4511
+ this.refresh();
4512
+ }
4513
+ }
4514
+ ;// ./src/state-tracker/SavedItemsManager.ts
4515
+
4516
+
4517
+ /**
4518
+ * The key of a saved item in the collection returned by {@link SavedItemsManager.get}.
4519
+ */
4520
+ const savedItemKey = (type, id) => `${type}:${id}`;
4521
+ const keyOf = item => savedItemKey(item.type, item.id);
4522
+ class SavedItemsManager {
4523
+ items = new ObservableIndexedObjectCollection(keyOf);
4524
+ messages = new ObservableIndexedObjectCollection('id');
4525
+ promises = new PromiseRegistry();
4526
+ hiddenRoomIds = new Set();
4527
+ itemsWanted = false;
4528
+ messagesWanted = false;
4529
+ refreshScheduled = false;
4530
+ constructor(tracker) {
4531
+ this.tracker = tracker;
4532
+ this.tracker.client.on('ItemSaved', ev => this.handleItemSaved(ev));
4533
+ this.tracker.client.on('ItemUnsaved', ev => this.handleItemUnsaved(ev));
4534
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4535
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4536
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4537
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4538
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4539
+ this.tracker.client.on('Session', () => this.handleSession());
4540
+ }
4541
+
4542
+ /**
4543
+ * The rooms and messages you saved, keyed by {@link savedItemKey}; always the same collection. The first call fetches
4544
+ * the list, later ones resolve with it. Items of rooms you are not a member of are left out until you rejoin. The
4545
+ * collection keeps no meaningful order - sort by `savedAt`. Once fetched, the list is fetched again after every
4546
+ * reconnect. Saving and unsaving is done with the `SaveItem` and `UnsaveItem` commands.
4547
+ * @param fetchWithMessages Fetch the contents of the saved messages along, so {@link getMessages} needs no request.
4548
+ */
4549
+ async get(fetchWithMessages = false) {
4550
+ if (fetchWithMessages) {
4551
+ await this.getMessages();
4552
+ }
4553
+ if (this.promises.notExist('items')) {
4554
+ this.itemsWanted = true;
4555
+ this.registerFetch(false);
4556
+ }
4557
+ await this.promises.get('items');
4558
+ return this.items;
4559
+ }
4560
+
4561
+ /**
4562
+ * The contents of the saved messages, keyed by message id; always the same collection. The first call fetches them
4563
+ * together with the list of {@link get}, unless they were fetched already; afterwards they follow the edits and are
4564
+ * fetched again after every reconnect.
4565
+ */
4566
+ async getMessages() {
4567
+ if (this.promises.notExist('messages')) {
4568
+ this.itemsWanted = true;
4569
+ this.messagesWanted = true;
4570
+ this.registerFetch(true);
4571
+ }
4572
+ await this.promises.get('messages');
4573
+ return this.messages;
4574
+ }
4575
+ async isSaved(type, id) {
4576
+ return (await this.get()).has(savedItemKey(type, id));
4577
+ }
4578
+ registerFetch(withMessages) {
4579
+ const fetching = this.fetch(withMessages);
4580
+ this.promises.register(fetching, 'items');
4581
+ if (withMessages) {
4582
+ this.promises.register(fetching, 'messages');
4583
+ }
4584
+ }
4585
+ async fetch(withMessages) {
4586
+ const result = await this.tracker.client.send('GetSavedItems', {
4587
+ withMessages
4588
+ });
4589
+ if (result.error) {
4590
+ throw result.error;
4591
+ }
4592
+ this.apply(result.data, withMessages);
4593
+ }
4594
+ apply(ev, withMessages) {
4595
+ this.items.reconcile(...ev.items);
4596
+ if (withMessages) {
4597
+ this.messages.reconcile(...ev.messages);
4598
+ }
4599
+ }
4600
+ refresh() {
4601
+ if (this.messagesWanted) {
4602
+ this.registerFetch(true);
4603
+ } else if (this.itemsWanted) {
4604
+ this.registerFetch(false);
4605
+ }
4606
+ this.promises.get('items')?.catch(() => {});
4607
+ }
4608
+ handleItemSaved(ev) {
4609
+ if (!this.itemsWanted) {
4610
+ return;
4611
+ }
4612
+ this.items.set(ev.item);
4613
+ if (this.messagesWanted && ev.message) {
4614
+ this.messages.set(ev.message);
4615
+ }
4616
+ }
4617
+ handleItemUnsaved(ev) {
4618
+ this.items.delete(savedItemKey(ev.type, ev.id));
4619
+ if (ev.type === 'Message') {
4620
+ this.messages.delete(ev.id);
4621
+ }
4622
+ }
4623
+ handleMessageUpdated(ev) {
4624
+ if (this.messages.has(ev.message.id)) {
4625
+ this.messages.set(ev.message);
4626
+ }
4627
+ }
4628
+ handleMessagesRedacted(ev) {
4629
+ const saved = ev.ids.filter(id => this.items.has(savedItemKey('Message', id)));
4630
+ this.items.delete(...saved.map(id => savedItemKey('Message', id)));
4631
+ this.messages.delete(...saved.filter(id => this.messages.has(id)));
4632
+ }
4633
+ handleRoomDeleted(ev) {
4634
+ this.hiddenRoomIds.delete(ev.id);
4635
+ this.deleteRoomItems(ev.id);
4636
+ }
4637
+ handleRoomLeft(ev) {
4638
+ // The server keeps them and hands them back once you rejoin
4639
+ if (this.deleteRoomItems(ev.id)) {
4640
+ this.hiddenRoomIds.add(ev.id);
4641
+ }
4642
+ }
4643
+ handleRoomJoined(ev) {
4644
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4645
+ return;
4646
+ }
4647
+
4648
+ // Joining a space joins its rooms one by one; one request brings back the items of all of them
4649
+ this.refreshScheduled = true;
4650
+ setTimeout(() => {
4651
+ this.refreshScheduled = false;
4652
+ this.refresh();
4653
+ }, 0);
4654
+ }
4655
+ deleteRoomItems(roomId) {
4656
+ const items = this.items.items.filter(item => item.roomId === roomId);
4657
+ this.items.delete(...items.map(keyOf));
4658
+ this.messages.delete(...items.filter(item => this.messages.has(item.id)).map(item => item.id));
4659
+ return items.length > 0;
4660
+ }
4661
+ handleSession() {
4662
+ this.promises.forgetAll();
4663
+ this.refresh();
4664
+ }
4665
+ }
4038
4666
  ;// ./src/state-tracker/ChatStateTracker.ts
4039
4667
 
4040
4668
 
@@ -4044,6 +4672,9 @@ class RelationshipsManager {
4044
4672
 
4045
4673
 
4046
4674
 
4675
+
4676
+
4677
+
4047
4678
  class ChatStateTracker {
4048
4679
  client;
4049
4680
 
@@ -4076,6 +4707,24 @@ class ChatStateTracker {
4076
4707
  * State of relationships with other users.
4077
4708
  */
4078
4709
  relationships;
4710
+
4711
+ /**
4712
+ * State of the calls in your rooms and of the calls ringing at you.
4713
+ */
4714
+ calls;
4715
+
4716
+ /**
4717
+ * Your latest personal events from all spaces (mentions, replies, reactions, followed threads, missed calls) and the
4718
+ * activities the server publishes. Private conversations keep their own unread state. Nothing is fetched until you
4719
+ * ask for it. Not part of the state snapshot.
4720
+ */
4721
+ activities;
4722
+
4723
+ /**
4724
+ * The rooms and messages you saved, from all spaces. Nothing is fetched until you ask for it. Not part of the state
4725
+ * snapshot.
4726
+ */
4727
+ savedItems;
4079
4728
  _me = null;
4080
4729
  deferredSession = new DeferredTask();
4081
4730
  sessionReceived = false;
@@ -4089,6 +4738,9 @@ class ChatStateTracker {
4089
4738
  this.emoticons = new EmoticonsManager(this);
4090
4739
  this.users = new UsersManager(this);
4091
4740
  this.relationships = new RelationshipsManager(this);
4741
+ this.calls = new CallsManager(this);
4742
+ this.activities = new ActivitiesManager(this);
4743
+ this.savedItems = new SavedItemsManager(this);
4092
4744
 
4093
4745
  // Registered after the managers, so it runs once they have applied the session.
4094
4746
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -4702,9 +5354,22 @@ class FilesClient extends AbstractRestClient {
4702
5354
  return this.send('GET', 'files?' + searchParams);
4703
5355
  }
4704
5356
  }
5357
+ ;// ./src/protocol/schemes/Call.ts
5358
+ let CallMemberFlag = /*#__PURE__*/function (CallMemberFlag) {
5359
+ CallMemberFlag[CallMemberFlag["Camera"] = 1] = "Camera";
5360
+ CallMemberFlag[CallMemberFlag["ScreenShare"] = 2] = "ScreenShare";
5361
+ CallMemberFlag[CallMemberFlag["Speaker"] = 4] = "Speaker";
5362
+ CallMemberFlag[CallMemberFlag["RaiseBlocked"] = 16] = "RaiseBlocked";
5363
+ return CallMemberFlag;
5364
+ }({});
4705
5365
  ;// ./src/protocol/schemes/events/Error.ts
4706
5366
  let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4707
5367
  ErrorCode["Authentication"] = "AuthenticationException";
5368
+ ErrorCode["CallFull"] = "CallFullException";
5369
+ ErrorCode["CallMode"] = "CallModeException";
5370
+ ErrorCode["CallNotFound"] = "CallNotFoundException";
5371
+ ErrorCode["CallsNotAccepted"] = "CallsNotAcceptedException";
5372
+ ErrorCode["CallsUnavailable"] = "CallsUnavailableException";
4708
5373
  ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
4709
5374
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4710
5375
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
@@ -4712,9 +5377,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4712
5377
  ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4713
5378
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4714
5379
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
5380
+ ErrorCode["SavedItemsLimitReached"] = "SavedItemsLimitReachedException";
4715
5381
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
5382
+ ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
4716
5383
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4717
5384
  ErrorCode["UserNotFound"] = "UserNotFoundException";
5385
+ ErrorCode["UserType"] = "UserTypeException";
4718
5386
  return ErrorCode;
4719
5387
  }({});
4720
5388
  ;// ./src/protocol/schemes/MessageEmbed.ts
@@ -4857,6 +5525,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4857
5525
 
4858
5526
 
4859
5527
 
4860
- export { AbstractRestClient, 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 };
5528
+
5529
+ 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 };
4861
5530
 
4862
5531
  //# sourceMappingURL=index.mjs.map