@devanachat/sdk 0.12.0 → 0.14.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 (47) hide show
  1. package/CHANGELOG.md +104 -12
  2. package/README.md +13 -5
  3. package/build/index.cjs.js +345 -43
  4. package/build/index.cjs.js.map +1 -1
  5. package/build/index.mjs +345 -44
  6. package/build/index.mjs.map +1 -1
  7. package/build/index.umd.js +1 -1
  8. package/build/index.umd.js.map +1 -1
  9. package/build/types/AbstractChatClient.d.ts +16 -1
  10. package/build/types/Permissions.d.ts +34 -0
  11. package/build/types/WebSocketChatClient.d.ts +29 -2
  12. package/build/types/index.d.ts +4 -3
  13. package/build/types/protocol/index.d.ts +21 -2
  14. package/build/types/protocol/schemes/Call.d.ts +35 -0
  15. package/build/types/protocol/schemes/IncomingCall.d.ts +6 -0
  16. package/build/types/protocol/schemes/Message.d.ts +3 -1
  17. package/build/types/protocol/schemes/MessageCall.d.ts +9 -0
  18. package/build/types/protocol/schemes/Room.d.ts +2 -0
  19. package/build/types/protocol/schemes/RoomCall.d.ts +6 -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/CreateMessage.d.ts +2 -0
  23. package/build/types/protocol/schemes/commands/DeclineCall.d.ts +3 -0
  24. package/build/types/protocol/schemes/commands/GetCallMembers.d.ts +5 -0
  25. package/build/types/protocol/schemes/commands/InviteToCall.d.ts +5 -0
  26. package/build/types/protocol/schemes/commands/JoinCall.d.ts +4 -0
  27. package/build/types/protocol/schemes/commands/KickCallMember.d.ts +4 -0
  28. package/build/types/protocol/schemes/commands/MuteCallMember.d.ts +4 -0
  29. package/build/types/protocol/schemes/commands/SetPermissionOverwrites.d.ts +1 -0
  30. package/build/types/protocol/schemes/commands/SetSessionData.d.ts +1 -0
  31. package/build/types/protocol/schemes/commands/SetUserData.d.ts +1 -0
  32. package/build/types/protocol/schemes/commands/UpdateCallMember.d.ts +7 -0
  33. package/build/types/protocol/schemes/commands/UpdateRoom.d.ts +2 -0
  34. package/build/types/protocol/schemes/events/Bye.d.ts +1 -0
  35. package/build/types/protocol/schemes/events/CallJoined.d.ts +7 -0
  36. package/build/types/protocol/schemes/events/CallMemberJoined.d.ts +5 -0
  37. package/build/types/protocol/schemes/events/CallMemberLeft.d.ts +4 -0
  38. package/build/types/protocol/schemes/events/CallMemberUpdated.d.ts +6 -0
  39. package/build/types/protocol/schemes/events/CallMembers.d.ts +5 -0
  40. package/build/types/protocol/schemes/events/CallUpdated.d.ts +5 -0
  41. package/build/types/protocol/schemes/events/CallVideoLimitReached.d.ts +4 -0
  42. package/build/types/protocol/schemes/events/Error.d.ts +6 -0
  43. package/build/types/protocol/schemes/events/IncomingCallUpdated.d.ts +5 -0
  44. package/build/types/state-tracker/CallsManager.d.ts +74 -0
  45. package/build/types/state-tracker/ChatStateTracker.d.ts +5 -0
  46. package/build/types/state-tracker/StateSnapshot.d.ts +1 -1
  47. 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),
@@ -2289,7 +2290,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2289
2290
  /**
2290
2291
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2291
2292
  */
2292
- const STATE_SNAPSHOT_VERSION = 3;
2293
+ const STATE_SNAPSHOT_VERSION = 4;
2293
2294
 
