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

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.
@@ -1,4 +1,4 @@
1
- const require_operators = require('../operators-B8ipd4Xl.cjs');
1
+ const require_operators = require('../operators-BJ6QW1VP.cjs');
2
2
 
3
3
  exports.filterAs = require_operators.filterAs;
4
4
  exports.filterNull = require_operators.filterNull;
@@ -1,3 +1,3 @@
1
- import { a as filterNull, n as filterAs, r as ifIsMap, t as throwOnRPCError } from "../operators-BlUtq-t0.mjs";
1
+ import { a as filterNull, n as filterAs, r as ifIsMap, t as throwOnRPCError } from "../operators-BVxi3KpN.mjs";
2
2
 
3
3
  export { filterAs, filterNull, ifIsMap, throwOnRPCError };
@@ -36,6 +36,25 @@ const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;
36
36
  const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6e3;
37
37
  const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 300 * 1e3;
38
38
  const DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
39
+ /**
40
+ * How long call setup may wait for the network, measured from local media
41
+ * settling until the member id arrives.
42
+ *
43
+ * Local media acquisition is deliberately NOT inside this: a permission prompt
44
+ * or a device picker is human time, and a human may take as long as they like
45
+ * without spending the server's budget. The clock starts when acquisition ends.
46
+ *
47
+ * Must exceed `iceGatheringTimeout + the RPC timeout`, which both run inside it.
48
+ */
49
+ const DEFAULT_CALL_SIGNALING_TIMEOUT_MS = 12e3;
50
+ /**
51
+ * How long an auxiliary leg (screen share, additional device) may take to
52
+ * connect once its media is in hand.
53
+ *
54
+ * One bound for both: the picker is human time and sits outside it. What remains
55
+ * — offer, ICE, invite, answer, DTLS — is the same work for either leg kind.
56
+ */
57
+ const DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS = 15e3;
39
58
  const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;
40
59
  const DEFAULT_RECONNECT_DELAY_MAX_MS = 3e3;
41
60
  const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;
@@ -63,6 +82,14 @@ const CREDENTIAL_REFRESH_MAX_DELAY_MS = 3e4;
63
82
  /** Buffer in milliseconds before token expiry to trigger refresh. */
64
83
  const CREDENTIAL_REFRESH_BUFFER_MS = 5e3;
65
84
  /**
85
+ * Clock-skew allowance (ms) for treating an in-memory credential as expired
86
+ * when deciding whether a fresh (re)connect must re-mint the token before
87
+ * authenticating. A token within this window of its `expiry_at` is treated as
88
+ * stale so the reconnect re-mints via the credential provider instead of
89
+ * replaying a dead token (which the server rejects with -32003).
90
+ */
91
+ const CREDENTIAL_EXPIRY_SKEW_MS = 3e4;
92
+ /**
66
93
  * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`
67
94
  * to resolve before treating the activation as failed and falling back to
68
95
  * the developer-provided refresh path. Prevents a wedged HTTP layer from
@@ -81,6 +108,8 @@ const MEDIA_ACCESS_DENIAL_NAMES = [
81
108
  "SecurityError",
82
109
  "PermissionDeniedError"
83
110
  ];
111
+ /** Error names browsers use when the capture hardware is already held exclusively. */
112
+ const MEDIA_DEVICE_IN_USE_NAMES = ["NotReadableError", "TrackStartError"];
84
113
  /** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */
85
114
  const DEFAULT_STATS_POLLING_INTERVAL_MS = 1e3;
86
115
  /** Number of initial samples used to build a baseline for spike detection. */
@@ -295,6 +324,20 @@ var CallCreateError = class extends Error {
295
324
  this.name = "CallCreateError";
296
325
  }
297
326
  };
