@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
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,59 @@ 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
3485
3506
  }
3486
3507
  };
3508
+
3509
+ /**
3510
+ * Whether the permission mask (e.g. from {@link PermissionsManager.calculatePermissions}) grants the permission.
3511
+ * Use it and {@link union} / {@link subtract} instead of `&` and `|`: JavaScript bitwise operators keep only
3512
+ * 32 bits, and permissions go beyond them.
3513
+ */
3514
+ static has(mask, name) {
3515
+ const value = this.list[name].value;
3516
+ return combineWords(mask, value, (a, b) => a & b) === value;
3517
+ }
3518
+
3519
+ /**
3520
+ * The permission masks combined (`a | b`), safe for permissions beyond 32 bits.
3521
+ */
3522
+ static union(...masks) {
3523
+ let result = 0;
3524
+ for (const mask of masks) {
3525
+ result = combineWords(result, mask, (a, b) => a | b);
3526
+ }
3527
+ return result;
3528
+ }
3529
+
3530
+ /**
3531
+ * The mask without the permissions of `removed` (`mask & ~removed`), safe for permissions beyond 32 bits.
3532
+ */
3533
+ static subtract(mask, removed) {
3534
+ return combineWords(mask, removed, (a, b) => a & ~b);
3535
+ }
3536
+
3537
+ /**
3538
+ * Mask of all the permissions this version of the SDK knows - for `SetPermissionOverwrites.knownPermissions`.
3539
+ */
3540
+ static getKnownMask() {
3541
+ return this.union(...Object.values(this.list).map(permission => permission.value));
3542
+ }
3487
3543
  static getNames() {
3488
3544
  return Object.keys(this.list);
3489
3545
  }
@@ -3547,11 +3603,11 @@ class PermissionsManager extends EventTarget {
3547
3603
  }
3548
3604
  const ownedPermissions = await this.calculatePermissions(location);
3549
3605
  const missing = [];