2294
2295
  /**
2295
2296
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -3413,6 +3414,12 @@ class PermissionDefinition {
3413
3414
  value;
3414
3415
  maxLayer;
3415
3416
  }
3417
+ const WORD = 2 ** 32;
3418
+ function combineWords(a, b, operation) {
3419
+ const high = operation(Math.floor(a / WORD), Math.floor(b / WORD)) >>> 0;
3420
+ const low = operation(a % WORD, b % WORD) >>> 0;
3421
+ return high * WORD + low;
3422
+ }
3416
3423
  class Permissions {
3417
3424
  static list = {
3418
3425
  Root: {
@@ -3431,7 +3438,6 @@ class Permissions {
3431
3438
  value: 1 << 3,
3432
3439
  maxLayer: Layer.Space
3433
3440
  },
3434
- //ManageRoom: {value: 1 << 4, maxLayer: Layer.Room},
3435
3441
  CreateTopics: {
3436
3442
  value: 1 << 5,
3437
3443
  maxLayer: Layer.Room
@@ -3531,8 +3537,59 @@ class Permissions {
3531
3537
  EditMessages: {
3532
3538
  value: 1 << 29,
3533
3539
  maxLayer: Layer.Topic
3540
+ },
3541
+ JoinCalls: {
3542
+ value: 2 ** 30,
3543
+ maxLayer: Layer.Room
3544
+ },
3545
+ ShareVideo: {
3546
+ value: 2 ** 31,
3547
+ maxLayer: Layer.Room
3548
+ },
3549
+ InviteToCall: {
3550
+ value: 2 ** 32,
3551
+ maxLayer: Layer.Room
3552
+ },
3553
+ ManageCalls: {
3554
+ value: 2 ** 33,
3555
+ maxLayer: Layer.Room
3534
3556
  }
3535
3557
  };
3558
+
3559
+ /**
3560
+ * Whether the permission mask (e.g. from {@link PermissionsManager.calculatePermissions}) grants the permission.
3561
+ * Use it and {@link union} / {@link subtract} instead of `&` and `|`: JavaScript bitwise operators keep only
3562
+ * 32 bits, and permissions go beyond them.
3563
+ */
3564
+ static has(mask, name) {
3565
+ const value = this.list[name].value;
3566
+ return combineWords(mask, value, (a, b) => a & b) === value;
3567
+ }
3568
+
3569
+ /**
3570
+ * The permission masks combined (`a | b`), safe for permissions beyond 32 bits.
3571
+ */
3572
+ static union(...masks) {
3573
+ let result = 0;
3574
+ for (const mask of masks) {
3575
+ result = combineWords(result, mask, (a, b) => a | b);
3576
+ }
3577
+ return result;
3578
+ }
3579
+
3580
+ /**
3581
+ * The mask without the permissions of `removed` (`mask & ~removed`), safe for permissions beyond 32 bits.
3582
+ */
3583
+ static subtract(mask, removed) {
3584
+ return combineWords(mask, removed, (a, b) => a & ~b);
3585
+ }
3586
+
3587
+ /**
3588
+ * Mask of all the permissions this version of the SDK knows - for `SetPermissionOverwrites.knownPermissions`.
3589
+ */
3590
+ static getKnownMask() {
3591
+ return this.union(...Object.values(this.list).map(permission => permission.value));
3592
+ }
3536
3593
  static getNames() {
3537
3594
  return Object.keys(this.list);
3538
3595
  }
@@ -3596,11 +3653,11 @@ class PermissionsManager extends EventTarget {
3596
3653
  }
3597
3654
  const ownedPermissions = await this.calculatePermissions(location);
3598
3655
  const missing = [];
