@elevenlabs/client 1.7.0 → 1.7.1

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/lib.iife.js CHANGED
@@ -442,7 +442,7 @@ var ElevenLabsClient = (function(exports) {
442
442
  //#region src/sourceInfo.ts
443
443
  let sourceInfo = Object.freeze({
444
444
  name: "js_sdk",
445
- version: "1.7.0"
445
+ version: "1.7.1"
446
446
  });
447
447
  //#endregion
448
448
  //#region src/utils/events.ts
@@ -605,7 +605,7 @@ var ElevenLabsClient = (function(exports) {
605
605
  }
606
606
  };
607
607
  //#endregion
608
- //#region ../../node_modules/.pnpm/livekit-client@2.16.0_patch_hash=9017aa1cb7fee2ea056f4126969008ea86ed7876e3f35563fc967f_de6444965912a2a802f1cc23289b5c5d/node_modules/livekit-client/dist/livekit-client.esm.mjs
608
+ //#region ../../node_modules/.pnpm/livekit-client@2.16.1_patch_hash=d922ae1654b16c2729a80163c34eb23e5844912948547243600e8c_d1ce20d6e8ed22c8e8eab81412419be8/node_modules/livekit-client/dist/livekit-client.esm.mjs
609
609
  function _mergeNamespaces(n, m) {
610
610
  m.forEach(function(e) {
611
611
  e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
@@ -6827,20 +6827,6 @@ var ElevenLabsClient = (function(exports) {
6827
6827
  return retryDelay + Math.random() * 1e3;
6828
6828
  }
6829
6829
  };
6830
- /******************************************************************************
6831
- Copyright (c) Microsoft Corporation.
6832
-
6833
- Permission to use, copy, modify, and/or distribute this software for any
6834
- purpose with or without fee is hereby granted.
6835
-
6836
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
6837
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
6838
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
6839
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
6840
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
6841
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6842
- PERFORMANCE OF THIS SOFTWARE.
6843
- ***************************************************************************** */
6844
6830
  function __rest(s, e) {
6845
6831
  var t = {};
6846
6832
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
@@ -9186,44 +9172,68 @@ var ElevenLabsClient = (function(exports) {
9186
9172
  return adapter;
9187
9173
  }
9188
9174
  adapterFactory({ window: typeof window === "undefined" ? void 0 : window });
9189
- const E2EE_FLAG = "lk_e2ee";
9190
- var KeyProviderEvent;
9191
- (function(KeyProviderEvent) {
9192
- KeyProviderEvent["SetKey"] = "setKey";
9193
- /** Event for requesting to ratchet the key used to encrypt the stream */
9194
- KeyProviderEvent["RatchetRequest"] = "ratchetRequest";
9195
- /** Emitted when a key is ratcheted. Could be after auto-ratcheting on decryption failure or
9196
- * following a `RatchetRequest`, will contain the ratcheted key material */
9197
- KeyProviderEvent["KeyRatcheted"] = "keyRatcheted";
9198
- })(KeyProviderEvent || (KeyProviderEvent = {}));
9199
- var KeyHandlerEvent;
9200
- (function(KeyHandlerEvent) {
9201
- /** Emitted when a key has been ratcheted. Is emitted when any key has been ratcheted
9202
- * i.e. when the FrameCryptor tried to ratchet when decryption is failing */
9203
- KeyHandlerEvent["KeyRatcheted"] = "keyRatcheted";
9204
- })(KeyHandlerEvent || (KeyHandlerEvent = {}));
9205
- var EncryptionEvent;
9206
- (function(EncryptionEvent) {
9207
- EncryptionEvent["ParticipantEncryptionStatusChanged"] = "participantEncryptionStatusChanged";
9208
- EncryptionEvent["EncryptionError"] = "encryptionError";
9209
- })(EncryptionEvent || (EncryptionEvent = {}));
9210
- var CryptorEvent;
9211
- (function(CryptorEvent) {
9212
- CryptorEvent["Error"] = "cryptorError";
9213
- })(CryptorEvent || (CryptorEvent = {}));
9214
- function isE2EESupported() {
9215
- return isInsertableStreamSupported() || isScriptTransformSupported();
9216
- }
9217
- function isScriptTransformSupported() {
9218
- return typeof window.RTCRtpScriptTransform !== "undefined";
9175
+ const commonVersionIdentifier = /version\/(\d+(\.?_?\d+)+)/i;
9176
+ let browserDetails;
9177
+ /**
9178
+ * @internal
9179
+ */
9180
+ function getBrowser(userAgent) {
9181
+ let force = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
9182
+ if (typeof userAgent === "undefined" && typeof navigator === "undefined") return;
9183
+ const ua = (userAgent !== null && userAgent !== void 0 ? userAgent : navigator.userAgent).toLowerCase();
9184
+ if (browserDetails === void 0 || force) {
9185
+ const browser = browsersList.find((_ref) => {
9186
+ let { test } = _ref;
9187
+ return test.test(ua);
9188
+ });
9189
+ browserDetails = browser === null || browser === void 0 ? void 0 : browser.describe(ua);
9190
+ }
9191
+ return browserDetails;
9219
9192
  }
9220
- function isInsertableStreamSupported() {
9221
- return typeof window.RTCRtpSender !== "undefined" && typeof window.RTCRtpSender.prototype.createEncodedStreams !== "undefined";
9193
+ const browsersList = [
9194
+ {
9195
+ test: /firefox|iceweasel|fxios/i,
9196
+ describe(ua) {
9197
+ return {
9198
+ name: "Firefox",
9199
+ version: getMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, ua),
9200
+ os: ua.toLowerCase().includes("fxios") ? "iOS" : void 0,
9201
+ osVersion: getOSVersion(ua)
9202
+ };
9203
+ }
9204
+ },
9205
+ {
9206
+ test: /chrom|crios|crmo/i,
9207
+ describe(ua) {
9208
+ return {
9209
+ name: "Chrome",
9210
+ version: getMatch(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i, ua),
9211
+ os: ua.toLowerCase().includes("crios") ? "iOS" : void 0,
9212
+ osVersion: getOSVersion(ua)
9213
+ };
9214
+ }
9215
+ },
9216
+ {
9217
+ test: /safari|applewebkit/i,
9218
+ describe(ua) {
9219
+ return {
9220
+ name: "Safari",
9221
+ version: getMatch(commonVersionIdentifier, ua),
9222
+ os: ua.includes("mobile/") ? "iOS" : "macOS",
9223
+ osVersion: getOSVersion(ua)
9224
+ };
9225
+ }
9226
+ }
9227
+ ];
9228
+ function getMatch(exp, ua) {
9229
+ let id = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1;
9230
+ const match = ua.match(exp);
9231
+ return match && match.length >= id && match[id] || "";
9222
9232
  }
9223
- function asEncryptablePacket(packet) {
9224
- var _a, _b, _c, _d, _e;
9225
- if (((_a = packet.value) === null || _a === void 0 ? void 0 : _a.case) !== "sipDtmf" && ((_b = packet.value) === null || _b === void 0 ? void 0 : _b.case) !== "metrics" && ((_c = packet.value) === null || _c === void 0 ? void 0 : _c.case) !== "speaker" && ((_d = packet.value) === null || _d === void 0 ? void 0 : _d.case) !== "transcription" && ((_e = packet.value) === null || _e === void 0 ? void 0 : _e.case) !== "encryptedPacket") return new EncryptedPacketPayload({ value: packet.value });
9233
+ function getOSVersion(ua) {
9234
+ return ua.includes("mac os") ? getMatch(/\(.+?(\d+_\d+(:?_\d+)?)/, ua, 1).replace(/_/g, ".") : void 0;
9226
9235
  }
9236
+ const version = "2.16.1";
9227
9237
  var LivekitError = class extends Error {
9228
9238
  constructor(code, message) {
9229
9239
  super(message || "an error has occured");
@@ -9239,8 +9249,9 @@ var ElevenLabsClient = (function(exports) {
9239
9249
  ConnectionErrorReason[ConnectionErrorReason["Cancelled"] = 3] = "Cancelled";
9240
9250
  ConnectionErrorReason[ConnectionErrorReason["LeaveRequest"] = 4] = "LeaveRequest";
9241
9251
  ConnectionErrorReason[ConnectionErrorReason["Timeout"] = 5] = "Timeout";
9252
+ ConnectionErrorReason[ConnectionErrorReason["WebSocket"] = 6] = "WebSocket";
9242
9253
  })(ConnectionErrorReason || (ConnectionErrorReason = {}));
9243
- var ConnectionError = class extends LivekitError {
9254
+ var ConnectionError = class ConnectionError extends LivekitError {
9244
9255
  constructor(message, reason, status, context) {
9245
9256
  super(1, message);
9246
9257
  this.name = "ConnectionError";
@@ -9249,6 +9260,27 @@ var ElevenLabsClient = (function(exports) {
9249
9260
  this.context = context;
9250
9261
  this.reasonName = ConnectionErrorReason[reason];
9251
9262
  }
9263
+ static notAllowed(message, status, context) {
9264
+ return new ConnectionError(message, ConnectionErrorReason.NotAllowed, status, context);
9265
+ }
9266
+ static timeout(message) {
9267
+ return new ConnectionError(message, ConnectionErrorReason.Timeout);
9268
+ }
9269
+ static leaveRequest(message, context) {
9270
+ return new ConnectionError(message, ConnectionErrorReason.LeaveRequest, void 0, context);
9271
+ }
9272
+ static internal(message, context) {
9273
+ return new ConnectionError(message, ConnectionErrorReason.InternalError, void 0, context);
9274
+ }
9275
+ static cancelled(message) {
9276
+ return new ConnectionError(message, ConnectionErrorReason.Cancelled);
9277
+ }
9278
+ static serverUnreachable(message, status) {
9279
+ return new ConnectionError(message, ConnectionErrorReason.ServerUnreachable, status);
9280
+ }
9281
+ static websocket(message, status, reason) {
9282
+ return new ConnectionError(message, ConnectionErrorReason.WebSocket, status, reason);
9283
+ }
9252
9284
  };
9253
9285
  var DeviceUnsupportedError = class extends LivekitError {
9254
9286
  constructor(message) {
@@ -9290,6 +9322,7 @@ var ElevenLabsClient = (function(exports) {
9290
9322
  var SignalRequestError = class extends LivekitError {
9291
9323
  constructor(message, reason) {
9292
9324
  super(15, message);
9325
+ this.name = "SignalRequestError";
9293
9326
  this.reason = reason;
9294
9327
  this.reasonName = typeof reason === "string" ? reason : RequestResponse_Reason[reason];
9295
9328
  }
@@ -9312,6 +9345,12 @@ var ElevenLabsClient = (function(exports) {
9312
9345
  this.reasonName = DataStreamErrorReason[reason];
9313
9346
  }
9314
9347
  };
9348
+ var SignalReconnectError = class extends LivekitError {
9349
+ constructor(message) {
9350
+ super(18, message);
9351
+ this.name = "SignalReconnectError";
9352
+ }
9353
+ };
9315
9354
  var MediaDeviceFailure;
9316
9355
  (function(MediaDeviceFailure) {
9317
9356
  MediaDeviceFailure["PermissionDenied"] = "PermissionDenied";
@@ -9330,21 +9369,19 @@ var ElevenLabsClient = (function(exports) {
9330
9369
  }
9331
9370
  MediaDeviceFailure.getFailure = getFailure;
9332
9371
  })(MediaDeviceFailure || (MediaDeviceFailure = {}));
9333
- var CryptorErrorReason;
9334
- (function(CryptorErrorReason) {
9335
- CryptorErrorReason[CryptorErrorReason["InvalidKey"] = 0] = "InvalidKey";
9336
- CryptorErrorReason[CryptorErrorReason["MissingKey"] = 1] = "MissingKey";
9337
- CryptorErrorReason[CryptorErrorReason["InternalError"] = 2] = "InternalError";
9338
- })(CryptorErrorReason || (CryptorErrorReason = {}));
9339
- /**
9340
- * Events are the primary way LiveKit notifies your application of changes.
9341
- *
9342
- * The following are events emitted by [[Room]], listen to room events like
9343
- *
9344
- * ```typescript
9345
- * room.on(RoomEvent.TrackPublished, (track, publication, participant) => {})
9346
- * ```
9347
- */
9372
+ var CriticalTimers = class {};
9373
+ CriticalTimers.setTimeout = function() {
9374
+ return setTimeout(...arguments);
9375
+ };
9376
+ CriticalTimers.setInterval = function() {
9377
+ return setInterval(...arguments);
9378
+ };
9379
+ CriticalTimers.clearTimeout = function() {
9380
+ return clearTimeout(...arguments);
9381
+ };
9382
+ CriticalTimers.clearInterval = function() {
9383
+ return clearInterval(...arguments);
9384
+ };
9348
9385
  var RoomEvent;
9349
9386
  (function(RoomEvent) {
9350
9387
  /**
@@ -9960,86 +9997,338 @@ var ElevenLabsClient = (function(exports) {
9960
9997
  return structuredClone(value);
9961
9998
  } else return JSON.parse(JSON.stringify(value));
9962
9999
  }
9963
- const commonVersionIdentifier = /version\/(\d+(\.?_?\d+)+)/i;
9964
- let browserDetails;
9965
- /**
9966
- * @internal
9967
- */
9968
- function getBrowser(userAgent) {
9969
- let force = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
9970
- if (typeof userAgent === "undefined" && typeof navigator === "undefined") return;
9971
- const ua = (userAgent !== null && userAgent !== void 0 ? userAgent : navigator.userAgent).toLowerCase();
9972
- if (browserDetails === void 0 || force) {
9973
- const browser = browsersList.find((_ref) => {
9974
- let { test } = _ref;
9975
- return test.test(ua);
9976
- });
9977
- browserDetails = browser === null || browser === void 0 ? void 0 : browser.describe(ua);
9978
- }
9979
- return browserDetails;
9980
- }
9981
- const browsersList = [
9982
- {
9983
- test: /firefox|iceweasel|fxios/i,
9984
- describe(ua) {
9985
- return {
9986
- name: "Firefox",
9987
- version: getMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, ua),
9988
- os: ua.toLowerCase().includes("fxios") ? "iOS" : void 0,
9989
- osVersion: getOSVersion(ua)
9990
- };
9991
- }
9992
- },
9993
- {
9994
- test: /chrom|crios|crmo/i,
9995
- describe(ua) {
9996
- return {
9997
- name: "Chrome",
9998
- version: getMatch(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i, ua),
9999
- os: ua.toLowerCase().includes("crios") ? "iOS" : void 0,
10000
- osVersion: getOSVersion(ua)
10000
+ var VideoPreset = class {
10001
+ constructor(widthOrOptions, height, maxBitrate, maxFramerate, priority) {
10002
+ if (typeof widthOrOptions === "object") {
10003
+ this.width = widthOrOptions.width;
10004
+ this.height = widthOrOptions.height;
10005
+ this.aspectRatio = widthOrOptions.aspectRatio;
10006
+ this.encoding = {
10007
+ maxBitrate: widthOrOptions.maxBitrate,
10008
+ maxFramerate: widthOrOptions.maxFramerate,
10009
+ priority: widthOrOptions.priority
10001
10010
  };
10002
- }
10003
- },
10004
- {
10005
- test: /safari|applewebkit/i,
10006
- describe(ua) {
10007
- return {
10008
- name: "Safari",
10009
- version: getMatch(commonVersionIdentifier, ua),
10010
- os: ua.includes("mobile/") ? "iOS" : "macOS",
10011
- osVersion: getOSVersion(ua)
10011
+ } else if (height !== void 0 && maxBitrate !== void 0) {
10012
+ this.width = widthOrOptions;
10013
+ this.height = height;
10014
+ this.aspectRatio = widthOrOptions / height;
10015
+ this.encoding = {
10016
+ maxBitrate,
10017
+ maxFramerate,
10018
+ priority
10012
10019
  };
10013
- }
10020
+ } else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");
10021
+ }
10022
+ get resolution() {
10023
+ return {
10024
+ width: this.width,
10025
+ height: this.height,
10026
+ frameRate: this.encoding.maxFramerate,
10027
+ aspectRatio: this.aspectRatio
10028
+ };
10014
10029
  }
10030
+ };
10031
+ const backupVideoCodecs = ["vp8", "h264"];
10032
+ const videoCodecs = [
10033
+ "vp8",
10034
+ "h264",
10035
+ "vp9",
10036
+ "av1",
10037
+ "h265"
10015
10038
  ];
10016
- function getMatch(exp, ua) {
10017
- let id = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1;
10018
- const match = ua.match(exp);
10019
- return match && match.length >= id && match[id] || "";
10020
- }
10021
- function getOSVersion(ua) {
10022
- return ua.includes("mac os") ? getMatch(/\(.+?(\d+_\d+(:?_\d+)?)/, ua, 1).replace(/_/g, ".") : void 0;
10039
+ function isBackupVideoCodec(codec) {
10040
+ return !!backupVideoCodecs.find((backup) => backup === codec);
10023
10041
  }
10024
- const version = "2.16.0";
10042
+ /** @deprecated Use {@link isBackupVideoCodec} instead */
10043
+ const isBackupCodec = isBackupVideoCodec;
10044
+ var BackupCodecPolicy;
10045
+ (function(BackupCodecPolicy) {
10046
+ BackupCodecPolicy[BackupCodecPolicy["PREFER_REGRESSION"] = 0] = "PREFER_REGRESSION";
10047
+ BackupCodecPolicy[BackupCodecPolicy["SIMULCAST"] = 1] = "SIMULCAST";
10048
+ BackupCodecPolicy[BackupCodecPolicy["REGRESSION"] = 2] = "REGRESSION";
10049
+ })(BackupCodecPolicy || (BackupCodecPolicy = {}));
10050
+ var AudioPresets;
10051
+ (function(AudioPresets) {
10052
+ AudioPresets.telephone = { maxBitrate: 12e3 };
10053
+ AudioPresets.speech = { maxBitrate: 24e3 };
10054
+ AudioPresets.music = { maxBitrate: 48e3 };
10055
+ AudioPresets.musicStereo = { maxBitrate: 64e3 };
10056
+ AudioPresets.musicHighQuality = { maxBitrate: 96e3 };
10057
+ AudioPresets.musicHighQualityStereo = { maxBitrate: 128e3 };
10058
+ })(AudioPresets || (AudioPresets = {}));
10025
10059
  /**
10026
- * Timers that can be overridden with platform specific implementations
10027
- * that ensure that they are fired. These should be used when it is critical
10028
- * that the timer fires on time.
10060
+ * Sane presets for video resolution/encoding
10029
10061
  */
10030
- var CriticalTimers = class {};
10031
- CriticalTimers.setTimeout = function() {
10032
- return setTimeout(...arguments);
10033
- };
10034
- CriticalTimers.setInterval = function() {
10035
- return setInterval(...arguments);
10062
+ const VideoPresets = {
10063
+ h90: new VideoPreset(160, 90, 9e4, 20),
10064
+ h180: new VideoPreset(320, 180, 16e4, 20),
10065
+ h216: new VideoPreset(384, 216, 18e4, 20),
10066
+ h360: new VideoPreset(640, 360, 45e4, 20),
10067
+ h540: new VideoPreset(960, 540, 8e5, 25),
10068
+ h720: new VideoPreset(1280, 720, 17e5, 30),
10069
+ h1080: new VideoPreset(1920, 1080, 3e6, 30),
10070
+ h1440: new VideoPreset(2560, 1440, 5e6, 30),
10071
+ h2160: new VideoPreset(3840, 2160, 8e6, 30)
10036
10072
  };
10037
- CriticalTimers.clearTimeout = function() {
10038
- return clearTimeout(...arguments);
10073
+ /**
10074
+ * Four by three presets
10075
+ */
10076
+ const VideoPresets43 = {
10077
+ h120: new VideoPreset(160, 120, 7e4, 20),
10078
+ h180: new VideoPreset(240, 180, 125e3, 20),
10079
+ h240: new VideoPreset(320, 240, 14e4, 20),
10080
+ h360: new VideoPreset(480, 360, 33e4, 20),
10081
+ h480: new VideoPreset(640, 480, 5e5, 20),
10082
+ h540: new VideoPreset(720, 540, 6e5, 25),
10083
+ h720: new VideoPreset(960, 720, 13e5, 30),
10084
+ h1080: new VideoPreset(1440, 1080, 23e5, 30),
10085
+ h1440: new VideoPreset(1920, 1440, 38e5, 30)
10039
10086
  };
10040
- CriticalTimers.clearInterval = function() {
10041
- return clearInterval(...arguments);
10087
+ const ScreenSharePresets = {
10088
+ h360fps3: new VideoPreset(640, 360, 2e5, 3, "medium"),
10089
+ h360fps15: new VideoPreset(640, 360, 4e5, 15, "medium"),
10090
+ h720fps5: new VideoPreset(1280, 720, 8e5, 5, "medium"),
10091
+ h720fps15: new VideoPreset(1280, 720, 15e5, 15, "medium"),
10092
+ h720fps30: new VideoPreset(1280, 720, 2e6, 30, "medium"),
10093
+ h1080fps15: new VideoPreset(1920, 1080, 25e5, 15, "medium"),
10094
+ h1080fps30: new VideoPreset(1920, 1080, 5e6, 30, "medium"),
10095
+ original: new VideoPreset(0, 0, 7e6, 30, "medium")
10042
10096
  };
10097
+ function mergeDefaultOptions(options, audioDefaults, videoDefaults) {
10098
+ var _a, _b;
10099
+ var _c, _d;
10100
+ const { optionsWithoutProcessor, audioProcessor, videoProcessor } = extractProcessorsFromOptions(options !== null && options !== void 0 ? options : {});
10101
+ const defaultAudioProcessor = audioDefaults === null || audioDefaults === void 0 ? void 0 : audioDefaults.processor;
10102
+ const defaultVideoProcessor = videoDefaults === null || videoDefaults === void 0 ? void 0 : videoDefaults.processor;
10103
+ const clonedOptions = optionsWithoutProcessor !== null && optionsWithoutProcessor !== void 0 ? optionsWithoutProcessor : {};
10104
+ if (clonedOptions.audio === true) clonedOptions.audio = {};
10105
+ if (clonedOptions.video === true) clonedOptions.video = {};
10106
+ if (clonedOptions.audio) {
10107
+ mergeObjectWithoutOverwriting(clonedOptions.audio, audioDefaults);
10108
+ (_a = (_c = clonedOptions.audio).deviceId) !== null && _a !== void 0 || (_c.deviceId = { ideal: "default" });
10109
+ if (audioProcessor || defaultAudioProcessor) clonedOptions.audio.processor = audioProcessor !== null && audioProcessor !== void 0 ? audioProcessor : defaultAudioProcessor;
10110
+ }
10111
+ if (clonedOptions.video) {
10112
+ mergeObjectWithoutOverwriting(clonedOptions.video, videoDefaults);
10113
+ (_b = (_d = clonedOptions.video).deviceId) !== null && _b !== void 0 || (_d.deviceId = { ideal: "default" });
10114
+ if (videoProcessor || defaultVideoProcessor) clonedOptions.video.processor = videoProcessor !== null && videoProcessor !== void 0 ? videoProcessor : defaultVideoProcessor;
10115
+ }
10116
+ return clonedOptions;
10117
+ }
10118
+ function mergeObjectWithoutOverwriting(mainObject, objectToMerge) {
10119
+ Object.keys(objectToMerge).forEach((key) => {
10120
+ if (mainObject[key] === void 0) mainObject[key] = objectToMerge[key];
10121
+ });
10122
+ return mainObject;
10123
+ }
10124
+ function constraintsForOptions(options) {
10125
+ var _a, _b;
10126
+ var _c, _d;
10127
+ const constraints = {};
10128
+ if (options.video) if (typeof options.video === "object") {
10129
+ const videoOptions = {};
10130
+ const target = videoOptions;
10131
+ const source = options.video;
10132
+ Object.keys(source).forEach((key) => {
10133
+ switch (key) {
10134
+ case "resolution":
10135
+ mergeObjectWithoutOverwriting(target, source.resolution);
10136
+ break;
10137
+ default: target[key] = source[key];
10138
+ }
10139
+ });
10140
+ constraints.video = videoOptions;
10141
+ (_a = (_c = constraints.video).deviceId) !== null && _a !== void 0 || (_c.deviceId = { ideal: "default" });
10142
+ } else constraints.video = options.video ? { deviceId: { ideal: "default" } } : false;
10143
+ else constraints.video = false;
10144
+ if (options.audio) if (typeof options.audio === "object") {
10145
+ constraints.audio = options.audio;
10146
+ (_b = (_d = constraints.audio).deviceId) !== null && _b !== void 0 || (_d.deviceId = { ideal: "default" });
10147
+ } else constraints.audio = { deviceId: { ideal: "default" } };
10148
+ else constraints.audio = false;
10149
+ return constraints;
10150
+ }
10151
+ /**
10152
+ * This function detects silence on a given [[Track]] instance.
10153
+ * Returns true if the track seems to be entirely silent.
10154
+ */
10155
+ function detectSilence(track_1) {
10156
+ return __awaiter(this, arguments, void 0, function(track) {
10157
+ let timeOffset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 200;
10158
+ return function* () {
10159
+ const ctx = getNewAudioContext();
10160
+ if (ctx) {
10161
+ const analyser = ctx.createAnalyser();
10162
+ analyser.fftSize = 2048;
10163
+ const bufferLength = analyser.frequencyBinCount;
10164
+ const dataArray = new Uint8Array(bufferLength);
10165
+ ctx.createMediaStreamSource(new MediaStream([track.mediaStreamTrack])).connect(analyser);
10166
+ yield sleep(timeOffset);
10167
+ analyser.getByteTimeDomainData(dataArray);
10168
+ const someNoise = dataArray.some((sample) => sample !== 128 && sample !== 0);
10169
+ ctx.close();
10170
+ return !someNoise;
10171
+ }
10172
+ return false;
10173
+ }();
10174
+ });
10175
+ }
10176
+ /**
10177
+ * @internal
10178
+ */
10179
+ function getNewAudioContext() {
10180
+ var _a;
10181
+ const AudioContext = typeof window !== "undefined" && (window.AudioContext || window.webkitAudioContext);
10182
+ if (AudioContext) {
10183
+ const audioContext = new AudioContext({ latencyHint: "interactive" });
10184
+ if (audioContext.state === "suspended" && typeof window !== "undefined" && ((_a = window.document) === null || _a === void 0 ? void 0 : _a.body)) {
10185
+ const handleResume = () => __awaiter(this, void 0, void 0, function* () {
10186
+ var _a;
10187
+ try {
10188
+ if (audioContext.state === "suspended") yield audioContext.resume();
10189
+ } catch (e) {
10190
+ console.warn("Error trying to auto-resume audio context", e);
10191
+ } finally {
10192
+ (_a = window.document.body) === null || _a === void 0 || _a.removeEventListener("click", handleResume);
10193
+ }
10194
+ });
10195
+ audioContext.addEventListener("statechange", () => {
10196
+ var _a;
10197
+ if (audioContext.state === "closed") (_a = window.document.body) === null || _a === void 0 || _a.removeEventListener("click", handleResume);
10198
+ });
10199
+ window.document.body.addEventListener("click", handleResume);
10200
+ }
10201
+ return audioContext;
10202
+ }
10203
+ }
10204
+ /**
10205
+ * @internal
10206
+ */
10207
+ function kindToSource(kind) {
10208
+ if (kind === "audioinput") return Track.Source.Microphone;
10209
+ else if (kind === "videoinput") return Track.Source.Camera;
10210
+ else return Track.Source.Unknown;
10211
+ }
10212
+ /**
10213
+ * @internal
10214
+ */
10215
+ function sourceToKind(source) {
10216
+ if (source === Track.Source.Microphone) return "audioinput";
10217
+ else if (source === Track.Source.Camera) return "videoinput";
10218
+ else return;
10219
+ }
10220
+ /**
10221
+ * @internal
10222
+ */
10223
+ function screenCaptureToDisplayMediaStreamOptions(options) {
10224
+ var _a, _b;
10225
+ let videoConstraints = (_a = options.video) !== null && _a !== void 0 ? _a : true;
10226
+ if (options.resolution && options.resolution.width > 0 && options.resolution.height > 0) {
10227
+ videoConstraints = typeof videoConstraints === "boolean" ? {} : videoConstraints;
10228
+ if (isSafari()) videoConstraints = Object.assign(Object.assign({}, videoConstraints), {
10229
+ width: { max: options.resolution.width },
10230
+ height: { max: options.resolution.height },
10231
+ frameRate: options.resolution.frameRate
10232
+ });
10233
+ else videoConstraints = Object.assign(Object.assign({}, videoConstraints), {
10234
+ width: { ideal: options.resolution.width },
10235
+ height: { ideal: options.resolution.height },
10236
+ frameRate: options.resolution.frameRate
10237
+ });
10238
+ }
10239
+ return {
10240
+ audio: (_b = options.audio) !== null && _b !== void 0 ? _b : false,
10241
+ video: videoConstraints,
10242
+ controller: options.controller,
10243
+ selfBrowserSurface: options.selfBrowserSurface,
10244
+ surfaceSwitching: options.surfaceSwitching,
10245
+ systemAudio: options.systemAudio,
10246
+ preferCurrentTab: options.preferCurrentTab
10247
+ };
10248
+ }
10249
+ function mimeTypeToVideoCodecString(mimeType) {
10250
+ return mimeType.split("/")[1].toLowerCase();
10251
+ }
10252
+ function getTrackPublicationInfo(tracks) {
10253
+ const infos = [];
10254
+ tracks.forEach((track) => {
10255
+ if (track.track !== void 0) infos.push(new TrackPublishedResponse({
10256
+ cid: track.track.mediaStreamID,
10257
+ track: track.trackInfo
10258
+ }));
10259
+ });
10260
+ return infos;
10261
+ }
10262
+ function getLogContextFromTrack(track) {
10263
+ if ("mediaStreamTrack" in track) return {
10264
+ trackID: track.sid,
10265
+ source: track.source,
10266
+ muted: track.isMuted,
10267
+ enabled: track.mediaStreamTrack.enabled,
10268
+ kind: track.kind,
10269
+ streamID: track.mediaStreamID,
10270
+ streamTrackID: track.mediaStreamTrack.id
10271
+ };
10272
+ else return {
10273
+ trackID: track.trackSid,
10274
+ enabled: track.isEnabled,
10275
+ muted: track.isMuted,
10276
+ trackInfo: Object.assign({
10277
+ mimeType: track.mimeType,
10278
+ name: track.trackName,
10279
+ encrypted: track.isEncrypted,
10280
+ kind: track.kind,
10281
+ source: track.source
10282
+ }, track.track ? getLogContextFromTrack(track.track) : {})
10283
+ };
10284
+ }
10285
+ function supportsSynchronizationSources() {
10286
+ return typeof RTCRtpReceiver !== "undefined" && "getSynchronizationSources" in RTCRtpReceiver;
10287
+ }
10288
+ function diffAttributes(oldValues, newValues) {
10289
+ var _a;
10290
+ if (oldValues === void 0) oldValues = {};
10291
+ if (newValues === void 0) newValues = {};
10292
+ const allKeys = [...Object.keys(newValues), ...Object.keys(oldValues)];
10293
+ const diff = {};
10294
+ for (const key of allKeys) if (oldValues[key] !== newValues[key]) diff[key] = (_a = newValues[key]) !== null && _a !== void 0 ? _a : "";
10295
+ return diff;
10296
+ }
10297
+ /** @internal */
10298
+ function extractProcessorsFromOptions(options) {
10299
+ const newOptions = Object.assign({}, options);
10300
+ let audioProcessor;
10301
+ let videoProcessor;
10302
+ if (typeof newOptions.audio === "object" && newOptions.audio.processor) {
10303
+ audioProcessor = newOptions.audio.processor;
10304
+ newOptions.audio = Object.assign(Object.assign({}, newOptions.audio), { processor: void 0 });
10305
+ }
10306
+ if (typeof newOptions.video === "object" && newOptions.video.processor) {
10307
+ videoProcessor = newOptions.video.processor;
10308
+ newOptions.video = Object.assign(Object.assign({}, newOptions.video), { processor: void 0 });
10309
+ }
10310
+ return {
10311
+ audioProcessor,
10312
+ videoProcessor,
10313
+ optionsWithoutProcessor: cloneDeep(newOptions)
10314
+ };
10315
+ }
10316
+ function getTrackSourceFromProto(source) {
10317
+ switch (source) {
10318
+ case TrackSource.CAMERA: return Track.Source.Camera;
10319
+ case TrackSource.MICROPHONE: return Track.Source.Microphone;
10320
+ case TrackSource.SCREEN_SHARE: return Track.Source.ScreenShare;
10321
+ case TrackSource.SCREEN_SHARE_AUDIO: return Track.Source.ScreenShareAudio;
10322
+ default: return Track.Source.Unknown;
10323
+ }
10324
+ }
10325
+ function areDimensionsSmaller(a, b) {
10326
+ return a.width * a.height < b.width * b.height;
10327
+ }
10328
+ function layerDimensionsFor(trackInfo, quality) {
10329
+ var _a;
10330
+ return (_a = trackInfo.layers) === null || _a === void 0 ? void 0 : _a.find((l) => l.quality === quality);
10331
+ }
10043
10332
  const BACKGROUND_REACTION_DELAY = 5e3;
10044
10333
  const recycledElements = [];
10045
10334
  var VideoQuality;
@@ -10311,103 +10600,6 @@ var ElevenLabsClient = (function(exports) {
10311
10600
  }
10312
10601
  Track.streamStateFromProto = streamStateFromProto;
10313
10602
  })(Track || (Track = {}));
10314
- var VideoPreset = class {
10315
- constructor(widthOrOptions, height, maxBitrate, maxFramerate, priority) {
10316
- if (typeof widthOrOptions === "object") {
10317
- this.width = widthOrOptions.width;
10318
- this.height = widthOrOptions.height;
10319
- this.aspectRatio = widthOrOptions.aspectRatio;
10320
- this.encoding = {
10321
- maxBitrate: widthOrOptions.maxBitrate,
10322
- maxFramerate: widthOrOptions.maxFramerate,
10323
- priority: widthOrOptions.priority
10324
- };
10325
- } else if (height !== void 0 && maxBitrate !== void 0) {
10326
- this.width = widthOrOptions;
10327
- this.height = height;
10328
- this.aspectRatio = widthOrOptions / height;
10329
- this.encoding = {
10330
- maxBitrate,
10331
- maxFramerate,
10332
- priority
10333
- };
10334
- } else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");
10335
- }
10336
- get resolution() {
10337
- return {
10338
- width: this.width,
10339
- height: this.height,
10340
- frameRate: this.encoding.maxFramerate,
10341
- aspectRatio: this.aspectRatio
10342
- };
10343
- }
10344
- };
10345
- const backupVideoCodecs = ["vp8", "h264"];
10346
- const videoCodecs = [
10347
- "vp8",
10348
- "h264",
10349
- "vp9",
10350
- "av1",
10351
- "h265"
10352
- ];
10353
- function isBackupVideoCodec(codec) {
10354
- return !!backupVideoCodecs.find((backup) => backup === codec);
10355
- }
10356
- /** @deprecated Use {@link isBackupVideoCodec} instead */
10357
- const isBackupCodec = isBackupVideoCodec;
10358
- var BackupCodecPolicy;
10359
- (function(BackupCodecPolicy) {
10360
- BackupCodecPolicy[BackupCodecPolicy["PREFER_REGRESSION"] = 0] = "PREFER_REGRESSION";
10361
- BackupCodecPolicy[BackupCodecPolicy["SIMULCAST"] = 1] = "SIMULCAST";
10362
- BackupCodecPolicy[BackupCodecPolicy["REGRESSION"] = 2] = "REGRESSION";
10363
- })(BackupCodecPolicy || (BackupCodecPolicy = {}));
10364
- var AudioPresets;
10365
- (function(AudioPresets) {
10366
- AudioPresets.telephone = { maxBitrate: 12e3 };
10367
- AudioPresets.speech = { maxBitrate: 24e3 };
10368
- AudioPresets.music = { maxBitrate: 48e3 };
10369
- AudioPresets.musicStereo = { maxBitrate: 64e3 };
10370
- AudioPresets.musicHighQuality = { maxBitrate: 96e3 };
10371
- AudioPresets.musicHighQualityStereo = { maxBitrate: 128e3 };
10372
- })(AudioPresets || (AudioPresets = {}));
10373
- /**
10374
- * Sane presets for video resolution/encoding
10375
- */
10376
- const VideoPresets = {
10377
- h90: new VideoPreset(160, 90, 9e4, 20),
10378
- h180: new VideoPreset(320, 180, 16e4, 20),
10379
- h216: new VideoPreset(384, 216, 18e4, 20),
10380
- h360: new VideoPreset(640, 360, 45e4, 20),
10381
- h540: new VideoPreset(960, 540, 8e5, 25),
10382
- h720: new VideoPreset(1280, 720, 17e5, 30),
10383
- h1080: new VideoPreset(1920, 1080, 3e6, 30),
10384
- h1440: new VideoPreset(2560, 1440, 5e6, 30),
10385
- h2160: new VideoPreset(3840, 2160, 8e6, 30)
10386
- };
10387
- /**
10388
- * Four by three presets
10389
- */
10390
- const VideoPresets43 = {
10391
- h120: new VideoPreset(160, 120, 7e4, 20),
10392
- h180: new VideoPreset(240, 180, 125e3, 20),
10393
- h240: new VideoPreset(320, 240, 14e4, 20),
10394
- h360: new VideoPreset(480, 360, 33e4, 20),
10395
- h480: new VideoPreset(640, 480, 5e5, 20),
10396
- h540: new VideoPreset(720, 540, 6e5, 25),
10397
- h720: new VideoPreset(960, 720, 13e5, 30),
10398
- h1080: new VideoPreset(1440, 1080, 23e5, 30),
10399
- h1440: new VideoPreset(1920, 1440, 38e5, 30)
10400
- };
10401
- const ScreenSharePresets = {
10402
- h360fps3: new VideoPreset(640, 360, 2e5, 3, "medium"),
10403
- h360fps15: new VideoPreset(640, 360, 4e5, 15, "medium"),
10404
- h720fps5: new VideoPreset(1280, 720, 8e5, 5, "medium"),
10405
- h720fps15: new VideoPreset(1280, 720, 15e5, 15, "medium"),
10406
- h720fps30: new VideoPreset(1280, 720, 2e6, 30, "medium"),
10407
- h1080fps15: new VideoPreset(1920, 1080, 25e5, 15, "medium"),
10408
- h1080fps30: new VideoPreset(1920, 1080, 5e6, 30, "medium"),
10409
- original: new VideoPreset(0, 0, 7e6, 30, "medium")
10410
- };
10411
10603
  const separator = "|";
10412
10604
  const ddExtensionURI = "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";
10413
10605
  function unpackStreamId(packed) {
@@ -10734,277 +10926,115 @@ var ElevenLabsClient = (function(exports) {
10734
10926
  function isRemoteTrack(track) {
10735
10927
  return !!track && !track.isLocal;
10736
10928
  }
10737
- function isRemotePub(pub) {
10738
- return !!pub && !pub.isLocal;
10739
- }
10740
- function isRemoteVideoTrack(track) {
10741
- return isRemoteTrack(track) && isVideoTrack(track);
10742
- }
10743
- function isLocalParticipant(p) {
10744
- return p.isLocal;
10745
- }
10746
- function splitUtf8(s, n) {
10747
- const result = [];
10748
- let encoded = new TextEncoder().encode(s);
10749
- while (encoded.length > n) {
10750
- let k = n;
10751
- while (k > 0) {
10752
- const byte = encoded[k];
10753
- if (byte !== void 0 && (byte & 192) !== 128) break;
10754
- k--;
10755
- }
10756
- result.push(encoded.slice(0, k));
10757
- encoded = encoded.slice(k);
10758
- }
10759
- if (encoded.length > 0) result.push(encoded);
10760
- return result;
10761
- }
10762
- function extractMaxAgeFromRequestHeaders(headers) {
10763
- var _a;
10764
- const cacheControl = headers.get("Cache-Control");
10765
- if (cacheControl) {
10766
- const maxAge = (_a = cacheControl.match(/(?:^|[,\s])max-age=(\d+)/)) === null || _a === void 0 ? void 0 : _a[1];
10767
- if (maxAge) return parseInt(maxAge, 10);
10768
- }
10769
- }
10770
- function mergeDefaultOptions(options, audioDefaults, videoDefaults) {
10771
- var _a, _b;
10772
- var _c, _d;
10773
- const { optionsWithoutProcessor, audioProcessor, videoProcessor } = extractProcessorsFromOptions(options !== null && options !== void 0 ? options : {});
10774
- const defaultAudioProcessor = audioDefaults === null || audioDefaults === void 0 ? void 0 : audioDefaults.processor;
10775
- const defaultVideoProcessor = videoDefaults === null || videoDefaults === void 0 ? void 0 : videoDefaults.processor;
10776
- const clonedOptions = optionsWithoutProcessor !== null && optionsWithoutProcessor !== void 0 ? optionsWithoutProcessor : {};
10777
- if (clonedOptions.audio === true) clonedOptions.audio = {};
10778
- if (clonedOptions.video === true) clonedOptions.video = {};
10779
- if (clonedOptions.audio) {
10780
- mergeObjectWithoutOverwriting(clonedOptions.audio, audioDefaults);
10781
- (_a = (_c = clonedOptions.audio).deviceId) !== null && _a !== void 0 || (_c.deviceId = { ideal: "default" });
10782
- if (audioProcessor || defaultAudioProcessor) clonedOptions.audio.processor = audioProcessor !== null && audioProcessor !== void 0 ? audioProcessor : defaultAudioProcessor;
10783
- }
10784
- if (clonedOptions.video) {
10785
- mergeObjectWithoutOverwriting(clonedOptions.video, videoDefaults);
10786
- (_b = (_d = clonedOptions.video).deviceId) !== null && _b !== void 0 || (_d.deviceId = { ideal: "default" });
10787
- if (videoProcessor || defaultVideoProcessor) clonedOptions.video.processor = videoProcessor !== null && videoProcessor !== void 0 ? videoProcessor : defaultVideoProcessor;
10788
- }
10789
- return clonedOptions;
10790
- }
10791
- function mergeObjectWithoutOverwriting(mainObject, objectToMerge) {
10792
- Object.keys(objectToMerge).forEach((key) => {
10793
- if (mainObject[key] === void 0) mainObject[key] = objectToMerge[key];
10794
- });
10795
- return mainObject;
10796
- }
10797
- function constraintsForOptions(options) {
10798
- var _a, _b;
10799
- var _c, _d;
10800
- const constraints = {};
10801
- if (options.video) if (typeof options.video === "object") {
10802
- const videoOptions = {};
10803
- const target = videoOptions;
10804
- const source = options.video;
10805
- Object.keys(source).forEach((key) => {
10806
- switch (key) {
10807
- case "resolution":
10808
- mergeObjectWithoutOverwriting(target, source.resolution);
10809
- break;
10810
- default: target[key] = source[key];
10811
- }
10812
- });
10813
- constraints.video = videoOptions;
10814
- (_a = (_c = constraints.video).deviceId) !== null && _a !== void 0 || (_c.deviceId = { ideal: "default" });
10815
- } else constraints.video = options.video ? { deviceId: { ideal: "default" } } : false;
10816
- else constraints.video = false;
10817
- if (options.audio) if (typeof options.audio === "object") {
10818
- constraints.audio = options.audio;
10819
- (_b = (_d = constraints.audio).deviceId) !== null && _b !== void 0 || (_d.deviceId = { ideal: "default" });
10820
- } else constraints.audio = { deviceId: { ideal: "default" } };
10821
- else constraints.audio = false;
10822
- return constraints;
10823
- }
10824
- /**
10825
- * This function detects silence on a given [[Track]] instance.
10826
- * Returns true if the track seems to be entirely silent.
10827
- */
10828
- function detectSilence(track_1) {
10829
- return __awaiter(this, arguments, void 0, function(track) {
10830
- let timeOffset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 200;
10831
- return function* () {
10832
- const ctx = getNewAudioContext();
10833
- if (ctx) {
10834
- const analyser = ctx.createAnalyser();
10835
- analyser.fftSize = 2048;
10836
- const bufferLength = analyser.frequencyBinCount;
10837
- const dataArray = new Uint8Array(bufferLength);
10838
- ctx.createMediaStreamSource(new MediaStream([track.mediaStreamTrack])).connect(analyser);
10839
- yield sleep(timeOffset);
10840
- analyser.getByteTimeDomainData(dataArray);
10841
- const someNoise = dataArray.some((sample) => sample !== 128 && sample !== 0);
10842
- ctx.close();
10843
- return !someNoise;
10844
- }
10845
- return false;
10846
- }();
10847
- });
10848
- }
10849
- /**
10850
- * @internal
10851
- */
10852
- function getNewAudioContext() {
10853
- var _a;
10854
- const AudioContext = typeof window !== "undefined" && (window.AudioContext || window.webkitAudioContext);
10855
- if (AudioContext) {
10856
- const audioContext = new AudioContext({ latencyHint: "interactive" });
10857
- if (audioContext.state === "suspended" && typeof window !== "undefined" && ((_a = window.document) === null || _a === void 0 ? void 0 : _a.body)) {
10858
- const handleResume = () => __awaiter(this, void 0, void 0, function* () {
10859
- var _a;
10860
- try {
10861
- if (audioContext.state === "suspended") yield audioContext.resume();
10862
- } catch (e) {
10863
- console.warn("Error trying to auto-resume audio context", e);
10864
- } finally {
10865
- (_a = window.document.body) === null || _a === void 0 || _a.removeEventListener("click", handleResume);
10866
- }
10867
- });
10868
- audioContext.addEventListener("statechange", () => {
10869
- var _a;
10870
- if (audioContext.state === "closed") (_a = window.document.body) === null || _a === void 0 || _a.removeEventListener("click", handleResume);
10871
- });
10872
- window.document.body.addEventListener("click", handleResume);
10873
- }
10874
- return audioContext;
10875
- }
10876
- }
10877
- /**
10878
- * @internal
10879
- */
10880
- function kindToSource(kind) {
10881
- if (kind === "audioinput") return Track.Source.Microphone;
10882
- else if (kind === "videoinput") return Track.Source.Camera;
10883
- else return Track.Source.Unknown;
10929
+ function isRemotePub(pub) {
10930
+ return !!pub && !pub.isLocal;
10884
10931
  }
10885
- /**
10886
- * @internal
10887
- */
10888
- function sourceToKind(source) {
10889
- if (source === Track.Source.Microphone) return "audioinput";
10890
- else if (source === Track.Source.Camera) return "videoinput";
10891
- else return;
10932
+ function isRemoteVideoTrack(track) {
10933
+ return isRemoteTrack(track) && isVideoTrack(track);
10892
10934
  }
10893
- /**
10894
- * @internal
10895
- */
10896
- function screenCaptureToDisplayMediaStreamOptions(options) {
10897
- var _a, _b;
10898
- let videoConstraints = (_a = options.video) !== null && _a !== void 0 ? _a : true;
10899
- if (options.resolution && options.resolution.width > 0 && options.resolution.height > 0) {
10900
- videoConstraints = typeof videoConstraints === "boolean" ? {} : videoConstraints;
10901
- if (isSafari()) videoConstraints = Object.assign(Object.assign({}, videoConstraints), {
10902
- width: { max: options.resolution.width },
10903
- height: { max: options.resolution.height },
10904
- frameRate: options.resolution.frameRate
10905
- });
10906
- else videoConstraints = Object.assign(Object.assign({}, videoConstraints), {
10907
- width: { ideal: options.resolution.width },
10908
- height: { ideal: options.resolution.height },
10909
- frameRate: options.resolution.frameRate
10910
- });
10935
+ function isLocalParticipant(p) {
10936
+ return p.isLocal;
10937
+ }
10938
+ function splitUtf8(s, n) {
10939
+ const result = [];
10940
+ let encoded = new TextEncoder().encode(s);
10941
+ while (encoded.length > n) {
10942
+ let k = n;
10943
+ while (k > 0) {
10944
+ const byte = encoded[k];
10945
+ if (byte !== void 0 && (byte & 192) !== 128) break;
10946
+ k--;
10947
+ }
10948
+ result.push(encoded.slice(0, k));
10949
+ encoded = encoded.slice(k);
10911
10950
  }
10912
- return {
10913
- audio: (_b = options.audio) !== null && _b !== void 0 ? _b : false,
10914
- video: videoConstraints,
10915
- controller: options.controller,
10916
- selfBrowserSurface: options.selfBrowserSurface,
10917
- surfaceSwitching: options.surfaceSwitching,
10918
- systemAudio: options.systemAudio,
10919
- preferCurrentTab: options.preferCurrentTab
10920
- };
10951
+ if (encoded.length > 0) result.push(encoded);
10952
+ return result;
10921
10953
  }
10922
- function mimeTypeToVideoCodecString(mimeType) {
10923
- return mimeType.split("/")[1].toLowerCase();
10954
+ function extractMaxAgeFromRequestHeaders(headers) {
10955
+ var _a;
10956
+ const cacheControl = headers.get("Cache-Control");
10957
+ if (cacheControl) {
10958
+ const maxAge = (_a = cacheControl.match(/(?:^|[,\s])max-age=(\d+)/)) === null || _a === void 0 ? void 0 : _a[1];
10959
+ if (maxAge) return parseInt(maxAge, 10);
10960
+ }
10924
10961
  }
10925
- function getTrackPublicationInfo(tracks) {
10926
- const infos = [];
10927
- tracks.forEach((track) => {
10928
- if (track.track !== void 0) infos.push(new TrackPublishedResponse({
10929
- cid: track.track.mediaStreamID,
10930
- track: track.trackInfo
10931
- }));
10962
+ function createRtcUrl(url, searchParams) {
10963
+ const urlObj = new URL(toWebsocketUrl(url));
10964
+ searchParams.forEach((value, key) => {
10965
+ urlObj.searchParams.set(key, value);
10932
10966
  });
10933
- return infos;
10967
+ return appendUrlPath(urlObj, "rtc");
10934
10968
  }
10935
- function getLogContextFromTrack(track) {
10936
- if ("mediaStreamTrack" in track) return {
10937
- trackID: track.sid,
10938
- source: track.source,
10939
- muted: track.isMuted,
10940
- enabled: track.mediaStreamTrack.enabled,
10941
- kind: track.kind,
10942
- streamID: track.mediaStreamID,
10943
- streamTrackID: track.mediaStreamTrack.id
10944
- };
10945
- else return {
10946
- trackID: track.trackSid,
10947
- enabled: track.isEnabled,
10948
- muted: track.isMuted,
10949
- trackInfo: Object.assign({
10950
- mimeType: track.mimeType,
10951
- name: track.trackName,
10952
- encrypted: track.isEncrypted,
10953
- kind: track.kind,
10954
- source: track.source
10955
- }, track.track ? getLogContextFromTrack(track.track) : {})
10956
- };
10969
+ function createValidateUrl(rtcWsUrl) {
10970
+ return appendUrlPath(new URL(toHttpUrl(rtcWsUrl)), "validate");
10957
10971
  }
10958
- function supportsSynchronizationSources() {
10959
- return typeof RTCRtpReceiver !== "undefined" && "getSynchronizationSources" in RTCRtpReceiver;
10972
+ function ensureTrailingSlash(path) {
10973
+ return path.endsWith("/") ? path : "".concat(path, "/");
10960
10974
  }
10961
- function diffAttributes(oldValues, newValues) {
10962
- var _a;
10963
- if (oldValues === void 0) oldValues = {};
10964
- if (newValues === void 0) newValues = {};
10965
- const allKeys = [...Object.keys(newValues), ...Object.keys(oldValues)];
10966
- const diff = {};
10967
- for (const key of allKeys) if (oldValues[key] !== newValues[key]) diff[key] = (_a = newValues[key]) !== null && _a !== void 0 ? _a : "";
10968
- return diff;
10975
+ function appendUrlPath(urlObj, path) {
10976
+ urlObj.pathname = "".concat(ensureTrailingSlash(urlObj.pathname)).concat(path);
10977
+ return urlObj.toString();
10969
10978
  }
10970
- /** @internal */
10971
- function extractProcessorsFromOptions(options) {
10972
- const newOptions = Object.assign({}, options);
10973
- let audioProcessor;
10974
- let videoProcessor;
10975
- if (typeof newOptions.audio === "object" && newOptions.audio.processor) {
10976
- audioProcessor = newOptions.audio.processor;
10977
- newOptions.audio = Object.assign(Object.assign({}, newOptions.audio), { processor: void 0 });
10978
- }
10979
- if (typeof newOptions.video === "object" && newOptions.video.processor) {
10980
- videoProcessor = newOptions.video.processor;
10981
- newOptions.video = Object.assign(Object.assign({}, newOptions.video), { processor: void 0 });
10982
- }
10983
- return {
10984
- audioProcessor,
10985
- videoProcessor,
10986
- optionsWithoutProcessor: cloneDeep(newOptions)
10987
- };
10979
+ function parseSignalResponse(value) {
10980
+ if (typeof value === "string") return SignalResponse.fromJson(JSON.parse(value), { ignoreUnknownFields: true });
10981
+ else if (value instanceof ArrayBuffer) return SignalResponse.fromBinary(new Uint8Array(value));
10982
+ throw new Error("could not decode websocket message: ".concat(typeof value));
10988
10983
  }
10989
- function getTrackSourceFromProto(source) {
10990
- switch (source) {
10991
- case TrackSource.CAMERA: return Track.Source.Camera;
10992
- case TrackSource.MICROPHONE: return Track.Source.Microphone;
10993
- case TrackSource.SCREEN_SHARE: return Track.Source.ScreenShare;
10994
- case TrackSource.SCREEN_SHARE_AUDIO: return Track.Source.ScreenShareAudio;
10995
- default: return Track.Source.Unknown;
10984
+ function getAbortReasonAsString(signal) {
10985
+ let defaultMessage = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "Unknown reason";
10986
+ if (!(signal instanceof AbortSignal)) return defaultMessage;
10987
+ const reason = signal.reason;
10988
+ switch (typeof reason) {
10989
+ case "string": return reason;
10990
+ case "object": return reason instanceof Error ? reason.message : defaultMessage;
10991
+ default: return "toString" in reason ? reason.toString() : defaultMessage;
10996
10992
  }
10997
10993
  }
10998
- function areDimensionsSmaller(a, b) {
10999
- return a.width * a.height < b.width * b.height;
10994
+ const E2EE_FLAG = "lk_e2ee";
10995
+ var KeyProviderEvent;
10996
+ (function(KeyProviderEvent) {
10997
+ KeyProviderEvent["SetKey"] = "setKey";
10998
+ /** Event for requesting to ratchet the key used to encrypt the stream */
10999
+ KeyProviderEvent["RatchetRequest"] = "ratchetRequest";
11000
+ /** Emitted when a key is ratcheted. Could be after auto-ratcheting on decryption failure or
11001
+ * following a `RatchetRequest`, will contain the ratcheted key material */
11002
+ KeyProviderEvent["KeyRatcheted"] = "keyRatcheted";
11003
+ })(KeyProviderEvent || (KeyProviderEvent = {}));
11004
+ var KeyHandlerEvent;
11005
+ (function(KeyHandlerEvent) {
11006
+ /** Emitted when a key has been ratcheted. Is emitted when any key has been ratcheted
11007
+ * i.e. when the FrameCryptor tried to ratchet when decryption is failing */
11008
+ KeyHandlerEvent["KeyRatcheted"] = "keyRatcheted";
11009
+ })(KeyHandlerEvent || (KeyHandlerEvent = {}));
11010
+ var EncryptionEvent;
11011
+ (function(EncryptionEvent) {
11012
+ EncryptionEvent["ParticipantEncryptionStatusChanged"] = "participantEncryptionStatusChanged";
11013
+ EncryptionEvent["EncryptionError"] = "encryptionError";
11014
+ })(EncryptionEvent || (EncryptionEvent = {}));
11015
+ var CryptorEvent;
11016
+ (function(CryptorEvent) {
11017
+ CryptorEvent["Error"] = "cryptorError";
11018
+ })(CryptorEvent || (CryptorEvent = {}));
11019
+ function isE2EESupported() {
11020
+ return isInsertableStreamSupported() || isScriptTransformSupported();
11000
11021
  }
11001
- function layerDimensionsFor(trackInfo, quality) {
11002
- var _a;
11003
- return (_a = trackInfo.layers) === null || _a === void 0 ? void 0 : _a.find((l) => l.quality === quality);
11022
+ function isScriptTransformSupported() {
11023
+ return typeof window.RTCRtpScriptTransform !== "undefined";
11004
11024
  }
11005
- /**
11006
- * @experimental
11007
- */
11025
+ function isInsertableStreamSupported() {
11026
+ return typeof window.RTCRtpSender !== "undefined" && typeof window.RTCRtpSender.prototype.createEncodedStreams !== "undefined";
11027
+ }
11028
+ function asEncryptablePacket(packet) {
11029
+ var _a, _b, _c, _d, _e;
11030
+ if (((_a = packet.value) === null || _a === void 0 ? void 0 : _a.case) !== "sipDtmf" && ((_b = packet.value) === null || _b === void 0 ? void 0 : _b.case) !== "metrics" && ((_c = packet.value) === null || _c === void 0 ? void 0 : _c.case) !== "speaker" && ((_d = packet.value) === null || _d === void 0 ? void 0 : _d.case) !== "transcription" && ((_e = packet.value) === null || _e === void 0 ? void 0 : _e.case) !== "encryptedPacket") return new EncryptedPacketPayload({ value: packet.value });
11031
+ }
11032
+ var CryptorErrorReason;
11033
+ (function(CryptorErrorReason) {
11034
+ CryptorErrorReason[CryptorErrorReason["InvalidKey"] = 0] = "InvalidKey";
11035
+ CryptorErrorReason[CryptorErrorReason["MissingKey"] = 1] = "MissingKey";
11036
+ CryptorErrorReason[CryptorErrorReason["InternalError"] = 2] = "InternalError";
11037
+ })(CryptorErrorReason || (CryptorErrorReason = {}));
11008
11038
  var E2EEManager = class extends eventsExports.EventEmitter {
11009
11039
  constructor(options, dcEncryptionEnabled) {
11010
11040
  super();
@@ -11539,11 +11569,6 @@ var ElevenLabsClient = (function(exports) {
11539
11569
  return Array.from(this.pendingTasks.values());
11540
11570
  }
11541
11571
  };
11542
- /**
11543
- * [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) with [Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API)
11544
- *
11545
- * @see https://web.dev/websocketstream/
11546
- */
11547
11572
  var WebSocketStream = class {
11548
11573
  get readyState() {
11549
11574
  return this.ws.readyState;
@@ -11615,38 +11640,6 @@ var ElevenLabsClient = (function(exports) {
11615
11640
  this.close = closeWithInfo;
11616
11641
  }
11617
11642
  };
11618
- function createRtcUrl(url, searchParams) {
11619
- const urlObj = new URL(toWebsocketUrl(url));
11620
- searchParams.forEach((value, key) => {
11621
- urlObj.searchParams.set(key, value);
11622
- });
11623
- return appendUrlPath(urlObj, "rtc");
11624
- }
11625
- function createValidateUrl(rtcWsUrl) {
11626
- return appendUrlPath(new URL(toHttpUrl(rtcWsUrl)), "validate");
11627
- }
11628
- function ensureTrailingSlash(path) {
11629
- return path.endsWith("/") ? path : "".concat(path, "/");
11630
- }
11631
- function appendUrlPath(urlObj, path) {
11632
- urlObj.pathname = "".concat(ensureTrailingSlash(urlObj.pathname)).concat(path);
11633
- return urlObj.toString();
11634
- }
11635
- function parseSignalResponse(value) {
11636
- if (typeof value === "string") return SignalResponse.fromJson(JSON.parse(value), { ignoreUnknownFields: true });
11637
- else if (value instanceof ArrayBuffer) return SignalResponse.fromBinary(new Uint8Array(value));
11638
- throw new Error("could not decode websocket message: ".concat(typeof value));
11639
- }
11640
- function getAbortReasonAsString(signal) {
11641
- let defaultMessage = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "Unknown reason";
11642
- if (!(signal instanceof AbortSignal)) return defaultMessage;
11643
- const reason = signal.reason;
11644
- switch (typeof reason) {
11645
- case "string": return reason;
11646
- case "object": return reason instanceof Error ? reason.message : defaultMessage;
11647
- default: return "toString" in reason ? reason.toString() : defaultMessage;
11648
- }
11649
- }
11650
11643
  const passThroughQueueSignals = [
11651
11644
  "syncState",
11652
11645
  "trickle",
@@ -11761,15 +11754,14 @@ var ElevenLabsClient = (function(exports) {
11761
11754
  const abortHandler = (eventOrError) => __awaiter(this, void 0, void 0, function* () {
11762
11755
  if (alreadyAborted) return;
11763
11756
  alreadyAborted = true;
11764
- const target = eventOrError instanceof Event ? eventOrError.currentTarget : eventOrError;
11765
- const reason = getAbortReasonAsString(target, "Abort handler called");
11757
+ const reason = getAbortReasonAsString(eventOrError instanceof Event ? eventOrError.currentTarget : eventOrError, "Abort handler called");
11766
11758
  if (this.streamWriter && !this.isDisconnected) this.sendLeave().then(() => this.close(reason)).catch((e) => {
11767
11759
  this.log.error(e);
11768
11760
  this.close();
11769
11761
  });
11770
11762
  else this.close();
11771
11763
  cleanupAbortHandlers();
11772
- reject(target instanceof AbortSignal ? target.reason : target);
11764
+ reject(ConnectionError.cancelled(reason));
11773
11765
  });
11774
11766
  abortSignal === null || abortSignal === void 0 || abortSignal.addEventListener("abort", abortHandler);
11775
11767
  const cleanupAbortHandlers = () => {
@@ -11777,7 +11769,7 @@ var ElevenLabsClient = (function(exports) {
11777
11769
  abortSignal === null || abortSignal === void 0 || abortSignal.removeEventListener("abort", abortHandler);
11778
11770
  };
11779
11771
  const wsTimeout = setTimeout(() => {
11780
- abortHandler(new ConnectionError("room connection has timed out (signal)", ConnectionErrorReason.ServerUnreachable));
11772
+ abortHandler(ConnectionError.timeout("room connection has timed out (signal)"));
11781
11773
  }, opts.websocketTimeout);
11782
11774
  const handleSignalConnected = (connection, firstMessage) => {
11783
11775
  this.handleSignalConnected(connection, wsTimeout, firstMessage);
@@ -11793,7 +11785,7 @@ var ElevenLabsClient = (function(exports) {
11793
11785
  try {
11794
11786
  this.ws.closed.then((closeInfo) => {
11795
11787
  var _a;
11796
- if (this.isEstablishingConnection) reject(new ConnectionError("Websocket got closed during a (re)connection attempt: ".concat(closeInfo.reason), ConnectionErrorReason.InternalError));
11788
+ if (this.isEstablishingConnection) reject(ConnectionError.internal("Websocket got closed during a (re)connection attempt: ".concat(closeInfo.reason)));
11797
11789
  if (closeInfo.closeCode !== 1e3) {
11798
11790
  this.log.warn("websocket closed", Object.assign(Object.assign({}, this.logContext), {
11799
11791
  reason: closeInfo.reason,
@@ -11804,7 +11796,7 @@ var ElevenLabsClient = (function(exports) {
11804
11796
  if (this.state === SignalConnectionState.CONNECTED) this.handleOnClose((_a = closeInfo.reason) !== null && _a !== void 0 ? _a : "Unexpected WS error");
11805
11797
  }
11806
11798
  }).catch((reason) => {
11807
- if (this.isEstablishingConnection) reject(new ConnectionError("Websocket error during a (re)connection attempt: ".concat(reason), ConnectionErrorReason.InternalError));
11799
+ if (this.isEstablishingConnection) reject(ConnectionError.internal("Websocket error during a (re)connection attempt: ".concat(reason)));
11808
11800
  });
11809
11801
  const connection = yield this.ws.opened.catch((reason) => __awaiter(this, void 0, void 0, function* () {
11810
11802
  if (this.state !== SignalConnectionState.CONNECTED) {
@@ -11822,7 +11814,7 @@ var ElevenLabsClient = (function(exports) {
11822
11814
  this.streamWriter = connection.writable.getWriter();
11823
11815
  const firstMessage = yield signalReader.read();
11824
11816
  signalReader.releaseLock();
11825
- if (!firstMessage.value) throw new ConnectionError("no message received as first message", ConnectionErrorReason.InternalError);
11817
+ if (!firstMessage.value) throw ConnectionError.internal("no message received as first message");
11826
11818
  const firstSignalResponse = parseSignalResponse(firstMessage.value);
11827
11819
  const validation = this.validateFirstMessage(firstSignalResponse, (_a = opts.reconnect) !== null && _a !== void 0 ? _a : false);
11828
11820
  if (!validation.isValid) {
@@ -12213,15 +12205,15 @@ var ElevenLabsClient = (function(exports) {
12213
12205
  }
12214
12206
  else if (this.isEstablishingConnection && ((_d = firstSignalResponse.message) === null || _d === void 0 ? void 0 : _d.case) === "leave") return {
12215
12207
  isValid: false,
12216
- error: new ConnectionError("Received leave request while trying to (re)connect", ConnectionErrorReason.LeaveRequest, void 0, firstSignalResponse.message.value.reason)
12208
+ error: ConnectionError.leaveRequest("Received leave request while trying to (re)connect", firstSignalResponse.message.value.reason)
12217
12209
  };
12218
12210
  else if (!isReconnect) return {
12219
12211
  isValid: false,
12220
- error: new ConnectionError("did not receive join response, got ".concat((_e = firstSignalResponse.message) === null || _e === void 0 ? void 0 : _e.case, " instead"), ConnectionErrorReason.InternalError)
12212
+ error: ConnectionError.internal("did not receive join response, got ".concat((_e = firstSignalResponse.message) === null || _e === void 0 ? void 0 : _e.case, " instead"))
12221
12213
  };
12222
12214
  return {
12223
12215
  isValid: false,
12224
- error: new ConnectionError("Unexpected first message", ConnectionErrorReason.InternalError)
12216
+ error: ConnectionError.internal("Unexpected first message")
12225
12217
  };
12226
12218
  }
12227
12219
  /**
@@ -12235,11 +12227,16 @@ var ElevenLabsClient = (function(exports) {
12235
12227
  return __awaiter(this, void 0, void 0, function* () {
12236
12228
  try {
12237
12229
  const resp = yield fetch(validateUrl);
12238
- if (resp.status.toFixed(0).startsWith("4")) return new ConnectionError(yield resp.text(), ConnectionErrorReason.NotAllowed, resp.status);
12239
- else if (reason instanceof ConnectionError) return reason;
12240
- else return new ConnectionError("Encountered unknown websocket error during connection: ".concat(reason), ConnectionErrorReason.InternalError, resp.status);
12230
+ if (resp.status.toFixed(0).startsWith("4")) {
12231
+ const msg = yield resp.text();
12232
+ return ConnectionError.notAllowed(msg, resp.status);
12233
+ } else if (reason instanceof ConnectionError) return reason;
12234
+ else return ConnectionError.internal("Encountered unknown websocket error during connection: ".concat(reason), {
12235
+ status: resp.status,
12236
+ statusText: resp.statusText
12237
+ });
12241
12238
  } catch (e) {
12242
- return e instanceof ConnectionError ? e : new ConnectionError(e instanceof Error ? e.message : "server was not reachable", ConnectionErrorReason.ServerUnreachable);
12239
+ return e instanceof ConnectionError ? e : ConnectionError.serverUnreachable(e instanceof Error ? e.message : "server was not reachable");
12243
12240
  }
12244
12241
  });
12245
12242
  }
@@ -13824,18 +13821,18 @@ var ElevenLabsClient = (function(exports) {
13824
13821
  const abortHandler = () => {
13825
13822
  this.log.warn("abort transport connection", this.logContext);
13826
13823
  CriticalTimers.clearTimeout(connectTimeout);
13827
- reject(new ConnectionError("room connection has been cancelled", ConnectionErrorReason.Cancelled));
13824
+ reject(ConnectionError.cancelled("room connection has been cancelled"));
13828
13825
  };
13829
13826
  if (abortController === null || abortController === void 0 ? void 0 : abortController.signal.aborted) abortHandler();
13830
13827
  abortController === null || abortController === void 0 || abortController.signal.addEventListener("abort", abortHandler);
13831
13828
  const connectTimeout = CriticalTimers.setTimeout(() => {
13832
13829
  abortController === null || abortController === void 0 || abortController.signal.removeEventListener("abort", abortHandler);
13833
- reject(new ConnectionError("could not establish pc connection", ConnectionErrorReason.InternalError));
13830
+ reject(ConnectionError.internal("could not establish pc connection"));
13834
13831
  }, timeout);
13835
13832
  while (this.state !== PCTransportState.CONNECTED) {
13836
13833
  yield sleep(50);
13837
13834
  if (abortController === null || abortController === void 0 ? void 0 : abortController.signal.aborted) {
13838
- reject(new ConnectionError("room connection has been cancelled", ConnectionErrorReason.Cancelled));
13835
+ reject(ConnectionError.cancelled("room connection has been cancelled"));
13839
13836
  return;
13840
13837
  }
13841
13838
  }
@@ -13866,11 +13863,12 @@ var ElevenLabsClient = (function(exports) {
13866
13863
  updatedAtInMs: Date.now(),
13867
13864
  maxAgeInMs
13868
13865
  };
13869
- } else throw new ConnectionError("Could not fetch region settings: ".concat(regionSettingsResponse.statusText), regionSettingsResponse.status === 401 ? ConnectionErrorReason.NotAllowed : ConnectionErrorReason.InternalError, regionSettingsResponse.status);
13866
+ } else if (regionSettingsResponse.status === 401) throw ConnectionError.notAllowed("Could not fetch region settings: ".concat(regionSettingsResponse.statusText), regionSettingsResponse.status);
13867
+ else throw ConnectionError.internal("Could not fetch region settings: ".concat(regionSettingsResponse.statusText));
13870
13868
  } catch (e) {
13871
13869
  if (e instanceof ConnectionError) throw e;
13872
- else if (signal === null || signal === void 0 ? void 0 : signal.aborted) throw new ConnectionError("Region fetching was aborted", ConnectionErrorReason.Cancelled);
13873
- else throw new ConnectionError("Could not fetch region settings, ".concat(e instanceof Error ? "".concat(e.name, ": ").concat(e.message) : e), ConnectionErrorReason.ServerUnreachable, 500);
13870
+ else if (signal === null || signal === void 0 ? void 0 : signal.aborted) throw ConnectionError.cancelled("Region fetching was aborted");
13871
+ else throw ConnectionError.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error ? "".concat(e.name, ": ").concat(e.message) : e));
13874
13872
  } finally {
13875
13873
  unlock();
13876
13874
  }
@@ -14509,8 +14507,6 @@ var ElevenLabsClient = (function(exports) {
14509
14507
  * Sets a processor on this track.
14510
14508
  * See https://github.com/livekit/track-processors-js for example usage
14511
14509
  *
14512
- * @experimental
14513
- *
14514
14510
  * @param processor
14515
14511
  * @param showProcessedStreamLocally
14516
14512
  * @returns
@@ -14570,8 +14566,6 @@ var ElevenLabsClient = (function(exports) {
14570
14566
  * Stops the track processor
14571
14567
  * See https://github.com/livekit/track-processors-js for example usage
14572
14568
  *
14573
- * @experimental
14574
- * @returns
14575
14569
  */
14576
14570
  stopProcessor() {
14577
14571
  return __awaiter(this, arguments, void 0, function() {
@@ -14832,7 +14826,6 @@ var ElevenLabsClient = (function(exports) {
14832
14826
  });
14833
14827
  }
14834
14828
  };
14835
- /** @internal */
14836
14829
  function mediaTrackToLocalTrack(mediaStreamTrack, constraints, loggerOptions) {
14837
14830
  switch (mediaStreamTrack.kind) {
14838
14831
  case "audio": return new LocalAudioTrack(mediaStreamTrack, constraints, false, void 0, loggerOptions);
@@ -15567,6 +15560,8 @@ var ElevenLabsClient = (function(exports) {
15567
15560
  const minReconnectWait = 2 * 1e3;
15568
15561
  const leaveReconnect = "leave-reconnect";
15569
15562
  const reliabeReceiveStateTTL = 3e4;
15563
+ const lossyDataChannelBufferThresholdMin = 8 * 1024;
15564
+ const lossyDataChannelBufferThresholdMax = 256 * 1024;
15570
15565
  var PCState;
15571
15566
  (function(PCState) {
15572
15567
  PCState[PCState["New"] = 0] = "New";
@@ -15610,6 +15605,9 @@ var ElevenLabsClient = (function(exports) {
15610
15605
  this.reliableDataSequence = 1;
15611
15606
  this.reliableMessageBuffer = new DataPacketBuffer();
15612
15607
  this.reliableReceivedState = new TTLMap(reliabeReceiveStateTTL);
15608
+ this.lossyDataStatCurrentBytes = 0;
15609
+ this.lossyDataStatByterate = 0;
15610
+ this.lossyDataDropCount = 0;
15613
15611
  this.midToTrackId = {};
15614
15612
  /** used to indicate whether the browser is currently waiting to reconnect */
15615
15613
  this.isWaitingForNetworkReconnect = false;
@@ -15826,6 +15824,7 @@ var ElevenLabsClient = (function(exports) {
15826
15824
  this.removeAllListeners();
15827
15825
  this.deregisterOnLineListener();
15828
15826
  this.clearPendingReconnect();
15827
+ this.cleanupLossyDataStats();
15829
15828
  yield this.cleanupPeerConnections();
15830
15829
  yield this.cleanupClient();
15831
15830
  } finally {
@@ -15861,6 +15860,15 @@ var ElevenLabsClient = (function(exports) {
15861
15860
  this.reliableReceivedState.clear();
15862
15861
  });
15863
15862
  }
15863
+ cleanupLossyDataStats() {
15864
+ this.lossyDataStatByterate = 0;
15865
+ this.lossyDataStatCurrentBytes = 0;
15866
+ if (this.lossyDataStatInterval) {
15867
+ clearInterval(this.lossyDataStatInterval);
15868
+ this.lossyDataStatInterval = void 0;
15869
+ }
15870
+ this.lossyDataDropCount = 0;
15871
+ }
15864
15872
  cleanupClient() {
15865
15873
  return __awaiter(this, void 0, void 0, function* () {
15866
15874
  yield this.client.close();
@@ -15872,7 +15880,7 @@ var ElevenLabsClient = (function(exports) {
15872
15880
  return new Promise((resolve, reject) => {
15873
15881
  const publicationTimeout = setTimeout(() => {
15874
15882
  delete this.pendingTrackResolvers[req.cid];
15875
- reject(new ConnectionError("publication of local track timed out, no response from server", ConnectionErrorReason.Timeout));
15883
+ reject(ConnectionError.timeout("publication of local track timed out, no response from server"));
15876
15884
  }, 1e4);
15877
15885
  this.pendingTrackResolvers[req.cid] = {
15878
15886
  resolve: (info) => {
@@ -16110,6 +16118,16 @@ var ElevenLabsClient = (function(exports) {
16110
16118
  this.reliableDC.bufferedAmountLowThreshold = 65535;
16111
16119
  this.lossyDC.onbufferedamountlow = this.handleBufferedAmountLow;
16112
16120
  this.reliableDC.onbufferedamountlow = this.handleBufferedAmountLow;
16121
+ this.cleanupLossyDataStats();
16122
+ this.lossyDataStatInterval = setInterval(() => {
16123
+ this.lossyDataStatByterate = this.lossyDataStatCurrentBytes;
16124
+ this.lossyDataStatCurrentBytes = 0;
16125
+ const dc = this.dataChannelForKind(DataPacket_Kind.LOSSY);
16126
+ if (dc) {
16127
+ const threshold = this.lossyDataStatByterate / 10;
16128
+ dc.bufferedAmountLowThreshold = Math.min(Math.max(threshold, lossyDataChannelBufferThresholdMin), lossyDataChannelBufferThresholdMax);
16129
+ }
16130
+ }, 1e3);
16113
16131
  }
16114
16132
  createSender(track, opts, encodings) {
16115
16133
  return __awaiter(this, void 0, void 0, function* () {
@@ -16303,7 +16321,7 @@ var ElevenLabsClient = (function(exports) {
16303
16321
  this.pcState = PCState.Connected;
16304
16322
  } catch (e) {
16305
16323
  this.pcState = PCState.Disconnected;
16306
- throw new ConnectionError("could not establish PC connection, ".concat(e.message), ConnectionErrorReason.InternalError);
16324
+ throw ConnectionError.internal("could not establish PC connection, ".concat(e.message));
16307
16325
  }
16308
16326
  });
16309
16327
  }
@@ -16366,13 +16384,22 @@ var ElevenLabsClient = (function(exports) {
16366
16384
  this.reliableDataSequence += 1;
16367
16385
  }
16368
16386
  const msg = packet.toBinary();
16369
- yield this.waitForBufferStatusLow(kind);
16370
16387
  const dc = this.dataChannelForKind(kind);
16371
16388
  if (dc) {
16372
- if (kind === DataPacket_Kind.RELIABLE) this.reliableMessageBuffer.push({
16373
- data: msg,
16374
- sequence: packet.sequence
16375
- });
16389
+ if (kind === DataPacket_Kind.RELIABLE) {
16390
+ yield this.waitForBufferStatusLow(kind);
16391
+ this.reliableMessageBuffer.push({
16392
+ data: msg,
16393
+ sequence: packet.sequence
16394
+ });
16395
+ } else {
16396
+ if (!this.isBufferStatusLow(kind)) {
16397
+ this.lossyDataDropCount += 1;
16398
+ if (this.lossyDataDropCount % 100 === 0) this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount), this.logContext);
16399
+ return;
16400
+ }
16401
+ this.lossyDataStatCurrentBytes += msg.byteLength;
16402
+ }
16376
16403
  if (this.attemptingReconnect) return;
16377
16404
  dc.send(msg);
16378
16405
  }
@@ -16416,7 +16443,7 @@ var ElevenLabsClient = (function(exports) {
16416
16443
  if (!_this2.pcManager) throw new UnexpectedConnectionState("PC manager is closed");
16417
16444
  const transport = subscriber ? _this2.pcManager.subscriber : _this2.pcManager.publisher;
16418
16445
  const transportName = subscriber ? "Subscriber" : "Publisher";
16419
- if (!transport) throw new ConnectionError("".concat(transportName, " connection not set"), ConnectionErrorReason.InternalError);
16446
+ if (!transport) throw ConnectionError.internal("".concat(transportName, " connection not set"));
16420
16447
  let needNegotiation = false;
16421
16448
  if (!subscriber && !_this2.dataChannelForKind(kind, subscriber)) {
16422
16449
  _this2.createDataChannels();
@@ -16433,7 +16460,7 @@ var ElevenLabsClient = (function(exports) {
16433
16460
  if (transport.isICEConnected && ((_a = _this2.dataChannelForKind(kind, subscriber)) === null || _a === void 0 ? void 0 : _a.readyState) === "open") return;
16434
16461
  yield sleep(50);
16435
16462
  }
16436
- throw new ConnectionError("could not establish ".concat(transportName, " connection, state: ").concat(transport.getICEConnectionState()), ConnectionErrorReason.InternalError);
16463
+ throw ConnectionError.internal("could not establish ".concat(transportName, " connection, state: ").concat(transport.getICEConnectionState()));
16437
16464
  }();
16438
16465
  });
16439
16466
  }
@@ -16595,7 +16622,6 @@ var ElevenLabsClient = (function(exports) {
16595
16622
  }
16596
16623
  }
16597
16624
  };
16598
- var SignalReconnectError = class extends Error {};
16599
16625
  function supportOptionalDatachannel(protocol) {
16600
16626
  return protocol !== void 0 && protocol > 13;
16601
16627
  }
@@ -17091,7 +17117,6 @@ var ElevenLabsClient = (function(exports) {
17091
17117
  }
17092
17118
  /**
17093
17119
  * @internal
17094
- * @experimental CAUTION, might get removed in a minor release
17095
17120
  */
17096
17121
  streamText(options) {
17097
17122
  return __awaiter(this, void 0, void 0, function* () {
@@ -17994,12 +18019,6 @@ var ElevenLabsClient = (function(exports) {
17994
18019
  } else return [];
17995
18020
  }
17996
18021
  };
17997
- /**
17998
- * Creates a local video and audio track at the same time. When acquiring both
17999
- * audio and video tracks together, it'll display a single permission prompt to
18000
- * the user instead of two separate ones.
18001
- * @param options
18002
- */
18003
18022
  function createLocalTracks(options, loggerOptions) {
18004
18023
  return __awaiter(this, void 0, void 0, function* () {
18005
18024
  options !== null && options !== void 0 || (options = {});
@@ -19493,7 +19512,7 @@ var ElevenLabsClient = (function(exports) {
19493
19512
  resolve: (responsePayload, responseError) => {
19494
19513
  clearTimeout(responseTimeoutId);
19495
19514
  if (this.pendingAcks.has(id)) {
19496
- console.warn("RPC response received before ack", id);
19515
+ this.log.warn("RPC response received before ack", id);
19497
19516
  this.pendingAcks.delete(id);
19498
19517
  clearTimeout(ackTimeoutId);
19499
19518
  }
@@ -20130,7 +20149,7 @@ var ElevenLabsClient = (function(exports) {
20130
20149
  return this.connectFuture.promise;
20131
20150
  }
20132
20151
  this.setAndEmitConnectionState(ConnectionState.Connecting);
20133
- if (((_a = this.regionUrlProvider) === null || _a === void 0 ? void 0 : _a.getServerUrl().toString()) !== url) {
20152
+ if (((_a = this.regionUrlProvider) === null || _a === void 0 ? void 0 : _a.getServerUrl().toString()) !== ensureTrailingSlash(url)) {
20134
20153
  this.regionUrl = void 0;
20135
20154
  this.regionUrlProvider = void 0;
20136
20155
  }
@@ -20152,7 +20171,7 @@ var ElevenLabsClient = (function(exports) {
20152
20171
  unlockDisconnect === null || unlockDisconnect === void 0 || unlockDisconnect();
20153
20172
  try {
20154
20173
  yield BackOffStrategy.getInstance().getBackOffPromise(url);
20155
- if (abortController.signal.aborted) throw new ConnectionError("Connection attempt aborted", ConnectionErrorReason.Cancelled);
20174
+ if (abortController.signal.aborted) throw ConnectionError.cancelled("Connection attempt aborted");
20156
20175
  yield this.attemptConnection(regionUrl !== null && regionUrl !== void 0 ? regionUrl : url, token, opts, abortController);
20157
20176
  this.abortController = void 0;
20158
20177
  resolve();
@@ -20265,7 +20284,7 @@ var ElevenLabsClient = (function(exports) {
20265
20284
  } catch (err) {
20266
20285
  yield this.engine.close();
20267
20286
  this.recreateEngine();
20268
- const resultingError = new ConnectionError("could not establish signal connection", abortController.signal.aborted ? ConnectionErrorReason.Cancelled : ConnectionErrorReason.ServerUnreachable);
20287
+ const resultingError = abortController.signal.aborted ? ConnectionError.cancelled("Signal connection aborted") : ConnectionError.serverUnreachable("could not establish signal connection");
20269
20288
  if (err instanceof Error) resultingError.message = "".concat(resultingError.message, ": ").concat(err.message);
20270
20289
  if (err instanceof ConnectionError) {
20271
20290
  resultingError.reason = err.reason;
@@ -20277,7 +20296,7 @@ var ElevenLabsClient = (function(exports) {
20277
20296
  if (abortController.signal.aborted) {
20278
20297
  yield this.engine.close();
20279
20298
  this.recreateEngine();
20280
- throw new ConnectionError("Connection attempt aborted", ConnectionErrorReason.Cancelled);
20299
+ throw ConnectionError.cancelled("Connection attempt aborted");
20281
20300
  }
20282
20301
  try {
20283
20302
  yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout, abortController);
@@ -20290,7 +20309,7 @@ var ElevenLabsClient = (function(exports) {
20290
20309
  window.addEventListener("pagehide", this.onPageLeave);
20291
20310
  window.addEventListener("beforeunload", this.onPageLeave);
20292
20311
  }
20293
- if (isWeb()) document.addEventListener("freeze", this.onPageLeave);
20312
+ if (isWeb()) window.addEventListener("freeze", this.onPageLeave);
20294
20313
  this.setAndEmitConnectionState(ConnectionState.Connected);
20295
20314
  this.emit(RoomEvent.Connected);
20296
20315
  BackOffStrategy.getInstance().resetFailedConnectionAttempts(url);
@@ -20318,7 +20337,7 @@ var ElevenLabsClient = (function(exports) {
20318
20337
  const msg = "Abort connection attempt due to user initiated disconnect";
20319
20338
  _this2.log.warn(msg, _this2.logContext);
20320
20339
  (_a = _this2.abortController) === null || _a === void 0 || _a.abort(msg);
20321
- (_c = (_b = _this2.connectFuture) === null || _b === void 0 ? void 0 : _b.reject) === null || _c === void 0 || _c.call(_b, new ConnectionError("Client initiated disconnect", ConnectionErrorReason.Cancelled));
20340
+ (_c = (_b = _this2.connectFuture) === null || _b === void 0 ? void 0 : _b.reject) === null || _c === void 0 || _c.call(_b, ConnectionError.cancelled("Client initiated disconnect"));
20322
20341
  _this2.connectFuture = void 0;
20323
20342
  }
20324
20343
  if (_this2.engine) {
@@ -21296,12 +21315,12 @@ var ElevenLabsClient = (function(exports) {
21296
21315
  });
21297
21316
  if (byteLength(response) > MAX_PAYLOAD_BYTES) {
21298
21317
  responseError = RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE");
21299
- console.warn("RPC Response payload too large for ".concat(method));
21318
+ this.log.warn("RPC Response payload too large for ".concat(method));
21300
21319
  } else responsePayload = response;
21301
21320
  } catch (error) {
21302
21321
  if (error instanceof RpcError) responseError = error;
21303
21322
  else {
21304
- console.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
21323
+ this.log.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
21305
21324
  responseError = RpcError.builtIn("APPLICATION_ERROR");
21306
21325
  }
21307
21326
  }
@@ -22154,7 +22173,7 @@ registerProcessor("rawAudioProcessor", RawAudioProcessor);
22154
22173
  throw new Error(`Failed to fetch conversation token for agent ${config.agentId}: ${msg}`);
22155
22174
  }
22156
22175
  else throw new Error("Either conversationToken or agentId is required for WebRTC connection");
22157
- const room = new Room();
22176
+ const room = new Room({ singlePeerConnection: false });
22158
22177
  try {
22159
22178
  const connection = new WebRTCConnection(room, `room_${Date.now()}`, parseFormat("pcm_48000"), parseFormat("pcm_48000"), config);
22160
22179
  const livekitUrl = config.livekitUrl || DEFAULT_LIVEKIT_WS_URL;