@stream-io/video-client 1.60.0 → 1.61.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.
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export * from './src/helpers/sound-detector';
22
22
  export * from './src/helpers/loopback';
23
23
  export * from './src/helpers/MediaStreamRecorder';
24
24
  export * from './src/helpers/participantUtils';
25
+ export * from './src/helpers/TypedEventEmitter';
25
26
  export * from './src/rtc/e2ee/E2EEManager';
26
27
  export * from './src/rtc/e2ee/EncryptionManager';
27
28
  export * as Browsers from './src/helpers/browsers';
package/dist/index.es.js CHANGED
@@ -5082,7 +5082,7 @@ const toIceCandidate = (iceTrickle) => {
5082
5082
  }
5083
5083
  };
5084
5084
 
5085
- const version = "1.60.0";
5085
+ const version = "1.61.0";
5086
5086
  const [major, minor, patch] = version.split('.');
5087
5087
  let sdkInfo = {
5088
5088
  type: SdkType.PLAIN_JAVASCRIPT,
@@ -9147,6 +9147,25 @@ class TransceiverCache {
9147
9147
  this.cache.push(bundle);
9148
9148
  this.transceiverOrder.push(bundle.transceiver);
9149
9149
  };
9150
+ /**
9151
+ * Retires a failed sender from the reusable cache.
9152
+ *
9153
+ * A transceiver that never reached an m-section also leaves the creation
9154
+ * history: once stopped, it is left out of every later offer, so counting
9155
+ * it would shift the `mid` index of every transceiver added after it. One
9156
+ * that is already associated keeps its slot, since its m-section survives
9157
+ * as a rejected one.
9158
+ */
9159
+ remove = (transceiver) => {
9160
+ const index = this.cache.findIndex((b) => b.transceiver === transceiver);
9161
+ if (index !== -1)
9162
+ this.cache.splice(index, 1);
9163
+ if (transceiver.mid)
9164
+ return;
9165
+ const orderIndex = this.transceiverOrder.indexOf(transceiver);
9166
+ if (orderIndex !== -1)
9167
+ this.transceiverOrder.splice(orderIndex, 1);
9168
+ };
9150
9169
  /**
9151
9170
  * Gets the transceiver for the given publish option.
9152
9171
  */
@@ -9318,7 +9337,9 @@ class Publisher extends BasePeerConnection {
9318
9337
  const sendEncodings = isSvcCodec(publishOption.codec?.name)
9319
9338
  ? toSvcEncodings(encodings)
9320
9339
  : encodings;
9321
- const transceiver = this.pc.addTransceiver(track, {
9340
+ // An E2EE sender must never have media before its transform is attached,
9341
+ // including when another track or an ICE restart negotiates this PC.
9342
+ const transceiver = this.pc.addTransceiver(this.e2ee ? track.kind : track, {
9322
9343
  direction: 'sendonly',
9323
9344
  sendEncodings,
9324
9345
  });
@@ -9328,16 +9349,63 @@ class Publisher extends BasePeerConnection {
9328
9349
  this.transceiverCache.add({ publishOption, transceiver, options });
9329
9350
  this.trackIdToTrackType.set(track.id, trackType);
9330
9351
  this.logger.debug(`Added ${TrackType[trackType]} transceiver`);
9331
- const params = transceiver.sender.getParameters();
9352
+ if (this.e2ee) {
9353
+ await this.initEncryptedSender(transceiver, track, publishOption);
9354
+ }
9355
+ else {
9356
+ await this.setDegradationPreference(transceiver.sender, publishOption);
9357
+ }
9358
+ await this.negotiate();
9359
+ };
9360
+ /**
9361
+ * Attaches the encryptor, applies sender parameters, then attaches the track.
9362
+ *
9363
+ * `encrypt` must run before the first await: Chrome short-circuits a sender
9364
+ * whose encoded streams aren't created in the task that created it, and the
9365
+ * track goes on last so the sender has no media until both steps succeed.
9366
+ */
9367
+ initEncryptedSender = async (transceiver, track, publishOption) => {
9368
+ try {
9369
+ const { sender } = transceiver;
9370
+ const codec = publishOption.codec?.name.toLowerCase();
9371
+ this.e2ee.encrypt(sender, codec, TrackType[publishOption.trackType]);
9372
+ this.logger.debug('E2EE encryptor attached to sender');
9373
+ await this.setDegradationPreference(sender, publishOption);
9374
+ await sender.replaceTrack(track);
9375
+ }
9376
+ catch (err) {
9377
+ this.retireTransceiver(transceiver, track);
9378
+ throw err;
9379
+ }
9380
+ };
9381
+ setDegradationPreference = async (sender, publishOption) => {
9382
+ const params = sender.getParameters();
9332
9383
  params.degradationPreference =
9333
9384
  toRTCDegradationPreference(publishOption.degradationPreference) ??
9334
9385
  'maintain-framerate';
9335
- await transceiver.sender.setParameters(params);
9336
- if (this.e2ee) {
9337
- this.e2ee.encrypt(transceiver.sender, publishOption.codec?.name.toLowerCase(), TrackType[publishOption.trackType]);
9338
- this.logger.debug('E2EE encryptor attached to sender');
9386
+ await sender.setParameters(params);
9387
+ };
9388
+ /**
9389
+ * Discards a sender whose E2EE initialization failed.
9390
+ *
9391
+ * A partially initialized sender may carry no transform, so publish() must
9392
+ * not reuse it: retiring it from the cache is what keeps a later publish or
9393
+ * ICE restart from putting cleartext on the wire. Cleanup cannot throw, so
9394
+ * the initialization failure is what reaches the caller.
9395
+ */
9396
+ retireTransceiver = (transceiver, track) => {
9397
+ this.transceiverCache.remove(transceiver);
9398
+ this.trackIdToTrackType.delete(track.id);
9399
+ // on React Native a clone shares its native source, so stopping it here
9400
+ // would stop the track the caller passed in. dispose() releases it.
9401
+ if (!isReactNative())
9402
+ this.stopTrack(track);
9403
+ try {
9404
+ transceiver.stop();
9405
+ }
9406
+ catch (err) {
9407
+ this.logger.debug('Failed to stop a retired transceiver', err);
9339
9408
  }
9340
- await this.negotiate();
9341
9409
  };
9342
9410
  /**
9343
9411
  * Updates the transceiver with the given track and track type.
@@ -15903,6 +15971,11 @@ class Call {
15903
15971
  this.audioBindingsWatchdog?.dispose();
15904
15972
  await this.dynascaleManager?.dispose();
15905
15973
  this.state.setCallingState(CallingState.LEFT);
15974
+ // `ringingSubject` is cleared further down, so this still reads true for
15975
+ // a call that was ringing.
15976
+ if (this.ringing) {
15977
+ globalThis.streamRNVideoSDK?.ringingCallLifecycle?.onLeave(this);
15978
+ }
15906
15979
  this.state.setParticipants([]);
15907
15980
  this.state.dispose();
15908
15981
  // Reset reconnect-related accumulators so a future `call.join()` on the
@@ -16071,8 +16144,11 @@ class Call {
16071
16144
  * @param params.video if set to true, in a ringing scenario, mobile SDKs will show "incoming video call", audio only otherwise.
16072
16145
  */
16073
16146
  get = async (params) => {
16147
+ const getLeaveGeneration = this.leaveGeneration;
16074
16148
  await this.setup();
16075
16149
  const response = await this.streamClient.get(this.streamClientBasePath, params);
16150
+ if (this.leaveGeneration !== getLeaveGeneration)
16151
+ return response;
16076
16152
  this.updateFromCallStateResponse(response);
16077
16153
  if (params?.ring) {
16078
16154
  this.ringingSubject.next(true);
@@ -16177,42 +16253,80 @@ class Call {
16177
16253
  /**
16178
16254
  * Will start to watch for call related WebSocket events and initiate a call session with the server.
16179
16255
  *
16256
+ * One instance is one call flow: discard it after leaving, cancelling, or a
16257
+ * failed join, and create a fresh one for a later flow. Reconnection inside a
16258
+ * live call is handled here and needs no new instance.
16259
+ *
16180
16260
  * @returns a promise which resolves once the call join-flow has finished.
16181
16261
  */
16182
16262
  join = singleFlight(async ({ maxJoinRetries = 3, joinResponseTimeout, rpcRequestTimeout, allowOwnTracksLoopback = false, joinSource, ...data } = {}) => {
16183
16263
  const callingState = this.state.callingState;
16264
+ // Ahead of the failure boundary below on purpose: a duplicate join on a
16265
+ // live call is refused without tearing that call down.
16184
16266
  if ([CallingState.JOINED, CallingState.JOINING].includes(callingState)) {
16185
16267
  throw new Error(`Illegal State: call.join() shall be called only once`);
16186
16268
  }
16269
+ // snapshot before the first await: a leave() landing at any point from
16270
+ // here on supersedes this join, and the retry loop must bail out instead
16271
+ // of resurrecting a call that leave() already tore down.
16272
+ const joinLeaveGeneration = this.leaveGeneration;
16273
+ const supersededByLeave = () => this.leaveGeneration !== joinLeaveGeneration;
16187
16274
  // we need this to be set before the callingx.joinCall() is
16188
16275
  // called to avoid registering the test call in the CallKit/Telecom
16189
16276
  this.allowOwnTracksLoopback = allowOwnTracksLoopback;
16190
16277
  if (data?.ring) {
16191
16278
  this.ringingSubject.next(true);
16192
16279
  }
16280
+ // A ringing call is joined by the SDK rather than by app code, so React
16281
+ // Native prepares it from in here - there is no earlier point at which the
16282
+ // app holds the call. Read after `data.ring` above, which is what makes an
16283
+ // outgoing call ringing in the first place.
16284
+ const ringingLifecycle = this.ringing
16285
+ ? globalThis.streamRNVideoSDK?.ringingCallLifecycle
16286
+ : undefined;
16193
16287
  const callingX = globalThis.streamRNVideoSDK?.callingX;
16194
- if (callingX) {
16195
- // for Android/iOS, we need to start the call in the callingx library as soon as possible
16196
- await callingX.joinCall(this, this.clientStore.calls);
16197
- }
16198
- await this.setup();
16199
- this.clientEventReporter.registerCall(this.cid, {
16200
- callType: this.type,
16201
- callId: this.id,
16202
- getCallSessionId: () => this.state.session?.id ?? '',
16203
- getSfuId: () => this.credentials?.server.edge_name ?? '',
16204
- });
16205
- this.joinResponseTimeout = joinResponseTimeout;
16206
- this.rpcRequestTimeout = rpcRequestTimeout;
16207
- // we will count the number of join failures per SFU.
16208
- // once the number of failures reaches 2, we will piggyback on the `migrating_from`
16209
- // field to force the coordinator to provide us another SFU
16210
- const sfuJoinFailures = new Map();
16211
- const joinData = data;
16212
- maxJoinRetries = Math.max(maxJoinRetries, 1);
16213
16288
  try {
16289
+ if (ringingLifecycle) {
16290
+ await ringingLifecycle.beforeJoin(this);
16291
+ if (supersededByLeave()) {
16292
+ this.logger.debug('Join superseded by leave; not joining');
16293
+ return;
16294
+ }
16295
+ }
16296
+ if (callingX) {
16297
+ // for Android/iOS, we need to start the call in the callingx library as soon as possible
16298
+ await callingX.joinCall(this, this.clientStore.calls, supersededByLeave);
16299
+ if (supersededByLeave()) {
16300
+ this.logger.debug('Join superseded by leave; not setting up');
16301
+ return;
16302
+ }
16303
+ }
16304
+ await this.setup();
16305
+ if (supersededByLeave()) {
16306
+ this.logger.debug('Join superseded by leave; not registering');
16307
+ return;
16308
+ }
16309
+ this.clientEventReporter.registerCall(this.cid, {
16310
+ callType: this.type,
16311
+ callId: this.id,
16312
+ getCallSessionId: () => this.state.session?.id ?? '',
16313
+ getSfuId: () => this.credentials?.server.edge_name ?? '',
16314
+ });
16315
+ this.joinResponseTimeout = joinResponseTimeout;
16316
+ this.rpcRequestTimeout = rpcRequestTimeout;
16317
+ // we will count the number of join failures per SFU.
16318
+ // once the number of failures reaches 2, we will piggyback on the `migrating_from`
16319
+ // field to force the coordinator to provide us another SFU
16320
+ const sfuJoinFailures = new Map();
16321
+ const joinData = data;
16322
+ maxJoinRetries = Math.max(maxJoinRetries, 1);
16214
16323
  await this.clientEventReporter.withJoinLifecycle(this.cid, { joinReason: 'first-attempt', joinSource }, async () => {
16215
16324
  for (let attempt = 0; attempt < maxJoinRetries; attempt++) {
16325
+ // Also covers a leave that lands during the backoff below.
16326
+ if (supersededByLeave()) {
16327
+ this.logger.debug('Join superseded by leave; not attempting');
16328
+ return;
16329
+ }
16216
16330
  try {
16217
16331
  this.logger.trace(`Joining call (${attempt})`, this.cid);
16218
16332
  await this.doJoin(data);
@@ -16221,6 +16335,10 @@ class Call {
16221
16335
  return;
16222
16336
  }
16223
16337
  catch (err) {
16338
+ if (supersededByLeave()) {
16339
+ this.logger.debug('Join superseded by leave; not retrying');
16340
+ return;
16341
+ }
16224
16342
  this.logger.warn(`Failed to join call (${attempt})`, this.cid);
16225
16343
  if ((err instanceof ErrorFromResponse && err.unrecoverable) ||
16226
16344
  (err instanceof SfuJoinError && err.unrecoverable)) {
@@ -16250,6 +16368,9 @@ class Call {
16250
16368
  }
16251
16369
  catch (error) {
16252
16370
  callingX?.endCall(this, 'error');
16371
+ // Ends the failed ringing flow and releases what its setup installed.
16372
+ // Never rejects, so `error` is what the caller sees.
16373
+ await ringingLifecycle?.onJoinFailed(this);
16253
16374
  throw error;
16254
16375
  }
16255
16376
  });
@@ -16272,6 +16393,10 @@ class Call {
16272
16393
  // globals resolve to the call's factory. Idempotent across
16273
16394
  // reconnect/migration attempts.
16274
16395
  await this.ensureMediaFactory();
16396
+ if (supersededByLeave()) {
16397
+ this.logger.debug('Join superseded by leave; not wiring media');
16398
+ return;
16399
+ }
16275
16400
  const callingX = globalThis.streamRNVideoSDK?.callingX;
16276
16401
  if (callingX) {
16277
16402
  callingX.wireAudioEngineSubscription();
@@ -16287,11 +16412,17 @@ class Call {
16287
16412
  data?.migrating_from) {
16288
16413
  try {
16289
16414
  const joinResponse = await this.clientEventReporter.track(this.cid, 'CoordinatorJoin', () => this.doJoinRequest(data));
16415
+ if (!joinResponse || supersededByLeave()) {
16416
+ this.logger.debug('Join superseded by leave; not creating SFU client');
16417
+ return;
16418
+ }
16290
16419
  this.credentials = joinResponse.credentials;
16291
16420
  statsOptions = joinResponse.stats_options;
16292
16421
  this.lastStatsOptions = statsOptions;
16293
16422
  }
16294
16423
  catch (error) {
16424
+ if (supersededByLeave())
16425
+ return;
16295
16426
  // prevent triggering reconnect flow if the state is OFFLINE
16296
16427
  const avoidRestoreState = this.state.callingState === CallingState.OFFLINE;
16297
16428
  if (!avoidRestoreState) {
@@ -16339,6 +16470,10 @@ class Call {
16339
16470
  getGenericSdp('recvonly', dangerouslyForceCodec, subscriberFmtpLine),
16340
16471
  getGenericSdp('sendonly', dangerouslyForceCodec, fmtpLine),
16341
16472
  ]);
16473
+ if (supersededByLeave()) {
16474
+ this.logger.debug('Join superseded by leave; not joining SFU');
16475
+ return;
16476
+ }
16342
16477
  const isReconnecting = this.reconnectStrategy !== WebsocketReconnectStrategy.UNSPECIFIED;
16343
16478
  const reconnectDetails = isReconnecting
16344
16479
  ? this.getReconnectDetails(previousSfuClient?.edgeName, previousSessionId)
@@ -16364,6 +16499,10 @@ class Call {
16364
16499
  capabilities,
16365
16500
  source: ParticipantSource.WEBRTC_UNSPECIFIED,
16366
16501
  }));
16502
+ if (supersededByLeave()) {
16503
+ this.logger.debug('Join superseded by leave; not applying SFU response');
16504
+ return;
16505
+ }
16367
16506
  this.currentPublishOptions = publishOptions;
16368
16507
  this.fastReconnectDeadlineSeconds = fastReconnectDeadlineSeconds;
16369
16508
  if (callState) {
@@ -16371,6 +16510,10 @@ class Call {
16371
16510
  }
16372
16511
  }
16373
16512
  catch (error) {
16513
+ if (supersededByLeave()) {
16514
+ this.logger.debug('Join superseded by leave; ignoring SFU failure');
16515
+ return;
16516
+ }
16374
16517
  this.logger.warn('Join SFU request failed', error);
16375
16518
  sfuClient.close(StreamSfuClient.JOIN_FAILED, 'Join request failed, connection considered unhealthy');
16376
16519
  // restore the previous call state if the join-flow fails
@@ -16378,8 +16521,8 @@ class Call {
16378
16521
  throw error;
16379
16522
  }
16380
16523
  }
16381
- // If the user left while this join was in flight, bail before re-setting JOINED and before
16382
- // peer-connection setup below (both run synchronously after this, so one check covers them).
16524
+ // If the user left while this join was in flight, bail before re-setting JOINED
16525
+ // or starting peer-connection setup below.
16383
16526
  if (supersededByLeave()) {
16384
16527
  this.logger.debug('Join superseded by leave; aborting join flow');
16385
16528
  return;
@@ -16408,6 +16551,10 @@ class Call {
16408
16551
  unifiedSessionId: this.unifiedSessionId,
16409
16552
  });
16410
16553
  }
16554
+ if (supersededByLeave()) {
16555
+ this.logger.debug('Join superseded by leave; not completing join flow');
16556
+ return;
16557
+ }
16411
16558
  // make sure we only track connection timing if we are not calling this method as part of a reconnection flow
16412
16559
  if (!performingRejoin && !performingFastReconnect && !performingMigration) {
16413
16560
  this.sfuStatsReporter?.sendConnectionTime((Date.now() - connectStartTime) / 1000);
@@ -16553,15 +16700,20 @@ class Call {
16553
16700
  * @internal
16554
16701
  */
16555
16702
  initPublisherAndSubscriber = async (opts) => {
16703
+ const joinLeaveGeneration = this.leaveGeneration;
16556
16704
  const { sfuClient, connectionConfig, clientDetails, statsOptions, publishOptions, closePreviousInstances, unifiedSessionId, } = opts;
16557
16705
  const { enable_rtc_stats: enableTracing, reporting_interval_ms: reportingIntervalMs, } = statsOptions;
16558
16706
  // Flush the previous reporter's final sample while its peer connections are
16559
16707
  // still alive, before we dispose them below. Awaits only the sampling step.
16560
16708
  await this.sfuStatsReporter?.flush();
16709
+ if (this.leaveGeneration !== joinLeaveGeneration)
16710
+ return;
16561
16711
  this.sfuStatsReporter?.stop();
16562
16712
  this.sfuStatsReporter = undefined;
16563
16713
  if (closePreviousInstances && this.subscriber) {
16564
16714
  await this.subscriber.dispose();
16715
+ if (this.leaveGeneration !== joinLeaveGeneration)
16716
+ return;
16565
16717
  this.state.removeAllOrphanedTracks();
16566
16718
  }
16567
16719
  const basePeerConnectionOptions = {
@@ -16604,6 +16756,8 @@ class Call {
16604
16756
  if (!isAnonymous) {
16605
16757
  if (closePreviousInstances && this.publisher) {
16606
16758
  await this.publisher.dispose();
16759
+ if (this.leaveGeneration !== joinLeaveGeneration)
16760
+ return;
16607
16761
  }
16608
16762
  this.publisher = new Publisher(basePeerConnectionOptions, publishOptions, {
16609
16763
  selfSubEnabled: this.allowOwnTracksLoopback,
@@ -16640,12 +16794,22 @@ class Call {
16640
16794
  *
16641
16795
  * @internal
16642
16796
  * @param data the join call data.
16797
+ * @returns The coordinator response, or undefined if leave superseded the request before it was sent.
16643
16798
  */
16644
16799
  doJoinRequest = async (data) => {
16800
+ const joinLeaveGeneration = this.leaveGeneration;
16645
16801
  const location = await this.streamClient.getLocationHint();
16802
+ if (this.leaveGeneration !== joinLeaveGeneration) {
16803
+ this.logger.debug('Join superseded by leave; not sending coordinator request');
16804
+ return;
16805
+ }
16646
16806
  const e2ee = !!this.e2eeManager;
16647
16807
  const request = { ...data, location, e2ee };
16648
16808
  const joinResponse = await this.streamClient.post(`${this.streamClientBasePath}/join`, request);
16809
+ if (this.leaveGeneration !== joinLeaveGeneration) {
16810
+ this.logger.debug('Join superseded by leave; not applying coordinator response');
16811
+ return joinResponse;
16812
+ }
16649
16813
  this.state.updateFromCallResponse(joinResponse.call);
16650
16814
  this.state.setMembers(joinResponse.members);
16651
16815
  this.state.setOwnCapabilities(joinResponse.own_capabilities);
@@ -16656,6 +16820,8 @@ class Call {
16656
16820
  if (!isReconnecting && this.ringing && !this.isCreatedByMe) {
16657
16821
  // signals other users that I have accepted the incoming call.
16658
16822
  await this.accept();
16823
+ if (this.leaveGeneration !== joinLeaveGeneration)
16824
+ return joinResponse;
16659
16825
  }
16660
16826
  if (this.streamClient._hasConnectionID()) {
16661
16827
  this.watching = true;
@@ -16745,6 +16911,7 @@ class Call {
16745
16911
  if (callingState === CallingState.JOINING ||
16746
16912
  callingState === CallingState.RECONNECTING ||
16747
16913
  callingState === CallingState.MIGRATING ||
16914
+ callingState === CallingState.LEFT ||
16748
16915
  callingState === CallingState.RECONNECTING_FAILED)
16749
16916
  return;
16750
16917
  // Drop redundant reconnect calls. If a reconnect is already queued or
@@ -16753,19 +16920,27 @@ class Call {
16753
16920
  // `POST /join` per entry) once the call is already healthy again.
16754
16921
  if (hasPending(this.reconnectConcurrencyTag))
16755
16922
  return;
16923
+ const reconnectLeaveGeneration = this.leaveGeneration;
16924
+ const supersededByLeave = () => this.leaveGeneration !== reconnectLeaveGeneration;
16756
16925
  return withoutConcurrency(this.reconnectConcurrencyTag, async () => {
16926
+ if (supersededByLeave())
16927
+ return;
16757
16928
  const reconnectStartTime = Date.now();
16758
16929
  this.reconnectStrategy = strategy;
16759
16930
  this.reconnectReason = reason;
16760
16931
  const sfuRejoinFailures = new Map();
16761
16932
  const markAsReconnectingFailed = async () => {
16933
+ if (supersededByLeave())
16934
+ return;
16762
16935
  try {
16763
16936
  // attempt to fetch the call data from the server, as the call
16764
16937
  // state might have changed while we were reconnecting or were offline
16765
16938
  await this.get();
16766
16939
  }
16767
16940
  finally {
16768
- this.state.setCallingState(CallingState.RECONNECTING_FAILED);
16941
+ if (!supersededByLeave()) {
16942
+ this.state.setCallingState(CallingState.RECONNECTING_FAILED);
16943
+ }
16769
16944
  }
16770
16945
  };
16771
16946
  const giveUpAndLeave = async (message) => {
@@ -16821,6 +16996,8 @@ class Call {
16821
16996
  try {
16822
16997
  // wait until the network is available
16823
16998
  await this.networkAvailableTask?.promise;
16999
+ if (supersededByLeave())
17000
+ return;
16824
17001
  this.logger.info(`[Reconnect] Reconnecting with strategy ${WebsocketReconnectStrategy[this.reconnectStrategy]}`);
16825
17002
  switch (this.reconnectStrategy) {
16826
17003
  case WebsocketReconnectStrategy.UNSPECIFIED:
@@ -16860,6 +17037,8 @@ class Call {
16860
17037
  break; // do-while loop, reconnection worked, exit the loop
16861
17038
  }
16862
17039
  catch (error) {
17040
+ if (supersededByLeave())
17041
+ return;
16863
17042
  if (attemptedStrategy === WebsocketReconnectStrategy.REJOIN) {
16864
17043
  const failedSfu = this.credentials?.server.edge_name;
16865
17044
  if (failedSfu) {
@@ -16890,6 +17069,8 @@ class Call {
16890
17069
  }
16891
17070
  // exponential backoff with jitter, capped at 5 s
16892
17071
  await sleep(retryInterval(attempt));
17072
+ if (supersededByLeave())
17073
+ return;
16893
17074
  const wasMigrating = this.reconnectStrategy === WebsocketReconnectStrategy.MIGRATE;
16894
17075
  const mustPerformRejoin = (Date.now() - reconnectStartTime) / 1000 >
16895
17076
  this.fastReconnectDeadlineSeconds;
@@ -16908,7 +17089,8 @@ class Call {
16908
17089
  this.reconnectStrategy = nextStrategy;
16909
17090
  this.logger.info(`[Reconnect] ${currentStrategy} (${this.reconnectAttempts}) failed. Attempting with ${WebsocketReconnectStrategy[nextStrategy]}`, error);
16910
17091
  }
16911
- } while (this.state.callingState !== CallingState.JOINED &&
17092
+ } while (!supersededByLeave() &&
17093
+ this.state.callingState !== CallingState.JOINED &&
16912
17094
  this.state.callingState !== CallingState.RECONNECTING_FAILED &&
16913
17095
  this.state.callingState !== CallingState.LEFT);
16914
17096
  this.logger.info('[Reconnect] Reconnection flow finished');
@@ -16919,10 +17101,13 @@ class Call {
16919
17101
  * @internal
16920
17102
  */
16921
17103
  reconnectFast = async () => {
17104
+ const reconnectLeaveGeneration = this.leaveGeneration;
16922
17105
  const reconnectStartTime = Date.now();
16923
17106
  this.reconnectStrategy = WebsocketReconnectStrategy.FAST;
16924
17107
  this.state.setCallingState(CallingState.RECONNECTING);
16925
17108
  await this.doJoin(this.joinCallData);
17109
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17110
+ return;
16926
17111
  await this.get(); // fetch the latest call state, as it might have changed
16927
17112
  this.sfuStatsReporter?.sendReconnectionTime(WebsocketReconnectStrategy.FAST, (Date.now() - reconnectStartTime) / 1000);
16928
17113
  };
@@ -16931,6 +17116,7 @@ class Call {
16931
17116
  * @internal
16932
17117
  */
16933
17118
  reconnectRejoin = async () => {
17119
+ const reconnectLeaveGeneration = this.leaveGeneration;
16934
17120
  const reconnectStartTime = Date.now();
16935
17121
  this.reconnectStrategy = WebsocketReconnectStrategy.REJOIN;
16936
17122
  this.state.setCallingState(CallingState.RECONNECTING);
@@ -16938,7 +17124,11 @@ class Call {
16938
17124
  ? 'network-available'
16939
17125
  : 'full-rejoin';
16940
17126
  await this.clientEventReporter.withJoinLifecycle(this.cid, { joinReason }, () => this.doJoin(this.joinCallData));
17127
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17128
+ return;
16941
17129
  await this.restorePublishedTracks();
17130
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17131
+ return;
16942
17132
  this.restoreSubscribedTracks();
16943
17133
  this.sfuStatsReporter?.sendReconnectionTime(WebsocketReconnectStrategy.REJOIN, (Date.now() - reconnectStartTime) / 1000);
16944
17134
  };
@@ -16947,6 +17137,7 @@ class Call {
16947
17137
  * @internal
16948
17138
  */
16949
17139
  reconnectMigrate = async () => {
17140
+ const reconnectLeaveGeneration = this.leaveGeneration;
16950
17141
  const reconnectStartTime = Date.now();
16951
17142
  const currentSfuClient = this.sfuClient;
16952
17143
  if (!currentSfuClient) {
@@ -16960,26 +17151,32 @@ class Call {
16960
17151
  currentPublisher?.detachEventHandlers();
16961
17152
  const migrationTask = makeSafePromise(currentSfuClient.enterMigration());
16962
17153
  try {
16963
- const currentSfu = currentSfuClient.edgeName;
16964
- await this.clientEventReporter.withJoinLifecycle(this.cid, { joinReason: 'migration' }, () => this.doJoin({
16965
- ...this.joinCallData,
16966
- migrating_from: currentSfu,
16967
- migrating_from_list: [currentSfu],
16968
- }));
16969
- }
16970
- finally {
16971
- // cleanup the migration_from field after the migration is complete or failed
16972
- // as we don't want to keep dirty data in the join call data
16973
- delete this.joinCallData?.migrating_from;
16974
- delete this.joinCallData?.migrating_from_list;
16975
- }
16976
- await this.restorePublishedTracks();
16977
- this.restoreSubscribedTracks();
16978
- try {
17154
+ try {
17155
+ const currentSfu = currentSfuClient.edgeName;
17156
+ await this.clientEventReporter.withJoinLifecycle(this.cid, { joinReason: 'migration' }, () => this.doJoin({
17157
+ ...this.joinCallData,
17158
+ migrating_from: currentSfu,
17159
+ migrating_from_list: [currentSfu],
17160
+ }));
17161
+ }
17162
+ finally {
17163
+ // cleanup the migration_from field after the migration is complete or failed
17164
+ // as we don't want to keep dirty data in the join call data
17165
+ delete this.joinCallData?.migrating_from;
17166
+ delete this.joinCallData?.migrating_from_list;
17167
+ }
17168
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17169
+ return;
17170
+ await this.restorePublishedTracks();
17171
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17172
+ return;
17173
+ this.restoreSubscribedTracks();
16979
17174
  // Wait for the migration to complete, then close the previous SFU client
16980
17175
  // and the peer connection instances. In case of failure, the migration
16981
17176
  // task would throw an error and REJOIN would be attempted.
16982
17177
  await migrationTask();
17178
+ if (this.leaveGeneration !== reconnectLeaveGeneration)
17179
+ return;
16983
17180
  // in MIGRATE, we can consider the call as joined only after
16984
17181
  // `participantMigrationComplete` event is received, signaled by
16985
17182
  // the `migrationTask`
@@ -17264,10 +17461,11 @@ class Call {
17264
17461
  * Must be called before {@link join} so the RTCPeerConnection can be
17265
17462
  * configured for E2EE.
17266
17463
  *
17267
- * The manager is kept across {@link leave} so a rejoin of this same instance
17268
- * stays encrypted: do not dispose it while this call may be joined again.
17269
- * A disposed manager throws from `encrypt`/`decrypt` rather than silently
17270
- * publishing nothing, so re-attach a fresh one instead of reusing it.
17464
+ * The application owns the manager's lifetime - the SDK never disposes it, and
17465
+ * closing the peer connections does not release it. Discard the manager
17466
+ * together with this call instance once its flow has ended, and create a fresh
17467
+ * pair for a later flow: a disposed manager throws from `encrypt`/`decrypt`
17468
+ * rather than silently publishing nothing.
17271
17469
  *
17272
17470
  * @param e2ee - Any `E2EEManager`. Use `EncryptionManager.create()` for the
17273
17471
  * built-in AES-GCM scheme, or pass your own implementation.
@@ -19434,11 +19632,11 @@ class StreamClient {
19434
19632
  return await this.wsConnection.connect(this.defaultWSTimeout);
19435
19633
  };
19436
19634
  getSdkVersion = () => this.options.clientAppIdentifier?.sdkVersion ||
19437
- "1.60.0";
19635
+ "1.61.0";
19438
19636
  getUserAgent = () => {
19439
19637
  if (!this.cachedUserAgent) {
19440
19638
  const { clientAppIdentifier = {} } = this.options;
19441
- const { sdkName = 'js', sdkVersion = "1.60.0", ...extras } = clientAppIdentifier;
19639
+ const { sdkName = 'js', sdkVersion = "1.61.0", ...extras } = clientAppIdentifier;
19442
19640
  this.cachedUserAgent = [
19443
19641
  `stream-video-${sdkName}-v${sdkVersion}`,
19444
19642
  ...Object.entries(extras).map(([key, value]) => `${key}=${value}`),
@@ -21147,9 +21345,9 @@ class EncryptionManager extends TypedEventEmitter {
21147
21345
  }
21148
21346
  if ((this.piped ??= new WeakSet()).has(target))
21149
21347
  return;
21150
- this.piped.add(target);
21151
21348
  // @ts-expect-error createEncodedStreams is not in the standard typedefs
21152
21349
  const { readable, writable } = target.createEncodedStreams();
21350
+ this.piped.add(target);
21153
21351
  this.worker.postMessage({ type: 'cmd.setup_transform', ...options, readable, writable }, [readable, writable]);
21154
21352
  };
21155
21353
  /**
@@ -21238,5 +21436,5 @@ var e2eeWorker$1 = /*#__PURE__*/Object.freeze({
21238
21436
  e2eeWorker: e2eeWorker
21239
21437
  });
21240
21438
 
21241
- export { AudioSettingsRequestDefaultDeviceEnum, AudioSettingsResponseDefaultDeviceEnum, browsers as Browsers, Call, CallRecordingFailedEventRecordingTypeEnum, CallRecordingReadyEventRecordingTypeEnum, CallRecordingStartedEventRecordingTypeEnum, CallRecordingStoppedEventRecordingTypeEnum, CallState, CallType, CallTypes, CallingState, CameraManager, CameraManagerState, CreateDeviceRequestPushProviderEnum, DEFAULT_LOOPBACK_RECORDING_DURATION_MS, DebounceType, DeviceManager, DeviceManagerState, DynascaleManager, EncryptionManager, EncryptionSettingsRequestModeEnum, EncryptionSettingsResponseModeEnum, ErrorFromResponse, FrameRecordingSettingsRequestModeEnum, FrameRecordingSettingsRequestQualityEnum, FrameRecordingSettingsResponseModeEnum, HLSSettingsRequestQualityTracksEnum, IndividualRecordingSettingsRequestModeEnum, IndividualRecordingSettingsRequestOutputTypesEnum, IndividualRecordingSettingsResponseModeEnum, IngressAudioEncodingOptionsRequestChannelsEnum, IngressSourceRequestFpsEnum, IngressVideoLayerRequestCodecEnum, LOOPBACK_STREAMS_WAIT_TIMEOUT_MS, LayoutSettingsRequestNameEnum, LoopbackStreamsTimeoutError, MAX_LOOPBACK_RECORDING_DURATION_MS, MIN_LOOPBACK_RECORDING_DURATION_MS, MediaStreamRecorder, MicrophoneManager, MicrophoneManagerState, NoiseCancellationSettingsModeEnum, OwnCapability, RTMPBroadcastRequestQualityEnum, RTMPSettingsRequestQualityEnum, RawRecordingSettingsRequestModeEnum, RawRecordingSettingsResponseModeEnum, RecordSettingsRequestModeEnum, RecordSettingsRequestQualityEnum, RequestPermissionRequestPermissionsEnum, rxUtils as RxUtils, ScreenShareManager, ScreenShareState, events as SfuEvents, SfuJoinError, models as SfuModels, SfuTimeoutError, SpeakerManager, SpeakerState, StartClosedCaptionsRequestLanguageEnum, StartTranscriptionRequestLanguageEnum, StreamSfuClient, StreamVideoClient, StreamVideoReadOnlyStateStore, StreamVideoWriteableStateStore, TranscriptionSettingsRequestClosedCaptionModeEnum, TranscriptionSettingsRequestLanguageEnum, TranscriptionSettingsRequestModeEnum, TranscriptionSettingsResponseClosedCaptionModeEnum, TranscriptionSettingsResponseLanguageEnum, TranscriptionSettingsResponseModeEnum, TranslationSettingsLanguagesEnum, UpdateUserPermissionsRequestGrantPermissionsEnum, UpdateUserPermissionsRequestRevokePermissionsEnum, VideoSettingsRequestCameraFacingEnum, VideoSettingsResponseCameraFacingEnum, ViewportTracker, VisibilityState, WSAuthMessageProductsEnum, checkIfAudioOutputChangeSupported, clampLoopbackRecordingDuration, combineComparators, conditional, createSoundDetector, defaultSortPreset, descending, deviceIds$, disposeOfMediaStream, dominantSpeaker, enableLoopbackAudio, getAudioBrowserPermission, getAudioDevices, getAudioOutputDevices, getAudioStream, getCallMediaEngineProvider, getClientDetails, getDeviceState, getLoopbackStreams, getLoopbackTracks, getScreenShareStream, getSdkInfo, getVideoBrowserPermission, getVideoDevices, getVideoStream, getWebRTCInfo, hasAudio$1 as hasAudio, hasInterruptedTrack, hasPausedTrack, hasScreenShare, hasScreenShareAudio, hasVideo, humanize, isPinned, livestreamOrAudioRoomSortPreset, logToConsole, name, noopComparator, paginatedLayoutSortPreset, pinned, publishing, publishingAudio, publishingVideo, reactionType, resolveDeviceId, role, screenSharing, setCallMediaEngineProvider, setDeviceInfo, setOSInfo, setPowerState, setSdkInfo, setThermalState, setWebRTCInfo, speakerLayoutSortPreset, speaking, videoLoggerSystem, waitForLoopbackStreams, withLoopbackAudioEnabled, withParticipantSource };
21439
+ export { AudioSettingsRequestDefaultDeviceEnum, AudioSettingsResponseDefaultDeviceEnum, browsers as Browsers, Call, CallRecordingFailedEventRecordingTypeEnum, CallRecordingReadyEventRecordingTypeEnum, CallRecordingStartedEventRecordingTypeEnum, CallRecordingStoppedEventRecordingTypeEnum, CallState, CallType, CallTypes, CallingState, CameraManager, CameraManagerState, CreateDeviceRequestPushProviderEnum, DEFAULT_LOOPBACK_RECORDING_DURATION_MS, DebounceType, DeviceManager, DeviceManagerState, DynascaleManager, EncryptionManager, EncryptionSettingsRequestModeEnum, EncryptionSettingsResponseModeEnum, ErrorFromResponse, FrameRecordingSettingsRequestModeEnum, FrameRecordingSettingsRequestQualityEnum, FrameRecordingSettingsResponseModeEnum, HLSSettingsRequestQualityTracksEnum, IndividualRecordingSettingsRequestModeEnum, IndividualRecordingSettingsRequestOutputTypesEnum, IndividualRecordingSettingsResponseModeEnum, IngressAudioEncodingOptionsRequestChannelsEnum, IngressSourceRequestFpsEnum, IngressVideoLayerRequestCodecEnum, LOOPBACK_STREAMS_WAIT_TIMEOUT_MS, LayoutSettingsRequestNameEnum, LoopbackStreamsTimeoutError, MAX_LOOPBACK_RECORDING_DURATION_MS, MIN_LOOPBACK_RECORDING_DURATION_MS, MediaStreamRecorder, MicrophoneManager, MicrophoneManagerState, NoiseCancellationSettingsModeEnum, OwnCapability, RTMPBroadcastRequestQualityEnum, RTMPSettingsRequestQualityEnum, RawRecordingSettingsRequestModeEnum, RawRecordingSettingsResponseModeEnum, RecordSettingsRequestModeEnum, RecordSettingsRequestQualityEnum, RequestPermissionRequestPermissionsEnum, rxUtils as RxUtils, ScreenShareManager, ScreenShareState, events as SfuEvents, SfuJoinError, models as SfuModels, SfuTimeoutError, SpeakerManager, SpeakerState, StartClosedCaptionsRequestLanguageEnum, StartTranscriptionRequestLanguageEnum, StreamSfuClient, StreamVideoClient, StreamVideoReadOnlyStateStore, StreamVideoWriteableStateStore, TranscriptionSettingsRequestClosedCaptionModeEnum, TranscriptionSettingsRequestLanguageEnum, TranscriptionSettingsRequestModeEnum, TranscriptionSettingsResponseClosedCaptionModeEnum, TranscriptionSettingsResponseLanguageEnum, TranscriptionSettingsResponseModeEnum, TranslationSettingsLanguagesEnum, TypedEventEmitter, UpdateUserPermissionsRequestGrantPermissionsEnum, UpdateUserPermissionsRequestRevokePermissionsEnum, VideoSettingsRequestCameraFacingEnum, VideoSettingsResponseCameraFacingEnum, ViewportTracker, VisibilityState, WSAuthMessageProductsEnum, checkIfAudioOutputChangeSupported, clampLoopbackRecordingDuration, combineComparators, conditional, createSoundDetector, defaultSortPreset, descending, deviceIds$, disposeOfMediaStream, dominantSpeaker, enableLoopbackAudio, getAudioBrowserPermission, getAudioDevices, getAudioOutputDevices, getAudioStream, getCallMediaEngineProvider, getClientDetails, getDeviceState, getLoopbackStreams, getLoopbackTracks, getScreenShareStream, getSdkInfo, getVideoBrowserPermission, getVideoDevices, getVideoStream, getWebRTCInfo, hasAudio$1 as hasAudio, hasInterruptedTrack, hasPausedTrack, hasScreenShare, hasScreenShareAudio, hasVideo, humanize, isPinned, livestreamOrAudioRoomSortPreset, logToConsole, name, noopComparator, paginatedLayoutSortPreset, pinned, publishing, publishingAudio, publishingVideo, reactionType, resolveDeviceId, role, screenSharing, setCallMediaEngineProvider, setDeviceInfo, setOSInfo, setPowerState, setSdkInfo, setThermalState, setWebRTCInfo, speakerLayoutSortPreset, speaking, videoLoggerSystem, waitForLoopbackStreams, withLoopbackAudioEnabled, withParticipantSource };
21242
21440
  //# sourceMappingURL=index.es.js.map