@signalwire/js 4.0.0-rc.1 → 4.0.0-rc.2

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.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { A as StorageNotAvailableError, B as VertoPongError, C as OverconstrainedFallbackError, D as RequestError, E as RecoveryError, F as UnexpectedError, H as WebSocketTimeoutError, I as UnimplementedError, L as ValidationError, M as StorageWriteError, N as TokenRefreshError, O as RequestTimeoutError, P as TransportConnectionError, R as VertoAttachHandlerError, S as MessageParseError, T as RPCTimeoutError, V as WebSocketConnectionError, _ as DeviceTokenError, a as filterNull, b as JSONRPCError, c as setLogLevel, d as CallCreateError, f as CollectionFetchError, g as DeserializationError, h as DependencyError, i as getValueFrom, j as StorageReadError, k as SerializationError, l as setLogger, m as DPoPInitError, n as filterAs, o as getLogger, p as ConversationError, s as setDebugOptions, t as throwOnRPCError, u as AuthStateHandlerError, v as InvalidCredentialsError, w as PreflightError, x as MediaTrackError, y as InvalidParams, z as VertoInviteHandlerError } from "./operators-CX_lCCJm.mjs";
1
+ import { $ as DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS, $t as VAD_HOLD_MS, A as SerializationError, At as DEFAULT_STATS_POLLING_INTERVAL_MS, B as VertoInviteHandlerError, Bt as DEVICE_TOKEN_ENDPOINT, C as MessageParseError, Ct as DEFAULT_REINVITE_MAX_ATTEMPTS, D as RecoveryError, Dt as DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER, E as RPCTimeoutError, Et as DEFAULT_STATS_HISTORY_SIZE, F as TransportConnectionError, Ft as DEVICE_REFRESH_ENDPOINT, G as CREDENTIAL_ACTIVATE_TIMEOUT_MS, Gt as INVITE_VERSION, H as WebSocketConnectionError, Ht as DEVICE_TOKEN_REFRESH_MAX_RETRIES, I as UnexpectedError, It as DEVICE_STORAGE_KEY_AUDIO_INPUT, J as CREDENTIAL_REFRESH_MAX_RETRIES, Jt as PREFERENCES_STORAGE_KEY, K as CREDENTIAL_REFRESH_BUFFER_MS, Kt as PEER_CONNECTION_RECOVERY_POLL_MS, L as UnimplementedError, Lt as DEVICE_STORAGE_KEY_AUDIO_OUTPUT, M as StorageReadError, Mt as DEFAULT_STEREO_AUDIO, N as StorageWriteError, Nt as DEFAULT_STEREO_MAX_AVERAGE_BITRATE, O as RequestError, Ot as DEFAULT_STATS_NO_PACKET_THRESHOLD_MS, P as TokenRefreshError, Pt as DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS, Q as DEFAULT_CONNECTION_TIMEOUT_MS, Qt as SAT_REFRESH_SCOPE, R as ValidationError, Rt as DEVICE_STORAGE_KEY_VIDEO_INPUT, S as MediaTrackError, St as DEFAULT_REINVITE_DEBOUNCE_TIME_MS, T as PreflightError, Tt as DEFAULT_STATS_BASELINE_SAMPLES, U as WebSocketTimeoutError, Ut as DEVICE_TOKEN_REFRESH_RETRY_BASE_MS, V as VertoPongError, Vt as DEVICE_TOKEN_REFRESH_BUFFER_MS, W as AUDIO_LEVEL_POLL_INTERVAL_MS, Wt as ICE_GATHERING_COMPLETE_TIMEOUT_MS, X as DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN, Xt as RPC_ERROR_INVALID_PARAMS, Y as CREDENTIAL_REFRESH_RETRY_BASE_MS, Yt as RPC_ERROR_AUTHENTICATION_FAILED, Z as DEFAULT_CHECK_CONNECTION_ON_VISIBLE, Zt as RPC_ERROR_REQUESTER_VALIDATION_FAILED, _ as DeviceTokenError, _t as DEFAULT_RECONNECT_DELAY_MAX_MS, a as filterNull, at as DEFAULT_ENABLE_RELAY_FALLBACK, b as JSONRPCError, bt as DEFAULT_RECOVERY_DEBOUNCE_TIME_MS, c as setLogLevel, ct as DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS, d as CallCreateError, dt as DEFAULT_KEYFRAME_BURST_WINDOW_MS$1, en as VAD_THRESHOLD, et as DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS, f as CollectionFetchError, ft as DEFAULT_KEYFRAME_COOLDOWN_MS$1, g as DeserializationError, gt as DEFAULT_RECONNECT_CALLS_TIMEOUT_MS, h as DependencyError, ht as DEFAULT_PERSIST_DEVICE_SELECTION, i as getValueFrom, it as DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION, j as StorageNotAvailableError, jt as DEFAULT_STATS_RTT_SPIKE_MULTIPLIER, k as RequestTimeoutError, kt as DEFAULT_STATS_PACKET_LOSS_THRESHOLD, l as setLogger, lt as DEFAULT_ICE_GATHERING_TIMEOUT_MS, m as DPoPInitError, mt as DEFAULT_MAX_RECOVERY_ATTEMPTS, n as filterAs, nt as DEFAULT_DEVICE_POLLING_INTERVAL_MS, o as getLogger, ot as DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION, p as ConversationError, pt as DEFAULT_KEYFRAME_MAX_BURST$1, q as CREDENTIAL_REFRESH_MAX_DELAY_MS, qt as PEER_CONNECTION_RECOVERY_WAIT_MS, rt as DEFAULT_ENABLE_AUTO_DEGRADATION, s as setDebugOptions, st as DEFAULT_ICE_CANDIDATE_TIMEOUT_MS, t as throwOnRPCError, tt as DEFAULT_DEVICE_DEBOUNCE_TIME_MS, u as AuthStateHandlerError, ut as DEFAULT_ICE_RESTART_TIMEOUT_MS$1, v as InvalidCredentialsError, vt as DEFAULT_RECONNECT_DELAY_MIN_MS, w as OverconstrainedFallbackError, wt as DEFAULT_REINVITE_TIMEOUT_MS, x as MediaAccessError, xt as DEFAULT_REFRESH_DEVICES_ON_VISIBLE, y as InvalidParams, yt as DEFAULT_RECOVERY_COOLDOWN_MS, z as VertoAttachHandlerError, zt as DEVICE_TOKEN_DEFAULT_EXPIRE_IN } from "./operators-BlUtq-t0.mjs";
2
2
  import { jwtDecode } from "jwt-decode";
