@twilio/voice-sdk
Version:
Twilio's JavaScript Voice SDK
1 lines • 321 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 TwilioError=require("./twilio/errors");exports.TwilioError=TwilioError;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}})},{"./twilio/call":8,"./twilio/device":11,"./twilio/errors":14,"./twilio/log":17,"./twilio/preflight/preflight":19}],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;return g={next:verb(0),throw:verb(1),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(_)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":10}],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){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 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 mediadevices_1=require("./shims/mediadevices");var util_1=require("./util");var kindAliases={audioinput:"Audio Input",audiooutput:"Audio Output"};var AudioHelper=function(_super){__extends(AudioHelper,_super);function AudioHelper(onActiveOutputsChanged,onActiveInputChanged,getUserMedia,options){var _a;var _this=_super.call(this)||this;_this.availableInputDevices=new Map;_this.availableOutputDevices=new Map;_this._audioConstraints=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._inputStream=null;_this._isPollingInputVolume=false;_this._log=log_1.default.getInstance();_this._unknownDeviceIndexes={audioinput:{},audiooutput:{}};_this._removeLostInput=function(lostDevice){if(!_this.inputDevice||_this.inputDevice.deviceId!==lostDevice.deviceId){return false}_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};_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. "+reason)})}})})};options=Object.assign({AudioContext:typeof AudioContext!=="undefined"&&AudioContext,setSinkId:typeof HTMLAudioElement!=="undefined"&&HTMLAudioElement.prototype.setSinkId},options);_this._getUserMedia=getUserMedia;_this._mediaDevices=options.mediaDevices||mediadevices_1.default();_this._onActiveInputChanged=onActiveInputChanged;_this._enumerateDevices=typeof options.enumerateDevices==="function"?options.enumerateDevices:_this._mediaDevices&&_this._mediaDevices.enumerateDevices;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()}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._inputStream},enumerable:false,configurable:true});AudioHelper.prototype._getEnabledSounds=function(){return this._enabledSounds};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=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._unbind=function(){if(!this._mediaDevices||!this._enumerateDevices){throw new errors_1.NotSupportedError("Enumeration is not supported")}if(this._mediaDevices.removeEventListener){this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices);this._mediaDevices.removeEventListener("deviceinfochange",this._updateAvailableDevices)}};AudioHelper.prototype.disconnect=function(doEnable){return this._maybeEnableSound(device_1.default.SoundName.Disconnect,doEnable)};AudioHelper.prototype.incoming=function(doEnable){return this._maybeEnableSound(device_1.default.SoundName.Incoming,doEnable)};AudioHelper.prototype.outgoing=function(doEnable){return this._maybeEnableSound(device_1.default.SoundName.Outgoing,doEnable)};AudioHelper.prototype.setAudioConstraints=function(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){return!util_1.isFirefox()?this._setInputDevice(deviceId,false):Promise.reject(new errors_1.NotSupportedError("Firefox does not currently support opening multiple "+"audio input tracks simultaneously, even across different tabs. As a result, "+"Device.audio.setInputDevice is disabled on Firefox until support is added.\n"+"Related BugZilla thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1299324"))};AudioHelper.prototype.unsetAudioConstraints=function(){this._audioConstraints=null;return this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,true):Promise.resolve()};AudioHelper.prototype.unsetInputDevice=function(){var _this=this;if(!this.inputDevice){return Promise.resolve()}return this._onActiveInputChanged(null).then(function(){_this._replaceStream(null);_this._inputDevice=null;_this._maybeStopPollingVolume()})};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._mediaDevices.addEventListener("deviceinfochange",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. "+reason)})})};AudioHelper.prototype._maybeEnableSound=function(soundName,doEnable){if(typeof doEnable!=="undefined"){this._enabledSounds[soundName]=doEnable}return this._enabledSounds[soundName]};AudioHelper.prototype._replaceStream=function(stream){if(this._inputStream){this._inputStream.getTracks().forEach(function(track){track.stop()})}this._inputStream=stream};AudioHelper.prototype._setInputDevice=function(deviceId,forceGetUserMedia){var _this=this;if(typeof deviceId!=="string"){return Promise.reject(new errors_1.InvalidArgumentError("Must specify the device to set"))}var device=this.availableInputDevices.get(deviceId);if(!device){return Promise.reject(new errors_1.InvalidArgumentError("Device not found: "+deviceId))}if(this._inputDevice&&this._inputDevice.deviceId===deviceId&&this._inputStream){if(!forceGetUserMedia){return Promise.resolve()}this._inputStream.getTracks().forEach(function(track){track.stop()})}var constraints={audio:Object.assign({deviceId:{exact:deviceId}},this.audioConstraints)};return this._getUserMedia(constraints).then(function(stream){return _this._onActiveInputChanged(stream).then(function(){_this._replaceStream(stream);_this._inputDevice=device;_this._maybeStartPollingVolume()})})};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=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){if(this.inputDevice!==null&&this.inputDevice.deviceId==="default"){this._log.warn("Calling getUserMedia after device change to ensure that the tracks of the active device (default) have not gone stale.");this._setInputDevice(this.inputDevice.deviceId,true)}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 "+kindAliases[options.kind]+" Device "+index}}return new mediadeviceinfo_1.default(options)};return AudioHelper}(events_1.EventEmitter);(function(AudioHelper){})(AudioHelper||(AudioHelper={}));exports.default=AudioHelper},{"./device":11,"./errors":14,"./log":17,"./outputdevicecollection":18,"./shims/mediadeviceinfo":33,"./shims/mediadevices":34,"./util":37,events:40}],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){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;return g={next:verb(0),throw:verb(1),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(_)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 __spreadArrays=this&&this.__spreadArrays||function(){for(var s=0,i=0,il=arguments.length;i<il;i++)s+=arguments[i].length;for(var r=Array(s),k=0,i=0;i<il;i++)for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++)r[k]=a[j];return r};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,__spreadArrays([name],args))};EventTarget.prototype.removeEventListener=function(name,handler){return this._eventEmitter.removeListener(name,handler)};return EventTarget}();exports.default=EventTarget},{events:40}],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){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:40}],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){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 statsMonitor_1=require("./statsMonitor");var util_1=require("./util");var uuid_1=require("./uuid");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=log_1.default.getInstance();_this._mediaStatus=Call.State.Pending;_this._messages=new Map;_this._metricsSamples=[];_this._options={MediaHandler:rtc_1.PeerConnection,offerSdp:null,shouldPlayDisconnect:function(){return true},voiceEventSidGenerator:uuid_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=groupPrefix+"warning"+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.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: "+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.emit("cancel");_this._pstream.removeListener("cancel",_this._onCancel)}};_this._onConnected=function(){_this._log.info("Received connected from pstream");if(_this._signalingReconnectToken){_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 error=new errors_1.GeneralErrors.ConnectionError("Error sent from gateway in HANGUP");_this._log.error("Received an error from the gateway:",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(!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.info("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.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.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: "+callsid);return}_this.emit("messageReceived",{content:content,contentType:contenttype,messageType:messagetype,voiceEventSid:voiceeventsid})};_this._onMessageSent=function(voiceEventSid){if(!_this._messages.has(voiceEventSid)){_this._log.warn("Received a messageSent with a voiceEventSid that doesn't exists: "+voiceEventSid);return}var message=_this._messages.get(voiceEventSid);_this._messages.delete(voiceEventSid);_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.emit("ringing",hasEarlyMedia)};_this._onRTCSample=function(sample){var callMetrics=__assign(__assign({},sample),{inputVolume:_this._latestInputVolume,outputVolume:_this._latestOutputVolume});_this._codec=callMetrics.codecName;_this._metricsSamples.push(callMetrics);if(_this._metricsSamples.length>=METRICS_BATCH_SIZE){_this._publishMetrics()}_this.emit("sample",sample)};_this._onSignalingError=function(payload){var callsid=payload.callsid,voiceeventsid=payload.voiceeventsid;if(_this.parameters.CallSid!==callsid){_this._log.warn("Received an error from a different callsid: "+callsid);return}if(voiceeventsid&&_this._messages.has(voiceeventsid)){_this._messages.delete(voiceeventsid);_this._log.warn("Received an error while sending a message.",payload)}};_this._onSignalingReconnected=function(){if(_this._signalingStatus!==Call.State.Reconnecting){return}_this._log.info("Signaling Connection reestablished.");_this._signalingStatus=Call.State.Open;if(_this._mediaStatus===Call.State.Open){_this._publisher.info("connection","reconnected",null,_this);_this.emit("reconnected");_this._status=Call.State.Open}};_this._onTransportClose=function(){_this._log.error("Received transportClose from pstream");_this.emit("transportClose");if(_this._signalingReconnectToken){_this._status=Call.State.Reconnecting;_this._signalingStatus=Call.State.Reconnecting;_this.emit("reconnecting",new errors_1.SignalingErrors.ConnectionDisconnected)}else{_this._status=Call.State.Closed;_this._signalingStatus=Call.State.Closed}};_this._reemitWarning=function(warningData,wasCleared){var groupPrefix=/^audio/.test(warningData.name)?"audio-level-":"network-quality-";var warningPrefix=WARNING_PREFIXES[warningData.threshold.name];var warningName;if(warningData.name in MULTIPLE_THRESHOLD_WARNING_NAMES){warningName=MULTIPLE_THRESHOLD_WARNING_NAMES[warningData.name][warningData.threshold.name]}else if(warningData.name in WARNING_NAMES){warningName=WARNING_NAMES[warningData.name]}var warning=warningPrefix+warningName;_this._emitWarning(groupPrefix,warning,warningData.threshold.value,warningData.values||warningData.value,wasCleared,warningData)};_this._reemitWarningCleared=function(warningData){_this._reemitWarning(warningData,true)};_this._isUnifiedPlanDefault=config.isUnifiedPlanDefault;_this._soundcache=config.soundcache;if(typeof config.onIgnore==="function"){_this._onIgnore=config.onIgnore}var message=options&&options.twimlParams||{};_this.customParameters=new Map(Object.entries(message).map(function(_a){var key=_a[0],val=_a[1];return[key,String(val)]}));Object.assign(_this._options,options);if(_this._options.callParameters){_this.parameters=_this._options.callParameters}if(_this._options.reconnectToken){_this._signalingReconnectToken=_this._options.reconnectToken}_this._voiceEventSidGenerator=_this._options.voiceEventSidGenerator||uuid_1.generateVoiceEventSid;_this._direction=_this.parameters.CallSid?Call.CallDirection.Incoming:Call.CallDirection.Outgoing;if(_this._direction===Call.CallDirection.Incoming&&_this.parameters){_this.callerInfo=_this.parameters.StirStatus?{isVerified:_this.parameters.StirStatus==="TN-Validation-Passed-A"}:null}else{_this.callerInfo=null}_this._mediaReconnectBackoff=new backoff_1.default(BACKOFF_CONFIG);_this._mediaReconnectBackoff.on("ready",function(){return _this._mediaHandler.iceRestart()});_this.outboundConnectionId=generateTempCallSid();var publisher=_this._publisher=config.publisher;if(_this._direction===Call.CallDirection.Incoming){publisher.info("connection","incoming",null,_this)}else{publisher.info("connection","outgoing",{preflight:_this._options.preflight},_this)}var monitor=_this._monitor=new(_this._options.StatsMonitor||statsMonitor_1.default);monitor.on("sample",_this._onRTCSample);monitor.disableWarnings();setTimeout(function(){return monitor.enableWarnings()},METRICS_DELAY);monitor.on("warning",function(data,wasCleared){if(data.name==="bytesSent"||data.name==="bytesReceived"){_this._onMediaFailure(Call.MediaFailure.LowBytes)}_this._reemitWarning(data,wasCleared)});monitor.on("warning-cleared",function(data){_this._reemitWarningCleared(data)});_this._mediaHandler=new _this._options.MediaHandler(config.audioHelper,config.pstream,config.getUserMedia,{RTCPeerConnection:_this._options.RTCPeerConnection,codecPreferences:_this._options.codecPreferences,dscp:_this._options.dscp,forceAggressiveIceNomination:_this._options.forceAggressiveIceNomination,isUnifiedPlan:_this._isUnifiedPlanDefault,maxAverageBitrate:_this._options.maxAverageBitrate,preflight:_this._options.preflight});_this.on("volume",function(inputVolume,outputVolume){_this._inputVolumeStreak=_this._checkVolume(inputVolume,_this._inputVolumeStreak,_this._latestInputVolume,"input");_this._outputVolumeStreak=_this._checkVolume(outputVolume,_this._outputVolumeStreak,_this._latestOutputVolume,"output");_this._latestInputVolume=inputVolume;_this._latestOutputVolume=outputVolume});_this._mediaHandler.onaudio=function(remoteAudio){_this._log.info("Remote audio created");_this.emit("audio",remoteAudio)};_this._mediaHandler.onvolume=function(inputVolume,outputVolume,internalInputVolume,internalOutputVolume){monitor.addVolumes(internalInputVolume/255*32767,internalOutputVolume/255*32767);_this.emit("volume",inputVolume,outputVolume)};_this._mediaHandler.ondtlstransportstatechange=function(state){var level=state==="failed"?"error":"debug";_this._publisher.post(level,"dtls-transport-state",state,null,_this)};_this._mediaHandler.onpcconnectionstatechange=function(state){var level="debug";var dtlsTransport=_this._mediaHandler.getRTCDtlsTransport();if(state==="failed"){level=dtlsTransport&&dtlsTransport.state==="failed"?"error":"warning"}_this._publisher.post(level,"pc-connection-state",state,null,_this)};_this._mediaHandler.onicecandidate=function(candidate){var payload=new icecandidate_1.IceCandidate(candidate).toPayload();_this._publisher.debug("ice-candidate","ice-candidate",payload,_this)};_this._mediaHandler.onselectedcandidatepairchange=function(pair){var localCandidatePayload=new icecandidate_1.IceCandidate(pair.local).toPayload();var remoteCandidatePayload=new icecandidate_1.IceCandidate(pair.remote,true).toPayload();_this._publisher.debug("ice-candidate","selected-ice-candidate-pair",{local_candidate:localCandidatePayload,remote_candidate:remoteCandidatePayload},_this)};_this._mediaHandler.oniceconnectionstatechange=function(state){var level=state==="failed"?"error":"debug";_this._publisher.post(level,"ice-connection-state",state,null,_this)};_this._mediaHandler.onicegatheringfailure=function(type){_this._publisher.warn("ice-gathering-state",type,null,_this);_this._onMediaFailure(Call.MediaFailure.IceGatheringFailed)};_this._mediaHandler.onicegatheringstatechange=function(state){_this._publisher.debug("ice-gathering-state",state,null,_this)};_this._mediaHandler.onsignalingstatechange=function(state){_this._publisher.debug("signaling-state",state,null,_this)};_this._mediaHandler.ondisconnected=function(msg){_this._log.info(msg);_this._publisher.warn("network-quality-warning-raised","ice-connectivity-lost",{message:msg},_this);_this.emit("warning","ice-connectivity-lost");_this._onMediaFailure(Call.MediaFailure.ConnectionDisconnected)};_this._mediaHandler.onfailed=function(msg){_this._onMediaFailure(Call.MediaFailure.ConnectionFailed)};_this._mediaHandler.onconnected=function(){if(_this._status===Call.State.Reconnecting){_this._onMediaReconnected()}};_this._mediaHandler.onreconnected=function(msg){_this._log.info(msg);_this._publisher.info("network-quality-warning-cleared","ice-connectivity-lost",{message:msg},_this);_this.emit("warning-cleared","ice-connectivity-lost");_this._onMediaReconnected()};_this._mediaHandler.onerror=function(e){if(e.disconnect===true){_this._disconnect(e.info&&e.info.message)}var error=e.info.twilioError||new errors_1.GeneralErrors.UnknownError(e.info.message);_this._log.error("Received an error from MediaStream:",e);_this.emit("error",error)};_this._mediaHandler.onopen=function(){if(_this._status===Call.State.Open||_this._status===Call.State.Reconnecting){return}else if(_this._status===Call.State.Ringing||_this._status===Call.State.Connecting){_this.mute(false);_this._mediaStatus=Call.State.Open;_this._maybeTransitionToOpen()}else{_this._mediaHandler.close()}};_this._mediaHandler.onclose=function(){_this._status=Call.State.Closed;if(_this._options.shouldPlayDisconnect&&_this._options.shouldPlayDisconnect()&&!_this._isCancelled&&!_this._isRejected){_this._soundcache.get(device_1.default.SoundName.Disconnect).play()}monitor.disable();_this._publishMetrics();if(!_this._isCancelled&&!_this._isRejected){_this.emit("disconnect",_this)}};_this._pstream=config.pstream;_this._pstream.on("ack",_this._onAck);_this._pstream.on("cancel",_this._onCancel);_this._pstream.on("error",_this._onSignalingError);_this._pstream.on("ringing",_this._onRinging);_this._pstream.on("transportClose",_this._onTransportClose);_this._pstream.on("connected",_this._onConnected);_this._pstream.on("message",_this._onMessageReceived);_this.on("error",function(error){_this._publisher.error("connection","error",{code:error.code,message:error.message},_this);if(_this._pstream&&_this._pstream.status==="disconnected"){_this._cleanupEventListeners()}});_this.on("disconnect",function(){_this._cleanupEventListeners()});return _this}Object.defineProperty(Call.prototype,"direction",{get:function(){return this._direction},enumerable:false,configurable:true});Object.defineProperty(Call.prototype,"codec",{get:function(){return this._codec},enumerable:false,configurable:true});Call.prototype._setInputTracksFromStream=function(stream){return this._mediaHandler.setInputTracksFromStream(stream)};Call.prototype._setSinkIds=function(sinkIds){return this._mediaHandler._setSinkIds(sinkIds)};Call.prototype.accept=function(options){var _this=this;if(this._status!==Call.State.Pending){return}options=options||{};var rtcConfiguration=options.rtcConfiguration||this._options.rtcConfiguration;var rtcConstraints=options.rtcConstraints||this._options.rtcConstraints||{};var audioConstraints=rtcConstraints.audio||{audio:true};this._status=Call.State.Connecting;var connect=function(){if(_this._status!==Call.State.Connecting){_this._cleanupEventListeners();_this._mediaHandler.close();return}var onAnswer=function(pc,reconnectToken){var eventName=_this._direction===Call.CallDirection.Incoming?"accepted-by-local":"accepted-by-remote";_this._publisher.info("connection",eventName,null,_this);if(typeof reconnectToken==="string"){_this._signalingReconnectToken=reconnectToken}var _a=sdp_1.getPreferredCodecInfo(_this._mediaHandler.version.getSDP()),codecName=_a.codecName,codecParams=_a.codecParams;_this._publisher.info("settings","codec",{codec_params:codecParams,selected_codec:codecName},_this);_this._monitor.enable(pc)};var sinkIds=typeof _this._options.getSinkIds==="function"&&_this._options.getSinkIds();if(Array.isArray(sinkIds)){_this._mediaHandler._setSinkIds(sinkIds).catch(function(){})}_this._pstream.addListener("hangup",_this._onHangup);if(_this._direction===Call.CallDirection.Incoming){_this._isAnswered=true;_this._pstream.on("answer",_this._onAnswer);_this._mediaHandler.answerIncomingCall(_this.parameters.CallSid,_this._options.offerSdp,rtcConstraints,rtcConfiguration,onAnswer)}else{var params=Array.from(_this.customParameters.entries()).map(function(pair){return encodeURIComponent(pair[0])+"="+encodeURIComponent(pair[1])}).join("&");_this._pstream.on("answer",_this._onAnswer);_this._mediaHandler.makeOutgoingCall(_this._pstream.token,params,_this.outboundConnectionId,rtcConstraints,rtcConfiguration,onAnswer)}};if(this._options.beforeAccept){this._options.beforeAccept(this)}var inputStream=typeof this._options.getInputStream==="function"&&this._options.getInputStream();var promise=inputStream?this._mediaHandler.setInputTracksFromStream(inputStream):this._mediaHandler.openWithConstraints(audioConstraints);promise.then(function(){_this._publisher.info("get-user-media","succeeded",{data:{audioConstraints:audioConstraints}},_this);connect()},function(error){var twilioError;if(error.code===31208||["PermissionDeniedError","NotAllowedError"].indexOf(err