3599
- permissionNames.forEach(name => {
3600
- if (~ownedPermissions & Permissions.getByName(name).value) {
3656
+ for (const name of permissionNames) {
3657
+ if (!Permissions.has(ownedPermissions, name)) {
3601
3658
  missing.push(name);
3602
3659
  }
3603
- });
3660
+ }
3604
3661
  return {
3605
3662
  ok: missing.length === 0,
3606
3663
  hasAll: missing.length === 0,
@@ -3751,8 +3808,8 @@ class PermissionsManager extends EventTarget {
3751
3808
  for (const {
3752
3809
  overwrites
3753
3810
  } of rolesOverwrites) {
3754
- allow |= overwrites.allow ?? 0;
3755
- deny |= overwrites.deny ?? 0;
3811
+ allow = Permissions.union(allow, overwrites.allow ?? 0);
3812
+ deny = Permissions.union(deny, overwrites.deny ?? 0);
3756
3813
  }
3757
3814
  return {
3758
3815
  allow,
@@ -3762,19 +3819,15 @@ class PermissionsManager extends EventTarget {
3762
3819
  resolveOverwritesHierarchy(permissionOverwritesValues) {
3763
3820
  let result = 0;
3764
3821
  for (const value of permissionOverwritesValues) {
3765
- if (value.allow & Permissions.getByName('Root').value) {
3822
+ if (Permissions.has(value.allow ?? 0, 'Root')) {
3766
3823
  return this.getRootAccessValue();
3767
3824
  }
3768
- result = result & ~value.deny | value.allow;
3825
+ result = Permissions.union(Permissions.subtract(result, value.deny ?? 0), value.allow ?? 0);
3769
3826
  }
3770
3827
  return result;
3771
3828
  }
3772
3829
  getRootAccessValue() {
3773
- let result = 0;
3774
- for (const name of Permissions.getNames()) {
3775
- result |= Permissions.getByName(name).value;
3776
- }
3777
- return result;
3830
+ return Permissions.union(...Permissions.getNames().map(name => Permissions.getByName(name).value));
3778
3831
  }
3779
3832
  async fetchComputedPermissions(location) {
3780
3833
  const result = await this.tracker.client.send('GetComputedPermissions', {
@@ -4084,6 +4137,189 @@ class RelationshipsManager {
4084
4137
  this.promises.forgetAll();
4085
4138
  }
4086
4139
  }
4140
+ ;// ./src/state-tracker/CallsManager.ts
4141
+
4142
+ class CallsManager {
4143
+ list = new ObservableIndexedObjectCollection(call => call.location.roomId);
4144
+ ringing = new ObservableIndexedObjectCollection(incoming => incoming.call.location.roomId);
4145
+ constructor(tracker) {
4146
+ this.tracker = tracker;
4147
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
4148
+ this.tracker.client.on('CallUpdated', ev => this.handleCallUpdated(ev));
4149
+ this.tracker.client.on('CallMemberJoined', ev => this.handleMemberChanged(ev.roomId, ev.member.user.id, ev.member));
4150
+ this.tracker.client.on('CallMemberUpdated', ev => this.handleMemberChanged(ev.roomId, ev.userId, ev.member));
4151
+ this.tracker.client.on('CallMemberLeft', ev => this.handleMemberChanged(ev.roomId, ev.userId));
4152
+ this.tracker.client.on('IncomingCallUpdated', ev => this.handleIncomingCallUpdated(ev));
4153
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomGone(ev));
4154
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomGone(ev));
4155
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceGone(ev));
4156
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceGone(ev));
4157
+ }
4158
+
4159
+ /**
4160
+ * Ongoing calls in the rooms you are a member of, keyed by room id - at most one per room. Filled with the
4161
+ * session and kept current by the server; a call leaves the collection when its last member leaves.
4162
+ * Not part of the state snapshot, so it stays empty until the first session.
4163
+ */
4164
+ async get() {
4165
+ await this.tracker.getMe();
4166
+ return this.list;
4167
+ }
4168
+
4169
+ /**
4170
+ * Calls ringing at you, keyed by room id. A call leaves the collection when it is answered or declined on any of
4171
+ * your devices, or when it ends. Filled with the session, like the ongoing calls.
4172
+ */
4173
+ async getRinging() {
4174
+ await this.tracker.getMe();
4175
+ return this.ringing;
4176
+ }
4177
+
4178
+ /**
4179
+ * Members of the call with a raised hand, in the order they raised it - the queue in the `Queue` mode.
4180
+ */
4181
+ getQueue(call) {
4182
+ return call.members.filter(member => member.handRaisedAt)
4183
+ // Whole seconds; the server breaks ties by comparing user ids as plain strings.
4184
+ .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)));
4185
+ }
4186
+
4187
+ /**
4188
+ * A page of the members of the call the call message stands for, in the order they joined. The message itself
4189
+ * carries only some of them (`MessageCall.partialMembers`) and their count.
4190
+ */
4191
+ async getMembers(messageId, page = {}) {
4192
+ return (await this.send('GetCallMembers', {
4193
+ messageId,
4194
+ ...page
4195
+ })).members;
4196
+ }
4197
+
4198
+ /**
4199
+ * Join the call in the room, starting it if there is none. Connect to the media server with the returned access
4200
+ * yourself; leaving the call is disconnecting from it. Joining another call makes the server end your
4201
+ * participation in the previous one. In the `Stage` and `Queue` modes you join as a listener (a moderator as a
4202
+ * speaker), and the title given when starting the call names its topic.
4203
+ */
4204
+ join(roomId, title) {
4205
+ return this.send('JoinCall', {
4206
+ roomId,
4207
+ title
4208
+ });
4209
+ }
4210
+
4211
+ /**
4212
+ * Stop the call ringing at you, on all of your devices. In a one-to-one private room it also ends the call.
4213
+ */
4214
+ async decline(roomId) {
4215
+ await this.send('DeclineCall', {
4216
+ roomId
4217
+ });
4218
+ }
4219
+
4220
+ /**
4221
+ * Invite the given members of the room, or the room members having one of the roles, to the call - it rings at
4222
+ * them. Members already in the call and you are skipped.
4223
+ */
4224
+ async invite(roomId, target) {
4225
+ await this.send('InviteToCall', {
4226
+ roomId,
4227
+ ...target
4228
+ });
4229
+ }
4230
+
4231
+ /**
4232
+ * Turn off the microphone of a call member. Only they can turn it on again.
4233
+ */
4234
+ async muteMember(roomId, userId) {
4235
+ await this.send('MuteCallMember', {
4236
+ roomId,
4237
+ userId
4238
+ });
4239
+ }
4240
+ async kickMember(roomId, userId) {
4241
+ await this.send('KickCallMember', {
4242
+ roomId,
4243
+ userId
4244
+ });
4245
+ }
4246
+
4247
+ /**
4248
+ * Raise or lower your hand (in the `Queue` mode: enter or leave the queue) and leave the stage, which in the
4249
+ * `Queue` mode ends your turn. A moderator also moves a member to the stage and off it (skipping their turn),
4250
+ * lowers their hand and blocks them from raising it until the call ends.
4251
+ */
4252
+ async updateMember(roomId, userId, change) {
4253
+ await this.send('UpdateCallMember', {
4254
+ roomId,
4255
+ userId,
4256
+ ...change
4257
+ });
4258
+ }
4259
+ async send(type, data) {
4260
+ const result = await this.tracker.client.send(type, data);
4261
+ if (result.error) {
4262
+ throw result.error;
4263
+ }
4264
+ return result.data;
4265
+ }
4266
+ handleSession(ev) {
4267
+ this.list.reconcile(...ev.state.calls);
4268
+ this.ringing.reconcile(...ev.state.incomingCalls);
4269
+ }
4270
+ handleCallUpdated(ev) {
4271
+ if (ev.call) {
4272
+ // An update sent before the server learned you left the room
4273
+ if (this.tracker.rooms._getRoom(ev.roomId)) {
4274
+ this.setCall(ev.call);
4275
+ }
4276
+ } else {
4277
+ this.list.delete(ev.roomId);
4278
+ this.ringing.delete(ev.roomId);
4279
+ }
4280
+ }
4281
+ handleIncomingCallUpdated(ev) {
4282
+ if (ev.incomingCall) {
4283
+ this.ringing.set(ev.incomingCall);
4284
+ } else {
4285
+ this.ringing.delete(ev.roomId);
4286
+ }
4287
+ }
4288
+ handleMemberChanged(roomId, userId, member) {
4289
+ const call = this.list.get(roomId);
4290
+ if (!call) {
4291
+ return;
4292
+ }
4293
+ const members = call.members.filter(item => item.user.id !== userId);
4294
+ if (member) {
4295
+ const index = call.members.findIndex(item => item.user.id === userId);
4296
+ members.splice(index === -1 ? members.length : index, 0, member);
4297
+ }
4298
+ this.setCall({
4299
+ ...call,
4300
+ members
4301
+ });
4302
+ }
4303
+ setCall(call) {
4304
+ this.list.set(call);
4305
+ const incoming = this.ringing.get(call.location.roomId);
4306
+ if (incoming) {
4307
+ this.ringing.set({
4308
+ ...incoming,
4309
+ call
4310
+ });
4311
+ }
4312
+ }
4313
+ handleRoomGone(ev) {
4314
+ this.list.delete(ev.id);
4315
+ this.ringing.delete(ev.id);
4316
+ }
4317
+ handleSpaceGone(ev) {
4318
+ const roomIdsOf = calls => calls.filter(call => call.location.spaceId === ev.id).map(call => call.location.roomId);
4319
+ this.list.delete(...roomIdsOf(this.list.items));
4320
+ this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4321
+ }
4322
+ }
4087
4323
  ;// ./src/state-tracker/ChatStateTracker.ts
4088
4324
 
4089
4325
 
@@ -4093,6 +4329,7 @@ class RelationshipsManager {
4093
4329
 
4094
4330
 
4095
4331
 
4332
+
4096
4333
  class ChatStateTracker {
4097
4334
  client;
4098
4335
 
@@ -4125,6 +4362,11 @@ class ChatStateTracker {
4125
4362
  * State of relationships with other users.
4126
4363
  */
4127
4364
  relationships;
4365
+
4366
+ /**
4367
+ * State of the calls in your rooms and of the calls ringing at you.
4368
+ */
4369
+ calls;
4128
4370
  _me = null;
4129
4371
  deferredSession = new DeferredTask();
4130
4372
  sessionReceived = false;
@@ -4138,6 +4380,7 @@ class ChatStateTracker {
4138
4380
  this.emoticons = new EmoticonsManager(this);
4139
4381
  this.users = new UsersManager(this);
4140
4382
  this.relationships = new RelationshipsManager(this);
4383
+ this.calls = new CallsManager(this);
4141
4384
 
4142
4385
  // Registered after the managers, so it runs once they have applied the session.
4143
4386
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -4236,6 +4479,12 @@ class ChatStateTracker {
4236
4479
  ;// ./src/WebSocketChatClient.ts
4237
4480
 
4238
4481
 
4482
+ const MAX_RETRY_AFTER_MS = 60000;
4483
+ // Going Away, Service Restart, Try Again Later
4484
+ const SERVER_CLOSE_CODES = [1001, 1012, 1013];
4485
+ function normalizeRetryAfter(retryAfterMs) {
4486
+ return typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : undefined;
4487
+ }
4239
4488
  var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
4240
4489
  WebSocketChatClientEvent["connect"] = "connect";
4241
4490
  WebSocketChatClientEvent["disconnect"] = "disconnect";
@@ -4258,6 +4507,10 @@ class WebSocketChatClient extends AbstractChatClient {
4258
4507
  reconnectEnabled = false;
4259
4508
  reconnectTimeoutId;
4260
4509
  reconnectAttempts = 0;
4510
+ serverClosedSinceStable = false;
4511
+ byeReceived = false;
4512
+ byeRetryAfterMs;
4513
+ stableConnectionTimeoutId;
4261
4514
  constructor(options) {
4262
4515
  super();
4263
4516
  this.options = options;
@@ -4294,7 +4547,7 @@ class WebSocketChatClient extends AbstractChatClient {
4294
4547
  disconnect() {
4295
4548
  const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
4296
4549
  this.reconnectEnabled = false;
4297
- this.reconnectAttempts = 0;
4550
+ this.resetBackoff();
4298
4551
  this.cancelScheduledReconnect();
4299
4552
  this.releaseSocket(1000); // Normal closure
4300
4553
  this.failPendingCommands(new Error('Client disconnected before the command was answered'));
@@ -4336,9 +4589,16 @@ class WebSocketChatClient extends AbstractChatClient {
4336
4589
  // Not every implementation follows a failed handshake with a close
4337
4590
  // event (e.g. Node.js), so an error alone means the connection is lost.
4338
4591
  ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
4592
+ ws.onopen = () => ws === this.ws && this.startConnectingTimeout(this.options.sessionTimeoutMs ?? 60000);
4339
4593
  this.ws = ws;
4340
4594
  this.authenticated = false;
4341
- this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
4595
+ this.byeReceived = false;
4596
+ this.byeRetryAfterMs = undefined;
4597
+ this.startConnectingTimeout(this.options.connectingTimeoutMs ?? 10000);
4598
+ }
4599
+ startConnectingTimeout(timeoutMs) {
4600
+ clearTimeout(this.connectingTimeoutId);
4601
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), timeoutMs);
4342
4602
  }
4343
4603
  sendEnvelope(envelope) {
4344
4604
  if (this.isReady) {
@@ -4350,34 +4610,52 @@ class WebSocketChatClient extends AbstractChatClient {
4350
4610
  onMessage(event) {
4351
4611
  this.lastReceivedMessageAt = Date.now();
4352
4612
  const envelope = JSON.parse(event.data);
4613
+ const ws = this.ws;
4353
4614
  this.handleIncomingEnvelope(envelope);
4354
4615
  this.emit(envelope.type, envelope.data);
4355
4616
  this.emit(this.Event.message, envelope);
4356
4617
 
4618
+ // A listener has called disconnect() or connect(), which settled this socket already.
4619
+ if (ws !== this.ws) {
4620
+ return;
4621
+ }
4622
+ if (envelope.type === 'Bye') {
4623
+ this.onBye(envelope.data);
4624
+ return;
4625
+ }
4626
+
4357
4627
  // Login successfully
4358
4628
  if (!this.authenticated) {
4359
- const isAuthenticated = envelope.type !== 'Bye';
4360
- this.authenticated = isAuthenticated;
4361
- if (isAuthenticated) {
4362
- this.reconnectAttempts = 0;
4363
- this.startConnectionMonitor();
4364
- this.settleConnect();
4365
- this.emit(this.Event.connect);
4366
- this.sendFromQueue();
4367
- } else {
4368
- this.settleConnect(envelope.data);
4369
- const error = envelope.data?.reason?.error;
4370
- if (error?.code === 'AuthenticationException') {
4371
- // Invalid token - retrying would be rejected the same way.
4372
- this.handleConnectionLoss(false);
4373
- this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4374
- }
4375
- }
4629
+ this.authenticated = true;
4630
+ this.stableConnectionTimeoutId = setTimeout(() => this.resetBackoff(), this.options.reconnect?.stableConnectionMs ?? 30000);
4631
+ this.startConnectionMonitor();
4632
+ this.settleConnect();
4633
+ this.emit(this.Event.connect);
4634
+ this.sendFromQueue();
4635
+ }
4636
+ }
4637
+ onBye(bye) {
4638
+ this.byeReceived = true;
4639
+ this.byeRetryAfterMs = normalizeRetryAfter(bye?.retryAfterMs);
4640
+ if (bye?.reason?.type === 'Service' || bye?.reason?.error?.code === 'ServiceUnavailableException') {
4641
+ // Not left to the close code: the server may close with 1000 and some platforms rewrite the code.
4642
+ this.handleConnectionLoss(true, true);
4643
+ return;
4644
+ }
4645
+ if (this.authenticated) {
4646
+ return;
4647
+ }
4648
+ this.settleConnect(bye);
4649
+ const error = bye?.reason?.error;
4650
+ if (error?.code === 'AuthenticationException') {
4651
+ // Invalid token - retrying would be rejected the same way.
4652
+ this.handleConnectionLoss(false);
4653
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4376
4654
  }
4377
4655
  }
4378
4656
  onClose(event) {
4379
4657
  // Connection was closed because of error
4380
- this.handleConnectionLoss(event.code !== 1000);
4658
+ this.handleConnectionLoss(event.code !== 1000, this.byeReceived || SERVER_CLOSE_CODES.includes(event.code));
4381
4659
  }
4382
4660
 
4383
4661
  /**
@@ -4385,7 +4663,7 @@ class WebSocketChatClient extends AbstractChatClient {
4385
4663
  * may never come, or take minutes on a dead TCP connection), settle
4386
4664
  * everything that depended on it and schedule a retry when requested.
4387
4665
  */
4388
- handleConnectionLoss(reconnect) {
4666
+ handleConnectionLoss(reconnect, closedByServer = false) {
4389
4667
  this.releaseSocket(reconnect ? 3000 : 1000);
4390
4668
 
4391
4669
  // The server can no longer answer anything that was queued or in
@@ -4395,7 +4673,7 @@ class WebSocketChatClient extends AbstractChatClient {
4395
4673
  if (reconnect) {
4396
4674
  // Keep a pending connect() promise unsettled - the retry below is
4397
4675
  // expected to authenticate and will resolve it.
4398
- this.scheduleReconnect();
4676
+ this.scheduleReconnect(closedByServer);
4399
4677
  } else {
4400
4678
  this.reconnectEnabled = false;
4401
4679
  this.settleConnect(new Error('Connection closed before authentication'));
@@ -4411,13 +4689,15 @@ class WebSocketChatClient extends AbstractChatClient {
4411
4689
  this.stopConnectionMonitor();
4412
4690
  clearTimeout(this.connectingTimeoutId);
4413
4691
  this.connectingTimeoutId = undefined;
4692
+ clearTimeout(this.stableConnectionTimeoutId);
4693
+ this.stableConnectionTimeoutId = undefined;
4414
4694
  this.authenticated = false;
4415
4695
  const ws = this.ws;
4416
4696
  this.ws = null;
4417
4697
  if (!ws) {
4418
4698
  return;
4419
4699
  }
4420
- ws.onmessage = ws.onclose = ws.onerror = null;
4700
+ ws.onmessage = ws.onclose = ws.onerror = ws.onopen = null;
4421
4701
  if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
4422
4702
  try {
4423
4703
  ws.close(closeCode);
@@ -4426,19 +4706,27 @@ class WebSocketChatClient extends AbstractChatClient {
4426
4706
  }
4427
4707
  }
4428
4708
  }
4429
- scheduleReconnect() {
4709
+ scheduleReconnect(closedByServer) {
4430
4710
  this.cancelScheduledReconnect();
4431
- const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
4432
- const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
4711
+
4712
+ // Once the server has closed a connection, the attempts that fail while it is still down
4713
+ // keep the longer backoff.
4714
+ this.serverClosedSinceStable ||= closedByServer;
4715
+ const reconnectOptions = this.options.reconnect;
4716
+ const minDelay = Math.max(0, this.serverClosedSinceStable ? reconnectOptions?.serverCloseMinDelayMs ?? 5000 : reconnectOptions?.minDelayMs ?? 1000);
4717
+ const maxDelay = Math.max(minDelay, reconnectOptions?.maxDelayMs ?? 30000);
4433
4718
  const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
4434
4719
  this.reconnectAttempts++;
4435
4720
 
4436
- // Random jitter (50-100% of the delay) keeps clients from reconnecting
4437
- // in lockstep after a server restart.
4721
+ // Full jitter spreads the clients dropped together over the whole delay; the server jitters its own hint.
4438
4722
  this.reconnectTimeoutId = setTimeout(() => {
4439
4723
  this.reconnectTimeoutId = undefined;
4440
4724
  this.connect().catch(() => undefined);
4441
- }, delay / 2 + Math.random() * delay / 2);
4725
+ }, this.byeRetryAfterMs ?? Math.random() * delay);
4726
+ }
4727
+ resetBackoff() {
4728
+ this.reconnectAttempts = 0;
4729
+ this.serverClosedSinceStable = false;
4442
4730
  }
4443
4731
  cancelScheduledReconnect() {
4444
4732
  clearTimeout(this.reconnectTimeoutId);
@@ -4706,9 +4994,22 @@ class FilesClient extends AbstractRestClient {
4706
4994
  return this.send('GET', 'files?' + searchParams);
4707
4995
  }
4708
4996
  }
4997
+ ;// ./src/protocol/schemes/Call.ts
4998
+ let CallMemberFlag = /*#__PURE__*/function (CallMemberFlag) {
4999
+ CallMemberFlag[CallMemberFlag["Camera"] = 1] = "Camera";
5000
+ CallMemberFlag[CallMemberFlag["ScreenShare"] = 2] = "ScreenShare";
5001
+ CallMemberFlag[CallMemberFlag["Speaker"] = 4] = "Speaker";
5002
+ CallMemberFlag[CallMemberFlag["RaiseBlocked"] = 16] = "RaiseBlocked";
5003
+ return CallMemberFlag;
5004
+ }({});
4709
5005
  ;// ./src/protocol/schemes/events/Error.ts
4710
5006
  let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4711
5007
  ErrorCode["Authentication"] = "AuthenticationException";
5008
+ ErrorCode["CallFull"] = "CallFullException";
5009
+ ErrorCode["CallMode"] = "CallModeException";
5010
+ ErrorCode["CallNotFound"] = "CallNotFoundException";
5011
+ ErrorCode["CallsNotAccepted"] = "CallsNotAcceptedException";
5012
+ ErrorCode["CallsUnavailable"] = "CallsUnavailableException";
4712
5013
  ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
4713
5014
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4714
5015
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
@@ -4717,6 +5018,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4717
5018
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4718
5019
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4719
5020
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
5021
+ ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
4720
5022
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4721
5023
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4722
5024
  return ErrorCode;