3550
- permissionNames.forEach(name => {
3551
- if (~ownedPermissions & Permissions.getByName(name).value) {
3606
+ for (const name of permissionNames) {
3607
+ if (!Permissions.has(ownedPermissions, name)) {
3552
3608
  missing.push(name);
3553
3609
  }
3554
- });
3610
+ }
3555
3611
  return {
3556
3612
  ok: missing.length === 0,
3557
3613
  hasAll: missing.length === 0,
@@ -3702,8 +3758,8 @@ class PermissionsManager extends EventTarget {
3702
3758
  for (const {
3703
3759
  overwrites
3704
3760
  } of rolesOverwrites) {
3705
- allow |= overwrites.allow ?? 0;
3706
- deny |= overwrites.deny ?? 0;
3761
+ allow = Permissions.union(allow, overwrites.allow ?? 0);
3762
+ deny = Permissions.union(deny, overwrites.deny ?? 0);
3707
3763
  }
3708
3764
  return {
3709
3765
  allow,
@@ -3713,19 +3769,15 @@ class PermissionsManager extends EventTarget {
3713
3769
  resolveOverwritesHierarchy(permissionOverwritesValues) {
3714
3770
  let result = 0;
3715
3771
  for (const value of permissionOverwritesValues) {
3716
- if (value.allow & Permissions.getByName('Root').value) {
3772
+ if (Permissions.has(value.allow ?? 0, 'Root')) {
3717
3773
  return this.getRootAccessValue();
3718
3774
  }
3719
- result = result & ~value.deny | value.allow;
3775
+ result = Permissions.union(Permissions.subtract(result, value.deny ?? 0), value.allow ?? 0);
3720
3776
  }
3721
3777
  return result;
3722
3778
  }
3723
3779
  getRootAccessValue() {
3724
- let result = 0;
3725
- for (const name of Permissions.getNames()) {
3726
- result |= Permissions.getByName(name).value;
3727
- }
3728
- return result;
3780
+ return Permissions.union(...Permissions.getNames().map(name => Permissions.getByName(name).value));
3729
3781
  }
3730
3782
  async fetchComputedPermissions(location) {
3731
3783
  const result = await this.tracker.client.send('GetComputedPermissions', {
@@ -4035,6 +4087,189 @@ class RelationshipsManager {
4035
4087
  this.promises.forgetAll();
4036
4088
  }
4037
4089
  }
4090
+ ;// ./src/state-tracker/CallsManager.ts
4091
+
4092
+ class CallsManager {
4093
+ list = new ObservableIndexedObjectCollection(call => call.location.roomId);
4094
+ ringing = new ObservableIndexedObjectCollection(incoming => incoming.call.location.roomId);
4095
+ constructor(tracker) {
4096
+ this.tracker = tracker;
4097
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
4098
+ this.tracker.client.on('CallUpdated', ev => this.handleCallUpdated(ev));
4099
+ this.tracker.client.on('CallMemberJoined', ev => this.handleMemberChanged(ev.roomId, ev.member.user.id, ev.member));
4100
+ this.tracker.client.on('CallMemberUpdated', ev => this.handleMemberChanged(ev.roomId, ev.userId, ev.member));
4101
+ this.tracker.client.on('CallMemberLeft', ev => this.handleMemberChanged(ev.roomId, ev.userId));
4102
+ this.tracker.client.on('IncomingCallUpdated', ev => this.handleIncomingCallUpdated(ev));
4103
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomGone(ev));
4104
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomGone(ev));
4105
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceGone(ev));
4106
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceGone(ev));
4107
+ }
4108
+
4109
+ /**
4110
+ * Ongoing calls in the rooms you are a member of, keyed by room id - at most one per room. Filled with the
4111
+ * session and kept current by the server; a call leaves the collection when its last member leaves.
4112
+ * Not part of the state snapshot, so it stays empty until the first session.
4113
+ */
4114
+ async get() {
4115
+ await this.tracker.getMe();
4116
+ return this.list;
4117
+ }
4118
+
4119
+ /**
4120
+ * Calls ringing at you, keyed by room id. A call leaves the collection when it is answered or declined on any of
4121
+ * your devices, or when it ends. Filled with the session, like the ongoing calls.
4122
+ */
4123
+ async getRinging() {
4124
+ await this.tracker.getMe();
4125
+ return this.ringing;
4126
+ }
4127
+
4128
+ /**
4129
+ * Members of the call with a raised hand, in the order they raised it - the queue in the `Queue` mode.
4130
+ */
4131
+ getQueue(call) {
4132
+ return call.members.filter(member => member.handRaisedAt)
4133
+ // Whole seconds; the server breaks ties by comparing user ids as plain strings.
4134
+ .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)));
4135
+ }
4136
+
4137
+ /**
4138
+ * A page of the members of the call the call message stands for, in the order they joined. The message itself
4139
+ * carries only some of them (`MessageCall.partialMembers`) and their count.
4140
+ */
4141
+ async getMembers(messageId, page = {}) {
4142
+ return (await this.send('GetCallMembers', {
4143
+ messageId,
4144
+ ...page
4145
+ })).members;
4146
+ }
4147
+
4148
+ /**
4149
+ * Join the call in the room, starting it if there is none. Connect to the media server with the returned access
4150
+ * yourself; leaving the call is disconnecting from it. Joining another call makes the server end your
4151
+ * participation in the previous one. In the `Stage` and `Queue` modes you join as a listener (a moderator as a
4152
+ * speaker), and the title given when starting the call names its topic.
4153
+ */
4154
+ join(roomId, title) {
4155
+ return this.send('JoinCall', {
4156
+ roomId,
4157
+ title
4158
+ });
4159
+ }
4160
+
4161
+ /**
4162
+ * Stop the call ringing at you, on all of your devices. In a one-to-one private room it also ends the call.
4163
+ */
4164
+ async decline(roomId) {
4165
+ await this.send('DeclineCall', {
4166
+ roomId
4167
+ });
4168
+ }
4169
+
4170
+ /**
4171
+ * Invite the given members of the room, or the room members having one of the roles, to the call - it rings at
4172
+ * them. Members already in the call and you are skipped.
4173
+ */
4174
+ async invite(roomId, target) {
4175
+ await this.send('InviteToCall', {
4176
+ roomId,
4177
+ ...target
4178
+ });
4179
+ }
4180
+
4181
+ /**
4182
+ * Turn off the microphone of a call member. Only they can turn it on again.
4183
+ */
4184
+ async muteMember(roomId, userId) {
4185
+ await this.send('MuteCallMember', {
4186
+ roomId,
4187
+ userId
4188
+ });
4189
+ }
4190
+ async kickMember(roomId, userId) {
4191
+ await this.send('KickCallMember', {
4192
+ roomId,
4193
+ userId
4194
+ });
4195
+ }
4196
+
4197
+ /**
4198
+ * Raise or lower your hand (in the `Queue` mode: enter or leave the queue) and leave the stage, which in the
4199
+ * `Queue` mode ends your turn. A moderator also moves a member to the stage and off it (skipping their turn),
4200
+ * lowers their hand and blocks them from raising it until the call ends.
4201
+ */
4202
+ async updateMember(roomId, userId, change) {
4203
+ await this.send('UpdateCallMember', {
4204
+ roomId,
4205
+ userId,
4206
+ ...change
4207
+ });
4208
+ }
4209
+ async send(type, data) {
4210
+ const result = await this.tracker.client.send(type, data);
4211
+ if (result.error) {
4212
+ throw result.error;
4213
+ }
4214
+ return result.data;
4215
+ }
4216
+ handleSession(ev) {
4217
+ this.list.reconcile(...ev.state.calls);
4218
+ this.ringing.reconcile(...ev.state.incomingCalls);
4219
+ }
4220
+ handleCallUpdated(ev) {
4221
+ if (ev.call) {
4222
+ // An update sent before the server learned you left the room
4223
+ if (this.tracker.rooms._getRoom(ev.roomId)) {
4224
+ this.setCall(ev.call);
4225
+ }
4226
+ } else {
4227
+ this.list.delete(ev.roomId);
4228
+ this.ringing.delete(ev.roomId);
4229
+ }
4230
+ }
4231
+ handleIncomingCallUpdated(ev) {
4232
+ if (ev.incomingCall) {
4233
+ this.ringing.set(ev.incomingCall);
4234
+ } else {
4235
+ this.ringing.delete(ev.roomId);
4236
+ }
4237
+ }
4238
+ handleMemberChanged(roomId, userId, member) {
4239
+ const call = this.list.get(roomId);
4240
+ if (!call) {
4241
+ return;
4242
+ }
4243
+ const members = call.members.filter(item => item.user.id !== userId);
4244
+ if (member) {
4245
+ const index = call.members.findIndex(item => item.user.id === userId);
4246
+ members.splice(index === -1 ? members.length : index, 0, member);
4247
+ }
4248
+ this.setCall({
4249
+ ...call,
4250
+ members
4251
+ });
4252
+ }
4253
+ setCall(call) {
4254
+ this.list.set(call);
4255
+ const incoming = this.ringing.get(call.location.roomId);
4256
+ if (incoming) {
4257
+ this.ringing.set({
4258
+ ...incoming,
4259
+ call
4260
+ });
4261
+ }
4262
+ }
4263
+ handleRoomGone(ev) {
4264
+ this.list.delete(ev.id);
4265
+ this.ringing.delete(ev.id);
4266
+ }
4267
+ handleSpaceGone(ev) {
4268
+ const roomIdsOf = calls => calls.filter(call => call.location.spaceId === ev.id).map(call => call.location.roomId);
4269
+ this.list.delete(...roomIdsOf(this.list.items));
4270
+ this.ringing.delete(...roomIdsOf(this.ringing.items.map(incoming => incoming.call)));
4271
+ }
4272
+ }
4038
4273
  ;// ./src/state-tracker/ChatStateTracker.ts
4039
4274
 
4040
4275
 
@@ -4044,6 +4279,7 @@ class RelationshipsManager {
4044
4279
 
4045
4280
 
4046
4281
 
4282
+
4047
4283
  class ChatStateTracker {
4048
4284
  client;
4049
4285
 
@@ -4076,6 +4312,11 @@ class ChatStateTracker {
4076
4312
  * State of relationships with other users.
4077
4313
  */
4078
4314
  relationships;
4315
+
4316
+ /**
4317
+ * State of the calls in your rooms and of the calls ringing at you.
4318
+ */
4319
+ calls;
4079
4320
  _me = null;
4080
4321
  deferredSession = new DeferredTask();
4081
4322
  sessionReceived = false;
@@ -4089,6 +4330,7 @@ class ChatStateTracker {
4089
4330
  this.emoticons = new EmoticonsManager(this);
4090
4331
  this.users = new UsersManager(this);
4091
4332
  this.relationships = new RelationshipsManager(this);
4333
+ this.calls = new CallsManager(this);
4092
4334
 
4093
4335
  // Registered after the managers, so it runs once they have applied the session.
4094
4336
  this.client.on('Session', ev => this.handleSessionAfterImport(ev));
@@ -4187,6 +4429,12 @@ class ChatStateTracker {
4187
4429
  ;// ./src/WebSocketChatClient.ts
4188
4430
 
4189
4431
 
4432
+ const MAX_RETRY_AFTER_MS = 60000;
4433
+ // Going Away, Service Restart, Try Again Later
4434
+ const SERVER_CLOSE_CODES = [1001, 1012, 1013];
4435
+ function normalizeRetryAfter(retryAfterMs) {
4436
+ return typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : undefined;
4437
+ }
4190
4438
  var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
4191
4439
  WebSocketChatClientEvent["connect"] = "connect";
4192
4440
  WebSocketChatClientEvent["disconnect"] = "disconnect";
@@ -4209,6 +4457,10 @@ class WebSocketChatClient extends AbstractChatClient {
4209
4457
  reconnectEnabled = false;
4210
4458
  reconnectTimeoutId;
4211
4459
  reconnectAttempts = 0;
4460
+ serverClosedSinceStable = false;
4461
+ byeReceived = false;
4462
+ byeRetryAfterMs;
4463
+ stableConnectionTimeoutId;
4212
4464
  constructor(options) {
4213
4465
  super();
4214
4466
  this.options = options;
@@ -4245,7 +4497,7 @@ class WebSocketChatClient extends AbstractChatClient {
4245
4497
  disconnect() {
4246
4498
  const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
4247
4499
  this.reconnectEnabled = false;
4248
- this.reconnectAttempts = 0;
4500
+ this.resetBackoff();
4249
4501
  this.cancelScheduledReconnect();
4250
4502
  this.releaseSocket(1000); // Normal closure
4251
4503
  this.failPendingCommands(new Error('Client disconnected before the command was answered'));
@@ -4287,9 +4539,16 @@ class WebSocketChatClient extends AbstractChatClient {
4287
4539
  // Not every implementation follows a failed handshake with a close
4288
4540
  // event (e.g. Node.js), so an error alone means the connection is lost.
4289
4541
  ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
4542
+ ws.onopen = () => ws === this.ws && this.startConnectingTimeout(this.options.sessionTimeoutMs ?? 60000);
4290
4543
  this.ws = ws;
4291
4544
  this.authenticated = false;
4292
- this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
4545
+ this.byeReceived = false;
4546
+ this.byeRetryAfterMs = undefined;
4547
+ this.startConnectingTimeout(this.options.connectingTimeoutMs ?? 10000);
4548
+ }
4549
+ startConnectingTimeout(timeoutMs) {
4550
+ clearTimeout(this.connectingTimeoutId);
4551
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), timeoutMs);
4293
4552
  }
4294
4553
  sendEnvelope(envelope) {
4295
4554
  if (this.isReady) {
@@ -4301,34 +4560,52 @@ class WebSocketChatClient extends AbstractChatClient {
4301
4560
  onMessage(event) {
4302
4561
  this.lastReceivedMessageAt = Date.now();
4303
4562
  const envelope = JSON.parse(event.data);
4563
+ const ws = this.ws;
4304
4564
  this.handleIncomingEnvelope(envelope);
4305
4565
  this.emit(envelope.type, envelope.data);
4306
4566
  this.emit(this.Event.message, envelope);
4307
4567
 
4568
+ // A listener has called disconnect() or connect(), which settled this socket already.
4569
+ if (ws !== this.ws) {
4570
+ return;
4571
+ }
4572
+ if (envelope.type === 'Bye') {
4573
+ this.onBye(envelope.data);
4574
+ return;
4575
+ }
4576
+
4308
4577
  // Login successfully
4309
4578
  if (!this.authenticated) {
4310
- const isAuthenticated = envelope.type !== 'Bye';
4311
- this.authenticated = isAuthenticated;
4312
- if (isAuthenticated) {
4313
- this.reconnectAttempts = 0;
4314
- this.startConnectionMonitor();
4315
- this.settleConnect();
4316
- this.emit(this.Event.connect);
4317
- this.sendFromQueue();
4318
- } else {
4319
- this.settleConnect(envelope.data);
4320
- const error = envelope.data?.reason?.error;
4321
- if (error?.code === 'AuthenticationException') {
4322
- // Invalid token - retrying would be rejected the same way.
4323
- this.handleConnectionLoss(false);
4324
- this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4325
- }
4326
- }
4579
+ this.authenticated = true;
4580
+ this.stableConnectionTimeoutId = setTimeout(() => this.resetBackoff(), this.options.reconnect?.stableConnectionMs ?? 30000);
4581
+ this.startConnectionMonitor();
4582
+ this.settleConnect();
4583
+ this.emit(this.Event.connect);
4584
+ this.sendFromQueue();
4585
+ }
4586
+ }
4587
+ onBye(bye) {
4588
+ this.byeReceived = true;
4589
+ this.byeRetryAfterMs = normalizeRetryAfter(bye?.retryAfterMs);
4590
+ if (bye?.reason?.type === 'Service' || bye?.reason?.error?.code === 'ServiceUnavailableException') {
4591
+ // Not left to the close code: the server may close with 1000 and some platforms rewrite the code.
4592
+ this.handleConnectionLoss(true, true);
4593
+ return;
4594
+ }
4595
+ if (this.authenticated) {
4596
+ return;
4597
+ }
4598
+ this.settleConnect(bye);
4599
+ const error = bye?.reason?.error;
4600
+ if (error?.code === 'AuthenticationException') {
4601
+ // Invalid token - retrying would be rejected the same way.
4602
+ this.handleConnectionLoss(false);
4603
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4327
4604
  }
4328
4605
  }
4329
4606
  onClose(event) {
4330
4607
  // Connection was closed because of error
4331
- this.handleConnectionLoss(event.code !== 1000);
4608
+ this.handleConnectionLoss(event.code !== 1000, this.byeReceived || SERVER_CLOSE_CODES.includes(event.code));
4332
4609
  }
4333
4610
 
4334
4611
  /**
@@ -4336,7 +4613,7 @@ class WebSocketChatClient extends AbstractChatClient {
4336
4613
  * may never come, or take minutes on a dead TCP connection), settle
4337
4614
  * everything that depended on it and schedule a retry when requested.
4338
4615
  */
4339
- handleConnectionLoss(reconnect) {
4616
+ handleConnectionLoss(reconnect, closedByServer = false) {
4340
4617
  this.releaseSocket(reconnect ? 3000 : 1000);
4341
4618
 
4342
4619
  // The server can no longer answer anything that was queued or in
@@ -4346,7 +4623,7 @@ class WebSocketChatClient extends AbstractChatClient {
4346
4623
  if (reconnect) {
4347
4624
  // Keep a pending connect() promise unsettled - the retry below is
4348
4625
  // expected to authenticate and will resolve it.
4349
- this.scheduleReconnect();
4626
+ this.scheduleReconnect(closedByServer);
4350
4627
  } else {
4351
4628
  this.reconnectEnabled = false;
4352
4629
  this.settleConnect(new Error('Connection closed before authentication'));
@@ -4362,13 +4639,15 @@ class WebSocketChatClient extends AbstractChatClient {
4362
4639
  this.stopConnectionMonitor();
4363
4640
  clearTimeout(this.connectingTimeoutId);
4364
4641
  this.connectingTimeoutId = undefined;
4642
+ clearTimeout(this.stableConnectionTimeoutId);
4643
+ this.stableConnectionTimeoutId = undefined;
4365
4644
  this.authenticated = false;
4366
4645
  const ws = this.ws;
4367
4646
  this.ws = null;
4368
4647
  if (!ws) {
4369
4648
  return;
4370
4649
  }
4371
- ws.onmessage = ws.onclose = ws.onerror = null;
4650
+ ws.onmessage = ws.onclose = ws.onerror = ws.onopen = null;
4372
4651
  if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
4373
4652
  try {
4374
4653
  ws.close(closeCode);
@@ -4377,19 +4656,27 @@ class WebSocketChatClient extends AbstractChatClient {
4377
4656
  }
4378
4657
  }
4379
4658
  }
4380
- scheduleReconnect() {
4659
+ scheduleReconnect(closedByServer) {
4381
4660
  this.cancelScheduledReconnect();
4382
- const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
4383
- const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
4661
+
4662
+ // Once the server has closed a connection, the attempts that fail while it is still down
4663
+ // keep the longer backoff.
4664
+ this.serverClosedSinceStable ||= closedByServer;
4665
+ const reconnectOptions = this.options.reconnect;
4666
+ const minDelay = Math.max(0, this.serverClosedSinceStable ? reconnectOptions?.serverCloseMinDelayMs ?? 5000 : reconnectOptions?.minDelayMs ?? 1000);
4667
+ const maxDelay = Math.max(minDelay, reconnectOptions?.maxDelayMs ?? 30000);
4384
4668
  const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
4385
4669
  this.reconnectAttempts++;
4386
4670
 
4387
- // Random jitter (50-100% of the delay) keeps clients from reconnecting
4388
- // in lockstep after a server restart.
4671
+ // Full jitter spreads the clients dropped together over the whole delay; the server jitters its own hint.
4389
4672
  this.reconnectTimeoutId = setTimeout(() => {
4390
4673
  this.reconnectTimeoutId = undefined;
4391
4674
  this.connect().catch(() => undefined);
4392
- }, delay / 2 + Math.random() * delay / 2);
4675
+ }, this.byeRetryAfterMs ?? Math.random() * delay);
4676
+ }
4677
+ resetBackoff() {
4678
+ this.reconnectAttempts = 0;
4679
+ this.serverClosedSinceStable = false;
4393
4680
  }
4394
4681
  cancelScheduledReconnect() {
4395
4682
  clearTimeout(this.reconnectTimeoutId);
@@ -4657,9 +4944,22 @@ class FilesClient extends AbstractRestClient {
4657
4944
  return this.send('GET', 'files?' + searchParams);
4658
4945
  }
4659
4946
  }
4947
+ ;// ./src/protocol/schemes/Call.ts
4948
+ let CallMemberFlag = /*#__PURE__*/function (CallMemberFlag) {
4949
+ CallMemberFlag[CallMemberFlag["Camera"] = 1] = "Camera";
4950
+ CallMemberFlag[CallMemberFlag["ScreenShare"] = 2] = "ScreenShare";
4951
+ CallMemberFlag[CallMemberFlag["Speaker"] = 4] = "Speaker";
4952
+ CallMemberFlag[CallMemberFlag["RaiseBlocked"] = 16] = "RaiseBlocked";
4953
+ return CallMemberFlag;
4954
+ }({});
4660
4955
  ;// ./src/protocol/schemes/events/Error.ts
4661
4956
  let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4662
4957
  ErrorCode["Authentication"] = "AuthenticationException";
4958
+ ErrorCode["CallFull"] = "CallFullException";
4959
+ ErrorCode["CallMode"] = "CallModeException";
4960
+ ErrorCode["CallNotFound"] = "CallNotFoundException";
4961
+ ErrorCode["CallsNotAccepted"] = "CallsNotAcceptedException";
4962
+ ErrorCode["CallsUnavailable"] = "CallsUnavailableException";
4663
4963
  ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
4664
4964
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4665
4965
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
@@ -4668,6 +4968,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4668
4968
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4669
4969
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4670
4970
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
4971
+ ErrorCode["TooManyCallInvitees"] = "TooManyCallInviteesException";
4671
4972
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4672
4973
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4673
4974
  return ErrorCode;
@@ -4812,6 +5113,6 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4812
5113
 
4813
5114
 
4814
5115
 
4815
- 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 };
5116
+ export { AbstractRestClient, CallMemberFlag, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, MessageEmbedFlag, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
4816
5117
 
4817
5118
  //# sourceMappingURL=index.mjs.map