3
- import { BehaviorSubject, EMPTY, NEVER, Observable, ReplaySubject, Subject, TimeoutError, animationFrameScheduler, asapScheduler, auditTime, catchError, combineLatest, debounceTime, defer, distinctUntilChanged, exhaustMap, filter, first, firstValueFrom, from, interval, lastValueFrom, map, merge, mergeMap, observeOn, of, pipe, race, scan, share, shareReplay, skip, skipWhile, startWith, switchMap, take, takeUntil, tap, throwError, timeout, timer, toArray, withLatestFrom } from "rxjs";
3
+ import { BehaviorSubject, EMPTY, EmptyError, NEVER, Observable, ReplaySubject, Subject, TimeoutError, animationFrameScheduler, asapScheduler, auditTime, catchError, combineLatest, debounceTime, defer, distinctUntilChanged, exhaustMap, filter, first, firstValueFrom, from, interval, lastValueFrom, map, merge, mergeMap, observeOn, of, pipe, race, scan, share, shareReplay, skip, skipWhile, startWith, switchMap, take, takeUntil, tap, throwError, timeout, timer, toArray, withLatestFrom } from "rxjs";
4
4
  import { v4 } from "uuid";
5
5
  import { distinctUntilChanged as distinctUntilChanged$1, map as map$1 } from "rxjs/operators";
6
6
 
@@ -404,137 +404,6 @@ var DeviceHistoryManager = class {
404
404
  }
405
405
  };
406
406
 
