@twilio/voice-sdk
Version:
Twilio's JavaScript Voice SDK
1 lines • 299 kB
JavaScript
(function(root){var bundle=function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TwilioError=exports.Logger=exports.PreflightTest=exports.Device=exports.Call=void 0;var call_1=require("./twilio/call");exports.Call=call_1.default;var device_1=require("./twilio/device");exports.Device=device_1.default;var log_1=require("./twilio/log");Object.defineProperty(exports,"Logger",{enumerable:true,get:function(){return log_1.Logger}});var preflight_1=require("./twilio/preflight/preflight");Object.defineProperty(exports,"PreflightTest",{enumerable:true,get:function(){return preflight_1.PreflightTest}});var TwilioError=require("./twilio/errors");exports.TwilioError=TwilioError},{"./twilio/call":9,"./twilio/device":12,"./twilio/errors":15,"./twilio/log":18,"./twilio/preflight/preflight":20}],2:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return g.next=verb(0),g["throw"]=verb(1),g["return"]=verb(2),typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});exports.AsyncQueue=void 0;var deferred_1=require("./deferred");var AsyncQueue=function(){function AsyncQueue(){this._operations=[]}AsyncQueue.prototype.enqueue=function(callback){var hasPending=!!this._operations.length;var deferred=new deferred_1.default;this._operations.push({deferred:deferred,callback:callback});if(!hasPending){this._processQueue()}return deferred.promise};AsyncQueue.prototype._processQueue=function(){return __awaiter(this,void 0,void 0,function(){var _a,deferred,callback,result,error,hasResolved,e_1;return __generator(this,function(_b){switch(_b.label){case 0:if(!this._operations.length)return[3,5];_a=this._operations[0],deferred=_a.deferred,callback=_a.callback;result=void 0;error=void 0;hasResolved=void 0;_b.label=1;case 1:_b.trys.push([1,3,,4]);return[4,callback()];case 2:result=_b.sent();hasResolved=true;return[3,4];case 3:e_1=_b.sent();error=e_1;return[3,4];case 4:this._operations.shift();if(hasResolved){deferred.resolve(result)}else{deferred.reject(error)}return[3,0];case 5:return[2]}})})};return AsyncQueue}();exports.AsyncQueue=AsyncQueue},{"./deferred":11}],3:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return g.next=verb(0),g["throw"]=verb(1),g["return"]=verb(2),typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});var events_1=require("events");var device_1=require("./device");var errors_1=require("./errors");var log_1=require("./log");var outputdevicecollection_1=require("./outputdevicecollection");var mediadeviceinfo_1=require("./shims/mediadeviceinfo");var util_1=require("./util");var kindAliases={audioinput:"Audio Input",audiooutput:"Audio Output"};var AudioHelper=function(_super){__extends(AudioHelper,_super);function AudioHelper(onActiveOutputsChanged,onActiveInputChanged,options){var _a;var _this=_super.call(this)||this;_this.availableInputDevices=new Map;_this.availableOutputDevices=new Map;_this._audioConstraints=null;_this._defaultInputDeviceStream=null;_this._enabledSounds=(_a={},_a[device_1.default.SoundName.Disconnect]=true,_a[device_1.default.SoundName.Incoming]=true,_a[device_1.default.SoundName.Outgoing]=true,_a);_this._inputDevice=null;_this._inputDevicePromise=null;_this._isPollingInputVolume=false;_this._log=new log_1.default("AudioHelper");_this._processedStream=null;_this._selectedInputDeviceStream=null;_this._unknownDeviceIndexes={audioinput:{},audiooutput:{}};_this._updateAvailableDevices=function(){if(!_this._mediaDevices||!_this._enumerateDevices){return Promise.reject("Enumeration not supported")}return _this._enumerateDevices().then(function(devices){_this._updateDevices(devices.filter(function(d){return d.kind==="audiooutput"}),_this.availableOutputDevices,_this._removeLostOutput);_this._updateDevices(devices.filter(function(d){return d.kind==="audioinput"}),_this.availableInputDevices,_this._removeLostInput);var defaultDevice=_this.availableOutputDevices.get("default")||Array.from(_this.availableOutputDevices.values())[0];[_this.speakerDevices,_this.ringtoneDevices].forEach(function(outputDevices){if(!outputDevices.get().size&&_this.availableOutputDevices.size&&_this.isOutputSelectionSupported){outputDevices.set(defaultDevice.deviceId).catch(function(reason){_this._log.warn("Unable to set audio output devices. ".concat(reason))})}})})};_this._removeLostInput=function(lostDevice){if(!_this.inputDevice||_this.inputDevice.deviceId!==lostDevice.deviceId){return false}_this._destroyProcessedStream();_this._replaceStream(null);_this._inputDevice=null;_this._maybeStopPollingVolume();var defaultDevice=_this.availableInputDevices.get("default")||Array.from(_this.availableInputDevices.values())[0];if(defaultDevice){_this.setInputDevice(defaultDevice.deviceId)}return true};_this._removeLostOutput=function(lostDevice){var wasSpeakerLost=_this.speakerDevices.delete(lostDevice);var wasRingtoneLost=_this.ringtoneDevices.delete(lostDevice);return wasSpeakerLost||wasRingtoneLost};options=Object.assign({AudioContext:typeof AudioContext!=="undefined"&&AudioContext,setSinkId:typeof HTMLAudioElement!=="undefined"&&HTMLAudioElement.prototype.setSinkId},options);_this._beforeSetInputDevice=options.beforeSetInputDevice||function(){return Promise.resolve()};_this._updateUserOptions(options);_this._audioProcessorEventObserver=options.audioProcessorEventObserver;_this._mediaDevices=options.mediaDevices||navigator.mediaDevices;_this._onActiveInputChanged=onActiveInputChanged;_this._enumerateDevices=typeof options.enumerateDevices==="function"?options.enumerateDevices:_this._mediaDevices&&_this._mediaDevices.enumerateDevices.bind(_this._mediaDevices);var isAudioContextSupported=!!(options.AudioContext||options.audioContext);var isEnumerationSupported=!!_this._enumerateDevices;if(options.enabledSounds){_this._enabledSounds=options.enabledSounds}var isSetSinkSupported=typeof options.setSinkId==="function";_this.isOutputSelectionSupported=isEnumerationSupported&&isSetSinkSupported;_this.isVolumeSupported=isAudioContextSupported;if(_this.isVolumeSupported){_this._audioContext=options.audioContext||options.AudioContext&&new options.AudioContext;if(_this._audioContext){_this._inputVolumeAnalyser=_this._audioContext.createAnalyser();_this._inputVolumeAnalyser.fftSize=32;_this._inputVolumeAnalyser.smoothingTimeConstant=.3}}_this.ringtoneDevices=new outputdevicecollection_1.default("ringtone",_this.availableOutputDevices,onActiveOutputsChanged,_this.isOutputSelectionSupported);_this.speakerDevices=new outputdevicecollection_1.default("speaker",_this.availableOutputDevices,onActiveOutputsChanged,_this.isOutputSelectionSupported);_this.addListener("newListener",function(eventName){if(eventName==="inputVolume"){_this._maybeStartPollingVolume()}});_this.addListener("removeListener",function(eventName){if(eventName==="inputVolume"){_this._maybeStopPollingVolume()}});_this.once("newListener",function(){if(!_this.isOutputSelectionSupported){_this._log.warn("Warning: This browser does not support audio output selection.")}if(!_this.isVolumeSupported){_this._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}});if(isEnumerationSupported){_this._initializeEnumeration()}if(navigator&&navigator.permissions&&typeof navigator.permissions.query==="function"){navigator.permissions.query({name:"microphone"}).then(function(microphonePermissionStatus){if(microphonePermissionStatus.state!=="granted"){var handleStateChange=function(){_this._updateAvailableDevices();_this._stopMicrophonePermissionListener()};microphonePermissionStatus.addEventListener("change",handleStateChange);_this._microphonePermissionStatus=microphonePermissionStatus;_this._onMicrophonePermissionStatusChanged=handleStateChange}}).catch(function(reason){return _this._log.warn("Warning: unable to listen for microphone permission changes. ".concat(reason))})}else{_this._log.warn("Warning: current browser does not support permissions API.")}return _this}Object.defineProperty(AudioHelper.prototype,"audioConstraints",{get:function(){return this._audioConstraints},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"inputDevice",{get:function(){return this._inputDevice},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"inputStream",{get:function(){return this._processedStream||this._selectedInputDeviceStream},enumerable:false,configurable:true});Object.defineProperty(AudioHelper.prototype,"processedStream",{get:function(){return this._processedStream},enumerable:false,configurable:true});AudioHelper.prototype._destroy=function(){this._stopDefaultInputDeviceStream();this._stopSelectedInputDeviceStream();this._destroyProcessedStream();this._maybeStopPollingVolume();this.removeAllListeners();this._stopMicrophonePermissionListener();this._unbind()};AudioHelper.prototype._getInputDevicePromise=function(){return this._inputDevicePromise};AudioHelper.prototype._maybeStartPollingVolume=function(){var _this=this;if(!this.isVolumeSupported||!this.inputStream){return}this._updateVolumeSource();if(this._isPollingInputVolume||!this._inputVolumeAnalyser){return}var bufferLength=this._inputVolumeAnalyser.frequencyBinCount;var buffer=new Uint8Array(bufferLength);this._isPollingInputVolume=true;var emitVolume=function(){if(!_this._isPollingInputVolume){return}if(_this._inputVolumeAnalyser){_this._inputVolumeAnalyser.getByteFrequencyData(buffer);var inputVolume=(0,util_1.average)(buffer);_this.emit("inputVolume",inputVolume/255)}requestAnimationFrame(emitVolume)};requestAnimationFrame(emitVolume)};AudioHelper.prototype._maybeStopPollingVolume=function(){if(!this.isVolumeSupported){return}if(!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")){return}if(this._inputVolumeSource){this._inputVolumeSource.disconnect();delete this._inputVolumeSource}this._isPollingInputVolume=false};AudioHelper.prototype._openDefaultDeviceWithConstraints=function(constraints){var _this=this;this._log.info("Opening default device with constraints",constraints);return this._getUserMedia(constraints).then(function(stream){_this._log.info("Opened default device. Updating available devices.");_this._updateAvailableDevices().catch(function(error){_this._log.warn("Unable to updateAvailableDevices after gUM call",error)});_this._defaultInputDeviceStream=stream;return _this._maybeCreateProcessedStream(stream)})};AudioHelper.prototype._stopDefaultInputDeviceStream=function(){if(this._defaultInputDeviceStream){this._log.info("stopping default device stream");this._defaultInputDeviceStream.getTracks().forEach(function(track){return track.stop()});this._defaultInputDeviceStream=null;this._destroyProcessedStream()}};AudioHelper.prototype._unbind=function(){var _a;if((_a=this._mediaDevices)===null||_a===void 0?void 0:_a.removeEventListener){this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)}};AudioHelper.prototype._updateUserOptions=function(options){if(typeof options.enumerateDevices==="function"){this._enumerateDevices=options.enumerateDevices}if(typeof options.getUserMedia==="function"){this._getUserMedia=options.getUserMedia}};AudioHelper.prototype.addProcessor=function(processor){this._log.debug(".addProcessor");if(this._processor){throw new errors_1.NotSupportedError("Adding multiple AudioProcessors is not supported at this time.")}if(typeof processor!=="object"||processor===null){throw new errors_1.InvalidArgumentError("Missing AudioProcessor argument.")}if(typeof processor.createProcessedStream!=="function"){throw new errors_1.InvalidArgumentError("Missing createProcessedStream() method.")}if(typeof processor.destroyProcessedStream!=="function"){throw new errors_1.InvalidArgumentError("Missing destroyProcessedStream() method.")}this._processor=processor;this._audioProcessorEventObserver.emit("add");return this._restartStreams()};AudioHelper.prototype.disconnect=function(doEnable){this._log.debug(".disconnect",doEnable);return this._maybeEnableSound(device_1.default.SoundName.Disconnect,doEnable)};AudioHelper.prototype.incoming=function(doEnable){this._log.debug(".incoming",doEnable);return this._maybeEnableSound(device_1.default.SoundName.Incoming,doEnable)};AudioHelper.prototype.outgoing=function(doEnable){this._log.debug(".outgoing",doEnable);return this._maybeEnableSound(device_1.default.SoundName.Outgoing,doEnable)};AudioHelper.prototype.removeProcessor=function(processor){this._log.debug(".removeProcessor");if(typeof processor!=="object"||processor===null){throw new errors_1.InvalidArgumentError("Missing AudioProcessor argument.")}if(this._processor!==processor){throw new errors_1.InvalidArgumentError("Cannot remove an AudioProcessor that has not been previously added.")}this._destroyProcessedStream();this._processor=null;this._audioProcessorEventObserver.emit("remove");return this._restartStreams()};AudioHelper.prototype.setAudioConstraints=function(audioConstraints){this._log.debug(".setAudioConstraints",audioConstraints);this._audioConstraints=Object.assign({},audioConstraints);delete this._audioConstraints.deviceId;return this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,true):Promise.resolve()};AudioHelper.prototype.setInputDevice=function(deviceId){this._log.debug(".setInputDevice",deviceId);return this._setInputDevice(deviceId,false)};AudioHelper.prototype.unsetAudioConstraints=function(){this._log.debug(".unsetAudioConstraints");this._audioConstraints=null;return this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,true):Promise.resolve()};AudioHelper.prototype.unsetInputDevice=function(){var _this=this;this._log.debug(".unsetInputDevice",this.inputDevice);if(!this.inputDevice){return Promise.resolve()}this._destroyProcessedStream();return this._onActiveInputChanged(null).then(function(){_this._replaceStream(null);_this._inputDevice=null;_this._maybeStopPollingVolume()})};AudioHelper.prototype._destroyProcessedStream=function(){if(this._processor&&this._processedStream){this._log.info("destroying processed stream");var processedStream=this._processedStream;this._processedStream.getTracks().forEach(function(track){return track.stop()});this._processedStream=null;this._processor.destroyProcessedStream(processedStream);this._audioProcessorEventObserver.emit("destroy")}};AudioHelper.prototype._getUnknownDeviceIndex=function(mediaDeviceInfo){var id=mediaDeviceInfo.deviceId;var kind=mediaDeviceInfo.kind;var index=this._unknownDeviceIndexes[kind][id];if(!index){index=Object.keys(this._unknownDeviceIndexes[kind]).length+1;this._unknownDeviceIndexes[kind][id]=index}return index};AudioHelper.prototype._initializeEnumeration=function(){var _this=this;if(!this._mediaDevices||!this._enumerateDevices){throw new errors_1.NotSupportedError("Enumeration is not supported")}if(this._mediaDevices.addEventListener){this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices)}this._updateAvailableDevices().then(function(){if(!_this.isOutputSelectionSupported){return}Promise.all([_this.speakerDevices.set("default"),_this.ringtoneDevices.set("default")]).catch(function(reason){_this._log.warn("Warning: Unable to set audio output devices. ".concat(reason))})})};AudioHelper.prototype._maybeCreateProcessedStream=function(stream){var _this=this;if(this._processor){this._log.info("Creating processed stream");return this._processor.createProcessedStream(stream).then(function(processedStream){_this._processedStream=processedStream;_this._audioProcessorEventObserver.emit("create");return _this._processedStream})}return Promise.resolve(stream)};AudioHelper.prototype._maybeEnableSound=function(soundName,doEnable){if(typeof doEnable!=="undefined"){this._enabledSounds[soundName]=doEnable}return this._enabledSounds[soundName]};AudioHelper.prototype._replaceStream=function(stream){this._log.info("Replacing with new stream.");if(this._selectedInputDeviceStream){this._log.info("Old stream detected. Stopping tracks.");this._stopSelectedInputDeviceStream()}this._selectedInputDeviceStream=stream};AudioHelper.prototype._restartStreams=function(){if(this.inputDevice&&this._selectedInputDeviceStream){this._log.info("Restarting selected input device");return this._setInputDevice(this.inputDevice.deviceId,true)}if(this._defaultInputDeviceStream){var defaultDevice=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];this._log.info("Restarting default input device, now becoming selected.");return this._setInputDevice(defaultDevice.deviceId,true)}return Promise.resolve()};AudioHelper.prototype._setInputDevice=function(deviceId,forceGetUserMedia){return __awaiter(this,void 0,void 0,function(){var setInputDevice;var _this=this;return __generator(this,function(_a){setInputDevice=function(){return __awaiter(_this,void 0,void 0,function(){var device,constraints;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:return[4,this._beforeSetInputDevice()];case 1:_a.sent();if(typeof deviceId!=="string"){return[2,Promise.reject(new errors_1.InvalidArgumentError("Must specify the device to set"))]}device=this.availableInputDevices.get(deviceId);if(!device){return[2,Promise.reject(new errors_1.InvalidArgumentError("Device not found: ".concat(deviceId)))]}this._log.info("Setting input device. ID: "+deviceId);if(this._inputDevice&&this._inputDevice.deviceId===deviceId&&this._selectedInputDeviceStream){if(!forceGetUserMedia){return[2,Promise.resolve()]}this._log.info("Same track detected on setInputDevice, stopping old tracks.");this._stopSelectedInputDeviceStream()}this._stopDefaultInputDeviceStream();constraints={audio:Object.assign({deviceId:{exact:deviceId}},this.audioConstraints)};this._log.info("setInputDevice: getting new tracks.");return[2,this._getUserMedia(constraints).then(function(originalStream){_this._destroyProcessedStream();return _this._maybeCreateProcessedStream(originalStream).then(function(newStream){_this._log.info("setInputDevice: invoking _onActiveInputChanged.");return _this._onActiveInputChanged(newStream).then(function(){_this._replaceStream(originalStream);_this._inputDevice=device;_this._maybeStartPollingVolume()})})})]}})})};return[2,this._inputDevicePromise=setInputDevice().finally(function(){_this._inputDevicePromise=null})]})})};AudioHelper.prototype._stopMicrophonePermissionListener=function(){var _a;if((_a=this._microphonePermissionStatus)===null||_a===void 0?void 0:_a.removeEventListener){this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)}};AudioHelper.prototype._stopSelectedInputDeviceStream=function(){if(this._selectedInputDeviceStream){this._log.info("Stopping selected device stream");this._selectedInputDeviceStream.getTracks().forEach(function(track){return track.stop()})}};AudioHelper.prototype._updateDevices=function(updatedDevices,availableDevices,removeLostDevice){var _this=this;var updatedDeviceIds=updatedDevices.map(function(d){return d.deviceId});var knownDeviceIds=Array.from(availableDevices.values()).map(function(d){return d.deviceId});var lostActiveDevices=[];var lostDeviceIds=(0,util_1.difference)(knownDeviceIds,updatedDeviceIds);lostDeviceIds.forEach(function(lostDeviceId){var lostDevice=availableDevices.get(lostDeviceId);if(lostDevice){availableDevices.delete(lostDeviceId);if(removeLostDevice(lostDevice)){lostActiveDevices.push(lostDevice)}}});var deviceChanged=false;updatedDevices.forEach(function(newDevice){var existingDevice=availableDevices.get(newDevice.deviceId);var newMediaDeviceInfo=_this._wrapMediaDeviceInfo(newDevice);if(!existingDevice||existingDevice.label!==newMediaDeviceInfo.label){availableDevices.set(newDevice.deviceId,newMediaDeviceInfo);deviceChanged=true}});if(deviceChanged||lostDeviceIds.length){var defaultId_1="default";var isInputDeviceSet=this.inputDevice&&this.inputDevice.deviceId===defaultId_1;var isDefaultDeviceSet=this._defaultInputDeviceStream&&this.availableInputDevices.get(defaultId_1);if(isInputDeviceSet||isDefaultDeviceSet){this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale.");setTimeout(function(){_this._setInputDevice(defaultId_1,true)},0)}this._log.debug("#deviceChange",lostActiveDevices);this.emit("deviceChange",lostActiveDevices)}};AudioHelper.prototype._updateVolumeSource=function(){if(!this.inputStream||!this._audioContext||!this._inputVolumeAnalyser){return}if(this._inputVolumeSource){this._inputVolumeSource.disconnect()}try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream);this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(ex){this._log.warn("Unable to update volume source",ex);delete this._inputVolumeSource}};AudioHelper.prototype._wrapMediaDeviceInfo=function(mediaDeviceInfo){var options={deviceId:mediaDeviceInfo.deviceId,groupId:mediaDeviceInfo.groupId,kind:mediaDeviceInfo.kind,label:mediaDeviceInfo.label};if(!options.label){if(options.deviceId==="default"){options.label="Default"}else{var index=this._getUnknownDeviceIndex(mediaDeviceInfo);options.label="Unknown ".concat(kindAliases[options.kind]," Device ").concat(index)}}return new mediadeviceinfo_1.default(options)};return AudioHelper}(events_1.EventEmitter);(function(AudioHelper){})(AudioHelper||(AudioHelper={}));exports.default=AudioHelper},{"./device":12,"./errors":15,"./log":18,"./outputdevicecollection":19,"./shims/mediadeviceinfo":33,"./util":37,events:39}],4:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return g.next=verb(0),g["throw"]=verb(1),g["return"]=verb(2),typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});var deferred_1=require("./deferred");var eventtarget_1=require("./eventtarget");var AudioPlayer=function(_super){__extends(AudioPlayer,_super);function AudioPlayer(audioContext,srcOrOptions,options){if(srcOrOptions===void 0){srcOrOptions={}}if(options===void 0){options={}}var _this=_super.call(this)||this;_this._audioNode=null;_this._loop=false;_this._pendingPlayDeferreds=[];_this._sinkId="default";_this._src="";if(typeof srcOrOptions!=="string"){options=srcOrOptions}_this._audioContext=audioContext;_this._audioElement=new(options.AudioFactory||Audio);_this._bufferPromise=_this._createPlayDeferred().promise;_this._destination=_this._audioContext.destination;_this._gainNode=_this._audioContext.createGain();_this._gainNode.connect(_this._destination);_this._XMLHttpRequest=options.XMLHttpRequestFactory||XMLHttpRequest;_this.addEventListener("canplaythrough",function(){_this._resolvePlayDeferreds()});if(typeof srcOrOptions==="string"){_this.src=srcOrOptions}return _this}Object.defineProperty(AudioPlayer.prototype,"destination",{get:function(){return this._destination},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"loop",{get:function(){return this._loop},set:function(shouldLoop){var self=this;function pauseAfterPlaythrough(){self._audioNode.removeEventListener("ended",pauseAfterPlaythrough);self.pause()}if(!shouldLoop&&this.loop&&!this.paused){this._audioNode.addEventListener("ended",pauseAfterPlaythrough)}this._loop=shouldLoop},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"muted",{get:function(){return this._gainNode.gain.value===0},set:function(shouldBeMuted){this._gainNode.gain.value=shouldBeMuted?0:1},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"paused",{get:function(){return this._audioNode===null},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"src",{get:function(){return this._src},set:function(src){this._load(src)},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"srcObject",{get:function(){return this._audioElement.srcObject},set:function(srcObject){this._audioElement.srcObject=srcObject},enumerable:false,configurable:true});Object.defineProperty(AudioPlayer.prototype,"sinkId",{get:function(){return this._sinkId},enumerable:false,configurable:true});AudioPlayer.prototype.load=function(){this._load(this._src)};AudioPlayer.prototype.pause=function(){if(this.paused){return}this._audioElement.pause();this._audioNode.stop();this._audioNode.disconnect(this._gainNode);this._audioNode=null;this._rejectPlayDeferreds(new Error("The play() request was interrupted by a call to pause()."))};AudioPlayer.prototype.play=function(){return __awaiter(this,void 0,void 0,function(){var buffer;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:if(!!this.paused)return[3,2];return[4,this._bufferPromise];case 1:_a.sent();if(!this.paused){return[2]}throw new Error("The play() request was interrupted by a call to pause().");case 2:this._audioNode=this._audioContext.createBufferSource();this._audioNode.loop=this.loop;this._audioNode.addEventListener("ended",function(){if(_this._audioNode&&_this._audioNode.loop){return}_this.dispatchEvent("ended")});return[4,this._bufferPromise];case 3:buffer=_a.sent();if(this.paused){throw new Error("The play() request was interrupted by a call to pause().")}this._audioNode.buffer=buffer;this._audioNode.connect(this._gainNode);this._audioNode.start();if(this._audioElement.srcObject){return[2,this._audioElement.play()]}return[2]}})})};AudioPlayer.prototype.setSinkId=function(sinkId){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(typeof this._audioElement.setSinkId!=="function"){throw new Error("This browser does not support setSinkId.")}if(sinkId===this.sinkId){return[2]}if(sinkId==="default"){if(!this.paused){this._gainNode.disconnect(this._destination)}this._audioElement.srcObject=null;this._destination=this._audioContext.destination;this._gainNode.connect(this._destination);this._sinkId=sinkId;return[2]}return[4,this._audioElement.setSinkId(sinkId)];case 1:_a.sent();if(this._audioElement.srcObject){return[2]}this._gainNode.disconnect(this._audioContext.destination);this._destination=this._audioContext.createMediaStreamDestination();this._audioElement.srcObject=this._destination.stream;this._sinkId=sinkId;this._gainNode.connect(this._destination);return[2]}})})};AudioPlayer.prototype._createPlayDeferred=function(){var deferred=new deferred_1.default;this._pendingPlayDeferreds.push(deferred);return deferred};AudioPlayer.prototype._load=function(src){var _this=this;if(this._src&&this._src!==src){this.pause()}this._src=src;this._bufferPromise=new Promise(function(resolve,reject){return __awaiter(_this,void 0,void 0,function(){var buffer;return __generator(this,function(_a){switch(_a.label){case 0:if(!src){return[2,this._createPlayDeferred().promise]}return[4,bufferSound(this._audioContext,this._XMLHttpRequest,src)];case 1:buffer=_a.sent();this.dispatchEvent("canplaythrough");resolve(buffer);return[2]}})})})};AudioPlayer.prototype._rejectPlayDeferreds=function(reason){var deferreds=this._pendingPlayDeferreds;deferreds.splice(0,deferreds.length).forEach(function(_a){var reject=_a.reject;return reject(reason)})};AudioPlayer.prototype._resolvePlayDeferreds=function(result){var deferreds=this._pendingPlayDeferreds;deferreds.splice(0,deferreds.length).forEach(function(_a){var resolve=_a.resolve;return resolve(result)})};return AudioPlayer}(eventtarget_1.default);function bufferSound(context,RequestFactory,src){return __awaiter(this,void 0,void 0,function(){var request,event;return __generator(this,function(_a){switch(_a.label){case 0:request=new RequestFactory;request.open("GET",src,true);request.responseType="arraybuffer";return[4,new Promise(function(resolve){request.addEventListener("load",resolve);request.send()})];case 1:event=_a.sent();try{return[2,context.decodeAudioData(event.target.response)]}catch(e){return[2,new Promise(function(resolve){context.decodeAudioData(event.target.response,resolve)})]}return[2]}})})}exports.default=AudioPlayer},{"./deferred":5,"./eventtarget":6}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var Deferred=function(){function Deferred(){var _this=this;this.promise=new Promise(function(resolve,reject){_this._resolve=resolve;_this._reject=reject})}Object.defineProperty(Deferred.prototype,"reject",{get:function(){return this._reject},enumerable:false,configurable:true});Object.defineProperty(Deferred.prototype,"resolve",{get:function(){return this._resolve},enumerable:false,configurable:true});return Deferred}();exports.default=Deferred},{}],6:[function(require,module,exports){"use strict";var __spreadArray=this&&this.__spreadArray||function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l=from.length,ar;i<l;i++){if(ar||!(i in from)){if(!ar)ar=Array.prototype.slice.call(from,0,i);ar[i]=from[i]}}return to.concat(ar||Array.prototype.slice.call(from))};Object.defineProperty(exports,"__esModule",{value:true});var events_1=require("events");var EventTarget=function(){function EventTarget(){this._eventEmitter=new events_1.EventEmitter}EventTarget.prototype.addEventListener=function(name,handler){return this._eventEmitter.addListener(name,handler)};EventTarget.prototype.dispatchEvent=function(name){var _a;var args=[];for(var _i=1;_i<arguments.length;_i++){args[_i-1]=arguments[_i]}return(_a=this._eventEmitter).emit.apply(_a,__spreadArray([name],args,false))};EventTarget.prototype.removeEventListener=function(name,handler){return this._eventEmitter.removeListener(name,handler)};return EventTarget}();exports.default=EventTarget},{events:39}],7:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});exports.AudioProcessorEventObserver=void 0;var events_1=require("events");var log_1=require("./log");var AudioProcessorEventObserver=function(_super){__extends(AudioProcessorEventObserver,_super);function AudioProcessorEventObserver(){var _this=_super.call(this)||this;_this._log=new log_1.default("AudioProcessorEventObserver");_this._log.info("Creating AudioProcessorEventObserver instance");_this.on("enabled",function(){return _this._reEmitEvent("enabled")});_this.on("add",function(){return _this._reEmitEvent("add")});_this.on("remove",function(){return _this._reEmitEvent("remove")});_this.on("create",function(){return _this._reEmitEvent("create-processed-stream")});_this.on("destroy",function(){return _this._reEmitEvent("destroy-processed-stream")});return _this}AudioProcessorEventObserver.prototype.destroy=function(){this.removeAllListeners()};AudioProcessorEventObserver.prototype._reEmitEvent=function(name){this._log.info("AudioProcessor:".concat(name));this.emit("event",{name:name,group:"audio-processor"})};return AudioProcessorEventObserver}(events_1.EventEmitter);exports.AudioProcessorEventObserver=AudioProcessorEventObserver},{"./log":18,events:39}],8:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});var events_1=require("events");var Backoff=function(_super){__extends(Backoff,_super);function Backoff(options){var _this=_super.call(this)||this;Object.defineProperties(_this,{_attempts:{value:0,writable:true},_duration:{enumerable:false,get:function(){var ms=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){var rand=Math.random();var deviation=Math.floor(rand*this._jitter*ms);ms=(Math.floor(rand*10)&1)===0?ms-deviation:ms+deviation}return Math.min(ms,this._max)|0}},_factor:{value:options.factor||2},_jitter:{value:options.jitter>0&&options.jitter<=1?options.jitter:0},_max:{value:options.max||1e4},_min:{value:options.min||100},_timeoutID:{value:null,writable:true}});return _this}Backoff.prototype.backoff=function(){var _this=this;var duration=this._duration;if(this._timeoutID){clearTimeout(this._timeoutID);this._timeoutID=null}this.emit("backoff",this._attempts,duration);this._timeoutID=setTimeout(function(){_this.emit("ready",_this._attempts,duration);_this._attempts++},duration)};Backoff.prototype.reset=function(){this._attempts=0;if(this._timeoutID){clearTimeout(this._timeoutID);this._timeoutID=null}};return Backoff}(events_1.EventEmitter);exports.default=Backoff},{events:39}],9:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};Object.defineProperty(exports,"__esModule",{value:true});var events_1=require("events");var backoff_1=require("./backoff");var device_1=require("./device");var errors_1=require("./errors");var log_1=require("./log");var rtc_1=require("./rtc");var icecandidate_1=require("./rtc/icecandidate");var sdp_1=require("./rtc/sdp");var sid_1=require("./sid");var statsMonitor_1=require("./statsMonitor");var util_1=require("./util");var constants_1=require("./constants");var BACKOFF_CONFIG={factor:1.1,jitter:.5,max:3e4,min:1};var DTMF_INTER_TONE_GAP=70;var DTMF_PAUSE_DURATION=500;var DTMF_TONE_DURATION=160;var METRICS_BATCH_SIZE=10;var METRICS_DELAY=5e3;var MEDIA_DISCONNECT_ERROR={disconnect:true,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new errors_1.MediaErrors.ConnectionError}};var MULTIPLE_THRESHOLD_WARNING_NAMES={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}};var WARNING_NAMES={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"};var WARNING_PREFIXES={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"};var Call=function(_super){__extends(Call,_super);function Call(config,options){var _this=_super.call(this)||this;_this.parameters={};_this._inputVolumeStreak=0;_this._isAnswered=false;_this._isCancelled=false;_this._isRejected=false;_this._latestInputVolume=0;_this._latestOutputVolume=0;_this._log=new log_1.default("Call");_this._mediaStatus=Call.State.Pending;_this._messages=new Map;_this._metricsSamples=[];_this._options={MediaHandler:rtc_1.PeerConnection,MediaStream:null,enableImprovedSignalingErrorPrecision:false,offerSdp:null,shouldPlayDisconnect:function(){return true},voiceEventSidGenerator:sid_1.generateVoiceEventSid};_this._outputVolumeStreak=0;_this._shouldSendHangup=true;_this._signalingStatus=Call.State.Pending;_this._soundcache=new Map;_this._status=Call.State.Pending;_this._wasConnected=false;_this.toString=function(){return"[Twilio.Call instance]"};_this._emitWarning=function(groupPrefix,warningName,threshold,value,wasCleared,warningData){var groupSuffix=wasCleared?"-cleared":"-raised";var groupName="".concat(groupPrefix,"warning").concat(groupSuffix);if(warningName==="constant-audio-input-level"&&_this.isMuted()){return}var level=wasCleared?"info":"warning";if(warningName==="constant-audio-output-level"){level="info"}var payloadData={threshold:threshold};if(value){if(value instanceof Array){payloadData.values=value.map(function(val){if(typeof val==="number"){return Math.round(val*100)/100}return value})}else{payloadData.value=value}}_this._publisher.post(level,groupName,warningName,{data:payloadData},_this);if(warningName!=="constant-audio-output-level"){var emitName=wasCleared?"warning-cleared":"warning";_this._log.debug("#".concat(emitName),warningName);_this.emit(emitName,warningName,warningData&&!wasCleared?warningData:null)}};_this._onAck=function(payload){var acktype=payload.acktype,callsid=payload.callsid,voiceeventsid=payload.voiceeventsid;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received ack from a different callsid: ".concat(callsid));return}if(acktype==="message"){_this._onMessageSent(voiceeventsid)}};_this._onAnswer=function(payload){if(typeof payload.reconnect==="string"){_this._signalingReconnectToken=payload.reconnect}if(_this._isAnswered&&_this._status!==Call.State.Reconnecting){return}_this._setCallSid(payload);_this._isAnswered=true;_this._maybeTransitionToOpen()};_this._onCancel=function(payload){var callsid=payload.callsid;if(_this.parameters.CallSid===callsid){_this._isCancelled=true;_this._publisher.info("connection","cancel",null,_this);_this._cleanupEventListeners();_this._mediaHandler.close();_this._status=Call.State.Closed;_this._log.debug("#cancel");_this.emit("cancel");_this._pstream.removeListener("cancel",_this._onCancel)}};_this._onConnected=function(){_this._log.info("Received connected from pstream");if(_this._signalingReconnectToken&&_this._mediaHandler.version){_this._pstream.reconnect(_this._mediaHandler.version.getSDP(),_this.parameters.CallSid,_this._signalingReconnectToken)}};_this._onHangup=function(payload){if(_this.status()===Call.State.Closed){return}if(payload.callsid&&(_this.parameters.CallSid||_this.outboundConnectionId)){if(payload.callsid!==_this.parameters.CallSid&&payload.callsid!==_this.outboundConnectionId){return}}else if(payload.callsid){return}_this._log.info("Received HANGUP from gateway");if(payload.error){var code=payload.error.code;var errorConstructor=(0,errors_1.getPreciseSignalingErrorByCode)(_this._options.enableImprovedSignalingErrorPrecision,code);var error=typeof errorConstructor!=="undefined"?new errorConstructor(payload.error.message):new errors_1.GeneralErrors.ConnectionError("Error sent from gateway in HANGUP",payload.error);_this._log.error("Received an error from the gateway:",error);_this._log.debug("#error",error);_this.emit("error",error)}_this._shouldSendHangup=false;_this._publisher.info("connection","disconnected-by-remote",null,_this);_this._disconnect(null,true);_this._cleanupEventListeners()};_this._onMediaFailure=function(type){var _a=Call.MediaFailure,ConnectionDisconnected=_a.ConnectionDisconnected,ConnectionFailed=_a.ConnectionFailed,IceGatheringFailed=_a.IceGatheringFailed,LowBytes=_a.LowBytes;var isEndOfIceCycle=type===ConnectionFailed||type===IceGatheringFailed;if(!(0,util_1.isChrome)(window,window.navigator)&&type===ConnectionFailed){return _this._mediaHandler.onerror(MEDIA_DISCONNECT_ERROR)}if(_this._mediaStatus===Call.State.Reconnecting){if(isEndOfIceCycle){if(Date.now()-_this._mediaReconnectStartTime>BACKOFF_CONFIG.max){_this._log.warn("Exceeded max ICE retries");return _this._mediaHandler.onerror(MEDIA_DISCONNECT_ERROR)}try{_this._mediaReconnectBackoff.backoff()}catch(error){if(!(error.message&&error.message==="Backoff in progress.")){throw error}}}return}var pc=_this._mediaHandler.version.pc;var isIceDisconnected=pc&&pc.iceConnectionState==="disconnected";var hasLowBytesWarning=_this._monitor.hasActiveWarning("bytesSent","min")||_this._monitor.hasActiveWarning("bytesReceived","min");if(type===LowBytes&&isIceDisconnected||type===ConnectionDisconnected&&hasLowBytesWarning||isEndOfIceCycle){var mediaReconnectionError=new errors_1.MediaErrors.ConnectionError("Media connection failed.");_this._log.warn("ICE Connection disconnected.");_this._publisher.warn("connection","error",mediaReconnectionError,_this);_this._publisher.info("connection","reconnecting",null,_this);_this._mediaReconnectStartTime=Date.now();_this._status=Call.State.Reconnecting;_this._mediaStatus=Call.State.Reconnecting;_this._mediaReconnectBackoff.reset();_this._mediaReconnectBackoff.backoff();_this._log.debug("#reconnecting");_this.emit("reconnecting",mediaReconnectionError)}};_this._onMediaReconnected=function(){if(_this._mediaStatus!==Call.State.Reconnecting){return}_this._log.info("ICE Connection reestablished.");_this._mediaStatus=Call.State.Open;if(_this._signalingStatus===Call.State.Open){_this._publisher.info("connection","reconnected",null,_this);_this._log.debug("#reconnected");_this.emit("reconnected");_this._status=Call.State.Open}};_this._onMessageReceived=function(payload){var callsid=payload.callsid,content=payload.content,contenttype=payload.contenttype,messagetype=payload.messagetype,voiceeventsid=payload.voiceeventsid;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received a message from a different callsid: ".concat(callsid));return}var data={content:content,contentType:contenttype,messageType:messagetype,voiceEventSid:voiceeventsid};_this._publisher.info("call-message",messagetype,{content_type:contenttype,event_type:"received",voice_event_sid:voiceeventsid},_this);_this._log.debug("#messageReceived",JSON.stringify(data));_this.emit("messageReceived",data)};_this._onMessageSent=function(voiceEventSid){if(!_this._messages.has(voiceEventSid)){_this._log.warn("Received a messageSent with a voiceEventSid that doesn't exists: ".concat(voiceEventSid));return}var message=_this._messages.get(voiceEventSid);_this._messages.delete(voiceEventSid);_this._publisher.info("call-message",message===null||message===void 0?void 0:message.messageType,{content_type:message===null||message===void 0?void 0:message.contentType,event_type:"sent",voice_event_sid:voiceEventSid},_this);_this._log.debug("#messageSent",JSON.stringify(message));_this.emit("messageSent",message)};_this._onRinging=function(payload){_this._setCallSid(payload);if(_this._status!==Call.State.Connecting&&_this._status!==Call.State.Ringing){return}var hasEarlyMedia=!!payload.sdp;_this._status=Call.State.Ringing;_this._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:hasEarlyMedia},_this);_this._log.debug("#ringing");_this.emit("ringing",hasEarlyMedia)};_this._onRTCSample=function(sample){var callMetrics=__assign(__assign({},sample),{inputVolume:_this._latestInputVolume,outputVolume:_this._latest