327
+ var CallNotReadyError = class extends Error {
328
+ constructor(callId, options) {
329
+ super(`Call "${callId}" has no self member context yet: selfId/nodeId have not been received from the server`, options);
330
+ this.callId = callId;
331
+ this.name = "CallNotReadyError";
332
+ }
333
+ };
334
+ var ParticipantNotReadyError = class extends Error {
335
+ constructor(memberId, options) {
336
+ super(`Participant "${memberId}" has no call context yet: its member state (call_id/node_id) has not been received from the server`, options);
337
+ this.memberId = memberId;
338
+ this.name = "ParticipantNotReadyError";
339
+ }
340
+ };
298
341
  var JSONRPCError = class extends Error {
299
342
  constructor(code, message, data, options, requestId) {
300
343
  super(message, options);
@@ -366,6 +409,32 @@ var CollectionFetchError = class extends Error {
366
409
  this.name = "CollectionFetchError";
367
410
  }
368
411
  };
412
+ /**
413
+ * An auxiliary leg did not connect within its budget. Typed rather than a bare
414
+ * RxJS `TimeoutError` so the leg and cause survive.
415
+ */
416
+ var AuxiliaryLegTimeoutError = class extends Error {
417
+ constructor(leg, originalError) {
418
+ super(`Timed out waiting for the ${leg} connection to be established`, { cause: originalError });
419
+ this.leg = leg;
420
+ this.originalError = originalError;
421
+ this.name = "AuxiliaryLegTimeoutError";
422
+ }
423
+ };
424
+ /**
425
+ * An auxiliary leg was removed before it finished connecting.
426
+ *
427
+ * Typed rather than a bare resolve so a caller awaiting the start can tell a
428
+ * cancel apart from a share that actually came up — the public methods return
429
+ * `void`, so the promise is the only signal they have.
430
+ */
431
+ var AuxiliaryLegCancelledError = class extends Error {
432
+ constructor(leg) {
433
+ super(`The ${leg} leg was removed before it finished connecting`);
434
+ this.leg = leg;
435
+ this.name = "AuxiliaryLegCancelledError";
436
+ }
437
+ };
369
438
  var MediaTrackError = class extends Error {
370
439
  constructor(operation, kind, originalError) {
371
440
  super(`Media track ${operation} failed for ${kind}`, { cause: originalError instanceof Error ? originalError : void 0 });
@@ -379,6 +448,10 @@ var MediaTrackError = class extends Error {
379
448
  function isMediaAccessDenial(originalError) {
380
449
  return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);
381
450
  }
451
+ /** True when a `getUserMedia` rejection means the hardware is already held exclusively. */
452
+ function isMediaDeviceInUse(originalError) {
453
+ return originalError instanceof Error && MEDIA_DEVICE_IN_USE_NAMES.includes(originalError.name);
454
+ }
382
455
  /**
383
456
  * Failure to acquire local media (camera, microphone, or screen capture)
384
457
  * via `getUserMedia`/`getDisplayMedia`.
@@ -402,6 +475,22 @@ var MediaAccessError = class extends Error {
402
475
  return isMediaAccessDenial(this.originalError);
403
476
  }
404
477
  };
478
+ /**
479
+ * Thrown by `startScreenShare()` when the call is already sharing a screen.
480
+ *
481
+ * A call carries at most one screen share. Accepting a second one would
482
+ * overwrite the only reference the SDK holds to the first, leaving it
483
+ * capturing and sending with no way to stop it — so the second request is
484
+ * rejected and the live share is left untouched. Call `stopScreenShare()`
485
+ * first to replace it.
486
+ */
487
+ var ScreenShareAlreadyActiveError = class extends Error {
488
+ constructor(screenShareId, options) {
489
+ super(`A screen share is already active on this call (${screenShareId}). Call stopScreenShare() before starting another one.`, options);
490
+ this.screenShareId = screenShareId;
491
+ this.name = "ScreenShareAlreadyActiveError";
492
+ }
493
+ };
405
494
  var DPoPInitError = class extends Error {
406
495
  constructor(originalError, message = "Failed to initialize DPoP key pair") {
407
496
  super(message, { cause: originalError instanceof Error ? originalError : void 0 });
@@ -678,12 +767,30 @@ Object.defineProperty(exports, 'AuthStateHandlerError', {
678
767
  return AuthStateHandlerError;
679
768
  }
680
769
  });
770
+ Object.defineProperty(exports, 'AuxiliaryLegCancelledError', {
771
+ enumerable: true,
772
+ get: function () {
773
+ return AuxiliaryLegCancelledError;
774
+ }
775
+ });
776
+ Object.defineProperty(exports, 'AuxiliaryLegTimeoutError', {
777
+ enumerable: true,
778
+ get: function () {
779
+ return AuxiliaryLegTimeoutError;
780
+ }
781
+ });
681
782
  Object.defineProperty(exports, 'CREDENTIAL_ACTIVATE_TIMEOUT_MS', {
682
783
  enumerable: true,
683
784
  get: function () {
684
785
  return CREDENTIAL_ACTIVATE_TIMEOUT_MS;
685
786
  }
686
787
  });
788
+ Object.defineProperty(exports, 'CREDENTIAL_EXPIRY_SKEW_MS', {
789
+ enumerable: true,
790
+ get: function () {
791
+ return CREDENTIAL_EXPIRY_SKEW_MS;
792
+ }
793
+ });
687
794
  Object.defineProperty(exports, 'CREDENTIAL_REFRESH_BUFFER_MS', {
688
795
  enumerable: true,
689
796
  get: function () {
@@ -714,6 +821,12 @@ Object.defineProperty(exports, 'CallCreateError', {
714
821
  return CallCreateError;
715
822
  }
716
823
  });
824
+ Object.defineProperty(exports, 'CallNotReadyError', {
825
+ enumerable: true,
826
+ get: function () {
827
+ return CallNotReadyError;
828
+ }
829
+ });
717
830
  Object.defineProperty(exports, 'CollectionFetchError', {
718
831
  enumerable: true,
719
832
  get: function () {
@@ -732,6 +845,18 @@ Object.defineProperty(exports, 'DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN', {
732
845
  return DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN;
733
846
  }
734
847
  });
848
+ Object.defineProperty(exports, 'DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS', {
849
+ enumerable: true,
850
+ get: function () {
851
+ return DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS;
852
+ }
853
+ });
854
+ Object.defineProperty(exports, 'DEFAULT_CALL_SIGNALING_TIMEOUT_MS', {
855
+ enumerable: true,
856
+ get: function () {
857
+ return DEFAULT_CALL_SIGNALING_TIMEOUT_MS;
858
+ }
859
+ });
735
860
  Object.defineProperty(exports, 'DEFAULT_CHECK_CONNECTION_ON_VISIBLE', {
736
861
  enumerable: true,
737
862
  get: function () {
@@ -1110,6 +1235,12 @@ Object.defineProperty(exports, 'PREFERENCES_STORAGE_KEY', {
1110
1235
  return PREFERENCES_STORAGE_KEY;
1111
1236
  }
1112
1237
  });
1238
+ Object.defineProperty(exports, 'ParticipantNotReadyError', {
1239
+ enumerable: true,
1240
+ get: function () {
1241
+ return ParticipantNotReadyError;
1242
+ }
1243
+ });
1113
1244
  Object.defineProperty(exports, 'PreflightError', {
1114
1245
  enumerable: true,
1115
1246
  get: function () {
@@ -1164,6 +1295,12 @@ Object.defineProperty(exports, 'SAT_REFRESH_SCOPE', {
1164
1295
  return SAT_REFRESH_SCOPE;
1165
1296
  }
1166
1297
  });
1298
+ Object.defineProperty(exports, 'ScreenShareAlreadyActiveError', {
1299
+ enumerable: true,
1300
+ get: function () {
1301
+ return ScreenShareAlreadyActiveError;
1302
+ }
1303
+ });
1167
1304
  Object.defineProperty(exports, 'SerializationError', {
1168
1305
  enumerable: true,
1169
1306
  get: function () {
@@ -1296,6 +1433,12 @@ Object.defineProperty(exports, 'ifIsMap', {
1296
1433
  return ifIsMap;
1297
1434
  }
1298
1435
  });
1436
+ Object.defineProperty(exports, 'isMediaDeviceInUse', {
1437
+ enumerable: true,
1438
+ get: function () {
1439
+ return isMediaDeviceInUse;
1440
+ }
1441
+ });
1299
1442
  Object.defineProperty(exports, 'setDebugOptions', {
1300
1443
  enumerable: true,
1301
1444
  get: function () {
@@ -1320,4 +1463,4 @@ Object.defineProperty(exports, 'throwOnRPCError', {
1320
1463
  return throwOnRPCError;
1321
1464
  }
1322
1465
  });
1323
- //# sourceMappingURL=operators-B8ipd4Xl.cjs.map
1466
+ //# sourceMappingURL=operators-BJ6QW1VP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operators-BJ6QW1VP.cjs","names":["DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints","at?: string","requestId: string","timeoutMs: number","error: unknown","storageType: string","key: string","originalError: Error","description: string","message: string","direction: 'inbound' | 'outbound'","callId: string","memberId: string","code: number | string","data?: unknown","requestId?: string","originalError: unknown","operation: string","leg: RTCPeerConnectionPropose","originalError?: Error","kind: string","media: string","fatal: boolean","screenShareId: string","action: string","attempt: number","originalError?: unknown","deviceKind: string","phase: string","log","userLogger: SDKLogger | null","logger","debugOptions: DebugOptions","wsTraffic: InternalSDKLogger['wsTraffic']","payload: unknown","value: unknown"],"sources":["../src/core/constants.ts","../src/core/errors.ts","../src/utils/logger.ts","../src/operators/filterNull.ts","../src/utils/getValueFrom.ts","../src/operators/filterEventAs.ts","../src/operators/throwOnRPCError.ts"],"sourcesContent":["export const INVITE_VERSION = 1000;\nexport const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;\nexport const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6_000;\nexport const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nexport const DEFAULT_REATTACH_WAIT_TIMEOUT_MS = 10_000; // 10 seconds to wait for server verto.attach\nexport const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;\n/**\n * How long call setup may wait for the network, measured from local media\n * settling until the member id arrives.\n *\n * Local media acquisition is deliberately NOT inside this: a permission prompt\n * or a device picker is human time, and a human may take as long as they like\n * without spending the server's budget. The clock starts when acquisition ends.\n *\n * Must exceed `iceGatheringTimeout + the RPC timeout`, which both run inside it.\n */\nexport const DEFAULT_CALL_SIGNALING_TIMEOUT_MS = 12_000;\n/**\n * How long an auxiliary leg (screen share, additional device) may take to\n * connect once its media is in hand.\n *\n * One bound for both: the picker is human time and sits outside it. What remains\n * — offer, ICE, invite, answer, DTLS — is the same work for either leg kind.\n */\nexport const DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS = 15_000;\nexport const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;\nexport const DEFAULT_RECONNECT_DELAY_MAX_MS = 3000;\nexport const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;\nexport const DEFAULT_DEVICE_POLLING_INTERVAL_MS = 0; // Disabled by default\nexport const PREFERENCES_STORAGE_KEY = 'sw:preferences';\n\n/** Scope value that enables automatic token refresh. */\nexport const SAT_REFRESH_SCOPE = 'sat:refresh';\n\n/** API endpoints for device token operations. */\nexport const DEVICE_TOKEN_ENDPOINT = '/api/fabric/subscriber/devices/token';\nexport const DEVICE_REFRESH_ENDPOINT = '/api/fabric/subscriber/devices/refresh';\n\n/** Default device token TTL in seconds (15 minutes). */\nexport const DEVICE_TOKEN_DEFAULT_EXPIRE_IN = 900;\n\n/** Buffer time in milliseconds before expiry to trigger refresh. */\nexport const DEVICE_TOKEN_REFRESH_BUFFER_MS = 30_000;\n\n/** Maximum retry attempts for device token refresh on transient failure. */\nexport const DEVICE_TOKEN_REFRESH_MAX_RETRIES = 3;\n\n/** Base delay in milliseconds for exponential backoff on refresh retry. */\nexport const DEVICE_TOKEN_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum retry attempts for developer credential refresh on transient failure. */\nexport const CREDENTIAL_REFRESH_MAX_RETRIES = 5;\n\n/** Base delay in milliseconds for exponential backoff on credential refresh retry. */\nexport const CREDENTIAL_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum delay in milliseconds for credential refresh backoff. */\nexport const CREDENTIAL_REFRESH_MAX_DELAY_MS = 30_000;\n\n/** Buffer in milliseconds before token expiry to trigger refresh. */\nexport const CREDENTIAL_REFRESH_BUFFER_MS = 5000;\n\n/**\n * Clock-skew allowance (ms) for treating an in-memory credential as expired\n * when deciding whether a fresh (re)connect must re-mint the token before\n * authenticating. A token within this window of its `expiry_at` is treated as\n * stale so the reconnect re-mints via the credential provider instead of\n * replaying a dead token (which the server rejects with -32003).\n */\nexport const CREDENTIAL_EXPIRY_SKEW_MS = 30_000;\n\n/**\n * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`\n * to resolve before treating the activation as failed and falling back to\n * the developer-provided refresh path. Prevents a wedged HTTP layer from\n * leaving the session with no active refresh mechanism.\n */\nexport const CREDENTIAL_ACTIVATE_TIMEOUT_MS = 30_000;\n\n/** JSON-RPC error code for requester validation failure (corrupted auth state). */\nexport const RPC_ERROR_REQUESTER_VALIDATION_FAILED = -32003;\n\n/** JSON-RPC error code for invalid params (e.g., missing authentication block). */\nexport const RPC_ERROR_INVALID_PARAMS = -32602;\n\n/** JSON-RPC error code for authentication failure (invalid token, missing DPoP, etc.). */\nexport const RPC_ERROR_AUTHENTICATION_FAILED = -32002;\n\n/** Error names browsers use for a media permission denial (user or policy). */\nexport const MEDIA_ACCESS_DENIAL_NAMES = [\n 'NotAllowedError',\n 'SecurityError',\n 'PermissionDeniedError'\n];\n\n/** Error names browsers use when the capture hardware is already held exclusively. */\nexport const MEDIA_DEVICE_IN_USE_NAMES = ['NotReadableError', 'TrackStartError'];\n\n// =============================================================================\n// STATS MONITORING DEFAULTS (Section 1)\n// =============================================================================\n\n/** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */\nexport const DEFAULT_STATS_POLLING_INTERVAL_MS = 1000;\n\n/** Number of initial samples used to build a baseline for spike detection. */\nexport const DEFAULT_STATS_BASELINE_SAMPLES = 10;\n\n/** Duration in ms with no inbound audio packets before emitting a critical issue. */\nexport const DEFAULT_STATS_NO_PACKET_THRESHOLD_MS = 2000;\n\n/** Multiplier applied to baseline RTT to detect a warning-level RTT spike. */\nexport const DEFAULT_STATS_RTT_SPIKE_MULTIPLIER = 3;\n\n/** Packet loss fraction (0-1) above which a warning is emitted. */\nexport const DEFAULT_STATS_PACKET_LOSS_THRESHOLD = 0.05;\n\n/** Multiplier applied to baseline jitter to detect a jitter spike. */\nexport const DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER = 4;\n\n/** Number of seconds of metrics history to retain. */\nexport const DEFAULT_STATS_HISTORY_SIZE = 30;\n\n// =============================================================================\n// KEYFRAME THROTTLING DEFAULTS (Section 2)\n// =============================================================================\n\n/** Maximum keyframe requests allowed within a single burst window. */\nexport const DEFAULT_KEYFRAME_MAX_BURST = 3;\n\n/** Duration of the keyframe burst window in milliseconds. */\nexport const DEFAULT_KEYFRAME_BURST_WINDOW_MS = 3000;\n\n/** Cooldown period in ms after burst limit is reached before allowing more keyframes. */\nexport const DEFAULT_KEYFRAME_COOLDOWN_MS = 10_000;\n\n// =============================================================================\n// RE-INVITE / ICE RESTART DEFAULTS (Section 2 & 19)\n// =============================================================================\n\n/** Minimum time between re-INVITE attempts in milliseconds. */\nexport const DEFAULT_REINVITE_DEBOUNCE_TIME_MS = 10_000;\n\n/** Maximum number of re-INVITE attempts per call. */\nexport const DEFAULT_REINVITE_MAX_ATTEMPTS = 3;\n\n/** Timeout for a single re-INVITE attempt in milliseconds. */\nexport const DEFAULT_REINVITE_TIMEOUT_MS = 5000;\n\n// =============================================================================\n// RECOVERY PIPELINE DEFAULTS (Section 19)\n// =============================================================================\n\n/** Debounce window in ms to collapse multiple detection signals into one trigger. */\nexport const DEFAULT_RECOVERY_DEBOUNCE_TIME_MS = 2000;\n\n/** Cooldown period in ms between recovery attempts. */\nexport const DEFAULT_RECOVERY_COOLDOWN_MS = 10_000;\n\n/** Grace period in ms before treating ICE 'disconnected' as a failure. */\nexport const DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS = 3000;\n\n/** Timeout for a single ICE restart attempt in milliseconds. */\nexport const DEFAULT_ICE_RESTART_TIMEOUT_MS = 5000;\n\n/** Maximum recovery attempts before emitting 'max_attempts_reached'. */\nexport const DEFAULT_MAX_RECOVERY_ATTEMPTS = 3;\n\n/** Upper bound in ms for waiting on iceGatheringState === 'complete' after an ICE restart. */\nexport const ICE_GATHERING_COMPLETE_TIMEOUT_MS = 10_000;\n\n/** Upper bound in ms for waiting on RTCPeerConnection.connectionState === 'connected' after a recovery ICE restart. */\nexport const PEER_CONNECTION_RECOVERY_WAIT_MS = 5000;\n\n/** Polling interval in ms while waiting for RTCPeerConnection.connectionState to transition. */\nexport const PEER_CONNECTION_RECOVERY_POLL_MS = 100;\n\n// =============================================================================\n// AUDIO PIPELINE (local mic metering / gain / VAD)\n// =============================================================================\n\n/** Polling interval for LocalAudioPipeline.level$ (ms). ~30fps is smooth for meters. */\nexport const AUDIO_LEVEL_POLL_INTERVAL_MS = 33;\n\n/** RMS level threshold (0..1) above which the local participant is considered speaking. */\nexport const VAD_THRESHOLD = 0.03;\n\n/** Hold window in ms below the threshold before speaking$ flips back to false. */\nexport const VAD_HOLD_MS = 250;\n\n// =============================================================================\n// DEVICE MANAGEMENT DEFAULTS (Section 5)\n// =============================================================================\n\n/** Whether to persist device selections to storage by default. */\nexport const DEFAULT_PERSIST_DEVICE_SELECTION = true;\n\n/** Whether to auto-apply device changes to active calls by default. */\nexport const DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS = true;\n\n/** Storage keys for persisted device selections. */\nexport const DEVICE_STORAGE_KEY_AUDIO_INPUT = 'sw:device:audioinput';\nexport const DEVICE_STORAGE_KEY_AUDIO_OUTPUT = 'sw:device:audiooutput';\nexport const DEVICE_STORAGE_KEY_VIDEO_INPUT = 'sw:device:videoinput';\n\n/** SDK storage key prefix used for targeted cleanup (factory reset). */\nexport const SDK_STORAGE_KEY_PREFIX = 'sw:';\n\n// =============================================================================\n// VISIBILITY DEFAULTS (Section 4)\n// =============================================================================\n\n/** Whether to auto-mute video when the tab becomes hidden. */\nexport const DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN = false;\n\n/** Whether to re-enumerate devices when the page becomes visible. */\nexport const DEFAULT_REFRESH_DEVICES_ON_VISIBLE = true;\n\n/** Whether to check peer connection health when the page becomes visible. */\nexport const DEFAULT_CHECK_CONNECTION_ON_VISIBLE = true;\n\n// =============================================================================\n// DEGRADATION THRESHOLDS (Section 22)\n// =============================================================================\n\n/** Whether automatic video degradation on low bandwidth is enabled. */\nexport const DEFAULT_ENABLE_AUTO_DEGRADATION = true;\n\n/** Bitrate in kbps below which video is automatically disabled. */\nexport const DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS = 150;\n\n/** Bitrate in kbps above which video is automatically re-enabled (hysteresis). */\nexport const DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS = 300;\n\n// =============================================================================\n// NETWORK RECOVERY FEATURE FLAGS (Section 19)\n// =============================================================================\n\n/** Whether relay-only escalation is enabled as a last-resort recovery tier. */\nexport const DEFAULT_ENABLE_RELAY_FALLBACK = true;\n\n/** Whether to listen for browser online/offline/connection events. */\nexport const DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION = true;\n\n/** Whether to intercept server-sent media-timeout hangups and attempt recovery. */\nexport const DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION = true;\n\n// =============================================================================\n// DEFAULT AUDIO/VIDEO CONSTRAINTS (Section 16.5 & 16.6)\n// =============================================================================\n\n/** Default audio track constraints applied when no explicit constraints are provided. */\nexport const DEFAULT_AUDIO_CONSTRAINTS: MediaTrackConstraints = {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true\n};\n\n/** Default video track constraints applied when video is enabled without explicit constraints. */\nexport const DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints = {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n aspectRatio: 16 / 9\n};\n\n/** Whether stereo Opus is enabled by default. */\nexport const DEFAULT_STEREO_AUDIO = false;\n\n/** Max average bitrate for stereo Opus in bits per second. */\nexport const DEFAULT_STEREO_MAX_AVERAGE_BITRATE = 510_000;\n\n// =============================================================================\n// QUALITY LEVEL THRESHOLDS (Section 21)\n// =============================================================================\n\n/** MOS score threshold: at or above this is 'excellent'. */\nexport const QUALITY_THRESHOLD_EXCELLENT = 4.0;\n\n/** MOS score threshold: at or above this is 'good'. */\nexport const QUALITY_THRESHOLD_GOOD = 3.5;\n\n/** MOS score threshold: at or above this is 'fair'. */\nexport const QUALITY_THRESHOLD_FAIR = 3.0;\n\n/** MOS score threshold: at or above this is 'poor'. */\nexport const QUALITY_THRESHOLD_POOR = 2.0;\n\n/** MOS score at or below QUALITY_THRESHOLD_POOR is 'critical'. */\n\n// =============================================================================\n// PREFLIGHT DEFAULTS (Section 20)\n// =============================================================================\n\n/** Default duration for the preflight media/bandwidth test in seconds. */\nexport const DEFAULT_PREFLIGHT_DURATION_SEC = 10;\n","import { MEDIA_ACCESS_DENIAL_NAMES, MEDIA_DEVICE_IN_USE_NAMES } from './constants';\n\nimport type { RTCPeerConnectionPropose } from './types/call.types';\n\nexport class UnexpectedError extends Error {\n constructor(\n public at?: string,\n options?: ErrorOptions\n ) {\n super(`Unexpected Error${at ? ` at ${at}` : ''}`, options);\n this.name = 'UnexpectedError';\n }\n}\n\nexport class UnimplementedError extends Error {\n constructor(\n public reason = 'Not Implemented',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'UnimplementedError';\n }\n}\n\nexport class NotConnectedError extends Error {\n constructor(\n public reason = 'Not Connected',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'NotConnectedError';\n }\n}\n\nexport class InvalidCredentialsError extends Error {\n constructor(\n public reason = 'Invalid Credentials',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'InvalidCredentialsError';\n }\n}\n\nexport class WebSocketConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketConnectionError';\n }\n}\n\nexport class TransportConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TransportConnectionError';\n }\n}\n\nexport class WebSocketTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketTimeoutError';\n }\n}\n\nexport class RequestTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestTimeoutError';\n }\n}\n\nexport class RequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestError';\n }\n}\n\nexport class InvalidListenerError extends Error {\n constructor(options?: ErrorOptions) {\n super('listener is not a function', options);\n this.name = 'InvalidListenerError';\n }\n}\n\nexport class RPCTimeoutError extends Error {\n constructor(\n public requestId: string,\n public timeoutMs: number,\n options?: ErrorOptions\n ) {\n super(`RPC request ${requestId} timed out after ${timeoutMs}ms`, options);\n this.name = 'RPCTimeoutError';\n }\n}\n\nexport class AuthStateHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling authorization state update', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'AuthStateHandlerError';\n }\n}\n\nexport class InvalidStateTransitionError extends Error {\n constructor(\n public currentState: string,\n public targetState: string,\n options?: ErrorOptions\n ) {\n super(\n `Invalid transition: cannot transition from \"${currentState}\" to \"${targetState}\"`,\n options\n );\n this.name = 'InvalidStateTransitionError';\n }\n}\n\nexport class InvalidOptionError extends Error {\n constructor(\n public value: string,\n public availableOptions: string[],\n options?: ErrorOptions\n ) {\n super(\n `Invalid option: \"${value}\" must be one of the available options: ${availableOptions.join(', ')}`,\n options\n );\n this.name = 'InvalidOptionError';\n }\n}\n\nexport class StorageNotAvailableError extends Error {\n constructor(\n public storageType: string = 'localStorage',\n options?: ErrorOptions\n ) {\n super(`${storageType} is not available in this environment`, options);\n this.name = 'StorageNotAvailableError';\n }\n}\n\nexport class SerializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to serialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'SerializationError';\n }\n}\n\nexport class DeserializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to deserialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'DeserializationError';\n }\n}\n\nexport class StorageWriteError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to write to storage for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageWriteError';\n }\n}\n\nexport class StorageReadError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to read from storage \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageReadError';\n }\n}\n\nexport class InvalidStorageValueError extends Error {\n constructor(\n public key: string,\n public valueType: string,\n options?: ErrorOptions\n ) {\n super(\n `Cannot serialize value of type \"${valueType}\" for key \"${key}\": This type cannot be serialized to JSON`,\n options\n );\n this.name = 'InvalidStorageValueError';\n }\n}\n\nexport class DependencyError extends Error {\n constructor(\n public description: string,\n options?: ErrorOptions\n ) {\n super(`Dependency ${description} is not set or available.`, options);\n this.name = 'DependencyError';\n }\n}\n\nexport class DeviceNotFoundError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'DeviceNotFoundError';\n }\n}\n\n// =============================================================================\n// CALL ERROR TYPES\n// =============================================================================\n\n/**\n * Semantic category of a call-lifecycle error.\n *\n * - `'media'` – RTCPeerConnection / media device failure\n * - `'signaling'` – Verto / JSON-RPC protocol error\n * - `'timeout'` – Call setup timed out waiting for a response\n * - `'rejected'` – Remote side rejected the call\n * - `'network'` – Transport lost during an active call\n * - `'internal'` – Unexpected / unknown error\n */\nexport type CallErrorKind = 'media' | 'signaling' | 'timeout' | 'rejected' | 'network' | 'internal';\n\n/**\n * Structured error emitted on `call.errors$`.\n *\n * Provides actionable metadata so consumers can react without\n * resorting to `instanceof` checks on raw `Error` objects.\n */\nexport interface CallError {\n /** Semantic category of the error. */\n readonly kind: CallErrorKind;\n /**\n * Whether the error terminates the call.\n * When `true`, the call will automatically transition to `'failed'`\n * and be destroyed — no further action is needed from the consumer.\n */\n readonly fatal: boolean;\n /** The underlying error. */\n readonly error: Error;\n /** ID of the call that produced this error. */\n readonly callId: string;\n /**\n * Which peer connection failed. Auxiliary legs are never fatal, so a consumer\n * can surface \"screen share failed, call continues\". Absent for call- and\n * session-level errors.\n */\n readonly leg?: RTCPeerConnectionPropose;\n /** `callId` is always the call's id, never the leg's. Use this for the leg. */\n readonly legId?: string;\n}\n\nexport class CallCreateError extends Error {\n constructor(\n public message: string,\n public error: unknown = null,\n public direction: 'inbound' | 'outbound' = 'outbound',\n options?: ErrorOptions\n ) {\n super(message, {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'CallCreateError';\n }\n}\n\nexport class CallNotReadyError extends Error {\n constructor(\n public callId: string,\n options?: ErrorOptions\n ) {\n super(\n `Call \"${callId}\" has no self member context yet: selfId/nodeId have not been received from the server`,\n options\n );\n this.name = 'CallNotReadyError';\n }\n}\n\nexport class ParticipantNotReadyError extends Error {\n constructor(\n public memberId: string,\n options?: ErrorOptions\n ) {\n super(\n `Participant \"${memberId}\" has no call context yet: its member state (call_id/node_id) has not been received from the server`,\n options\n );\n this.name = 'ParticipantNotReadyError';\n }\n}\n\nexport class JSONRPCError extends Error {\n constructor(\n public code: number | string,\n message: string,\n public data?: unknown,\n options?: ErrorOptions,\n public requestId?: string\n ) {\n super(message, options);\n this.name = 'JSONRPCError';\n }\n}\n\nexport class InvalidParams extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'InvalidParams';\n }\n}\n\nexport class ConversationError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'ConversationError';\n }\n}\n\nexport class VertoInviteHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto invite', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoInviteHandlerError';\n }\n}\n\nexport class VertoAttachHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto attach', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoAttachHandlerError';\n }\n}\n\nexport class HttpRequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'HttpRequestError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ValidationError';\n }\n}\n\nexport class VertoPongError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to send Verto pong - call may disconnect', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'VertoPongError';\n }\n}\n\nexport class MessageParseError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to parse incoming WebSocket message', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MessageParseError';\n }\n}\n\nexport class CollectionFetchError extends Error {\n constructor(\n public operation: string,\n public originalError: unknown\n ) {\n super(`Collection fetch failed during ${operation}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'CollectionFetchError';\n }\n}\n\n/**\n * An auxiliary leg did not connect within its budget. Typed rather than a bare\n * RxJS `TimeoutError` so the leg and cause survive.\n */\nexport class AuxiliaryLegTimeoutError extends Error {\n constructor(\n public readonly leg: RTCPeerConnectionPropose,\n public readonly originalError?: Error\n ) {\n super(`Timed out waiting for the ${leg} connection to be established`, {\n cause: originalError\n });\n this.name = 'AuxiliaryLegTimeoutError';\n }\n}\n\n/**\n * An auxiliary leg was removed before it finished connecting.\n *\n * Typed rather than a bare resolve so a caller awaiting the start can tell a\n * cancel apart from a share that actually came up — the public methods return\n * `void`, so the promise is the only signal they have.\n */\nexport class AuxiliaryLegCancelledError extends Error {\n constructor(public readonly leg: RTCPeerConnectionPropose) {\n super(`The ${leg} leg was removed before it finished connecting`);\n this.name = 'AuxiliaryLegCancelledError';\n }\n}\n\nexport class MediaTrackError extends Error {\n constructor(\n public operation: string,\n public kind: string,\n public originalError: unknown\n ) {\n super(`Media track ${operation} failed for ${kind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MediaTrackError';\n }\n}\n\n/** True when a `getUserMedia`/`getDisplayMedia` rejection is a permission denial. */\nfunction isMediaAccessDenial(originalError: unknown): boolean {\n return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);\n}\n\n/** True when a `getUserMedia` rejection means the hardware is already held exclusively. */\nexport function isMediaDeviceInUse(originalError: unknown): boolean {\n return originalError instanceof Error && MEDIA_DEVICE_IN_USE_NAMES.includes(originalError.name);\n}\n\n/**\n * Failure to acquire local media (camera, microphone, or screen capture)\n * via `getUserMedia`/`getDisplayMedia`.\n *\n * Non-fatal by default: screenshare and additional-device failures never\n * end the call, and main-connection failures degrade to receive-only when\n * possible. The wrapping site sets `fatal` to `true` only when the call\n * cannot continue (receive-only fallback disabled or no receive intent).\n */\nexport class MediaAccessError extends Error {\n constructor(\n /** The SDK operation that failed, e.g. `'acquireLocalMedia'`, `'startScreenShare'`, `'addInputDevice'`. */\n public operation: string,\n /** The media being acquired: `'audio' | 'video' | 'audiovideo' | 'screen'`. */\n public media: string,\n /** The raw `getUserMedia`/`getDisplayMedia` error (typically a `DOMException`). */\n public originalError: unknown,\n /** Whether this failure terminates the call. */\n public readonly fatal: boolean = false\n ) {\n super(\n `Media access ${isMediaAccessDenial(originalError) ? 'denied' : 'failed'} for ${operation} (${media})`,\n {\n cause: originalError instanceof Error ? originalError : undefined\n }\n );\n this.name = 'MediaAccessError';\n }\n\n /** True when the underlying failure is a permission denial (user or policy). */\n get denied(): boolean {\n return isMediaAccessDenial(this.originalError);\n }\n}\n\n/**\n * Thrown by `startScreenShare()` when the call is already sharing a screen.\n *\n * A call carries at most one screen share. Accepting a second one would\n * overwrite the only reference the SDK holds to the first, leaving it\n * capturing and sending with no way to stop it — so the second request is\n * rejected and the live share is left untouched. Call `stopScreenShare()`\n * first to replace it.\n */\nexport class ScreenShareAlreadyActiveError extends Error {\n constructor(\n /** Id of the screen share leg that is already active. */\n public readonly screenShareId: string,\n options?: ErrorOptions\n ) {\n super(\n `A screen share is already active on this call (${screenShareId}). ` +\n 'Call stopScreenShare() before starting another one.',\n options\n );\n this.name = 'ScreenShareAlreadyActiveError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DPoPInitError extends Error {\n constructor(\n public originalError: unknown,\n message = 'Failed to initialize DPoP key pair'\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DPoPInitError';\n }\n}\n\n// =============================================================================\n// RESILIENCE ERROR TYPES\n// =============================================================================\n\n/**\n * Error thrown when a recovery attempt fails.\n *\n * Carries the recovery action and attempt number for diagnostic purposes.\n */\nexport class RecoveryError extends Error {\n constructor(\n public action: string,\n public attempt: number,\n public originalError?: unknown\n ) {\n super(`Recovery failed: ${action} (attempt ${attempt})`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'RecoveryError';\n }\n}\n\n/**\n * Error thrown when getUserMedia fails with OverconstrainedError\n * and all fallback levels have been exhausted.\n */\nexport class OverconstrainedFallbackError extends Error {\n constructor(\n public deviceKind: string,\n public originalError?: unknown\n ) {\n super(`All constraint fallback levels exhausted for ${deviceKind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'OverconstrainedFallbackError';\n }\n}\n\n/**\n * Error thrown when the preflight connectivity test fails.\n */\nexport class PreflightError extends Error {\n constructor(\n public phase: string,\n public originalError?: unknown\n ) {\n super(`Preflight test failed during ${phase}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'PreflightError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DeviceTokenError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DeviceTokenError';\n }\n}\n\nexport class TokenRefreshError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'TokenRefreshError';\n }\n}\n","import log from 'loglevel';\n\n// =============================================================================\n// Public Interfaces\n// =============================================================================\n\n/** Log level names supported by the SDK. */\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\n/**\n * Logger interface that consumers can implement to replace the built-in logger.\n * All methods accept variadic arguments matching the browser console API.\n */\nexport interface SDKLogger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n trace(...args: unknown[]): void;\n}\n\n/** Options for WebSocket traffic logging. */\nexport interface WsTrafficOptions {\n type: 'send' | 'recv' | 'http';\n /** Parsed object or raw string — will be JSON.stringify'd for display if an object. */\n payload: unknown;\n}\n\n/**\n * Options for WebSocket traffic logging using raw strings.\n * The string is only parsed when logging is enabled, avoiding\n * unnecessary JSON.parse on every message.\n */\nexport interface WsTrafficRawOptions {\n type: 'send' | 'recv';\n raw: string;\n}\n\n/** Debug options that control verbose SDK logging. */\nexport interface DebugOptions {\n /** Log all WebSocket send/recv traffic to the console. */\n logWsTraffic?: boolean;\n}\n\n/** Extended logger with SDK-internal helpers (wsTraffic). */\nexport interface InternalSDKLogger extends SDKLogger {\n wsTraffic: (options: WsTrafficOptions | WsTrafficRawOptions) => void;\n}\n\n// =============================================================================\n// Default Logger (loglevel)\n// =============================================================================\n\nconst datetime = () => new Date().toISOString();\nconst defaultLogger = log.getLogger('signalwire');\n\nconst originalFactory = defaultLogger.methodFactory;\ndefaultLogger.methodFactory = (methodName, logLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: unknown[]) {\n const prefixed = [datetime(), '-', ...args];\n // eslint-disable-next-line prefer-spread\n rawMethod.apply(undefined, prefixed);\n };\n};\n\n// Default to WARN in production; consumers opt in to verbose logging\nconst defaultLoggerLevel = defaultLogger.levels.WARN;\ndefaultLogger.setLevel(defaultLoggerLevel);\n\n// =============================================================================\n// Logger State\n// =============================================================================\n\nlet userLogger: SDKLogger | null = null;\n\n/** Replace the built-in logger with a custom implementation. Pass `null` to restore defaults. */\nconst setLogger = (logger: SDKLogger | null): void => {\n userLogger = logger;\n};\n\nlet debugOptions: DebugOptions = {};\n\n/** Configure debug options (e.g., `{ logWsTraffic: true }`). */\nconst setDebugOptions = (options: DebugOptions | null): void => {\n if (options == null) {\n debugOptions = {};\n return;\n }\n debugOptions = { ...debugOptions, ...options };\n};\n\n/**\n * Set the log level for the built-in logger.\n * Has no effect when a custom logger is set via `setLogger()`.\n */\nconst setLogLevel = (level: LogLevel): void => {\n defaultLogger.setLevel(level);\n};\n\n// =============================================================================\n// Logger Instance\n// =============================================================================\n\nconst getLoggerInstance = (): SDKLogger => {\n // loglevel's Logger matches SDKLogger (error, warn, info, debug, trace)\n return userLogger ?? (defaultLogger as SDKLogger);\n};\n\nconst shouldStringify = (payload: unknown): boolean => {\n if (payload != null && typeof payload === 'object' && 'method' in payload) {\n return (payload as Record<string, unknown>).method !== 'signalwire.ping';\n }\n return true;\n};\n\nconst wsTraffic: InternalSDKLogger['wsTraffic'] = (options) => {\n const { logWsTraffic } = debugOptions;\n\n if (!logWsTraffic) {\n return;\n }\n\n const loggerInstance = getLoggerInstance();\n\n // Support raw string payloads — parse only when logging is enabled\n let payload: unknown;\n if ('raw' in options) {\n try {\n payload = JSON.parse(options.raw);\n } catch {\n loggerInstance.debug(`[WebSocket] ${options.type.toUpperCase()}: non-JSON message`);\n return;\n }\n } else {\n ({ payload } = options);\n }\n\n const msg = shouldStringify(payload) ? JSON.stringify(payload, null, 2) : payload;\n loggerInstance.debug(`${options.type.toUpperCase()}: \\n`, msg, '\\n');\n};\n\nconst getLogger = (): InternalSDKLogger => {\n const logger = getLoggerInstance();\n\n return new Proxy(logger, {\n get(_target, prop: string | symbol, _receiver) {\n if (prop === 'wsTraffic') {\n return wsTraffic;\n }\n // Always resolve from the current logger instance so that\n // setLogger() takes effect for all existing references.\n const instance = getLoggerInstance();\n const value: unknown = Reflect.get(instance, prop);\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(instance);\n }\n return value;\n }\n }) as InternalSDKLogger;\n};\n\nexport { setLogger, getLogger, setDebugOptions, setLogLevel };\n","import { filter } from 'rxjs';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * RxJS operator that filters out `null` and `undefined` values with type narrowing.\n *\n * @example\n * ```ts\n * source$.pipe(filterNull()).subscribe(value => {\n * // value is guaranteed non-null\n * });\n * ```\n */\nexport function filterNull<T>(): OperatorFunction<T | null | undefined, T> {\n return filter((value): value is T => value != null);\n}\n","export const getValueFrom = <T = unknown>(\n obj: unknown,\n path: string,\n defaultValue?: T\n): T | undefined => {\n const keys = path.split('.');\n let result = obj;\n for (const key of keys) {\n if (result && typeof result === 'object' && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return defaultValue;\n }\n }\n return (result === undefined ? defaultValue : result) as T;\n};\n","import { pipe } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\n\nimport { getValueFrom } from '../utils/getValueFrom';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * Type helper to extract nested property types using dot notation.\n * Supports up to 4 levels of nesting.\n *\n * @example\n * type Example = { a: { b: { c: string } } }\n * type Result = PathValue<Example, 'a.b.c'> // string\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? PathValue<T[Key], Rest>\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n// Usage:\n// source$.pipe(\n// isEvent(\n// (event) => event.type === 'call.started',\n// (event) => ({ id: event.id, timestamp: event.timestamp })\n// )\n// );\n\n/**\n * RxJS operator that filters events based on a predicate and maps matching events.\n *\n * This operator combines filter and map operations:\n * 1. Only events that match the predicate are emitted\n * 2. Matching events are transformed using the map function\n *\n * @template TInput - The type of input events\n * @template TOutput - The type of output after mapping\n * @param predicate - Function to test each event. Returns true to include the event.\n * @param mapFn - Function to transform matching events\n * @returns An operator function that filters and maps events\n *\n * @example\n * ```typescript\n * interface CallEvent {\n * type: 'call.started' | 'call.ended';\n * id: string;\n * timestamp: number;\n * }\n *\n * events$.pipe(\n * isEvent(\n * (event: CallEvent) => event.type === 'call.started',\n * (event: CallEvent) => ({ id: event.id, timestamp: event.timestamp })\n * )\n * ).subscribe(startEvent => {\n * console.log('Call started:', startEvent);\n * });\n * ```\n */\nexport function ifIsMap<TInput, TOutput>(\n predicate: (event: unknown) => event is TInput,\n mapFn: (event: TInput) => TOutput\n): OperatorFunction<unknown, TOutput> {\n return pipe(filter(predicate), map(mapFn));\n}\n\n/**\n * Generic RxJS operator that filters events using a type guard and extracts a property.\n *\n * This is the generic version that works with any type, not just JSONRPCRequest.\n * Use this when you need to filter and extract properties from already-narrowed types.\n *\n * **Type inference**: The output type is automatically inferred from the input type and path!\n *\n * @template TInput - The type to narrow to (via type guard)\n * @template TPath - The dot-notation path to extract (inferred from parameter)\n * @param predicate - Type guard function to filter events\n * @param resultPath - Dot-notation path to extract (e.g., 'params', 'params.data')\n * @returns An operator function that filters and extracts\n *\n * @example\n * ```typescript\n * interface EventParams {\n * event_type: string;\n * data: { value: number };\n * }\n *\n * const isAuthEvent = (e: unknown): e is EventParams =>\n * typeof e === 'object' && e !== null && 'event_type' in e;\n *\n * // Type of 'data' is automatically inferred as { value: number }\n * params$.pipe(\n * filterAs(isAuthEvent, 'data')\n * ).subscribe(data => {\n * console.log('Event data:', data.value); // TypeScript knows about .value!\n * });\n *\n * // Deeply nested properties are also inferred\n * params$.pipe(\n * filterAs(isAuthEvent, 'data.value')\n * ).subscribe(value => {\n * console.log(value); // Type is 'number'\n * });\n * ```\n */\nexport function filterAs<TInput, TPath extends string>(\n predicate: (event: unknown) => event is TInput,\n resultPath: TPath\n): OperatorFunction<unknown, PathValue<TInput, TPath>> {\n return pipe(\n ifIsMap(predicate, (event) => {\n const result = getValueFrom<PathValue<TInput, TPath>>(event, resultPath);\n return result;\n }),\n filter((value): value is PathValue<TInput, TPath> => value !== undefined)\n );\n}\n","import { map, type OperatorFunction } from 'rxjs';\n\nimport { JSONRPCError } from '../core/errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { JSONRPCResponse } from '../core/RPCMessages/types/base';\n\nconst logger = getLogger();\n\n/**\n * RxJS operator that throws a {@link JSONRPCError} when the RPC response contains an error.\n * Passes successful responses through unchanged.\n */\nexport function throwOnRPCError<T extends JSONRPCResponse>(): OperatorFunction<T, T> {\n return map((response: T) => {\n if (response.error) {\n logger.error('[throwOnRPCError] RPC error response:', {\n code: response.error.code,\n message: response.error.message,\n data: response.error.data\n });\n\n throw new JSONRPCError(response.error.code, response.error.message, response.error.data);\n }\n logger.debug('[throwOnRPCError] RPC successful response:', response);\n return response;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,iBAAiB;AAC9B,MAAa,mCAAmC;AAChD,MAAa,mCAAmC;AAChD,MAAa,qCAAqC,MAAS;AAE3D,MAAa,gCAAgC;;;;;;;;;;;AAW7C,MAAa,oCAAoC;;;;;;;;AAQjD,MAAa,qCAAqC;AAClD,MAAa,iCAAiC;A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,8BACM,UAA6C,UAAU,OAAU,CAC1E;;;;;AC/GH,MAAM,SAAS,WAAW;;;;;AAM1B,SAAgB,kBAAqE;AACnF,uBAAY,aAAgB;AAC1B,MAAI,SAAS,OAAO;AAClB,UAAO,MAAM,yCAAyC;IACpD,MAAM,SAAS,MAAM;IACrB,SAAS,SAAS,MAAM;IACxB,MAAM,SAAS,MAAM;IACtB,CAAC;AAEF,SAAM,IAAI,aAAa,SAAS,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,MAAM,KAAK;;AAE1F,SAAO,MAAM,8CAA8C,SAAS;AACpE,SAAO;GACP"}
@@ -8,6 +8,25 @@ const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;
8
8
  const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6e3;
9
9
  const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 300 * 1e3;
10
10
  const DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
11
+ /**
12
+ * How long call setup may wait for the network, measured from local media
13
+ * settling until the member id arrives.
14
+ *
15
+ * Local media acquisition is deliberately NOT inside this: a permission prompt
16
+ * or a device picker is human time, and a human may take as long as they like
17
+ * without spending the server's budget. The clock starts when acquisition ends.
18
+ *
19
+ * Must exceed `iceGatheringTimeout + the RPC timeout`, which both run inside it.
20
+ */
21
+ const DEFAULT_CALL_SIGNALING_TIMEOUT_MS = 12e3;
22
+ /**
23
+ * How long an auxiliary leg (screen share, additional device) may take to
24
+ * connect once its media is in hand.
25
+ *
26
+ * One bound for both: the picker is human time and sits outside it. What remains
27
+ * — offer, ICE, invite, answer, DTLS — is the same work for either leg kind.
28
+ */
29
+ const DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS = 15e3;
11
30
  const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;
12
31
  const DEFAULT_RECONNECT_DELAY_MAX_MS = 3e3;
13
32
  const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;
@@ -35,6 +54,14 @@ const CREDENTIAL_REFRESH_MAX_DELAY_MS = 3e4;
35
54
  /** Buffer in milliseconds before token expiry to trigger refresh. */
36
55
  const CREDENTIAL_REFRESH_BUFFER_MS = 5e3;
37
56
  /**
57
+ * Clock-skew allowance (ms) for treating an in-memory credential as expired
58
+ * when deciding whether a fresh (re)connect must re-mint the token before
59
+ * authenticating. A token within this window of its `expiry_at` is treated as
60
+ * stale so the reconnect re-mints via the credential provider instead of
61
+ * replaying a dead token (which the server rejects with -32003).
62
+ */
63
+ const CREDENTIAL_EXPIRY_SKEW_MS = 3e4;
64
+ /**
38
65
  * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`
39
66
  * to resolve before treating the activation as failed and falling back to
40
67
  * the developer-provided refresh path. Prevents a wedged HTTP layer from
@@ -53,6 +80,8 @@ const MEDIA_ACCESS_DENIAL_NAMES = [
53
80
  "SecurityError",
54
81
  "PermissionDeniedError"
55
82
  ];
83
+ /** Error names browsers use when the capture hardware is already held exclusively. */
84
+ const MEDIA_DEVICE_IN_USE_NAMES = ["NotReadableError", "TrackStartError"];
56
85
  /** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */
57
86
  const DEFAULT_STATS_POLLING_INTERVAL_MS = 1e3;
58
87
  /** Number of initial samples used to build a baseline for spike detection. */
@@ -267,6 +296,20 @@ var CallCreateError = class extends Error {
267
296
  this.name = "CallCreateError";
268
297
  }
269
298
  };
299
+ var CallNotReadyError = class extends Error {
300
+ constructor(callId, options) {
301
+ super(`Call "${callId}" has no self member context yet: selfId/nodeId have not been received from the server`, options);
302
+ this.callId = callId;
303
+ this.name = "CallNotReadyError";
304
+ }
305
+ };
306
+ var ParticipantNotReadyError = class extends Error {
307
+ constructor(memberId, options) {
308
+ super(`Participant "${memberId}" has no call context yet: its member state (call_id/node_id) has not been received from the server`, options);
309
+ this.memberId = memberId;
310
+ this.name = "ParticipantNotReadyError";
311
+ }
312
+ };
270
313
  var JSONRPCError = class extends Error {
271
314
  constructor(code, message, data, options, requestId) {
272
315
  super(message, options);
@@ -338,6 +381,32 @@ var CollectionFetchError = class extends Error {
338
381
  this.name = "CollectionFetchError";
339
382
  }
340
383
  };
384
+ /**
385
+ * An auxiliary leg did not connect within its budget. Typed rather than a bare
386
+ * RxJS `TimeoutError` so the leg and cause survive.
387
+ */
388
+ var AuxiliaryLegTimeoutError = class extends Error {
389
+ constructor(leg, originalError) {
390
+ super(`Timed out waiting for the ${leg} connection to be established`, { cause: originalError });
391
+ this.leg = leg;
392
+ this.originalError = originalError;
393
+ this.name = "AuxiliaryLegTimeoutError";
394
+ }
395
+ };
396
+ /**
397
+ * An auxiliary leg was removed before it finished connecting.
398
+ *
399
+ * Typed rather than a bare resolve so a caller awaiting the start can tell a
400
+ * cancel apart from a share that actually came up — the public methods return
401
+ * `void`, so the promise is the only signal they have.
402
+ */
403
+ var AuxiliaryLegCancelledError = class extends Error {
404
+ constructor(leg) {
405
+ super(`The ${leg} leg was removed before it finished connecting`);
406
+ this.leg = leg;
407
+ this.name = "AuxiliaryLegCancelledError";
408
+ }
409
+ };
341
410
  var MediaTrackError = class extends Error {
342
411
  constructor(operation, kind, originalError) {
343
412
  super(`Media track ${operation} failed for ${kind}`, { cause: originalError instanceof Error ? originalError : void 0 });
@@ -351,6 +420,10 @@ var MediaTrackError = class extends Error {
351
420
  function isMediaAccessDenial(originalError) {
352
421
  return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);
353
422
  }
423
+ /** True when a `getUserMedia` rejection means the hardware is already held exclusively. */
424
+ function isMediaDeviceInUse(originalError) {
425
+ return originalError instanceof Error && MEDIA_DEVICE_IN_USE_NAMES.includes(originalError.name);
426
+ }
354
427
  /**
355
428
  * Failure to acquire local media (camera, microphone, or screen capture)
356
429
  * via `getUserMedia`/`getDisplayMedia`.
@@ -374,6 +447,22 @@ var MediaAccessError = class extends Error {
374
447
  return isMediaAccessDenial(this.originalError);
375
448
  }
376
449
  };
450
+ /**
451
+ * Thrown by `startScreenShare()` when the call is already sharing a screen.
452
+ *
453
+ * A call carries at most one screen share. Accepting a second one would
454
+ * overwrite the only reference the SDK holds to the first, leaving it
455
+ * capturing and sending with no way to stop it — so the second request is
456
+ * rejected and the live share is left untouched. Call `stopScreenShare()`
457
+ * first to replace it.
458
+ */
459
+ var ScreenShareAlreadyActiveError = class extends Error {
460
+ constructor(screenShareId, options) {
461
+ super(`A screen share is already active on this call (${screenShareId}). Call stopScreenShare() before starting another one.`, options);
462
+ this.screenShareId = screenShareId;
463
+ this.name = "ScreenShareAlreadyActiveError";
464
+ }
465
+ };
377
466
  var DPoPInitError = class extends Error {
378
467
  constructor(originalError, message = "Failed to initialize DPoP key pair") {
379
468
  super(message, { cause: originalError instanceof Error ? originalError : void 0 });
@@ -638,5 +727,5 @@ function throwOnRPCError() {
638
727
  }
639
728
 
640
729
  //#endregion
641
- export { DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS as $, VAD_HOLD_MS as $t, SerializationError as A, DEFAULT_STATS_POLLING_INTERVAL_MS as At, VertoInviteHandlerError as B, DEVICE_TOKEN_ENDPOINT as Bt, MessageParseError as C, DEFAULT_REINVITE_MAX_ATTEMPTS as Ct, RecoveryError as D, DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER as Dt, RPCTimeoutError as E, DEFAULT_STATS_HISTORY_SIZE as Et, TransportConnectionError as F, DEVICE_REFRESH_ENDPOINT as Ft, CREDENTIAL_ACTIVATE_TIMEOUT_MS as G, INVITE_VERSION as Gt, WebSocketConnectionError as H, DEVICE_TOKEN_REFRESH_MAX_RETRIES as Ht, UnexpectedError as I, DEVICE_STORAGE_KEY_AUDIO_INPUT as It, CREDENTIAL_REFRESH_MAX_RETRIES as J, PREFERENCES_STORAGE_KEY as Jt, CREDENTIAL_REFRESH_BUFFER_MS as K, PEER_CONNECTION_RECOVERY_POLL_MS as Kt, UnimplementedError as L, DEVICE_STORAGE_KEY_AUDIO_OUTPUT as Lt, StorageReadError as M, DEFAULT_STEREO_AUDIO as Mt, StorageWriteError as N, DEFAULT_STEREO_MAX_AVERAGE_BITRATE as Nt, RequestError as O, DEFAULT_STATS_NO_PACKET_THRESHOLD_MS as Ot, TokenRefreshError as P, DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS as Pt, DEFAULT_CONNECTION_TIMEOUT_MS as Q, SAT_REFRESH_SCOPE as Qt, ValidationError as R, DEVICE_STORAGE_KEY_VIDEO_INPUT as Rt, MediaTrackError as S, DEFAULT_REINVITE_DEBOUNCE_TIME_MS as St, PreflightError as T, DEFAULT_STATS_BASELINE_SAMPLES as Tt, WebSocketTimeoutError as U, DEVICE_TOKEN_REFRESH_RETRY_BASE_MS as Ut, VertoPongError as V, DEVICE_TOKEN_REFRESH_BUFFER_MS as Vt, AUDIO_LEVEL_POLL_INTERVAL_MS as W, ICE_GATHERING_COMPLETE_TIMEOUT_MS as Wt, DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN as X, RPC_ERROR_INVALID_PARAMS as Xt, CREDENTIAL_REFRESH_RETRY_BASE_MS as Y, RPC_ERROR_AUTHENTICATION_FAILED as Yt, DEFAULT_CHECK_CONNECTION_ON_VISIBLE as Z, RPC_ERROR_REQUESTER_VALIDATION_FAILED as Zt, DeviceTokenError as _, DEFAULT_RECONNECT_DELAY_MAX_MS as _t, filterNull as a, DEFAULT_ENABLE_RELAY_FALLBACK as at, JSONRPCError as b, DEFAULT_RECOVERY_DEBOUNCE_TIME_MS as bt, setLogLevel as c, DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS as ct, CallCreateError as d, DEFAULT_KEYFRAME_BURST_WINDOW_MS as dt, VAD_THRESHOLD as en, DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS as et, CollectionFetchError as f, DEFAULT_KEYFRAME_COOLDOWN_MS as ft, DeserializationError as g, DEFAULT_RECONNECT_CALLS_TIMEOUT_MS as gt, DependencyError as h, DEFAULT_PERSIST_DEVICE_SELECTION as ht, getValueFrom as i, DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION as it, StorageNotAvailableError as j, DEFAULT_STATS_RTT_SPIKE_MULTIPLIER as jt, RequestTimeoutError as k, DEFAULT_STATS_PACKET_LOSS_THRESHOLD as kt, setLogger as l, DEFAULT_ICE_GATHERING_TIMEOUT_MS as lt, DPoPInitError as m, DEFAULT_MAX_RECOVERY_ATTEMPTS as mt, filterAs as n, DEFAULT_DEVICE_POLLING_INTERVAL_MS as nt, getLogger as o, DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION as ot, ConversationError as p, DEFAULT_KEYFRAME_MAX_BURST as pt, CREDENTIAL_REFRESH_MAX_DELAY_MS as q, PEER_CONNECTION_RECOVERY_WAIT_MS as qt, ifIsMap as r, DEFAULT_ENABLE_AUTO_DEGRADATION as rt, setDebugOptions as s, DEFAULT_ICE_CANDIDATE_TIMEOUT_MS as st, throwOnRPCError as t, DEFAULT_DEVICE_DEBOUNCE_TIME_MS as tt, AuthStateHandlerError as u, DEFAULT_ICE_RESTART_TIMEOUT_MS as ut, InvalidCredentialsError as v, DEFAULT_RECONNECT_DELAY_MIN_MS as vt, OverconstrainedFallbackError as w, DEFAULT_REINVITE_TIMEOUT_MS as wt, MediaAccessError as x, DEFAULT_REFRESH_DEVICES_ON_VISIBLE as xt, InvalidParams as y, DEFAULT_RECOVERY_COOLDOWN_MS as yt, VertoAttachHandlerError as z, DEVICE_TOKEN_DEFAULT_EXPIRE_IN as zt };
642
- //# sourceMappingURL=operators-BlUtq-t0.mjs.map
730
+ export { CREDENTIAL_REFRESH_BUFFER_MS as $, ICE_GATHERING_COMPLETE_TIMEOUT_MS as $t, RPCTimeoutError as A, DEFAULT_REFRESH_DEVICES_ON_VISIBLE as At, TransportConnectionError as B, DEFAULT_STATS_RTT_SPIKE_MULTIPLIER as Bt, JSONRPCError as C, DEFAULT_MAX_RECOVERY_ATTEMPTS as Ct, OverconstrainedFallbackError as D, DEFAULT_RECONNECT_DELAY_MIN_MS as Dt, MessageParseError as E, DEFAULT_RECONNECT_DELAY_MAX_MS as Et, SerializationError as F, DEFAULT_STATS_HISTORY_SIZE as Ft, VertoInviteHandlerError as G, DEVICE_STORAGE_KEY_AUDIO_INPUT as Gt, UnimplementedError as H, DEFAULT_STEREO_MAX_AVERAGE_BITRATE as Ht, StorageNotAvailableError as I, DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER as It, WebSocketTimeoutError as J, DEVICE_TOKEN_DEFAULT_EXPIRE_IN as Jt, VertoPongError as K, DEVICE_STORAGE_KEY_AUDIO_OUTPUT as Kt, StorageReadError as L, DEFAULT_STATS_NO_PACKET_THRESHOLD_MS as Lt, RequestError as M, DEFAULT_REINVITE_MAX_ATTEMPTS as Mt, RequestTimeoutError as N, DEFAULT_REINVITE_TIMEOUT_MS as Nt, ParticipantNotReadyError as O, DEFAULT_RECOVERY_COOLDOWN_MS as Ot, ScreenShareAlreadyActiveError as P, DEFAULT_STATS_BASELINE_SAMPLES as Pt, CREDENTIAL_EXPIRY_SKEW_MS as Q, DEVICE_TOKEN_REFRESH_RETRY_BASE_MS as Qt, StorageWriteError as R, DEFAULT_STATS_PACKET_LOSS_THRESHOLD as Rt, InvalidParams as S, DEFAULT_KEYFRAME_MAX_BURST as St, MediaTrackError as T, DEFAULT_RECONNECT_CALLS_TIMEOUT_MS as Tt, ValidationError as U, DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS as Ut, UnexpectedError as V, DEFAULT_STEREO_AUDIO as Vt, VertoAttachHandlerError as W, DEVICE_REFRESH_ENDPOINT as Wt, AUDIO_LEVEL_POLL_INTERVAL_MS as X, DEVICE_TOKEN_REFRESH_BUFFER_MS as Xt, isMediaDeviceInUse as Y, DEVICE_TOKEN_ENDPOINT as Yt, CREDENTIAL_ACTIVATE_TIMEOUT_MS as Z, DEVICE_TOKEN_REFRESH_MAX_RETRIES as Zt, DPoPInitError as _, DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS as _t, filterNull as a, RPC_ERROR_INVALID_PARAMS as an, DEFAULT_CALL_SIGNALING_TIMEOUT_MS as at, DeviceTokenError as b, DEFAULT_KEYFRAME_BURST_WINDOW_MS as bt, setLogLevel as c, VAD_HOLD_MS as cn, DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS as ct, AuxiliaryLegCancelledError as d, DEFAULT_DEVICE_POLLING_INTERVAL_MS as dt, INVITE_VERSION as en, CREDENTIAL_REFRESH_MAX_DELAY_MS as et, AuxiliaryLegTimeoutError as f, DEFAULT_ENABLE_AUTO_DEGRADATION as ft, ConversationError as g, DEFAULT_ICE_CANDIDATE_TIMEOUT_MS as gt, CollectionFetchError as h, DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION as ht, getValueFrom as i, RPC_ERROR_AUTHENTICATION_FAILED as in, DEFAULT_AUX_LEG_CONNECT_TIMEOUT_MS as it, RecoveryError as j, DEFAULT_REINVITE_DEBOUNCE_TIME_MS as jt, PreflightError as k, DEFAULT_RECOVERY_DEBOUNCE_TIME_MS as kt, setLogger as l, VAD_THRESHOLD as ln, DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS as lt, CallNotReadyError as m, DEFAULT_ENABLE_RELAY_FALLBACK as mt, filterAs as n, PEER_CONNECTION_RECOVERY_WAIT_MS as nn, CREDENTIAL_REFRESH_RETRY_BASE_MS as nt, getLogger as o, RPC_ERROR_REQUESTER_VALIDATION_FAILED as on, DEFAULT_CHECK_CONNECTION_ON_VISIBLE as ot, CallCreateError as p, DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION as pt, WebSocketConnectionError as q, DEVICE_STORAGE_KEY_VIDEO_INPUT as qt, ifIsMap as r, PREFERENCES_STORAGE_KEY as rn, DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN as rt, setDebugOptions as s, SAT_REFRESH_SCOPE as sn, DEFAULT_CONNECTION_TIMEOUT_MS as st, throwOnRPCError as t, PEER_CONNECTION_RECOVERY_POLL_MS as tn, CREDENTIAL_REFRESH_MAX_RETRIES as tt, AuthStateHandlerError as u, DEFAULT_DEVICE_DEBOUNCE_TIME_MS as ut, DependencyError as v, DEFAULT_ICE_GATHERING_TIMEOUT_MS as vt, MediaAccessError as w, DEFAULT_PERSIST_DEVICE_SELECTION as wt, InvalidCredentialsError as x, DEFAULT_KEYFRAME_COOLDOWN_MS as xt, DeserializationError as y, DEFAULT_ICE_RESTART_TIMEOUT_MS as yt, TokenRefreshError as z, DEFAULT_STATS_POLLING_INTERVAL_MS as zt };
731
+ //# sourceMappingURL=operators-BVxi3KpN.mjs.map