407
- //#endregion
408
- //#region src/core/constants.ts
409
- const INVITE_VERSION = 1e3;
410
- const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;
411
- const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6e3;
412
- const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 300 * 1e3;
413
- const DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
414
- const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;
415
- const DEFAULT_RECONNECT_DELAY_MAX_MS = 3e3;
416
- const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;
417
- const DEFAULT_DEVICE_POLLING_INTERVAL_MS = 0;
418
- const PREFERENCES_STORAGE_KEY = "sw:preferences";
419
- /** Scope value that enables automatic token refresh. */
420
- const SAT_REFRESH_SCOPE = "sat:refresh";
421
- /** API endpoints for device token operations. */
422
- const DEVICE_TOKEN_ENDPOINT = "/api/fabric/subscriber/devices/token";
423
- const DEVICE_REFRESH_ENDPOINT = "/api/fabric/subscriber/devices/refresh";
424
- /** Default device token TTL in seconds (15 minutes). */
425
- const DEVICE_TOKEN_DEFAULT_EXPIRE_IN = 900;
426
- /** Buffer time in milliseconds before expiry to trigger refresh. */
427
- const DEVICE_TOKEN_REFRESH_BUFFER_MS = 3e4;
428
- /** Maximum retry attempts for device token refresh on transient failure. */
429
- const DEVICE_TOKEN_REFRESH_MAX_RETRIES = 3;
430
- /** Base delay in milliseconds for exponential backoff on refresh retry. */
431
- const DEVICE_TOKEN_REFRESH_RETRY_BASE_MS = 1e3;
432
- /** Maximum retry attempts for developer credential refresh on transient failure. */
433
- const CREDENTIAL_REFRESH_MAX_RETRIES = 5;
434
- /** Base delay in milliseconds for exponential backoff on credential refresh retry. */
435
- const CREDENTIAL_REFRESH_RETRY_BASE_MS = 1e3;
436
- /** Maximum delay in milliseconds for credential refresh backoff. */
437
- const CREDENTIAL_REFRESH_MAX_DELAY_MS = 3e4;
438
- /** Buffer in milliseconds before token expiry to trigger refresh. */
439
- const CREDENTIAL_REFRESH_BUFFER_MS = 5e3;
440
- /**
441
- * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`
442
- * to resolve before treating the activation as failed and falling back to
443
- * the developer-provided refresh path. Prevents a wedged HTTP layer from
444
- * leaving the session with no active refresh mechanism.
445
- */
446
- const CREDENTIAL_ACTIVATE_TIMEOUT_MS = 3e4;
447
- /** JSON-RPC error code for requester validation failure (corrupted auth state). */
448
- const RPC_ERROR_REQUESTER_VALIDATION_FAILED = -32003;
449
- /** JSON-RPC error code for invalid params (e.g., missing authentication block). */
450
- const RPC_ERROR_INVALID_PARAMS = -32602;
451
- /** JSON-RPC error code for authentication failure (invalid token, missing DPoP, etc.). */
452
- const RPC_ERROR_AUTHENTICATION_FAILED = -32002;
453
- /** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */
454
- const DEFAULT_STATS_POLLING_INTERVAL_MS = 1e3;
455
- /** Number of initial samples used to build a baseline for spike detection. */
456
- const DEFAULT_STATS_BASELINE_SAMPLES = 10;
457
- /** Duration in ms with no inbound audio packets before emitting a critical issue. */
458
- const DEFAULT_STATS_NO_PACKET_THRESHOLD_MS = 2e3;
459
- /** Multiplier applied to baseline RTT to detect a warning-level RTT spike. */
460
- const DEFAULT_STATS_RTT_SPIKE_MULTIPLIER = 3;
461
- /** Packet loss fraction (0-1) above which a warning is emitted. */
462
- const DEFAULT_STATS_PACKET_LOSS_THRESHOLD = .05;
463
- /** Multiplier applied to baseline jitter to detect a jitter spike. */
464
- const DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER = 4;
465
- /** Number of seconds of metrics history to retain. */
466
- const DEFAULT_STATS_HISTORY_SIZE = 30;
467
- /** Maximum keyframe requests allowed within a single burst window. */
468
- const DEFAULT_KEYFRAME_MAX_BURST$1 = 3;
469
- /** Duration of the keyframe burst window in milliseconds. */
470
- const DEFAULT_KEYFRAME_BURST_WINDOW_MS$1 = 3e3;
471
- /** Cooldown period in ms after burst limit is reached before allowing more keyframes. */
472
- const DEFAULT_KEYFRAME_COOLDOWN_MS$1 = 1e4;
473
- /** Minimum time between re-INVITE attempts in milliseconds. */
474
- const DEFAULT_REINVITE_DEBOUNCE_TIME_MS = 1e4;
475
- /** Maximum number of re-INVITE attempts per call. */
476
- const DEFAULT_REINVITE_MAX_ATTEMPTS = 3;
477
- /** Timeout for a single re-INVITE attempt in milliseconds. */
478
- const DEFAULT_REINVITE_TIMEOUT_MS = 5e3;
479
- /** Debounce window in ms to collapse multiple detection signals into one trigger. */
480
- const DEFAULT_RECOVERY_DEBOUNCE_TIME_MS = 2e3;
481
- /** Cooldown period in ms between recovery attempts. */
482
- const DEFAULT_RECOVERY_COOLDOWN_MS = 1e4;
483
- /** Grace period in ms before treating ICE 'disconnected' as a failure. */
484
- const DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS = 3e3;
485
- /** Timeout for a single ICE restart attempt in milliseconds. */
486
- const DEFAULT_ICE_RESTART_TIMEOUT_MS$1 = 5e3;
487
- /** Maximum recovery attempts before emitting 'max_attempts_reached'. */
488
- const DEFAULT_MAX_RECOVERY_ATTEMPTS = 3;
489
- /** Upper bound in ms for waiting on iceGatheringState === 'complete' after an ICE restart. */
490
- const ICE_GATHERING_COMPLETE_TIMEOUT_MS = 1e4;
491
- /** Upper bound in ms for waiting on RTCPeerConnection.connectionState === 'connected' after a recovery ICE restart. */
492
- const PEER_CONNECTION_RECOVERY_WAIT_MS = 5e3;
493
- /** Polling interval in ms while waiting for RTCPeerConnection.connectionState to transition. */
494
- const PEER_CONNECTION_RECOVERY_POLL_MS = 100;
495
- /** Polling interval for LocalAudioPipeline.level$ (ms). ~30fps is smooth for meters. */
496
- const AUDIO_LEVEL_POLL_INTERVAL_MS = 33;
497
- /** RMS level threshold (0..1) above which the local participant is considered speaking. */
498
- const VAD_THRESHOLD = .03;
499
- /** Hold window in ms below the threshold before speaking$ flips back to false. */
500
- const VAD_HOLD_MS = 250;
501
- /** Whether to persist device selections to storage by default. */
502
- const DEFAULT_PERSIST_DEVICE_SELECTION = true;
503
- /** Whether to auto-apply device changes to active calls by default. */
504
- const DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS = true;
505
- /** Storage keys for persisted device selections. */
506
- const DEVICE_STORAGE_KEY_AUDIO_INPUT = "sw:device:audioinput";
507
- const DEVICE_STORAGE_KEY_AUDIO_OUTPUT = "sw:device:audiooutput";
508
- const DEVICE_STORAGE_KEY_VIDEO_INPUT = "sw:device:videoinput";
509
- /** Whether to auto-mute video when the tab becomes hidden. */
510
- const DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN = false;
511
- /** Whether to re-enumerate devices when the page becomes visible. */
512
- const DEFAULT_REFRESH_DEVICES_ON_VISIBLE = true;
513
- /** Whether to check peer connection health when the page becomes visible. */
514
- const DEFAULT_CHECK_CONNECTION_ON_VISIBLE = true;
515
- /** Whether automatic video degradation on low bandwidth is enabled. */
516
- const DEFAULT_ENABLE_AUTO_DEGRADATION = true;
517
- /** Bitrate in kbps below which video is automatically disabled. */
518
- const DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS = 150;
519
- /** Bitrate in kbps above which video is automatically re-enabled (hysteresis). */
520
- const DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS = 300;
521
- /** Whether relay-only escalation is enabled as a last-resort recovery tier. */
522
- const DEFAULT_ENABLE_RELAY_FALLBACK = true;
523
- /** Whether to listen for browser online/offline/connection events. */
524
- const DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION = true;
525
- /** Whether to intercept server-sent media-timeout hangups and attempt recovery. */
526
- const DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION = true;
527
- /** Default video track constraints applied when video is enabled without explicit constraints. */
528
- const DEFAULT_VIDEO_CONSTRAINTS = {
529
- width: { ideal: 1280 },
530
- height: { ideal: 720 },
531
- aspectRatio: 16 / 9
532
- };
533
- /** Whether stereo Opus is enabled by default. */
534
- const DEFAULT_STEREO_AUDIO = false;
535
- /** Max average bitrate for stereo Opus in bits per second. */
536
- const DEFAULT_STEREO_MAX_AVERAGE_BITRATE = 51e4;
537
-
538
407
  //#endregion
