@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
@@ -40,6 +40,7 @@ __webpack_require__.r(__webpack_exports__);
40
40
  // EXPORTS
41
41
  __webpack_require__.d(__webpack_exports__, {
42
42
  AbstractRestClient: () => (/* reexport */ AbstractRestClient),
43
+ CallMemberFlag: () => (/* reexport */ CallMemberFlag),
43
44
  ErrorCode: () => (/* reexport */ ErrorCode),
44
45
  FilesClient: () => (/* reexport */ FilesClient),
45
46
  HistoryRotation: () => (/* reexport */ HistoryRotation),
@@ -68,7 +69,8 @@ __webpack_require__.d(__webpack_exports__, {
68
69
  WebSocketChatClient: () => (/* reexport */ WebSocketChatClient),
69
70
  extractUserFromMember: () => (/* reexport */ extractUserFromMember),
70
71
  getPmPeers: () => (/* reexport */ getPmPeers),
71
- isGroupPm: () => (/* reexport */ isGroupPm)
72
+ isGroupPm: () => (/* reexport */ isGroupPm),
73
+ savedItemKey: () => (/* reexport */ savedItemKey)
72
74
  });
73
75
 
74
76
  ;// ./src/EventTarget.ts
@@ -2289,7 +2291,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2289
2291
  /**
2290
2292
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2291
2293
  */
2292
- const STATE_SNAPSHOT_VERSION = 3;
2294
+ const STATE_SNAPSHOT_VERSION = 4;
2293
2295
 
2294
2296
  /**
2295
2297
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -3413,6 +3415,12 @@ class PermissionDefinition {
3413
3415
  value;
3414
3416
  maxLayer;
3415
3417
  }
3418
+ const WORD = 2 ** 32;
3419
+ function combineWords(a, b, operation) {
3420
+ const high = operation(Math.floor(a / WORD), Math.floor(b / WORD)) >>> 0;
3421
+ const low = operation(a % WORD, b % WORD) >>> 0;
3422
+ return high * WORD + low;
3423
+ }
3416
3424
  class Permissions {
3417
3425
  static list = {
3418
3426
  Root: {
@@ -3431,7 +3439,6 @@ class Permissions {
3431
3439
  value: 1 << 3,
3432
3440
  maxLayer: Layer.Space
3433
3441
  },
3434
- //ManageRoom: {value: 1 << 4, maxLayer: Layer.Room},
3435
3442
  CreateTopics: {
3436
3443
  value: 1 << 5,
3437
3444
  maxLayer: Layer.Room
@@ -3531,8 +3538,63 @@ class Permissions {
3531
3538
  EditMessages: {
3532
3539
  value: 1 << 29,
3533
3540
  maxLayer: Layer.Topic
3541
+ },
3542
+ JoinCalls: {
3543
+ value: 2 ** 30,
3544
+ maxLayer: Layer.Room
3545
+ },
3546
+ ShareVideo: {
3547
+ value: 2 ** 31,
3548
+ maxLayer: Layer.Room
3549
+ },
3550
+ InviteToCall: {
3551
+ value: 2 ** 32,
3552
+ maxLayer: Layer.Room
3553
+ },
3554
+ ManageCalls: {
3555
+ value: 2 ** 33,
3556
+ maxLayer: Layer.Room
3557
+ },
3558
+ StartCalls: {
3559
+ value: 2 ** 34,
3560
+ maxLayer: Layer.Room
3534
3561
  }
3535
3562
  };
3563
+
3564
+ /**
3565
+ * Whether the permission mask (e.g. from {@link PermissionsManager.calculatePermissions}) grants the permission.
3566
+ * Use it and {@link union} / {@link subtract} instead of `&` and `|`: JavaScript bitwise operators keep only
3567
+ * 32 bits, and permissions go beyond them.
3568
+ */
3569
+ static has(mask, name) {
3570
+ const value = this.list[name].value;
3571
+ return combineWords(mask, value, (a, b) => a & b) === value;
3572
+ }
3573
+
3574
+ /**
3575
+ * The permission masks combined (`a | b`), safe for permissions beyond 32 bits.
3576
+ */
3577
+ static union(...masks) {
3578
+ let result = 0;
3579
+ for (const mask of masks) {
3580
+ result = combineWords(result, mask, (a, b) => a | b);
3581
+ }
3582
+ return result;
3583
+ }
3584
+
3585
+ /**
3586
+ * The mask without the permissions of `removed` (`mask & ~removed`), safe for permissions beyond 32 bits.
3587
+ */
3588
+ static subtract(mask, removed) {
3589
+ return combineWords(mask, removed, (a, b) => a & ~b);
3590
+ }
3591
+
3592
+ /**
3593
+ * Mask of all the permissions this version of the SDK knows - for `SetPermissionOverwrites.knownPermissions`.
3594
+ */
3595
+ static getKnownMask() {
3596
+ return this.union(...Object.values(this.list).map(permission => permission.value));
3597
+ }
3536
3598
  static getNames() {
3537
3599
  return Object.keys(this.list);
3538
3600
  }
@@ -3596,11 +3658,11 @@ class PermissionsManager extends EventTarget {
3596
3658
  }
3597
3659
  const ownedPermissions = await this.calculatePermissions(location);
3598
3660
  const missing = [];
3599
- permissionNames.forEach(name => {
3600
- if (~ownedPermissions & Permissions.getByName(name).value) {
3661
+ for (const name of permissionNames) {
3662
+ if (!Permissions.has(ownedPermissions, name)) {
3601
3663
  missing.push(name);
3602
3664
  }
3603
- });
3665
+ }
3604
3666
  return {
3605
3667
  ok: missing.length === 0,
3606
3668
  hasAll: missing.length === 0,
@@ -3751,8 +3813,8 @@ class PermissionsManager extends EventTarget {
3751
3813
  for (const {
3752
3814
  overwrites
3753
3815
  } of rolesOverwrites) {
3754
- allow |= overwrites.allow ?? 0;
3755
- deny |= overwrites.deny ?? 0;
3816
+ allow = Permissions.union(allow, overwrites.allow ?? 0);
3817
+ deny = Permissions.union(deny, overwrites.deny ?? 0);
3756
3818
  }
3757
3819
  return {
3758
3820
  allow,
@@ -3762,19 +3824,15 @@ class PermissionsManager extends EventTarget {
3762
3824
  resolveOverwritesHierarchy(permissionOverwritesValues) {
3763
3825
  let result = 0;
3764
3826
  for (const value of permissionOverwritesValues) {
3765
- if (value.allow & Permissions.getByName('Root').value) {
3827
+ if (Permissions.has(value.allow ?? 0, 'Root')) {
3766
3828
  return this.getRootAccessValue();
3767
3829
  }
3768
- result = result & ~value.deny | value.allow;
3830
+ result = Permissions.union(Permissions.subtract(result, value.deny ?? 0), value.allow ?? 0);
3769
3831
  }
3770
3832
  return result;
3771
3833
  }
3772
3834
  getRootAccessValue() {
3773
- let result = 0;
3774
- for (const name of Permissions.getNames()) {
3775
- result |= Permissions.getByName(name).value;
3776
- }
3777
- return result;
3835
+ return Permissions.union(...Permissions.getNames().map(name => Permissions.getByName(name).value));
3778
3836
  }
3779
3837
  async fetchComputedPermissions(location) {
3780
3838
  const result = await this.tracker.client.send('GetComputedPermissions', {
@@ -4084,6 +4142,578 @@ class RelationshipsManager {
4084
4142
  this.promises.forgetAll();
4085
4143
  }
4086
4144
  }
4145
+ ;// ./src/state-tracker/CallsManager.ts
4146
+
4147
+ class CallsManager {
4148
+ list = new ObservableIndexedObjectCollection(call => call.location.roomId);
4149
+ ringing = new ObservableIndexedObjectCollection(incoming => incoming.call.location.roomId);
4150
+ constructor(tracker) {
4151
+ this.tracker = tracker;
4152
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
4153
+ this.tracker.client.on('CallUpdated', ev => this.handleCallUpdated(ev));
4154
+ this.tracker.client.on('CallMemberJoined', ev => this.handleMemberChanged(ev.roomId, ev.member.user.id, ev.member));
4155
+ this.tracker.client.on('CallMemberUpdated', ev => this.handleMemberChanged(ev.roomId, ev.userId, ev.member));
4156
+ this.tracker.client.on('CallMemberLeft', ev => this.handleMemberChanged(ev.roomId, ev.userId));
4157
+ this.tracker.client.on('IncomingCallUpdated', ev => this.handleIncomingCallUpdated(ev));
4158
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomGone(ev));
4159
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomGone(ev));
4160
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceGone(ev));
4161
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceGone(ev));
4162
+ }
4163
+
4164
+ /**
4165
+ * Ongoing calls in the rooms you are a member of, keyed by room id - at most one per room. Filled with the
4166
+ * session and kept current by the server; a call leaves the collection when its last member leaves.
4167
+ * Not part of the state snapshot, so it stays empty until the first session.
4168
+ */
4169
+ async get() {
4170
+ await this.tracker.getMe();
4171
+ return this.list;
4172
+ }
4173
+
4174
+ /**
4175
+ * Calls ringing at you, keyed by room id. A call leaves the collection when it is answered or declined on any of
4176
+ * your devices, or when it ends. Filled with the session, like the ongoing calls.
4177
+ */
4178
+ async getRinging() {
4179
+ await this.tracker.getMe();
4180
+ return this.ringing;
4181
+ }
4182
+
4183
+ /**
4184
+ * Members of the call with a raised hand, in the order they raised it - the queue in the `Queue` mode.
4185
+ */
4186
+ getQueue(call) {
4187
+ return call.members.filter(member => member.handRaisedAt)
4188
+ // Whole seconds; the server breaks ties by comparing user ids as plain strings.
4189
+ .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)));
4190
+ }
4191
+
4192
+ /**
4193
+ * A page of the members of the call the call message stands for, in the order they joined. The message itself
4194
+ * carries only some of them (`MessageCall.partialMembers`) and their count.
4195
+ */
4196
+ async getMembers(messageId, page = {}) {
4197
+ return (await this.send('GetCallMembers', {
4198
+ messageId,
4199
+ ...page
4200
+ })).members;
4201
+ }
4202
+
4203
+ /**
4204
+ * Join the call in the room, starting it if there is none. Connect to the media server with the returned access
4205
+ * yourself; leaving the call is disconnecting from it. Joining another call makes the server end your
4206
+ * participation in the previous one. In the `Stage` and `Queue` modes you join as a listener (a moderator as a
4207
+ * speaker), and the title given when starting the call names its topic.
4208
+ */
4209
+ join(roomId, title) {
4210
+ return this.send('JoinCall', {
4211
+ roomId,
4212
+ title
4213
+ });
4214
+ }
4215
+
4216
+ /**
4217
+ * Stop the call ringing at you, on all of your devices. In a one-to-one private room it also ends the call.
4218
+ */
4219
+ async decline(roomId) {
4220
+ await this.send('DeclineCall', {
4221
+ roomId
4222
+ });
4223
+ }
4224
+
4225
+ /**
4226
+ * Invite the given members of the room, or the room members having one of the roles, to the call - it rings at
4227
+ * them. Members already in the call and you are skipped.
4228
+ */
4229
+ async invite(roomId, target) {
4230
+ await this.send('InviteToCall', {
4231
+ roomId,
4232
+ ...target
4233
+ });
4234
+ }
4235
+
4236
+ /**
4237
+ * Turn off the microphone of a call member. Only they can turn it on again.
4238
+ */
4239
+ async muteMember(roomId, userId) {
4240
+ await this.send('MuteCallMember', {
4241
+ roomId,
4242
+ userId
4243
+ });
4244
+ }
4245
+ async kickMember(roomId, userId) {
4246
+ await this.send('KickCallMember', {
4247
+ roomId,
4248
+ userId
4249
+ });
4250
+ }
4251
+
4252
+ /**
4253
+ * Raise or lower your hand (in the `Queue` mode: enter or leave the queue) and leave the stage, which in the
4254
+ * `Queue` mode ends your turn. A moderator also moves a member to the stage and off it (skipping their turn),
4255
+ * lowers their hand and blocks them from raising it until the call ends.
4256
+ */
4257
+ async updateMember(roomId, userId, change) {
4258
+ await this.send('UpdateCallMember', {
4259
+ roomId,
4260
+ userId,
4261
+ ...change
4262
+ });
4263
+ }
4264
+ async send(type, data) {
4265
+ const result = await this.tracker.client.send(type, data);
4266
+ if (result.error) {
4267
+ throw result.error;
4268
+ }
4269
+ return result.data;
4270
+ }
4271
+ handleSession(ev) {
4272
+ this.list.reconcile(...ev.state.calls);
4273
+ this.ringing.reconcile(...ev.state.incomingCalls);
4274
+ }
4275
+ handleCallUpdated(ev) {
4276
+ if (ev.call) {
4277
+ // An update sent before the server learned you left the room
4278
+ if (this.tracker.rooms._getRoom(ev.roomId)) {
4279
+ this.setCall(ev.call);
4280
+ }
4281
+ } else {
4282
+ this.list.delete(ev.roomId);
4283
+ this.ringing.delete(ev.roomId);
4284
+ }
4285
+ }
4286
+ handleIncomingCallUpdated(ev) {
4287
+ if (ev.incomingCall) {
4288
+ this.ringing.set(ev.incomingCall);
4289
+ } else {
4290
+ this.ringing.delete(ev.roomId);
4291
+ }
4292
+ }
4293
+ handleMemberChanged(roomId, userId, member) {
4294
+ const call = this.list.get(roomId);
4295
+ if (!call) {
4296
+ return;
4297
+ }
4298
+ const members = call.members.filter(item => item.user.id !== userId);
4299
+ if (member) {
4300
+ const index = call.members.findIndex(item => item.user.id === userId);
4301
+ members.splice(index === -1 ? members.length : index, 0, member);
4302
+ }
4303
+ this.setCall({
4304
+ ...call,
4305
+ members
4306
+ });
4307
+ }
4308
+ setCall(call) {
4309
+ this.list.set(call);
4310
+ const incoming = this.ringing.get(call.location.roomId);
4311
+ if (incoming) {
4312
+ this.ringing.set({
4313
+ ...incoming,
4314
+ call
4315
+ });
4316
+ }
4317
+ }
4318
+ handleRoomGone(ev) {
4319
+ this.list.delete(ev.id);
4320
+ this.ringing.delete(ev.id);
4321
+ }
4322
+ handleSpaceGone(ev) {
4323
+ const roomIdsOf = calls => calls.filter(call => call.location.spaceId === ev.id).map(call => call.location.roomId);
4324
+ this.list.delete(...roomIdsOf(this.list.items));
4325
+ this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4326
+ }
4327
+ }
4328
+ ;// ./src/state-tracker/ActivitiesManager.ts
4329
+
4330
+
4331
+
4332
+ // Mirror the server, so a live activity joins its group as the stored one did
4333
+ const VISIBLE_LIMIT = 20;
4334
+ const GROUP_SCAN = 5;
4335
+ const MAX_ACTORS = 3;
4336
+ const time = isoDate => isoDate ? Date.parse(isoDate) : 0;
4337
+ const newestFirst = (a, b) => time(b.createdAt) - time(a.createdAt);
4338
+
4339
+ // A reaction is to one's own message, so acknowledging it says nothing about the reaction
4340
+ const isReadWithAck = activity => activity.type !== 'Reaction' && activity.type !== 'Custom';
4341
+
4342
+ // Message ids are time-ordered and their base58 form has a fixed length, so they compare as strings
4343
+ const isAcknowledged = (activity, topicId, lastAckMessageId) => isReadWithAck(activity) && activity.location?.topicId === topicId && activity.messageId !== null && activity.messageId <= lastAckMessageId;
4344
+ class ActivitiesManager extends EventTarget {
4345
+ activities = new ObservableIndexedObjectCollection('id');
4346
+ messages = new ObservableIndexedObjectCollection('id');
4347
+ users = new ObservableIndexedObjectCollection('id');
4348
+ promises = new PromiseRegistry();
4349
+ acks = new Map();
4350
+ hiddenRoomIds = new Set();
4351
+ activitiesWanted = false;
4352
+ messagesWanted = false;
4353
+ refreshScheduled = false;
4354
+ seen = null;
4355
+ constructor(tracker) {
4356
+ super();
4357
+ this.tracker = tracker;
4358
+ this.tracker.client.on('NewActivity', ev => this.handleNewActivity(ev));
4359
+ this.tracker.client.on('ActivityUpdated', ev => this.handleActivityUpdated(ev));
4360
+ this.tracker.client.on('ActivityDeleted', ev => this.handleActivityDeleted(ev));
4361
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
4362
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4363
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4364
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4365
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4366
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4367
+ this.tracker.client.on('Session', () => this.handleSession());
4368
+ }
4369
+
4370
+ /**
4371
+ * Your latest activities, keyed by id; always the same collection. The first call fetches them, later ones resolve
4372
+ * with them. Once fetched, they are fetched again after every reconnect, also when the first fetch failed because
4373
+ * the connection was not ready yet. The collection keeps no meaningful order - sort by `createdAt`. Marking the list
4374
+ * as seen and clearing it is done with the `UpdateActivities` command.
4375
+ * @param fetchWithMessages Fetch the messages and the actors of the activities along, so {@link getMessages} and
4376
+ * {@link getUsers} need no request.
4377
+ */
4378
+ async get(fetchWithMessages = false) {
4379
+ if (fetchWithMessages) {
4380
+ await this.getMessages();
4381
+ }
4382
+ if (this.promises.notExist('activities')) {
4383
+ this.activitiesWanted = true;
4384
+ this.registerFetch(false);
4385
+ }
4386
+ await this.promises.get('activities');
4387
+ return this.activities;
4388
+ }
4389
+
4390
+ /**
4391
+ * The messages the activities point at, keyed by message id; always the same collection. The first call fetches
4392
+ * them together with the list of {@link get}, unless they were fetched already; afterwards they come with new
4393
+ * activities, follow the edits and are fetched again after every reconnect.
4394
+ */
4395
+ async getMessages() {
4396
+ if (this.promises.notExist('messages')) {
4397
+ this.activitiesWanted = true;
4398
+ this.messagesWanted = true;
4399
+ this.registerFetch(true);
4400
+ }
4401
+ await this.promises.get('messages');
4402
+ return this.messages;
4403
+ }
4404
+
4405
+ /**
4406
+ * The actors of the activities, keyed by user id; always the same collection, fetched and kept together with
4407
+ * {@link getMessages}.
4408
+ */
4409
+ async getUsers() {
4410
+ await this.getMessages();
4411
+ return this.users;
4412
+ }
4413
+
4414
+ /**
4415
+ * When the list was last seen, on any device; null until it is fetched or while it was never seen. A change emits
4416
+ * `seenAtChange`. Activities created later that are not {@link Activity.isRead} are the unread ones.
4417
+ */
4418
+ get seenAt() {
4419
+ return this.seen;
4420
+ }
4421
+ registerFetch(withMessages) {
4422
+ const fetching = this.fetch(withMessages);
4423
+ this.promises.register(fetching, 'activities');
4424
+ if (withMessages) {
4425
+ this.promises.register(fetching, 'messages');
4426
+ }
4427
+ }
4428
+ async fetch(withMessages) {
4429
+ const result = await this.tracker.client.send('GetActivities', {
4430
+ withMessages
4431
+ });
4432
+ if (result.error) {
4433
+ throw result.error;
4434
+ }
4435
+ this.apply(result.data, withMessages);
4436
+ }
4437
+ apply(ev, withMessages) {
4438
+ this.activities.reconcile(...ev.activities);
4439
+ if (withMessages) {
4440
+ this.messages.reconcile(...ev.messages);
4441
+ this.users.reconcile(...ev.users);
4442
+ }
4443
+ this.setSeen(ev.seenAt);
4444
+ }
4445
+ refresh() {
4446
+ if (this.messagesWanted) {
4447
+ this.registerFetch(true);
4448
+ } else if (this.activitiesWanted) {
4449
+ this.registerFetch(false);
4450
+ }
4451
+ this.promises.get('activities')?.catch(() => {});
4452
+ }
4453
+ setSeen(seenAt) {
4454
+ if (seenAt !== this.seen) {
4455
+ this.seen = seenAt;
4456
+ this.emit('seenAtChange', {});
4457
+ }
4458
+ }
4459
+ handleNewActivity(ev) {
4460
+ if (!this.activitiesWanted) {
4461
+ return;
4462
+ }
4463
+ const topicId = ev.activity.location?.topicId ?? '';
4464
+ const lastAck = this.acks.get(topicId);
4465
+ const added = lastAck && isAcknowledged(ev.activity, topicId, lastAck) ? {
4466
+ ...ev.activity,
4467
+ isRead: true
4468
+ } : ev.activity;
4469
+ const newest = this.activities.items.sort(newestFirst);
4470
+ const group = added.groupKey === null ? undefined : newest.slice(0, GROUP_SCAN).find(activity => activity.groupKey === added.groupKey);
4471
+ if (group && time(group.createdAt) > time(this.seen)) {
4472
+ this.activities.set({
4473
+ ...added,
4474
+ id: group.id,
4475
+ count: group.count + 1,
4476
+ actorIds: [...new Set([...added.actorIds, ...group.actorIds])].slice(0, MAX_ACTORS)
4477
+ });
4478
+ } else {
4479
+ this.activities.set(added);
4480
+ this.activities.delete(...newest.slice(VISIBLE_LIMIT - 1).map(activity => activity.id));
4481
+ }
4482
+ if (this.messagesWanted) {
4483
+ if (ev.message) {
4484
+ this.messages.set(ev.message);
4485
+ }
4486
+ this.users.set(...ev.users);
4487
+ }
4488
+ }
4489
+ handleActivityUpdated(ev) {
4490
+ if (time(ev.seenAt) > time(this.seen)) {
4491
+ this.setSeen(ev.seenAt);
4492
+ }
4493
+ if (ev.cleared) {
4494
+ this.activities.deleteAll();
4495
+ this.messages.deleteAll();
4496
+ this.users.deleteAll();
4497
+ }
4498
+ }
4499
+ handleActivityDeleted(ev) {
4500
+ if (this.activities.has(ev.id)) {
4501
+ this.activities.delete(ev.id);
4502
+ }
4503
+ }
4504
+ handleFollowedTopicUpdated(ev) {
4505
+ const {
4506
+ location,
4507
+ lastAckMessageId
4508
+ } = ev.followedTopic;
4509
+ if (!location.topicId || !lastAckMessageId) {
4510
+ return;
4511
+ }
4512
+
4513
+ // An acknowledgement may come before the activity of the same message
4514
+ this.acks.set(location.topicId, lastAckMessageId);
4515
+ const read = this.activities.items.filter(activity => !activity.isRead && isAcknowledged(activity, location.topicId, lastAckMessageId)).map(activity => ({
4516
+ ...activity,
4517
+ isRead: true
4518
+ }));
4519
+ this.activities.set(...read);
4520
+ }
4521
+ handleMessageUpdated(ev) {
4522
+ if (this.messages.has(ev.message.id)) {
4523
+ this.messages.set(ev.message);
4524
+ }
4525
+ }
4526
+ handleMessagesRedacted(ev) {
4527
+ const ids = new Set(ev.ids);
4528
+ this.deleteActivities(activity => activity.messageId !== null && ids.has(activity.messageId));
4529
+ }
4530
+ handleRoomDeleted(ev) {
4531
+ this.hiddenRoomIds.delete(ev.id);
4532
+ this.deleteActivities(activity => activity.location?.roomId === ev.id);
4533
+ }
4534
+ handleRoomLeft(ev) {
4535
+ // The server keeps them and hands them back once you rejoin
4536
+ if (this.deleteActivities(activity => activity.location?.roomId === ev.id)) {
4537
+ this.hiddenRoomIds.add(ev.id);
4538
+ }
4539
+ }
4540
+ handleRoomJoined(ev) {
4541
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4542
+ return;
4543
+ }
4544
+
4545
+ // Joining a space joins its rooms one by one; one request brings back the activities of all of them
4546
+ this.refreshScheduled = true;
4547
+ setTimeout(() => {
4548
+ this.refreshScheduled = false;
4549
+ this.refresh();
4550
+ }, 0);
4551
+ }
4552
+ deleteActivities(predicate) {
4553
+ const deleted = this.activities.items.filter(predicate);
4554
+ const messageIds = deleted.map(activity => activity.messageId).filter(id => id !== null && this.messages.has(id));
4555
+ this.activities.delete(...deleted.map(activity => activity.id));
4556
+ this.messages.delete(...messageIds);
4557
+ return deleted.length > 0;
4558
+ }
4559
+ handleSession() {
4560
+ this.acks.clear();
4561
+ this.promises.forgetAll();
4562
+ this.refresh();
4563
+ }
4564
+ }
4565
+ ;// ./src/state-tracker/SavedItemsManager.ts
4566
+
4567
+
4568
+ /**
4569
+ * The key of a saved item in the collection returned by {@link SavedItemsManager.get}.
4570
+ */
4571
+ const savedItemKey = (type, id) => `${type}:${id}`;
4572
+ const keyOf = item => savedItemKey(item.type, item.id);
4573
+ class SavedItemsManager {
4574
+ items = new ObservableIndexedObjectCollection(keyOf);
4575
+ messages = new ObservableIndexedObjectCollection('id');
4576
+ promises = new PromiseRegistry();
4577
+ hiddenRoomIds = new Set();
4578
+ itemsWanted = false;
4579
+ messagesWanted = false;
4580
+ refreshScheduled = false;
4581
+ constructor(tracker) {
4582
+ this.tracker = tracker;
4583
+ this.tracker.client.on('ItemSaved', ev => this.handleItemSaved(ev));
4584
+ this.tracker.client.on('ItemUnsaved', ev => this.handleItemUnsaved(ev));
4585
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
4586
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
4587
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
4588
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
4589
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
4590
+ this.tracker.client.on('Session', () => this.handleSession());
4591
+ }
4592
+
4593
+ /**
4594
+ * The rooms and messages you saved, keyed by {@link savedItemKey}; always the same collection. The first call fetches
4595
+ * the list, later ones resolve with it. Items of rooms you are not a member of are left out until you rejoin. The
4596
+ * collection keeps no meaningful order - sort by `savedAt`. Once fetched, the list is fetched again after every
4597
+ * reconnect. Saving and unsaving is done with the `SaveItem` and `UnsaveItem` commands.
4598
+ * @param fetchWithMessages Fetch the contents of the saved messages along, so {@link getMessages} needs no request.
4599
+ */
4600
+ async get(fetchWithMessages = false) {
4601
+ if (fetchWithMessages) {
4602
+ await this.getMessages();
4603
+ }
4604
+ if (this.promises.notExist('items')) {
4605
+ this.itemsWanted = true;
4606
+ this.registerFetch(false);
4607
+ }
4608
+ await this.promises.get('items');
4609
+ return this.items;
4610
+ }
4611
+
4612
+ /**
4613
+ * The contents of the saved messages, keyed by message id; always the same collection. The first call fetches them
4614
+ * together with the list of {@link get}, unless they were fetched already; afterwards they follow the edits and are
4615
+ * fetched again after every reconnect.
4616
+ */
4617
+ async getMessages() {
4618
+ if (this.promises.notExist('messages')) {
4619
+ this.itemsWanted = true;
4620
+ this.messagesWanted = true;
4621
+ this.registerFetch(true);
4622
+ }
4623
+ await this.promises.get('messages');
4624
+ return this.messages;
4625
+ }
4626
+ async isSaved(type, id) {
4627
+ return (await this.get()).has(savedItemKey(type, id));
4628
+ }
4629
+ registerFetch(withMessages) {
4630
+ const fetching = this.fetch(withMessages);
4631
+ this.promises.register(fetching, 'items');
4632
+ if (withMessages) {
4633
+ this.promises.register(fetching, 'messages');
4634
+ }
4635
+ }
4636
+ async fetch(withMessages) {
4637
+ const result = await this.tracker.client.send('GetSavedItems', {
4638
+ withMessages
4639
+ });
4640
+ if (result.error) {
4641
+ throw result.error;
4642
+ }
4643
+ this.apply(result.data, withMessages);
4644
+ }
4645
+ apply(ev, withMessages) {
4646
+ this.items.reconcile(...ev.items);
4647
+ if (withMessages) {
4648
+ this.messages.reconcile(...ev.messages);
4649
+ }
4650
+ }
4651
+ refresh() {
4652
+ if (this.messagesWanted) {
4653
+ this.registerFetch(true);
4654
+ } else if (this.itemsWanted) {
4655
+ this.registerFetch(false);
4656
+ }
4657
+ this.promises.get('items')?.catch(() => {});
4658
+ }
4659
+ handleItemSaved(ev) {
4660
+ if (!this.itemsWanted) {
4661
+ return;
4662
+ }
4663
+ this.items.set(ev.item);
4664
+ if (this.messagesWanted && ev.message) {
4665
+ this.messages.set(ev.message);
4666
+ }
4667
+ }
4668
+ handleItemUnsaved(ev) {
4669
+ this.items.delete(savedItemKey(ev.type, ev.id));
4670
+ if (ev.type === 'Message') {
4671
+ this.messages.delete(ev.id);
4672
+ }
4673
+ }
4674
+ handleMessageUpdated(ev) {
4675
+ if (this.messages.has(ev.message.id)) {
4676
+ this.messages.set(ev.message);
4677
+ }
4678
+ }
4679
+ handleMessagesRedacted(ev) {
4680
+ const saved = ev.ids.filter(id => this.items.has(savedItemKey('Message', id)));
4681
+ this.items.delete(...saved.map(id => savedItemKey('Message', id)));
4682
+ this.messages.delete(...saved.filter(id => this.messages.has(id)));
4683
+ }
4684
+ handleRoomDeleted(ev) {
4685
+ this.hiddenRoomIds.delete(ev.id);
4686
+ this.deleteRoomItems(ev.id);
4687
+ }
4688
+ handleRoomLeft(ev) {
4689
+ // The server keeps them and hands them back once you rejoin
4690
+ if (this.deleteRoomItems(ev.id)) {
4691
+ this.hiddenRoomIds.add(ev.id);
4692
+ }
4693
+ }
4694
+ handleRoomJoined(ev) {
4695
+ if (!this.hiddenRoomIds.delete(ev.room.id) || this.refreshScheduled) {
4696
+ return;
4697
+ }
4698
+
4699
+ // Joining a space joins its rooms one by one; one request brings back the items of all of them
4700
+ this.refreshScheduled = true;
4701
+ setTimeout(() => {
4702
+ this.refreshScheduled = false;
4703
+ this.refresh();
4704
+ }, 0);
4705
+ }
4706
+ deleteRoomItems(roomId) {
4707
+ const items = this.items.items.filter(item => item.roomId === roomId);
4708
+ this.items.delete(...items.map(keyOf));
4709
+ this.messages.delete(...items.filter(item => this.messages.has(item.id)).map(item => item.id));
4710
+ return items.length > 0;
4711
+ }
4712
+ handleSession() {
4713
+ this.promises.forgetAll();
4714
+ this.refresh();
4715
+ }
4716
+ }
4087
4717
  ;// ./src/state-tracker/ChatStateTracker.ts
4088
4718
 
4089
4719
 
@@ -4093,6 +4723,9 @@ class RelationshipsManager {
4093
4723
 
4094
4724
 
4095
4725
 
4726
+
4727
+
4728
+
4096
4729
  class ChatStateTracker {
4097
4730
  client;
4098
4731
 
@@ -4125,6 +4758,24 @@ class ChatStateTracker {
4125
4758
  * State of relationships with other users.
4126
4759
  */
4127
4760
  relationships;
4761
+
4762
+ /**
4763
+ * State of the calls in your rooms and of the calls ringing at you.
4764
+ */
4765
+ calls;
4766
+
4767
+ /**
4768
+ * Your latest personal events from all spaces (mentions, replies, reactions, followed threads, missed calls) and the
4769
+ * activities the server publishes. Private conversations keep their own unread state. Nothing is fetched until you
4770
+ * ask for it. Not part of the state snapshot.
4771
+ */
4772
+ activities;
4773
+
4774
+ /**
4775
+ * The rooms and messages you saved, from all spaces. Nothing is fetched until you ask for it. Not part of the state
4776
+ * snapshot.
4777
+ */
4778
+ savedItems;
4128
4779
  _me = null;
4129
4780
  deferredSession = new DeferredTask();
4130
4781
  sessionReceived = false;
@@ -4138,6 +4789,9 @@ class ChatStateTracker {
4138
4789
  this.emoticons = new EmoticonsManager(this);
4139
4790
  this.users = new UsersManager(this);
4140
4791
  this.relationships = new RelationshipsManager(this);
4792
+ this.calls = new CallsManager(this);
4793
+ this.activities = new ActivitiesManager(this);
4794
+ this.savedItems = new SavedItemsManager(this);
4141
4795
 
4142
4796
  // Registered after the managers, so it runs once they have applied the session.
4143
4797
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -4751,9 +5405,22 @@ class FilesClient extends AbstractRestClient {
4751
5405
  return this.send('GET', 'files?' + searchParams);
4752
5406
  }
4753
5407
  }
5408
+ ;// ./src/protocol/schemes/Call.ts
5409
+ let CallMemberFlag = /*#__PURE__*/function (CallMemberFlag) {
5410
+ CallMemberFlag[CallMemberFlag["Camera"] = 1] = "Camera";
5411
+ CallMemberFlag[CallMemberFlag["ScreenShare"] = 2] = "ScreenShare";
5412
+ CallMemberFlag[CallMemberFlag["Speaker"] = 4] = "Speaker";
5413
+ CallMemberFlag[CallMemberFlag["RaiseBlocked"] = 16] = "RaiseBlocked";
5414
+ return CallMemberFlag;
5415
+ }({});
4754
5416
  ;// ./src/protocol/schemes/events/Error.ts
4755
5417
  let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4756
5418
  ErrorCode["Authentication"] = "AuthenticationException";
5419
+ ErrorCode["CallFull"] = "CallFullException";
5420
+ ErrorCode["CallMode"] = "CallModeException";
5421
+ ErrorCode["CallNotFound"] = "CallNotFoundException";
5422
+ ErrorCode["CallsNotAccepted"] = "CallsNotAcceptedException";
5423
+ ErrorCode["CallsUnavailable"] = "CallsUnavailableException";
4757
5424
  ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
4758
5425
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4759
5426
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
@@ -4761,9 +5428,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4761
5428
  ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4762
5429
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4763
5430
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
5431
+ ErrorCode["SavedItemsLimitReached"] = "SavedItemsLimitReachedException";
4764
5432
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
5433
+ ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
4765
5434
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4766
5435
  ErrorCode["UserNotFound"] = "UserNotFoundException";
5436
+ ErrorCode["UserType"] = "UserTypeException";
4767
5437
  return ErrorCode;
4768
5438
  }({});
4769
5439
  ;// ./src/protocol/schemes/MessageEmbed.ts
@@ -4906,6 +5576,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4906
5576
 
4907
5577
 
4908
5578
 
5579
+
4909
5580
  module.exports = __webpack_exports__;
4910
5581
  /******/ })()
4911
5582
  ;