539
408
  //#region src/utils/time.ts
540
409
  function fromSecToMs(seconds) {
@@ -3687,12 +3556,21 @@ var SelfParticipant = class extends Participant {
3687
3556
  noise_suppression: true
3688
3557
  });
3689
3558
  }
3690
- /** Starts sharing the local screen. */
3559
+ /**
3560
+ * Starts sharing the local screen.
3561
+ *
3562
+ * The call is unaffected when acquisition fails.
3563
+ *
3564
+ * @throws The raw `getDisplayMedia` error. A dismissed picker or a
3565
+ * permission denial rejects with a `NotAllowedError` `DOMException` —
3566
+ * inspect `error.name` to tell benign cancels apart from real failures.
3567
+ */
3691
3568
  async startScreenShare() {
3692
3569
  try {
3693
3570
  await this.vertoManager.addScreenMedia();
3694
3571
  } catch (error) {
3695
3572
  logger$23.error("[Participant.startScreenShare] Screen share error:", error);
3573
+ throw error;
3696
3574
  }
3697
3575
  }
3698
3576
  /** Observable of the current screen share status. */
@@ -3707,12 +3585,20 @@ var SelfParticipant = class extends Participant {
3707
3585
  async stopScreenShare() {
3708
3586
  return this.vertoManager.removeScreenMedia();
3709
3587
  }
3710
- /** Adds an additional media input device to the call. */
3588
+ /**
3589
+ * Adds an additional media input device to the call.
3590
+ *
3591
+ * The call is unaffected when acquisition fails.
3592
+ *
3593
+ * @throws The raw `getUserMedia` error (e.g. `NotAllowedError` on
3594
+ * permission denial) — inspect `error.name` to decide how to react.
3595
+ */
3711
3596
  async addAdditionalDevice(options) {
3712
3597
  try {
3713
3598
  await this.vertoManager.addInputDevice(options);
3714
3599
  } catch (error) {
3715
- logger$23.error("[Participant.startScreenShare] Screen share error:", error);
3600
+ logger$23.error("[Participant.addAdditionalDevice] Additional device error:", error);
3601
+ throw error;
3716
3602
  }
3717
3603
  }
3718
3604
  /** Removes an additional media input device by ID. */
@@ -5206,7 +5092,7 @@ var RTCPeerConnectionController = class extends Destroyable {
5206
5092
  logger$17.debug(`[RTCPeerConnectionController] ${kind} input device selected:`, deviceInfo?.label);
5207
5093
  } catch (error) {
5208
5094
  logger$17.error(`[RTCPeerConnectionController] Failed to select ${kind} input device:`, error);
5209
- this._errors$.next(toError(error));
5095
+ this._errors$.next(new MediaTrackError("updateSelectedInputDevice", kind, error));
5210
5096
  throw error;
5211
5097
  }
5212
5098
  };
@@ -5428,7 +5314,7 @@ var RTCPeerConnectionController = class extends Destroyable {
5428
5314
  case "main":
5429
5315
  default: return {
5430
5316
  ...options,
5431
- offerToReceiveAudio: true,
5317
+ offerToReceiveAudio: this.options.receiveAudio ?? true,
5432
5318
  offerToReceiveVideo: this.options.receiveVideo ?? Boolean(this.inputVideoDeviceConstraints)
5433
5319
  };
5434
5320
  }
@@ -5582,13 +5468,14 @@ var RTCPeerConnectionController = class extends Destroyable {
5582
5468
  */
5583
5469
  async acceptInbound(mediaOverrides) {
5584
5470
  if (mediaOverrides) {
5585
- const { audio, video, receiveAudio, receiveVideo } = mediaOverrides;
5471
+ const { audio, video, receiveAudio, receiveVideo, fallbackToReceiveOnly } = mediaOverrides;
5586
5472
  this.options = {
5587
5473
  ...this.options,
5588
5474
  ...audio !== void 0 ? { audio } : {},
5589
5475
  ...video !== void 0 ? { video } : {},
5590
5476
  ...receiveAudio !== void 0 ? { receiveAudio } : {},
5591
- ...receiveVideo !== void 0 ? { receiveVideo } : {}
5477
+ ...receiveVideo !== void 0 ? { receiveVideo } : {},
5478
+ ...fallbackToReceiveOnly !== void 0 ? { fallbackToReceiveOnly } : {}
5592
5479
  };
5593
5480
  this.transceiverController?.updateOptions({
5594
5481
  receiveAudio: this.receiveAudio,
@@ -5745,7 +5632,19 @@ var RTCPeerConnectionController = class extends Destroyable {
5745
5632
  }
5746
5633
  async setupLocalTracks() {
5747
5634
  logger$17.debug("[RTCPeerConnectionController] Setting up local tracks/transceivers.");
5748
- const localStream = this.localStream ?? await this.localStreamController.buildLocalStream();
5635
+ if (this.hasNoLocalMediaToSend()) {
5636
+ if (!this.receiveAudio && !this.receiveVideo) throw new InvalidParams("Call requests no media: enable audio/video or receiveAudio/receiveVideo");
5637
+ logger$17.debug("[RTCPeerConnectionController] No local media requested; negotiating receive-only.");
5638
+ this.setupReceiveOnlyTransceivers();
5639
+ return;
5640
+ }
5641
+ let localStream;
5642
+ try {
5643
+ localStream = this.localStream ?? await this.localStreamController.buildLocalStream();
5644
+ } catch (error) {
5645
+ this.handleLocalMediaFailure(error);
5646
+ return;
5647
+ }
5749
5648
  if (this.transceiverController?.useAddStream ?? false) {
5750
5649
  logger$17.warn("[RTCPeerConnectionController] Using deprecated addStream API to add local stream.");
5751
5650
  this.peerConnection?.addStream(localStream);
@@ -5772,6 +5671,48 @@ var RTCPeerConnectionController = class extends Destroyable {
5772
5671
  }
5773
5672
  }
5774
5673
  }
5674
+ /** True for a main connection with no local media to send. */
5675
+ hasNoLocalMediaToSend() {
5676
+ const hasInputStreams = Boolean(this.options.inputAudioStream ?? this.options.inputVideoStream);
5677
+ return this.propose === "main" && !this.localStream && !hasInputStreams && !this.inputAudioDeviceConstraints && !this.inputVideoDeviceConstraints;
5678
+ }
5679
+ /** The media kinds this connection wants to send: 'audiovideo' | 'video' | 'audio'. */
5680
+ get requestedMediaKinds() {
5681
+ const wantsAudio = Boolean(this.inputAudioDeviceConstraints);
5682
+ const wantsVideo = Boolean(this.inputVideoDeviceConstraints);
5683
+ if (wantsAudio && wantsVideo) return "audiovideo";
5684
+ return wantsVideo ? "video" : "audio";
5685
+ }
5686
+ /**
5687
+ * Handle a local media acquisition failure with a typed, semantically
5688
+ * accurate MediaAccessError created at the acquisition site:
5689
+ * - Auxiliary connections (screenshare / additional-device) throw a
5690
+ * non-fatal error — VertoManager surfaces it and the call is unaffected.
5691
+ * - The main connection degrades to receive-only when allowed (default),
5692
+ * otherwise fails with a fatal error.
5693
+ */
5694
+ handleLocalMediaFailure(error) {
5695
+ if (this.propose === "screenshare") throw new MediaAccessError("startScreenShare", "screen", error, false);
5696
+ if (this.propose === "additional-device") throw new MediaAccessError("addInputDevice", this.requestedMediaKinds, error, false);
5697
+ const canReceive = this.receiveAudio || this.receiveVideo;
5698
+ if (!((this.options.fallbackToReceiveOnly ?? true) && canReceive)) throw new MediaAccessError("acquireLocalMedia", this.requestedMediaKinds, error, true);
5699
+ logger$17.warn("[RTCPeerConnectionController] Local media unavailable; continuing receive-only:", error);
5700
+ this._errors$.next(new MediaAccessError("acquireLocalMedia", this.requestedMediaKinds, error, false));
5701
+ this.setupReceiveOnlyTransceivers();
5702
+ }
5703
+ /**
5704
+ * Negotiate receive-only m-lines when there are no local tracks to send.
5705
+ * Only offer-type connections add transceivers — answer-type connections
5706
+ * reuse the transceivers created from the remote offer.
5707
+ */
5708
+ setupReceiveOnlyTransceivers() {
5709
+ if (this.type !== "offer") return;
5710
+ if (this.transceiverController?.useAddTransceivers ?? false) {
5711
+ this.peerConnection?.addTransceiver("audio", { direction: this.receiveAudio ? "recvonly" : "inactive" });
5712
+ this.peerConnection?.addTransceiver("video", { direction: this.receiveVideo ? "recvonly" : "inactive" });
5713
+ }
5714
+ if (!this.isNegotiating) this.negotiationNeeded$.next();
5715
+ }
5775
5716
  async getUserMedia(constraints) {
5776
5717
  return (this.options.webRTCApiProvider?.mediaDevices ?? navigator.mediaDevices).getUserMedia(constraints);
5777
5718
  }
@@ -5808,7 +5749,7 @@ var RTCPeerConnectionController = class extends Destroyable {
5808
5749
  stream = await this.getUserMedia({ audio: constraints });
5809
5750
  } catch (error) {
5810
5751
  logger$17.error("[RTCPeerConnectionController] Failed to re-acquire mic for pipeline restore:", error);
5811
- this._errors$.next(toError(error));
5752
+ this._errors$.next(new MediaTrackError("restoreAudioPipelineInput", "audio", error));
5812
5753
  return;
5813
5754
  }
5814
5755
  const newTrack = stream.getAudioTracks().at(0);
@@ -5870,7 +5811,7 @@ var RTCPeerConnectionController = class extends Destroyable {
5870
5811
  logger$17.debug(`[RTCPeerConnectionController] ${track.kind} track added:`, track.id);
5871
5812
  } catch (error) {
5872
5813
  logger$17.error(`[RTCPeerConnectionController] Failed to add ${track.kind} track:`, error);
5873
- this._errors$.next(toError(error));
5814
+ this._errors$.next(new MediaTrackError("addLocalTrack", track.kind, error));
5874
5815
  throw error;
5875
5816
  }
5876
5817
  }
@@ -5895,7 +5836,7 @@ var RTCPeerConnectionController = class extends Destroyable {
5895
5836
  logger$17.debug(`[RTCPeerConnectionController] ${sender.track?.kind} track removed:`, trackId);
5896
5837
  } catch (error) {
5897
5838
  logger$17.error(`[RTCPeerConnectionController] Failed to remove ${sender.track?.kind} track:`, error);
5898
- this._errors$.next(toError(error));
5839
+ this._errors$.next(new MediaTrackError("removeLocalTrack", sender.track?.kind ?? "unknown", error));
5899
5840
  throw error;
5900
5841
  }
5901
5842
  }
@@ -6503,6 +6444,7 @@ var WebRTCVertoManager = class extends VertoManager {
6503
6444
  inputVideoStream: options.inputVideoStream,
6504
6445
  receiveAudio: options.receiveAudio,
6505
6446
  receiveVideo: options.receiveVideo,
6447
+ fallbackToReceiveOnly: options.fallbackToReceiveOnly,
6506
6448
  webRTCApiProvider: this.webRTCApiProvider,
6507
6449
  preferredVideoCodecs: options.preferredVideoCodecs,
6508
6450
  preferredAudioCodecs: options.preferredAudioCodecs,
@@ -6729,9 +6671,11 @@ var WebRTCVertoManager = class extends VertoManager {
6729
6671
  await this.initAdditionalPeerConnection("screenshare", options);
6730
6672
  }
6731
6673
  async initAdditionalPeerConnection(propose, options) {
6674
+ const isScreenShare = propose === "screenshare";
6675
+ let firstPeerConnectionError;
6732
6676
  let rtcPeerConnController = null;
6733
6677
  try {
6734
- this._screenShareStatus$.next("starting");
6678
+ if (isScreenShare) this._screenShareStatus$.next("starting");
6735
6679
  rtcPeerConnController = new RTCPeerConnectionController({
6736
6680
  ...options,
6737
6681
  ...this.RTCPeerConnectionConfig,
@@ -6739,21 +6683,27 @@ var WebRTCVertoManager = class extends VertoManager {
6739
6683
  webRTCApiProvider: this.webRTCApiProvider
6740
6684
  }, void 0, this.deviceController);
6741
6685
  this.setupLocalDescriptionHandler(rtcPeerConnController);
6742
- if (propose === "screenshare") this._screenShareId = rtcPeerConnController.id;
6686
+ if (isScreenShare) this._screenShareId = rtcPeerConnController.id;
6743
6687
  this._rtcPeerConnectionsMap.set(rtcPeerConnController.id, rtcPeerConnController);
6744
6688
  this._rtcPeerConnections$.next(Array.from(this._rtcPeerConnectionsMap.values()));
6745
6689
  this.subscribeTo(rtcPeerConnController.errors$, (error) => {
6746
- this.onError?.(error);
6690
+ firstPeerConnectionError ??= error;
6691
+ this.onError?.(error, { fatal: false });
6747
6692
  });
6748
6693
  await firstValueFrom(rtcPeerConnController.connectionState$.pipe(filter((state) => state === "connected"), take(1), timeout(this._screenShareTimeoutMs), takeUntil(this.destroyed$)));
6749
- this._screenShareStatus$.next("started");
6750
- logger$16.info("[WebRTCManager] Screen share started successfully.");
6694
+ if (isScreenShare) this._screenShareStatus$.next("started");
6695
+ logger$16.info(`[WebRTCManager] Additional peer connection connected (${propose}).`);
6751
6696
  return rtcPeerConnController.id;
6752
6697
  } catch (error) {
6753
6698
  logger$16.warn("[WebRTCManager] Error initializing additional peer connection:", error);
6754
- this.onError?.(error instanceof Error ? error : new Error(String(error), { cause: error }));
6755
6699
  if (rtcPeerConnController) rtcPeerConnController.destroy();
6756
- this._screenShareStatus$.next("none");
6700
+ if (isScreenShare) this._screenShareStatus$.next("none");
6701
+ if (firstPeerConnectionError) throw firstPeerConnectionError instanceof MediaAccessError && firstPeerConnectionError.originalError instanceof Error ? firstPeerConnectionError.originalError : firstPeerConnectionError;
6702
+ if (error instanceof EmptyError) {
6703
+ logger$16.debug("[WebRTCManager] Additional peer connection aborted before connecting.");
6704
+ return;
6705
+ }
6706
+ throw error instanceof Error ? error : new Error(String(error), { cause: error });
6757
6707
  }
6758
6708
  }
6759
6709
  async removeInputDevices(id) {
@@ -8696,6 +8646,7 @@ function inferCallErrorKind(error) {
8696
8646
  if (error instanceof RPCTimeoutError) return "timeout";
8697
8647
  if (error instanceof JSONRPCError) return "signaling";
8698
8648
  if (error instanceof MediaTrackError) return "media";
8649
+ if (error instanceof MediaAccessError) return "media";
8699
8650
  if (error instanceof WebSocketConnectionError || error instanceof TransportConnectionError) return "network";
8700
8651
  return "internal";
8701
8652
  }
@@ -8712,6 +8663,7 @@ const RECOVERABLE_RPC_CODES = new Set([
8712
8663
  function isFatalError(error) {
8713
8664
  if (error instanceof VertoPongError) return false;
8714
8665
  if (error instanceof MediaTrackError) return false;
8666
+ if (error instanceof MediaAccessError) return error.fatal;
8715
8667
  if (error instanceof RPCTimeoutError) return false;
8716
8668
  if (error instanceof JSONRPCError && RECOVERABLE_RPC_CODES.has(error.code)) return false;
8717
8669
  return true;
@@ -8737,10 +8689,10 @@ var CallFactory = class {
8737
8689
  return {
8738
8690
  vertoManager: new WebRTCVertoManager(callInstance, this.attachManager, this.deviceController, this.webRTCApiProvider, {
8739
8691
  nodeId: options.nodeId,
8740
- onError: (error) => {
8692
+ onError: (error, options$1) => {
8741
8693
  const callError = {
8742
8694
  kind: inferCallErrorKind(error),
8743
- fatal: isFatalError(error),
8695
+ fatal: options$1?.fatal ?? isFatalError(error),
8744
8696
  error,
8745
8697
  callId: callInstance.id
8746
8698
  };
@@ -9199,6 +9151,17 @@ var PendingRPC = class PendingRPC {
9199
9151
  //#endregion
9200
9152
  //#region src/managers/ClientSessionManager.ts
9201
9153
  const logger$9 = getLogger();
9154
+ /**
9155
+ * Decide whether an error emitted on `call.errors$` during dial should
9156
+ * abort the dial. A non-fatal MediaAccessError means the call degraded to
9157
+ * receive-only and still connects — everything else rejects `dial()` with
9158
+ * the real cause.
9159
+ *
9160
+ * Pure function — exported for unit testing.
9161
+ */
9162
+ function shouldAbortDial(callError) {
9163
+ return callError.fatal || !(callError.error instanceof MediaAccessError);
9164
+ }
9202
9165
  const getAddressSearchURI = (options) => {
9203
9166
  const to = options.to?.split("?")[0];
9204
9167
  const from$1 = options.from?.startsWith("subscriber://") ? options.from.replace("subscriber://", "") : options.from;
@@ -9625,7 +9588,7 @@ var ClientSessionManager = class extends Destroyable {
9625
9588
  to: destinationURI,
9626
9589
  ...options
9627
9590
  });
9628
- await firstValueFrom(race(callSession.selfId$.pipe(filter((id) => Boolean(id)), take(1), timeout(this.callCreateTimeout)), callSession.errors$.pipe(take(1), switchMap((callError) => throwError(() => callError.error)))));
9591
+ await firstValueFrom(race(callSession.selfId$.pipe(filter((id) => Boolean(id)), take(1), timeout(this.callCreateTimeout)), callSession.errors$.pipe(filter(shouldAbortDial), take(1), switchMap((callError) => throwError(() => callError.error)))));
9629
9592
  this._calls$.next({
9630
9593
  [`${callSession.id}`]: callSession,
9631
9594
  ...this._calls$.value
@@ -11331,7 +11294,7 @@ var SignalWire = class extends Destroyable {
11331
11294
  logger$1.warn("[SignalWire] Failed to initialize VisibilityController:", error);
11332
11295
  }
11333
11296
  try {
11334
- this._diagnosticsCollector = new DiagnosticsCollector({ sdkVersion: "4.0.0-rc.1" });
11297
+ this._diagnosticsCollector = new DiagnosticsCollector({ sdkVersion: "4.0.0-rc.2" });
11335
11298
  } catch (error) {
11336
11299
  logger$1.warn("[SignalWire] Failed to initialize DiagnosticsCollector:", error);
11337
11300
  }
@@ -11865,7 +11828,7 @@ var StaticCredentialProvider = class {
11865
11828
  /**
11866
11829
  * Library version from package.json, injected at build time.
11867
11830
  */
11868
- const version = "4.0.0-rc.1";
11831
+ const version = "4.0.0-rc.2";
11869
11832
  /**
11870
11833
  * Flag indicating the library has been loaded and is ready to use.
11871
11834
  * For UMD builds: `window.SignalWire.ready`
@@ -11887,12 +11850,12 @@ const ready = true;
11887
11850
  */
11888
11851
  const emitReadyEvent = () => {
11889
11852
  if (typeof window !== "undefined") {
11890
- const event = new CustomEvent("signalwire:js:ready", { detail: { version: "4.0.0-rc.1" } });
11853
+ const event = new CustomEvent("signalwire:js:ready", { detail: { version: "4.0.0-rc.2" } });
11891
11854
  window.dispatchEvent(event);
11892
11855
  }
11893
11856
  };
11894
11857
  emitReadyEvent();
11895
11858
 
11896
11859
  //#endregion
11897
- export { Address, CallCreateError, ClientPreferences, CollectionFetchError, DPoPInitError, DeviceTokenError, EmbedTokenCredentialProvider, InvalidCredentialsError, MediaTrackError, MessageParseError, OverconstrainedFallbackError, Participant, PreflightError, RecoveryError, SelfCapabilities, SelfParticipant, SignalWire, StaticCredentialProvider, TokenRefreshError, UnexpectedError, User, VertoPongError, WebRTCCall, embeddableCall, getLogger, isSelfParticipant, ready, setDebugOptions, setLogLevel, setLogger, version };
11860
+ export { Address, CallCreateError, ClientPreferences, CollectionFetchError, DPoPInitError, DeviceTokenError, EmbedTokenCredentialProvider, InvalidCredentialsError, MediaAccessError, MediaTrackError, MessageParseError, OverconstrainedFallbackError, Participant, PreflightError, RecoveryError, SelfCapabilities, SelfParticipant, SignalWire, StaticCredentialProvider, TokenRefreshError, UnexpectedError, User, VertoPongError, WebRTCCall, embeddableCall, getLogger, isSelfParticipant, ready, setDebugOptions, setLogLevel, setLogger, version };
11898
11861
  //# sourceMappingURL=index.mjs.map