PageSourceSearch

https://app.wonderchat.io/_next/static/chunks/9969.1933ff3c1c966f4d.js

js wonderchat.io collected 2026-09-24 17:14:19 UTC 178,457 bytes, 1 lines download raw bytes

1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9969],{19969:function(e,t,i){"use strict";i.r(t),i.d(t,{Call:function(){return tf},Device:function(){return tr},Logger:function(){return ee},PreflightTest:function(){return eW},TwilioError:function(){return L}});var s,n,o,r,a,c,l,d,h,u,p,m,g,_,f,v,y,b,S,w,C,E,T,k,I,P,x,D,A,R,O,L={};i.r(L),i.d(L,{AuthorizationErrors:function(){return w},ClientErrors:function(){return E},GeneralErrors:function(){return k},InvalidArgumentError:function(){return B},InvalidStateError:function(){return q},MalformedRequestErrors:function(){return I},MediaErrors:function(){return D},NotSupportedError:function(){return G},SIPServerErrors:function(){return T},SignalingErrors:function(){return x},SignatureValidationErrors:function(){return C},TwilioError:function(){return U},UserMediaErrors:function(){return P},getErrorByCode:function(){return z},getPreciseSignalingErrorByCode:function(){return V},hasErrorByCode:function(){return J}});var M={};i.r(M),i.d(M,{Exception:function(){return e_},average:function(){return eo},difference:function(){return er},flatMap:function(){return ep},isChrome:function(){return ec},isElectron:function(){return ea},isFirefox:function(){return el},isLegacyEdge:function(){return ed},isSafari:function(){return eh},promisifyEvents:function(){return em},queryToJson:function(){return eu},sortByMimeTypes:function(){return eg}});var j=i(17187);class $ extends j.EventEmitter{constructor(e){super(),Object.defineProperties(this,{_attempts:{value:0,writable:!0},_duration:{enumerable:!1,get(){if(this._useInitialValue&&0===this._attempts)return this._min;let e=this._min*Math.pow(this._factor,this._attempts);if(this._jitter){let t=Math.random(),i=Math.floor(t*this._jitter*e);e=(1&Math.floor(10*t))==0?e-i:e+i}return 0|Math.min(e,this._max)}},_factor:{value:e.factor||2},_jitter:{value:e.jitter>0&&e.jitter<=1?e.jitter:0},_max:{value:e.max||1e4},_min:{value:e.min||100},_timeoutID:{value:null,writable:!0},_useInitialValue:{value:e.useInitialValue||!1}})}backoff(){let e=this._duration;this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null),this.emit("backoff",this._attempts,e),this._timeoutID=setTimeout(()=>{this.emit("ready",this._attempts,e),this._attempts++},e)}reset(){this._attempts=0,this._timeoutID&&(clearTimeout(this._timeoutID),this._timeoutID=null)}}function F(e,t,i,s){return new(i||(i=Promise))(function(n,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;var N=i(2043);class U extends Error{constructor(e,t){super(),Object.setPrototypeOf(this,U.prototype);let i="string"==typeof e?e:this.explanation;this.message=`${this.name} (${this.code}): ${i}`,this.originalError="object"==typeof e?e:t}}!function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=20101,this.description="Invalid access token",this.explanation="Twilio was unable to validate your Access Token",this.name="AccessTokenInvalid",this.solutions=[],Object.setPrototypeOf(this,e.AccessTokenInvalid.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AccessTokenInvalid=t;class i extends U{constructor(t,i){super(t,i),this.causes=[],this.code=20104,this.description="Access token expired or expiration date invalid",this.explanation="The Access Token provided to the Twilio API has expired, the expiration time specified in the token was invalid, or the expiration time specified was too far in the future",this.name="AccessTokenExpired",this.solutions=[],Object.setPrototypeOf(this,e.AccessTokenExpired.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AccessTokenExpired=i;class s extends U{constructor(t,i){super(t,i),this.causes=[],this.code=20151,this.description="Authentication Failed",this.explanation="The Authentication with the provided JWT failed",this.name="AuthenticationFailed",this.solutions=[],Object.setPrototypeOf(this,e.AuthenticationFailed.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AuthenticationFailed=s}(w||(w={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=["The access token has an invali
1d Account SID, API Key, or API Key Secret."],this.code=31202,this.description="Signature validation failed.",this.explanation="The provided access token failed signature validation.",this.name="AccessTokenSignatureValidationFailed",this.solutions=["Ensure the Account SID, API Key, and API Key Secret are valid when generating your access token."],Object.setPrototypeOf(this,e.AccessTokenSignatureValidationFailed.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AccessTokenSignatureValidationFailed=t}(C||(C={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31400,this.description="Bad Request (HTTP/SIP)",this.explanation="The request could not be understood due to malformed syntax.",this.name="BadRequest",this.solutions=[],Object.setPrototypeOf(this,e.BadRequest.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.BadRequest=t;class i extends U{constructor(t,i){super(t,i),this.causes=["The outbound call was made to an invalid phone number.","The TwiML application sid is missing a Voice URL."],this.code=31404,this.description="Not Found (HTTP/SIP)",this.explanation="The server has not found anything matching the request.",this.name="NotFound",this.solutions=["Ensure the phone number dialed is valid.","Ensure the TwiML application is configured correctly with a Voice URL link."],Object.setPrototypeOf(this,e.NotFound.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}
1e.NotFound=i;class s extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31480,this.description="Temporarily Unavailable (SIP)",this.explanation="The callee is currently unavailable.",this.name="TemporarilyUnavailable",this.solutions=[],Object.setPrototypeOf(this,e.TemporarilyUnavailable.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.TemporarilyUnavailable=s;class n extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31486,this.description="Busy Here (SIP)",this.explanation="The callee is busy.",this.name="BusyHere",this.solutions=[],Object.setPrototypeOf(this,e.BusyHere.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.BusyHere=n}(E||(E={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31603,this.description="Decline (SIP)",this.explanation="The callee does not wish to participate in the call.",this.name="Decline",this.solutions=[],Object.setPrototypeOf(this,e.Decline.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.Decline=t}(T||(T={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31e3,this.description="Unknown Error",this.explanation="An unknown error has occurred. See error details for more information.",this.name="UnknownError",this.solutions=[],Object.setPrototypeOf(this,e.UnknownError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.UnknownError=t;class i extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31001,this.description="Application Not Found",this.explanation="",this.name="ApplicationNotFoundError",this.solutions=[],Object.setPrototypeOf(this,e.ApplicationNotFoundError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ApplicationNotFoundError=i;class s extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31002,this.description="Connection Declined",this.explanation="",this.name="ConnectionDeclinedError",this.solutions=[],Object.setPrototypeOf(this,e.ConnectionDeclinedError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionDeclinedError=s;class n extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31003,this.description="Connection Timeout",this.explanation="The server could not produce a response within a suitable amount of time.",this.name="ConnectionTimeoutError",this.solutions=[],Object.setPrototypeOf(this,e.ConnectionTimeoutError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionTimeoutError=n;class o extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31005,this.description="Connection error",this.explanation="A connection error occurred during the call",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,e.ConnectionError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionError=o;class r extends U{constructor(t,i){super(t,i),this.causes=["The incoming call was cancelled because it was not answered in time or it was accepted/rejected by another application instance registered with the same identity."],this.code=31008,this.description="Call cancelled",this.explanation="Unable to answer because the call has ended",this.name="CallCancelledError",this.solutions=[],Object.setPrototypeOf(this,e.CallCancelledError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.CallCancelledError=r;class a extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31009,this.description="Transport error",this.explanation="No transport available to send or receive messages",this.name="Trans
1portError",this.solutions=[],Object.setPrototypeOf(this,e.TransportError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.TransportError=a}(k||(k={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=["Invalid content or MessageType passed to sendMessage method."],this.code=31100,this.description="The request had malformed syntax.",this.explanation="The request could not be understood due to malformed syntax.",this.name="MalformedRequestError",this.solutions=["Ensure content and MessageType passed to sendMessage method are valid."],Object.setPrototypeOf(this,e.MalformedRequestError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.MalformedRequestError=t;class i extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31101,this.description="Missing parameter array in request",this.explanation="",this.name="MissingParameterArrayError",this.solutions=[],Object.setPrototypeOf(this,e.MissingParameterArrayError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.MissingParameterArrayError=i;class s extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31102,this.description="Authorization token missing in request.",this.explanation="",this.name="AuthorizationTokenMissingError",this.solutions=[],Object.setPrototypeOf(this,e.AuthorizationTokenMissingError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AuthorizationTokenMissingError=s;class n extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31103,this.description="Maximum parameter length has been exceeded.",this.explanation="Length of parameters cannot exceed MAX_PARAM_LENGTH.",this.name="MaxParameterLengthExceededError",this.solutions=[],Object.setPrototypeOf(this,e.MaxParameterLengthExceededError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.MaxParameterLengthExceededError=n;class o extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31104,this.description="Invalid bridge token",this.explanation="",this.name="InvalidBridgeTokenError",this.solutions=[],Object.setPrototypeOf(this,e.InvalidBridgeTokenError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.InvalidBridgeTokenError=o;class r extends U{constructor(t,i){super(t,i),this.causes=["Client name contains invalid characters."],this.code=31105,this.description="Invalid client name",this.explanation="Client name should not contain control, space, delims, or unwise characters.",this.name="InvalidClientNameError",this.solutions=["Make sure that client name does not contain any of the invalid characters."],Object.setPrototypeOf(this,e.InvalidClientNameError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.InvalidClientNameError=r;class a extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31107,this.description="The reconnect parameter is invalid",this.explanation="",this.name="ReconnectParameterInvalidError",this.solutions=[],Object.setPrototypeOf(this,e.ReconnectParameterInvalidError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ReconnectParameterInvalidError=a}(I||(I={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31201,this.description="Authorization error",this.explanation="The request requires user authentication. The server understood the request, but is refusing to fulfill it.",this.name="AuthorizationError",this.solutions=[],Object.setPrototypeOf(this,e.AuthorizationError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AuthorizationError=t;class i extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31203,this.description="No valid account",this.explanation="",this.name="NoValidAccountError",this.solutions=[],Object.setPrototypeOf(this,e.NoValidAccountError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}
1e.NoValidAccountError=i;class s extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31204,this.description="Invalid JWT token",this.explanation="",this.name="InvalidJWTTokenError",this.solutions=[],Object.setPrototypeOf(this,e.InvalidJWTTokenError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.InvalidJWTTokenError=s;class n extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31205,this.description="JWT token expired",this.explanation="",this.name="JWTTokenExpiredError",this.solutions=[],Object.setPrototypeOf(this,e.JWTTokenExpiredError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.JWTTokenExpiredError=n;class o extends U{constructor(t,i){super(t,i),this.causes=["Rate limit exceeded."],this.code=31206,this.description="Rate exceeded authorized limit.",this.explanation="The request performed exceeds the authorized limit.",this.name="RateExceededError",this.solutions=["Ensure message send rate does not exceed authorized limits."],Object.setPrototypeOf(this,e.RateExceededError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.RateExceededError=o;class r extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31207,this.description="JWT token expiration too long",this.explanation="",this.name="JWTTokenExpirationTooLongError",this.solutions=[],Object.setPrototypeOf(this,e.JWTTokenExpirationTooLongError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.JWTTokenExpirationTooLongError=r;class a extends U{constructor(t,i){super(t,i),this.causes=[],this.code=31209,this.description="Reconnect attempt is not authorized.",this.explanation="",this.name="ReconnectAttemptError",this.solutions=[],Object.setPrototypeOf(this,e.ReconnectAttemptError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ReconnectAttemptError=a;class c extends U{constructor(t,i){super(t,i),this.causes=["The Call Message Event Type is invalid and is not understood by Twilio Voice."],this.code=31210,this.description="Call Message Event Type is invalid.",this.explanation="The Call Message Event Type is invalid and is not understood by Twilio Voice.",this.name="CallMessageEventTypeInvalidError",this.solutions=["Ensure the Call Message Event Type is Valid and understood by Twilio Voice and try again."],Object.setPrototypeOf(this,e.CallMessageEventTypeInvalidError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.CallMessageEventTypeInvalidError=c;class l extends U{constructor(t,i){super(t,i),this.causes=["The payload size of Call Message Event exceeds the authorized limit."],this.code=31212,this.description="Call Message Event Payload size exceeded authorized limit.",this.explanation="The request performed to send a Call Message Event exceeds the payload size authorized limit",this.name="PayloadSizeExceededError",this.solutions=["Reduce payload size of Call Message Event to be within the authorized limit and try again."],Object.setPrototypeOf(this,e.PayloadSizeExceededError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.PayloadSizeExceededError=l}(w||(w={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=["The user denied the getUserMedia request.","The browser denied the getUserMedia request."],this.code=31401,this.description="UserMedia Permission Denied Error",this.explanation="The browser or end-user denied permissions to user media. Therefore we were unable to acquire input audio.",this.name="PermissionDeniedError",this.solutions=["The user should accept the request next time prompted. If the browser saved the deny, the user should change that permission in their browser.","The user should to verify that the browser has permission to access the microphone at this address."],Object.setPrototypeOf(this,e.PermissionDeniedError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.PermissionDeniedError=t;class i extends U{constructor(t,i){super(t,i),this.causes=["NotFoundError - The deviceID specified was not found.","The getUserMedia constraints were overconstrained and no devices matched."],this.code=31402,this.description="UserMedia Acquisition Failed Error",this.explanation="The browser and end-user allowed permissions, however getting the media failed. Usually this is due to bad constraints, but can sometimes fail due to browser, OS or hardware issues.",this.name="AcquisitionFailedError",this.solutions=["Ensure the deviceID being specified exists.","Try acquiring media with fewer constraints."],Object.setPrototypeOf(this,e.AcquisitionFailedError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.AcquisitionFailedError=i}(P||(P={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=[],this.code=53e3,this.description="Signaling connection error",this.explanation="Raised whenever a signaling connection error occurs that is not covered by a more specific error code.",this.name="ConnectionError",this.solutions=[],Object.setPrototypeOf(this,e.ConnectionError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionError=t;class i extends U{constructor(t,i){super(t,i),this.causes=["The device running your application lost its Internet connection."],this.code=53001,this.description="Signaling connection disconnected",this.explanation="Raised whenever the signaling connection is unexpectedly disconnected.",this.name="ConnectionDisconnected",this.solutions=["Ensure the device running your application has access to a stable Internet connection."],Object.setPrototypeOf(this,e.ConnectionDisconnected.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionDisconnected=i}(x||(x={})),function(e){class t extends U{constructor(t,i){super(t,i),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may not have the necessary resources to create or apply a new media description."],this.code=53400,this.description="Client is unable to create or apply a local media description",this.explanation="Raised whenever a Client is unable to create or apply a local media description.",this.name="ClientLocalDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,e.ClientLocalDescFailed.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ClientLocalDescFailed=t;class i extends U{constructor(t,i){super(t,i),this.causes=["The Client may not be using a supported WebRTC implementation.","The Client may be connecting peer-to-peer with another Participant that is not using a supported WebRTC implementation.","The Client may not have the necessary resources to apply a new media description."],this.code=53402,this.description="Client is unable to apply a remote media description",this.explanation="Raised whenever the Client receives a remote media description but is unable to apply it.",this.name="ClientRemoteDescFailed",this.solutions=["If you are experiencing this error using the JavaScript SDK, ensure you are running it with a supported WebRTC implementation."],Object.setPrototypeOf(this,e.ClientRemoteDescFailed.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ClientRemoteDescFailed=i;class s extends U{constructor(t,i){super(t,i),this.causes=["The Client was unable to establish a media connection.","A media connection which was active failed liveliness checks."],this.code=53405,this.description="Media connection failed",this.explanation="Raised by the Client or Server whenever a media connection fails.",this.name="ConnectionError",this.solutions=["If the problem persists, try connecting to another region.","Check your Client's network connectivity.","If you've provided custom ICE Servers then ensure that the URLs and credentials are valid."],Object.setPrototypeOf(this,e.ConnectionError.prototype);let s="string"==typeof t?t:this.explanation,n="object"==typeof t?t:i;this.message=`${this.name} (${this.code}): ${s}`,this.originalError=n}}e.ConnectionError=s}(D||(D={}));let W=new Map([[20101,w.AccessTokenInvalid],[20104,w.AccessTokenExpired],[20151,w.AuthenticationFailed],[3
11202,C.AccessTokenSignatureValidationFailed],[31400,E.BadRequest],[31404,E.NotFound],[31480,E.TemporarilyUnavailable],[31486,E.BusyHere],[31603,T.Decline],[31e3,k.UnknownError],[31001,k.ApplicationNotFoundError],[31002,k.ConnectionDeclinedError],[31003,k.ConnectionTimeoutError],[31005,k.ConnectionError],[31008,k.CallCancelledError],[31009,k.TransportError],[31100,I.MalformedRequestError],[31101,I.MissingParameterArrayError],[31102,I.AuthorizationTokenMissingError],[31103,I.MaxParameterLengthExceededError],[31104,I.InvalidBridgeTokenError],[31105,I.InvalidClientNameError],[31107,I.ReconnectParameterInvalidError],[31201,w.AuthorizationError],[31203,w.NoValidAccountError],[31204,w.InvalidJWTTokenError],[31205,w.JWTTokenExpiredError],[31206,w.RateExceededError],[31207,w.JWTTokenExpirationTooLongError],[31209,w.ReconnectAttemptError],[31210,w.CallMessageEventTypeInvalidError],[31212,w.PayloadSizeExceededError],[31401,P.PermissionDeniedError],[31402,P.AcquisitionFailedError],[53e3,x.ConnectionError],[53001,x.ConnectionDisconnected],[53400,D.ClientLocalDescFailed],[53402,D.ClientRemoteDescFailed],[53405,D.ConnectionError]]);Object.freeze(W);let H=new Set([31001,31002,31003,31101,31102,31103,31104,31105,31107,31201,31202,31203,31204,31205,31207,31404,31480,31486,31603]);function V(e,t){if("number"==typeof t&&J(t)&&(e||!H.has(t)))return z(t)}class B extends Error{constructor(e){super(e),this.name="InvalidArgumentError"}}class q extends Error{constructor(e){super(e),this.name="InvalidStateError"}}class G extends Error{constructor(e){super(e),this.name="NotSupportedError"}}function z(e){let t=W.get(e);if(!t)throw new B(`Error code ${e} not found`);return t}function J(e){return W.has(e)}let Q="@twilio/voice-sdk",K="2.18.1",X="https://sdk.twilio.com/js/client/sounds/releases/1.0.0",Y=`${X}/cowbell.mp3?cache=${K}`;class Z{static getLogLevelInstance(e){if(!Z.loglevelInstance)try{Z.loglevelInstance=(e&&e.LogLevelModule?e.LogLevelModule:N).getLogger(Q)}catch(e){console.warn("Cannot create custom logger"),Z.loglevelInstance=console}return Z.loglevelInstance}constructor(e,t){this._log=Z.getLogLevelInstance(t),this._prefix=`[TwilioVoice][${e}]`}debug(...e){this._log.debug(this._prefix,...e)}error(...e){this._log.error(this._prefix,...e)}info(...e){this._log.info(this._prefix,...e)}setDefaultLevel(e){this._log.setDefaultLevel?this._log.setDefaultLevel(e):console.warn("Logger cannot setDefaultLevel")}warn(...e){this._log.warn(this._prefix,...e)}}Z.levels=N.levels;let ee=Z.getLogLevelInstance(),et=`${X}/outgoing.mp3`;class ei{constructor(e,t,i,s){this._name=e,this._availableDevices=t,this._beforeChange=i,this._isSupported=s,this._activeDevices=new Set,this._log=new Z("OutputDeviceCollection")}delete(e){this._log.debug(".delete",e);let t=!!this._activeDevices.delete(e),i=this._availableDevices.get("default")||Array.from(this._availableDevices.values())[0];!this._activeDevices.size&&i&&this._activeDevices.add(i);let s=Array.from(this._activeDevices.values()).map(e=>e.deviceId);return this._beforeChange(this._name,s),!!t}get(){return this._activeDevices}set(e){if(this._log.debug(".set",e),!this._isSupported)return Promise.reject(new G("This browser does not support audio output selection"));let t=Array.isArray(e)?e:[e];if(!t.length)return Promise.reject(new B("Must specify at least one device to set"));let i=[],s=t.map(e=>{let t=this._availableDevices.get(e);return t||i.push(e),t});return i.length?Promise.reject(new B(`Devices not found: ${i.join(", ")}`)):new Promise(e=>{e(this._beforeChange(this._name,t))}).then(()=>{this._activeDevices.clear(),s.forEach(this._activeDevices.add,this._activeDevices)})}test(e=et){return this._isSupported?this._activeDevices.size?Promise.all(Array.from(this._activeDevices).map(t=>{let i;return new Promise(t=>{(i=new Audio(e)).oncanplay=t}).then(()=>i.setSinkId(t.deviceId).then(()=>i.play()))})):Promise.reject(new q("No active output devices to test")):Promise.reject(new G("This browser does not support audio output selection"))}}class es{constructor(e){Object.defineProperties(this,{deviceId:{get:()=>e.deviceId},groupId:{get:()=>e.groupId}
vendor: 6,774 bytes, line 1
1,kind:{get:()=>e.kind},label:{get:()=>e.label}})}}function en(e){if(!(this instanceof en))return new en(e);this.message=e}function eo(e){return e&&e.length?e.reduce((e,t)=>e+t)/e.length:0}function er(e,t,i){i=i||(e=>e);let s=new Set(t.map(i));return e.filter(e=>!s.has(i(e)))}function ea(e){return!!e.userAgent.match("Electron")}function ec(e,t){let i=!!t.userAgent.match("CriOS"),s=!!t.userAgent.match("HeadlessChrome"),n=void 0!==e.chrome&&"Google Inc."===t.vendor&&-1===t.userAgent.indexOf("OPR")&&-1===t.userAgent.indexOf("Edge");return i||ea(t)||n||s}function el(e){return!!(e=e||("undefined"==typeof window?i.g.navigator:window.navigator))&&"string"==typeof e.userAgent&&/firefox|fxios/i.test(e.userAgent)}function ed(e){return!!(e=e||("undefined"==typeof window?i.g.navigator:window.navigator))&&"string"==typeof e.userAgent&&/edge\/\d+/i.test(e.userAgent)}function eh(e){return!!e.vendor&&-1!==e.vendor.indexOf("Apple")&&e.userAgent&&-1===e.userAgent.indexOf("CriOS")&&-1===e.userAgent.indexOf("FxiOS")}function eu(e){return e?e.split("&").reduce((e,t)=>{let i=t.split("="),s=i[0],n=decodeURIComponent((i[1]||"").replace(/\+/g,"%20"));return s&&(e[s]=n),e},{}):""}function ep(e,t){let i=e instanceof Map||e instanceof Set?Array.from(e.values()):e;return t=t||(e=>e),i.reduce((e,i)=>{let s=t(i);return e.concat(s)},[])}function em(e,t,i){return new Promise((s,n)=>{function o(){e.removeListener(i,r),s()}function r(){e.removeListener(t,o),n()}e.once(t,o),e.once(i,r)})}function eg(e,t){let i=t.map(e=>"audio/"+e.toLowerCase());return e.sort((e,t)=>{let s=i.indexOf(e.mimeType.toLowerCase()),n=i.indexOf(t.mimeType.toLowerCase());return(s>=0?s:Number.MAX_VALUE)-(n>=0?n:Number.MAX_VALUE)})}en.prototype.toString=function(){return`Twilio.Exception: ${this.message}`};let e_=en,ef={audioinput:"Audio Input",audiooutput:"Audio Output"};class ev extends j.EventEmitter{get audioConstraints(){return this._audioConstraints}get inputDevice(){return this._inputDevice}get inputStream(){return this._localProcessedStream||this._selectedInputDeviceStream}get processedStream(){return this._log.warn("AudioHelper#processedStream is deprecated. Please use AudioHelper#localProcessedStream instead."),this._localProcessedStream}get localProcessedStream(){return this._localProcessedStream}get remoteProcessedStream(){return this._remoteProcessedStream}constructor(e,t,i){super(),this.availableInputDevices=new Map,this.availableOutputDevices=new Map,this._audioConstraints=null,this._defaultInputDeviceStream=null,this._enabledSounds={[tr.SoundName.Disconnect]:!0,[tr.SoundName.Incoming]:!0,[tr.SoundName.Outgoing]:!0},this._inputDevice=null,this._inputDevicePromise=null,this._isPollingInputVolume=!1,this._log=new Z("AudioHelper"),this._localProcessedStream=null,this._remoteProcessedStream=null,this._selectedInputDeviceStream=null,this._unknownDeviceIndexes={audioinput:{},audiooutput:{}},this._updateAvailableDevices=()=>this._mediaDevices&&this._enumerateDevices?this._enumerateDevices().then(e=>{this._updateDevices(e.filter(e=>"audiooutput"===e.kind),this.availableOutputDevices,this._removeLostOutput),this._updateDevices(e.filter(e=>"audioinput"===e.kind),this.availableInputDevices,this._removeLostInput);let t=this.availableOutputDevices.get("default")||Array.from(this.availableOutputDevices.values())[0];[this.speakerDevices,this.ringtoneDevices].forEach(e=>{!e.get().size&&this.availableOutputDevices.size&&this.isOutputSelectionSupported&&e.set(t.deviceId).catch(e=>{this._log.warn(`Unable to set audio output devices. ${e}`)})})}):Promise.reject("Enumeration not supported"),this._removeLostInput=e=>{if(!this.inputDevice||this.inputDevice.deviceId!==e.deviceId)return!1;this._destroyLocalProcessedStream(),this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume();let t=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return t&&this.setInputDevice(t.deviceId),!0},this._removeLostOutput=e=>{let t=this.speakerDevices.delete(e),i=this.ringtoneDevices.delete(e);return t||i},i=Object.assign({AudioContext:"undefined"!=typeof AudioContext&&AudioContext,setSinkId:"undefined"!=typeof HTMLAudioElement&&HTMLAudioElement.prototype.setSinkId},i),this._beforeSetInputDevice=i.beforeSetInputDevice||(()=>Promise.resolve()),this._updateUserOptions(i),this._audioProcessorEventObserver=i.audioProcessorEventObserver,this._mediaDevices=i.mediaDevices||navigator.mediaDevices,this._onActiveInputChanged=t,this._enumerateDevices="function"==typeof i.enumerateDevices?i.enumerateDevices:this._mediaDevices&&this._mediaDevices.enumerateDevices.bind(this._mediaDevices);let s=!!(i.AudioContext||i.audioContext),n=!!this._enumerateDevices;i.enabledSounds&&(this._enabledSounds=i.enabledSounds);let o="function"==typeof i.setSinkId;this.isOutputSelectionSupported=n&&o,this.isVolumeSupported=s,this.isVolumeSupported&&(this._audioContext=i.audioContext||i.AudioContext&&new i.AudioContext,this._audioContext&&(this._inputVolumeAnalyser=this._audioContext.createAnalyser(),this._inputVolumeAnalyser.fftSize=32,this._inputVolumeAnalyser.smoothingTimeConstant=.3)),this.ringtoneDevices=new ei("ringtone",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.speakerDevices=new ei("speaker",this.availableOutputDevices,e,this.isOutputSelectionSupported),this.addListener("newListener",e=>{"inputVolume"===e&&this._maybeStartPollingVolume()}),this.addListener("removeListener",e=>{"inputVolume"===e&&this._maybeStopPollingVolume()}),this.once("newListener",()=>{this.isOutputSelectionSupported||this._log.warn("Warning: This browser does not support audio output selection."),this.isVolumeSupported||this._log.warn("Warning: This browser does not support Twilio's volume indicator feature.")}),n&&this._initializeEnumeration(),navigator&&navigator.permissions&&"function"==typeof navigator.permissions.query?navigator.permissions.query({name:"microphone"}).then(e=>{if("granted"!==e.state){let t=()=>{this._updateAvailableDevices(),this._stopMicrophonePermissionListener()};e.addEventListener("change",t),this._microphonePermissionStatus=e,this._onMicrophonePermissionStatusChanged=t}}).catch(e=>this._log.warn(`Warning: unable to listen for microphone permission changes. ${e}`)):this._log.warn("Warning: current browser does not support permissions API.")}_destroy(){this._stopDefaultInputDeviceStream(),this._stopSelectedInputDeviceStream(),this._destroyLocalProcessedStream(),this._destroyRemoteProcessedStream(),this._maybeStopPollingVolume(),this.removeAllListeners(),this._stopMicrophonePermissionListener(),this._unbind()}_destroyRemoteProcessedStream(){if(this._remoteProcessor&&this._remoteProcessedStream){this._log.info("destroying remote processed stream");let e=this._remoteProcessedStream;
1this._remoteProcessedStream.getTracks().forEach(e=>e.stop()),this._remoteProcessedStream=null,this._remoteProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!0)}}_getInputDevicePromise(){return this._inputDevicePromise}_getAudioProcessorEventObserver(){return this._audioProcessorEventObserver}_maybeCreateRemoteProcessedStream(e){return this._remoteProcessor?(this._log.info("Creating remote processed stream"),this._remoteProcessor.createProcessedStream(e).then(e=>(this._remoteProcessedStream=e,this._audioProcessorEventObserver.emit("create",!0),this._remoteProcessedStream))):Promise.resolve(e)}_maybeStartPollingVolume(){if(!this.isVolumeSupported||!this.inputStream||(this._updateVolumeSource(),this._isPollingInputVolume||!this._inputVolumeAnalyser))return;let e=new Uint8Array(this._inputVolumeAnalyser.frequencyBinCount);this._isPollingInputVolume=!0;let t=()=>{if(this._isPollingInputVolume){if(this._inputVolumeAnalyser){this._inputVolumeAnalyser.getByteFrequencyData(e);let t=eo(e);this.emit("inputVolume",t/255)}requestAnimationFrame(t)}};requestAnimationFrame(t)}_maybeStopPollingVolume(){!this.isVolumeSupported||!this._isPollingInputVolume||this.inputStream&&this.listenerCount("inputVolume")||(this._inputVolumeSource&&(this._inputVolumeSource.disconnect(),delete this._inputVolumeSource),this._isPollingInputVolume=!1)}_openDefaultDeviceWithConstraints(e){return this._log.info("Opening default device with constraints",e),this._getUserMedia(e).then(e=>(this._log.info("Opened default device. Updating available devices."),this._updateAvailableDevices().catch(e=>{this._log.warn("Unable to updateAvailableDevices after gUM call",e)}),this._defaultInputDeviceStream=e,this._maybeCreateLocalProcessedStream(e)))}_stopDefaultInputDeviceStream(){this._defaultInputDeviceStream&&(this._log.info("stopping default device stream"),this._defaultInputDeviceStream.getTracks().forEach(e=>e.stop()),this._defaultInputDeviceStream=null,this._destroyLocalProcessedStream())}_unbind(){var e;(null===(e=this._mediaDevices)||void 0===e?void 0:e.removeEventListener)&&this._mediaDevices.removeEventListener("devicechange",this._updateAvailableDevices)}_updateUserOptions(e){"function"==typeof e.enumerateDevices&&(this._enumerateDevices=e.enumerateDevices),"function"==typeof e.getUserMedia&&(this._getUserMedia=e.getUserMedia)}addProcessor(e,t=!1){if(this._log.debug(".addProcessor"),this._localProcessor&&!t)throw new G("Can only have one Local AudioProcessor at a time.");if(this._remoteProcessor&&t)throw new G("Can only have one Remote AudioProcessor at a time.");if("object"!=typeof e||null===e)throw new B("Missing AudioProcessor argument.");if("function"!=typeof e.createProcessedStream)throw new B("Missing createProcessedStream() method.");if("function"!=typeof e.destroyProcessedStream)throw new B("Missing destroyProcessedStream() method.");return t?(this._remoteProcessor=e,this._audioProcessorEventObserver.emit("add",!0),Promise.resolve()):(this._localProcessor=e,this._audioProcessorEventObserver.emit("add",!1),this._restartInputStreams())}disconnect(e){return this._log.debug(".disconnect",e),this._maybeEnableSound(tr.SoundName.Disconnect,e)}incoming(e){return this._log.debug(".incoming",e),this._maybeEnableSound(tr.SoundName.Incoming,e)}outgoing(e){return this._log.debug(".outgoing",e),this._maybeEnableSound(tr.SoundName.Outgoing,e)}removeProcessor(e,t=!1){if(this._log.debug(".removeProcessor"),"object"!=typeof e||null===e)throw new B("Missing AudioProcessor argument.");if(this._localProcessor!==e&&!t)throw new B("Cannot remove a Local AudioProcessor that has not been previously added.");if(this._remoteProcessor!==e&&t)throw new B("Cannot remove a Remote AudioProcessor that has not been previously added.");return t?(this._destroyRemoteProcessedStream(),this._remoteProcessor=null,this._audioProcessorEventObserver.emit("remove",!0),Promise.resolve()):(this._destroyLocalProcessedStream(),this._localProcessor=null,this._audioProcessorEventObserver.emit("remove",!1),this._restartInputStreams())}setAudioConstraints(e){return this._log.debug(".setAudioConstraints",e),this._audioConstraints=Object.assign({},e),delete this._audioConstraints.deviceId,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}setInputDevice(e){return this._log.debug(".setInputDevice",e),this._setInputDevice(e,!1)}unsetAudioConstraints(){return this._log.debug(".unsetAudioConstraints"),this._audioConstraints=null,this.inputDevice?this._setInputDevice(this.inputDevice.deviceId,!0):Promise.resolve()}unsetInputDevice(){return(this._log.debug(".unsetInputDevice",this.inputDevice),this.inputDevice)?(this._destroyLocalProcessedStream(),this._onActiveInputChanged(null).then(()=>{this._replaceStream(null),this._inputDevice=null,this._maybeStopPollingVolume()})):Promise.resolve()}_destroyLocalProcessedStream(){if(this._localProcessor&&this._localProcessedStream){this._log.info("destroying local processed stream");let e=this._localProcessedStream;
1this._localProcessedStream.getTracks().forEach(e=>e.stop()),this._localProcessedStream=null,this._localProcessor.destroyProcessedStream(e),this._audioProcessorEventObserver.emit("destroy",!1)}}_getUnknownDeviceIndex(e){let t=e.deviceId,i=e.kind,s=this._unknownDeviceIndexes[i][t];return s||(s=Object.keys(this._unknownDeviceIndexes[i]).length+1,this._unknownDeviceIndexes[i][t]=s),s}_initializeEnumeration(){if(!this._mediaDevices||!this._enumerateDevices)throw new G("Enumeration is not supported");this._mediaDevices.addEventListener&&this._mediaDevices.addEventListener("devicechange",this._updateAvailableDevices),this._updateAvailableDevices().then(()=>{this.isOutputSelectionSupported&&Promise.all([this.speakerDevices.set("default"),this.ringtoneDevices.set("default")]).catch(e=>{this._log.warn(`Warning: Unable to set audio output devices. ${e}`)})})}_maybeCreateLocalProcessedStream(e){return this._localProcessor?(this._log.info("Creating local processed stream"),this._localProcessor.createProcessedStream(e).then(e=>(this._localProcessedStream=e,this._audioProcessorEventObserver.emit("create",!1),this._localProcessedStream))):Promise.resolve(e)}_maybeEnableSound(e,t){return void 0!==t&&(this._enabledSounds[e]=t),this._enabledSounds[e]}_replaceStream(e){this._log.info("Replacing with new stream."),this._selectedInputDeviceStream&&(this._log.info("Old stream detected. Stopping tracks."),this._stopSelectedInputDeviceStream()),this._selectedInputDeviceStream=e}_restartInputStreams(){if(this.inputDevice&&this._selectedInputDeviceStream)return this._log.info("Restarting selected input device"),this._setInputDevice(this.inputDevice.deviceId,!0);if(this._defaultInputDeviceStream){let e=this.availableInputDevices.get("default")||Array.from(this.availableInputDevices.values())[0];return this._log.info("Restarting default input device, now becoming selected."),this._setInputDevice(e.deviceId,!0)}return Promise.resolve()}_setInputDevice(e,t){return F(this,void 0,void 0,function*(){return this._inputDevicePromise=F(this,void 0,void 0,function*(){if(yield this._beforeSetInputDevice(),"string"!=typeof e)return Promise.reject(new B("Must specify the device to set"));let i=this.availableInputDevices.get(e);if(!i)return Promise.reject(new B(`Device not found: ${e}`));if(this._log.info("Setting input device. ID: "+e),this._inputDevice&&this._inputDevice.deviceId===e&&this._selectedInputDeviceStream){if(!t)return Promise.resolve();this._log.info("Same track detected on setInputDevice, stopping old tracks."),this._stopSelectedInputDeviceStream()}this._stopDefaultInputDeviceStream();let s={audio:Object.assign({deviceId:{exact:e}},this.audioConstraints)};return this._log.info("setInputDevice: getting new tracks."),this._getUserMedia(s).then(e=>(this._destroyLocalProcessedStream(),this._maybeCreateLocalProcessedStream(e).then(t=>(this._log.info("setInputDevice: invoking _onActiveInputChanged."),this._onActiveInputChanged(t).then(()=>{this._replaceStream(e),this._inputDevice=i,this._maybeStartPollingVolume()})))))}).finally(()=>{this._inputDevicePromise=null})})}_stopMicrophonePermissionListener(){var e;(null===(e=this._microphonePermissionStatus)||void 0===e?void 0:e.removeEventListener)&&this._microphonePermissionStatus.removeEventListener("change",this._onMicrophonePermissionStatusChanged)}_stopSelectedInputDeviceStream(){this._selectedInputDeviceStream&&(this._log.info("Stopping selected device stream"),this._selectedInputDeviceStream.getTracks().forEach(e=>e.stop()))}_updateDevices(e,t,i){let s=e.map(e=>e.deviceId),n=Array.from(t.values()).map(e=>e.deviceId),o=[],r=er(n,s);r.forEach(e=>{let s=t.get(e);s&&(t.delete(e),i(s)&&o.push(s))});let a=!1;if(e.forEach(e=>{let i=t.get(e.deviceId),s=this._wrapMediaDeviceInfo(e);i&&i.label===s.label||(t.set(e.deviceId,s),a=!0)}),a||r.length){let e="default",t=this.inputDevice&&this.inputDevice.deviceId===e,i=this._defaultInputDeviceStream&&this.availableInputDevices.get(e);(t||i)&&(this._log.warn("Calling getUserMedia after device change to ensure that the           tracks of the active device (default) have not gone stale."),setTimeout(()=>{this._setInputDevice(e,!0)}
1,0)),this._log.debug("#deviceChange",o),this.emit("deviceChange",o)}}_updateVolumeSource(){if(this.inputStream&&this._audioContext&&this._inputVolumeAnalyser){this._inputVolumeSource&&this._inputVolumeSource.disconnect();try{this._inputVolumeSource=this._audioContext.createMediaStreamSource(this.inputStream),this._inputVolumeSource.connect(this._inputVolumeAnalyser)}catch(e){this._log.warn("Unable to update volume source",e),delete this._inputVolumeSource}}}_wrapMediaDeviceInfo(e){let t={deviceId:e.deviceId,groupId:e.groupId,kind:e.kind,label:e.label};if(!t.label){if("default"===t.deviceId)t.label="Default";else{let i=this._getUnknownDeviceIndex(e);t.label=`Unknown ${ef[t.kind]} Device ${i}`}}return new es(t)}}ev||(ev={});var ey=ev;class eb extends j.EventEmitter{constructor(){super(),this._log=new Z("AudioProcessorEventObserver"),this._log.info("Creating AudioProcessorEventObserver instance"),this.on("enabled",e=>this._reEmitEvent("enabled",e)),this.on("add",e=>this._reEmitEvent("add",e)),this.on("remove",e=>this._reEmitEvent("remove",e)),this.on("create",e=>this._reEmitEvent("create-processed-stream",e)),this.on("destroy",e=>this._reEmitEvent("destroy-processed-stream",e))}destroy(){this.removeAllListeners()}_reEmitEvent(e,t){this._log.info(`${t?"Remote":"Local"} AudioProcessor:${e}`),this.emit("event",{name:e,group:"audio-processor",isRemote:t})}}let eS={dtmf0:[1360,960],dtmf1:[1230,720],dtmf2:[1360,720],dtmf3:[1480,720],dtmf4:[1230,790],dtmf5:[1360,790],dtmf6:[1480,790],dtmf7:[1230,870],dtmf8:[1360,870],dtmf9:[1480,870],dtmfh:[1480,960],dtmfs:[1230,960]};class ew{constructor(e){this._context=e,this._gainNodes=[],this._gainNodes=[this._context.createGain(),this._context.createGain()],this._gainNodes.forEach(e=>{e.connect(this._context.destination),e.gain.value=.1,this._gainNodes.push(e)})}cleanup(){this._gainNodes.forEach(e=>{e.disconnect()})}play(e){let t=eS[e];if(!t)throw new B("Invalid DTMF sound name");[this._context.createOscillator(),this._context.createOscillator()].forEach((e,i)=>{e.type="sine",e.frequency.value=t[i],e.connect(this._gainNodes[i]),e.start(),e.stop(this._context.currentTime+.1),e.addEventListener("ended",()=>e.disconnect())})}}let eC=function(e,t,i){let s=JSON.stringify(t.body||{}),n=new Headers;t.headers=t.headers||[],Object.entries(t.headers).forEach(([e,t])=>n.append(e,t)),fetch(t.url,{body:s,headers:n,method:e}).then(e=>e.text(),i).then(e=>i(null,e),i)};eC.get=function(e,t){return new this("GET",e,t)},eC.post=function(e,t){return new this("POST",e,t)};class eE extends j.EventEmitter{constructor(e,t,i){if(super(),!(this instanceof eE))return new eE(e,t,i);let s=(i=Object.assign({defaultPayload:()=>({})},i)).defaultPayload;"function"!=typeof s&&(s=()=>Object.assign({},i.defaultPayload));let n=!0,o=Object.assign({app_name:void 0,app_version:void 0},i.metadata);Object.defineProperties(this,{_defaultPayload:{value:s},_host:{value:i.host,writable:!0},_isEnabled:{get:()=>n,set(e){n=e}},_log:{value:new Z("EventPublisher")},_request:{value:i.request||eC,writable:!0},_token:{value:t,writable:!0},isEnabled:{enumerable:!0,get:()=>n},metadata:{enumerable:!0,get:()=>o},productName:{enumerable:!0,value:e},token:{enumerable:!0,get(){return this._token}}})}}function eT(e){return{audio_codec:e.codecName,audio_level_in:e.audioInputLevel,audio_level_out:e.audioOutputLevel,bytes_received:e.bytesReceived,bytes_sent:e.bytesSent,call_volume_input:e.inputVolume,call_volume_output:e.outputVolume,jitter:e.jitter,mos:e.mos&&Math.round(100*e.mos)/100,packets_lost:e.packetsLost,packets_lost_fraction:e.packetsLostFraction&&Math.round(100*e.packetsLostFraction)/100,packets_received:e.packetsReceived,rtt:e.rtt,timestamp:new Date(e.timestamp).toISOString(),total_bytes_received:e.totals.bytesReceived,total_bytes_sent:e.totals.bytesSent,total_packets_lost:e.totals.packetsLost,total_packets_received:e.totals.packetsReceived,total_packets_sent:e.totals.packetsSent}}eE.prototype._post=function(e,t,i,s,n,o,r){if(!this.isEnabled&&!r||!this._host)return this._log.debug("Publishing cancelled",JSON.stringify({isEnabled:this.isEnabled,force:r,host:this._host})),Promise.resolve();if(!o||(!o.parameters||!o.parameters.CallSid)&&!o.outboundConnectionId)return o?this._log.debug("Publishing cancelled. Missing connection info",JSON.stringify({outboundConnectionId:o.outboundConnectionId,parameters:o.parameters})):this._log.debug("Publishing cancelled. Missing connection object"),Promise.resolve();
1let a={group:i,level:t.toUpperCase(),name:s,payload:n&&n.forEach?n.slice(0):Object.assign(this._defaultPayload(o),n),payload_type:"application/json",private:!1,publisher:this.productName,timestamp:new Date().toISOString()};this.metadata&&(a.publisher_metadata=this.metadata),"EndpointEvents"===e&&this._log.debug("Publishing insights",JSON.stringify({endpointName:e,event:a,force:r,host:this._host}));let c={body:a,headers:{"Content-Type":"application/json","X-Twilio-Token":this.token},url:`https://${this._host}/v4/${e}`};return new Promise((e,t)=>{this._request.post(c,i=>{i?(this.emit("error",i),t(i)):e()})}).catch(e=>{this._log.error(`Unable to post ${i} ${s} event to Insights. Received error: ${e}`)})},eE.prototype.post=function(e,t,i,s,n,o){return this._post("EndpointEvents",e,t,i,s,n,o)},eE.prototype.debug=function(e,t,i,s){return this.post("debug",e,t,i,s)},eE.prototype.info=function(e,t,i,s){return this.post("info",e,t,i,s)},eE.prototype.warn=function(e,t,i,s){return this.post("warning",e,t,i,s)},eE.prototype.error=function(e,t,i,s){return this.post("error",e,t,i,s)},eE.prototype.postMetrics=function(e,t,i,s,n){return new Promise(o=>{let r=i.map(eT).map(e=>Object.assign(e,s));o(this._post("EndpointMetrics","info",e,t,r,n))})},eE.prototype.setHost=function(e){this._host=e},eE.prototype.setToken=function(e){this._token=e},eE.prototype.enable=function(){this._isEnabled=!0},eE.prototype.disable=function(){this._isEnabled=!1};let ek="undefined"!=typeof window?window.RTCStatsReport:void 0;function eI(e){if(!(this instanceof eI))return new eI(e);let t=this;Object.defineProperties(this,{_map:{value:e},size:{enumerable:!0,get:()=>t._map.size}}),this[Symbol.iterator]=e[Symbol.iterator]}function eP(e){return{bytesReceived:void 0,bytesSent:void 0,dtlsState:void 0,id:e.id,localCertificateId:e.stat("localCertificateId"),remoteCertificateId:e.stat("remoteCertificateId"),rtcpTransportStatsId:void 0,selectedCandidatePairId:e.stat("selectedCandidatePairId"),timestamp:Date.parse(e.timestamp),type:"transport"}}function ex(e,t){return{associateStatsId:void 0,codecId:`codec-${e.id}`,firCount:t?eR(e,"googFirsSent"):void 0,id:e.id,isRemote:void 0,mediaType:e.stat("mediaType"),nackCount:t?eR(e,"googNacksSent"):eR(e,"googNacksReceived"),pliCount:t?eR(e,"googPlisSent"):eR(e,"googPlisReceived"),qpSum:eR(e,"qpSum"),sliCount:void 0,ssrc:e.stat("ssrc"),timestamp:Date.parse(e.timestamp),trackId:`track-${e.id}`,transportId:e.stat("transportId")}}function eD(e,t){return{candidateType:function(e){switch(e){case"peerreflexive":return"prflx";case"serverreflexive":return"srflx";default:return e}}(e.stat("candidateType")),deleted:void 0,id:e.id,ip:e.stat("ipAddress"),isRemote:t,port:eR(e,"portNumber"),priority:eO(e,"priority"),protocol:e.stat("transport"),relayProtocol:void 0,timestamp:Date.parse(e.timestamp),transportId:void 0,type:t?"remote-candidate":"local-candidate",url:void 0}}function eA(e){return isNaN(e)||""===e?void 0:parseInt(e,10)/1e3}function eR(e,t){let i=e.stat(t);return eM(e,t)?parseInt(i,10):void 0}function eO(e,t){let i=e.stat(t);return eM(e,t)?parseFloat(i):void 0}function eL(e,t){let i=e.stat(t);return eM(e,t)?"true"===i||!0===i:void 0}function eM(e,t){let i=e.stat(t);return void 0!==i&&""!==i}function ej(e,t){return"function"==typeof e.get?e.get(t):e.find(e=>e.id===t)}function e$(e){let t;if(!e)return Promise.reject(new B("PeerConnection is null"));if("function"!=typeof e.getStats)return Promise.reject(new G("WebRTC statistics are unsupported"));try{t=e.getStats()}catch(i){t=new Promise(t=>e.getStats(t)).then(eI.fromRTCStatsResponse)}return t}function eF(e,t){return t=Object.assign({createRTCSample:eU},t),e$(e).then(t.createRTCSample)}function eN(){}function eU(e){let t,i=null,s=new eN;Array.from(e.values()).forEach(n=>{if(n.isRemote)return;let o=n.type.replace("-","");if(t=t||n.timestamp,n.remoteId){let t=ej(e,n.remoteId);t&&t.roundTripTime&&(s.rtt=1e3*t.roundTripTime)}switch(o){case"inboundrtp":s.timestamp=s.timestamp||n.timestamp,s.jitter=1e3*n.jitter,s.packetsLost=n.packetsLost,s.packetsReceived=n.packetsReceived,s.bytesReceived=n.bytesReceived;break;case"outboundrtp":if(s.timestamp=n.timestamp,s.packetsSent=n.packetsSent,s.bytesSent=n.bytesSent,n.codecId){let t=ej(e,n.codecId);s.codecName=t?t.mimeType&&t.mimeType.match(/(.*\/)?(.*)/)[2]:n.co
1decId}break;case"transport":i=n.id}}),s.timestamp||(s.timestamp=t);let n=ej(e,i);if(!n)return s;let o=ej(e,n.selectedCandidatePairId);if(!o)return s;let r=ej(e,o.localCandidateId),a=ej(e,o.remoteCandidateId);return s.rtt||(s.rtt=o&&1e3*o.currentRoundTripTime),Object.assign(s,{localAddress:r&&(r.address||r.ip),remoteAddress:a&&(a.address||a.ip)}),s}ek&&(eI.prototype=Object.create(ek.prototype),eI.prototype.constructor=eI),["entries","forEach","get","has","keys","values"].forEach(e=>{eI.prototype[e]=function(...t){return this._map[e](...t)}}),eI.fromArray=function(e){return new eI(e.reduce((e,t)=>(e.set(t.id,t),e),new Map))},eI.fromRTCStatsResponse=function(e){let t;let i=new Map,s=e.result().reduce((e,s)=>{let n=s.id;switch(s.type){case"googCertificate":e.set(n,{base64Certificate:s.stat("googDerBase64"),fingerprint:s.stat("googFingerprint"),fingerprintAlgorithm:s.stat("googFingerprintAlgorithm"),id:s.id,issuerCertificateId:s.stat("googIssuerId"),timestamp:Date.parse(s.timestamp),type:"certificate"});break;case"datachannel":e.set(n,{bytesReceived:void 0,bytesSent:void 0,datachannelid:s.stat("datachannelid"),id:s.id,label:s.stat("label"),messagesReceived:void 0,messagesSent:void 0,protocol:s.stat("protocol"),state:s.stat("state"),timestamp:Date.parse(s.timestamp),transportId:s.stat("transportId"),type:"data-channel"});break;case"googCandidatePair":eL(s,"googActiveConnection")&&(t=n),e.set(n,{availableIncomingBitrate:void 0,availableOutgoingBitrate:void 0,bytesReceived:eR(s,"bytesReceived"),bytesSent:eR(s,"bytesSent"),consentRequestsSent:eR(s,"consentRequestsSent"),currentRoundTripTime:eA(s.stat("googRtt")),id:s.id,lastPacketReceivedTimestamp:void 0,lastPacketSentTimestamp:void 0,localCandidateId:s.stat("localCandidateId"),nominated:void 0,priority:void 0,readable:void 0,remoteCandidateId:s.stat("remoteCandidateId"),requestsReceived:eR(s,"requestsReceived"),requestsSent:eR(s,"requestsSent"),responsesReceived:eR(s,"responsesReceived"),responsesSent:eR(s,"responsesSent"),retransmissionsReceived:void 0,retransmissionsSent:void 0,state:void 0,timestamp:Date.parse(s.timestamp),totalRoundTripTime:void 0,transportId:s.stat("googChannelId"),type:"candidate-pair",writable:eL(s,"googWritable")});break;case"localcandidate":e.set(n,eD(s,!1));break;case"remotecandidate":e.set(n,eD(s,!0));break;case"ssrc":eM(s,"packetsReceived")?e.set(`rtp-${n}`,function(e){let t=ex(e,!0);return Object.assign(t,{burstDiscardCount:void 0,burstDiscardRate:void 0,burstLossCount:void 0,burstLossRate:void 0,burstPacketsDiscarded:void 0,burstPacketsLost:void 0,bytesReceived:eR(e,"bytesReceived"),fractionLost:void 0,framesDecoded:eR(e,"framesDecoded"),gapDiscardRate:void 0,gapLossRate:void 0,jitter:eA(e.stat("googJitterReceived")),packetsDiscarded:void 0,packetsLost:eR(e,"packetsLost"),packetsReceived:eR(e,"packetsReceived"),packetsRepaired:void 0,roundTripTime:eA(e.stat("googRtt")),type:"inbound-rtp"}),t}(s)):e.set(`rtp-${n}`,function(e){let t=ex(e,!1);return Object.assign(t,{bytesSent:eR(e,"bytesSent"),framesEncoded:eR(e,"framesEncoded"),packetsSent:eR(e,"packetsSent"),remoteTimestamp:void 0,targetBitrate:void 0,type:"outbound-rtp"}),t}(s)),e.set(`track-${n}`,{audioLevel:eM(s,"audioOutputLevel")?eR(s,"audioOutputLevel")/32767:(eR(s,"audioInputLevel")||0)/32767,detached:void 0,echoReturnLoss:eO(s,"googEchoCancellationReturnLoss"),echoReturnLossEnhancement:eO(s,"googEchoCancellationReturnLossEnhancement"),ended:void 0,frameHeight:eM(s,"googFrameHeightReceived")?eR(s,"googFrameHeightReceived"):eR(s,"googFrameHeightSent"),frameWidth:eM(s,"googFrameWidthReceived")?eR(s,"googFrameWidthReceived"):eR(s,"googFrameWidthSent"),framesCorrupted:void 0,framesDecoded:eR(s,"framesDecoded"),framesDropped:void 0,framesPerSecond:void 0,framesReceived:void 0,framesSent:eR(s,"framesEncoded"),fullFramesLost:void 0,id:s.id,kind:s.stat("mediaType"),partialFramesLost:void 0,remoteSource:void 0,ssr
1cIds:void 0,timestamp:Date.parse(s.timestamp),trackIdentifier:s.stat("googTrackId"),type:"track"}),e.set(`codec-${n}`,{channels:void 0,clockRate:void 0,id:s.id,implementation:void 0,mimeType:`${s.stat("mediaType")}/${s.stat("googCodecName")}`,payloadType:void 0,sdpFmtpLine:void 0,timestamp:Date.parse(s.timestamp),type:"codec"});break;case"googComponent":let o=eP(s);i.set(o.selectedCandidatePairId,n),e.set(n,eP(s))}return e},new Map);if(t){let e=i.get(t);e&&(s.get(e).dtlsState="connected")}return new eI(s)};class eW extends j.EventEmitter{constructor(e,t){super(),this._hasInsightsErrored=!1,this._log=new Z("PreflightTest"),this._networkTiming={},this._options={codecPreferences:[tf.Codec.PCMU,tf.Codec.Opus],edge:"roaming",fakeMicInput:!1,logLevel:"error",signalingTimeoutMs:1e4},this._status=eW.Status.Connecting,Object.assign(this._options,t),this._samples=[],this._warnings=[],this._startTime=Date.now(),this._initDevice(e,Object.assign(Object.assign({},this._options),{fileInputStream:this._options.fakeMicInput?this._getStreamFromFile():void 0}));let i=["codecPreferences","edge","fakeMicInput","logLevel","signalingTimeoutMs"],s=["audioContext","deviceFactory","fileInputStream","getRTCIceCandidateStatsReport","iceServers","rtcConfiguration"];if("object"==typeof t){let e=Object.assign({},t);Object.keys(e).forEach(t=>{i.includes(t)||s.includes(t)||delete e[t],s.includes(t)&&(e[t]=!0)}),this._log.debug(".constructor",JSON.stringify(e))}}stop(){this._log.debug(".stop");let e=new k.CallCancelledError;this._device?(this._device.once(tr.EventName.Unregistered,()=>this._onFailed(e)),this._device.destroy()):this._onFailed(e)}_emitWarning(e,t,i){let s={name:e,description:t};i&&(s.rtcWarning=i),this._warnings.push(s),this._log.debug(`#${eW.Events.Warning}`,JSON.stringify(s)),this.emit(eW.Events.Warning,s)}_getCallQuality(e){return e>4.2?eW.CallQuality.Excellent:e>=4.1&&e<=4.2?eW.CallQuality.Great:e>=3.7&&e<=4?eW.CallQuality.Good:e>=3.1&&e<=3.6?eW.CallQuality.Fair:eW.CallQuality.Degraded}_getReport(){var e,t,i;let s=this._getRTCStats(),n={start:this._startTime};this._endTime&&(n.end=this._endTime,n.duration=this._endTime-this._startTime);let o={callSid:this._callSid,edge:this._edge,iceCandidateStats:null!==(t=null===(e=this._rtcIceCandidateStatsReport)||void 0===e?void 0:e.iceCandidateStats)&&void 0!==t?t:[],networkTiming:this._networkTiming,samples:this._samples,selectedEdge:this._options.edge,stats:s,testTiming:n,totals:this._getRTCSampleTotals(),warnings:this._warnings},r=null===(i=this._rtcIceCandidateStatsReport)||void 0===i?void 0:i.selectedIceCandidatePairStats;return r&&(o.selectedIceCandidatePairStats=r,o.isTurnRequired="relay"===r.localCandidate.candidateType||"relay"===r.remoteCandidate.candidateType),s&&(o.callQuality=this._getCallQuality(s.mos.average)),o}_getRTCSampleTotals(){if(this._latestSample)return Object.assign({},this._latestSample.totals)}_getRTCStats(){let e=this._samples.findIndex(e=>"number"==typeof e.mos&&e.mos>0),t=e>=0?this._samples.slice(e):[];if(t&&t.length)return["jitter","mos","rtt"].reduce((e,i)=>{let s=t.map(e=>e[i]);return Object.assign(Object.assign({},e),{[i]:{average:Number((s.reduce((e,t)=>e+t)/s.length).toPrecision(5)),max:Math.max(...s),min:Math.min(...s)}})},{})}_getStreamFromFile(){let e=this._options.audioContext;if(!e)throw new G("Cannot fake input audio stream: AudioContext is not supported by this browser.");let t=new Audio(Y);t.addEventListener("canplaythrough",()=>t.play()),"function"==typeof t.setAttribute&&t.setAttribute("crossorigin","anonymous");let i=e.createMediaElementSource(t),s=e.createMediaStreamDestination();return i.connect(s),s.stream}_initDevice(e,t){try{this._device=new(t.deviceFactory||tr)(e,{chunderw:t.chunderw,codecPreferences:t.codecPreferences,edge:t.edge,eventgw:t.eventgw,fileInputStream:t.fileInputStream,logLevel:t.logLevel,preflight:!0}),this._device.once(tr.EventName.Registered,()=>{this._onDeviceRegistered()}),this._device.once(tr.EventName.Error,e=>{this._onDeviceError(e)}),this._device.register()}catch(e){setTimeout(()=>{this._onFailed(e)});return}this._signalingTimeoutTimer=setTimeout(()=>{this._onDeviceError(new x.ConnectionError("WebSocket Connection Timeout"))},t.signalingTimeoutMs)}_onDeviceError(e){this._device.destroy(),this._onFailed(e)}_onDeviceRegistered(){return F(this,void 0,void 0,function*(){if(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._call=yield this._device.connect({rtcConfiguration:this._options.rtcConfiguration}),this._networkTiming.signaling={start:Date.now()},this._setupCallHandlers(this._call),this._edge=this._device.edge||void 0,this._options.fakeMicInput){this._echoTimer=setTimeout(()=>this._device.disconnectAll(),2e4);let e=this._device.audio;e&&(e.disconnect(!1),e.outgoing(!1))}this._call.once("disconnect",()=>{this._device.once(tr.EventName.Unregistered,()=>this._onUnregistered()),this._device.destroy()}),this._call._publisher.on("error",()=>{this._hasInsightsErrored||this._emitWarning("insights-connection-error","Received an error when attempting to connect to Insights gateway"),this._hasInsightsErrored=!0})})}_onFailed(e){clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=eW.Status.Failed,this._log.debug(`#${eW.Events.Failed}
1`,e),this.emit(eW.Events.Failed,e)}_onUnregistered(){setTimeout(()=>{this._status!==eW.Status.Failed&&(clearTimeout(this._echoTimer),clearTimeout(this._signalingTimeoutTimer),this._releaseHandlers(),this._endTime=Date.now(),this._status=eW.Status.Completed,this._report=this._getReport(),this._log.debug(`#${eW.Events.Completed}`,JSON.stringify(this._report)),this.emit(eW.Events.Completed,this._report))},10)}_releaseHandlers(){[this._device,this._call].forEach(e=>{e&&e.eventNames().forEach(t=>e.removeAllListeners(t))})}_setupCallHandlers(e){this._options.fakeMicInput&&e.once("volume",()=>{e._mediaHandler.outputs.forEach(e=>e.audio.muted=!0)}),e.on("warning",(e,t)=>{this._emitWarning(e,"Received an RTCWarning. See .rtcWarning for the RTCWarning",t)}),e.once("accept",()=>{this._callSid=e._mediaHandler.callSid,this._status=eW.Status.Connected,this._log.debug(`#${eW.Events.Connected}`),this.emit(eW.Events.Connected)}),e.on("sample",t=>F(this,void 0,void 0,function*(){this._latestSample||(this._rtcIceCandidateStatsReport=yield(this._options.getRTCIceCandidateStatsReport||function(e){return e$(e).then(e=>{let t;let{candidatePairs:i,localCandidates:s,remoteCandidates:n,transport:o}=Array.from(e.values()).reduce((e,t)=>{switch(["candidatePairs","localCandidates","remoteCandidates"].forEach(t=>{e[t]||(e[t]=[])}),t.type){case"candidate-pair":e.candidatePairs.push(t);break;case"local-candidate":e.localCandidates.push(t);break;case"remote-candidate":e.remoteCandidates.push(t);break;case"transport":t.selectedCandidatePairId&&(e.transport=t)}return e},{}),r=i.find(e=>e.selected||o&&e.id===o.selectedCandidatePairId);return r&&(t={localCandidate:s.find(e=>e.id===r.localCandidateId),remoteCandidate:n.find(e=>e.id===r.remoteCandidateId)}),{iceCandidateStats:[...s,...n],selectedIceCandidatePairStats:t}})})(e._mediaHandler.version.pc)),this._latestSample=t,this._samples.push(t),this._log.debug(`#${eW.Events.Sample}`,JSON.stringify(t)),this.emit(eW.Events.Sample,t)})),[{reportLabel:"peerConnection",type:"pcconnection"},{reportLabel:"ice",type:"iceconnection"},{reportLabel:"dtls",type:"dtlstransport"},{reportLabel:"signaling",type:"signaling"}].forEach(({type:t,reportLabel:i})=>{let s=`on${t}statechange`,n=e._mediaHandler[s];e._mediaHandler[s]=e=>{let t=this._networkTiming[i]=this._networkTiming[i]||{start:0};"connecting"===e||"checking"===e?t.start=Date.now():"connected"!==e&&"stable"!==e||t.duration||(t.end=Date.now(),t.duration=t.end-t.start),n(e)}})}get callSid(){return this._callSid}get endTime(){return this._endTime}get latestSample(){return this._latestSample}get report(){return this._report}get startTime(){return this._startTime}get status(){return this._status}}(n=(s=eW||(eW={})).CallQuality||(s.CallQuality={})).Excellent="excellent",n.Great="great",n.Good="good",n.Fair="fair",n.Degraded="degraded",(o=s.Events||(s.Events={})).Completed="completed",o.Connected="connected",o.Failed="failed",o.Sample="sample",o.Warning="warning",(r=s.Status||(s.Status={})).Connecting="connecting",r.Connected="connected",r.Completed="completed",r.Failed="failed";let eH=globalThis.WebSocket;(a=A||(A={})).Connecting="connecting",a.Closed="closed",a.Open="open";class eV extends j.EventEmitter{constructor(e,t={}){super(),this.state=A.Closed,this._backoffStartTime={preferred:null,primary:null},this._connectedUri=null,this._log=new Z("WSTransport"),this._retryAfter=null,this._shouldFallback=!1,this._uriIndex=0,this._moveUriIndex=()=>{this._uriIndex++,this._uriIndex>=this._uris.length&&(this._uriIndex=0)},this._onSocketClose=e=>{if(this._log.error(`Received websocket close event code: ${e.code}. Reason: ${e.reason}`),1006===e.code||1015===e.code){this.emit("error",{code:31005,message:e.reason||"Websocket connection to Twilio's signaling servers were unexpectedly ended. If this is happening consistently, there may be an issue resolving the hostname provided. If a region or an edge is being specified in Device setup, ensure it is valid.",twilioError:new x.ConnectionError});let t=this.state===A.Open||this._previousState===A.Open;(this._shouldFallback||!t)&&this._moveUriIndex(),this._shouldFallback=!0}this._closeSocket()},this._onSocketError=e=>{this._log.error(`WebSocket received error: ${e.message}
1`),this.emit("error",{code:31e3,message:e.message||"WSTransport socket error",twilioError:new x.ConnectionDisconnected})},this._onSocketMessage=e=>{if(this._setHeartbeatTimeout(),this._socket&&"\n"===e.data){this._socket.send("\n"),this._log.debug("heartbeat");return}if(e&&"string"==typeof e.data){this._log.debug(`Received: ${e.data}`);let{type:t,payload:i={}}=JSON.parse(e.data);"error"===t&&i.error&&i.error.retryAfter&&(this._retryAfter=1e3*i.error.retryAfter)}this.emit("message",e)},this._onSocketOpen=()=>{this._log.info("WebSocket opened successfully."),this._timeOpened=Date.now(),this._shouldFallback=!1,this._setState(A.Open),clearTimeout(this._connectTimeout),this._backoff&&this._resetBackoffs(),this._setHeartbeatTimeout(),this.emit("open")},this._options=Object.assign(Object.assign({},eV.defaultConstructorOptions),t),this._uris=e,this._backoff=null}close(){this._log.info("WSTransport.close() called..."),this._close()}open(){if(this._log.info("WSTransport.open() called..."),this._socket&&(this._socket.readyState===eH.CONNECTING||this._socket.readyState===eH.OPEN)){this._log.info("WebSocket already open.");return}this._preferredUri?this._connect(this._preferredUri):this._connect(this._uris[this._uriIndex])}send(e){if(this._log.debug(`Sending: ${e}`),!this._socket||this._socket.readyState!==eH.OPEN)return this._log.debug("Cannot send message. WebSocket is not open."),!1;try{this._socket.send(e)}catch(e){return this._log.error("Error while sending message:",e.message),this._closeSocket(),!1}return!0}updatePreferredURI(e){this._preferredUri=e}updateURIs(e){"string"==typeof e&&(e=[e]),this._uris=e,this._uriIndex=0}_close(){this._setState(A.Closed),this._closeSocket()}_closeSocket(){if(clearTimeout(this._connectTimeout),clearTimeout(this._heartbeatTimeout),this._log.info("Closing and cleaning up WebSocket..."),!this._socket){this._log.info("No WebSocket to clean up.");return}this._socket.removeEventListener("close",this._onSocketClose),this._socket.removeEventListener("error",this._onSocketError),this._socket.removeEventListener("message",this._onSocketMessage),this._socket.removeEventListener("open",this._onSocketOpen),(this._socket.readyState===eH.CONNECTING||this._socket.readyState===eH.OPEN)&&this._socket.close(),this._backoff&&this._timeOpened&&Date.now()-this._timeOpened>1e4&&this._resetBackoffs(),this.state!==A.Closed&&(this._backoff||(this._backoff=this._setupBackoffs()),this._performBackoff()),delete this._socket,this.emit("close")}_connect(e,t){this._log.info("number"==typeof t?`Attempting to reconnect (retry #${t})...`:"Attempting to connect..."),this._closeSocket(),this._setState(A.Connecting),this._connectedUri=e;try{this._socket=new this._options.WebSocket(this._connectedUri)}catch(e){this._log.error("Could not connect to endpoint:",e.message),this._close(),this.emit("error",{code:31e3,message:e.message||`Could not connect to ${this._connectedUri}`,twilioError:new x.ConnectionDisconnected});return}this._socket.addEventListener("close",this._onSocketClose),this._socket.addEventListener("error",this._onSocketError),this._socket.addEventListener("message",this._onSocketMessage),this._socket.addEventListener("open",this._onSocketOpen),delete this._timeOpened,this._connectTimeout=setTimeout(()=>{this._log.info("WebSocket connection attempt timed out."),this._moveUriIndex(),this._closeSocket()},this._options.connectTimeoutMs)}_performBackoff(){if(!this._backoff){this._log.info("No backoff instance to perform backoff.");return}this._preferredUri?(this._log.info("Preferred URI set; backing off."),this._backoff.preferred.backoff()):(this._log.info("Preferred URI not set; backing off."),this._backoff.primary.backoff())}_resetBackoffs(){if(!this._backoff){this._log.info("No backoff instance to reset.");return}this._backoff.preferred.removeAllListeners("backoff"),this._backoff.preferred.removeAllListeners("ready"),this._backoff.primary.removeAllListeners("backoff"),this._backoff.primary.removeAllListeners("ready"),this._backoff=null,this._retryAfter=null,this._backoffStartTime.preferred=null,this._backoffStartTime.primary=null}_setHeartbeatTimeout(){clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=setTimeout(()=>{this._log.info("No messages received in 15 seconds. Reconnecting..."),this._shouldFallback=!0,this._closeSocket()},15e3)}_setState(e){this._previousState=this.state,this.state=e}_setupBackoffs(){let e=null!==this._retryAfter&&this._preferredUri?this._retryAfter:null;e&&this._log.info(`Setting initial preferred backoff value to retryAfter: ${e}ms`);let t=e?this._options.maxRetryAfterDurationMs:this._options.maxPreferredDurationMs,i={factor:2,jitter:.4,max:e?this._options.maxRetryAfterDelayMs:this._options.maxPreferredDelayMs,min:e||100,useInitialValue:!!e};this._log.info("Initializing preferred transport backoff using config: ",i);let s=new $(i);s.on("backoff",(e,t)=>{if(this.state===A.Closed){this._log.info("Preferred backoff initiated but transport state is closed; not attempting a connection.");return}
1this._log.info(`Will attempt to reconnect Websocket to preferred URI in ${t}ms`),0===e&&(this._backoffStartTime.preferred=Date.now(),this._log.info(`Preferred backoff start; ${this._backoffStartTime.preferred}`))}),s.on("ready",(e,i)=>{if(this.state===A.Closed){this._log.info("Preferred backoff ready but transport state is closed; not attempting a connection.");return}if(null===this._backoffStartTime.preferred){this._log.info("Preferred backoff start time invalid; not attempting a connection.");return}if(!this._backoff){this._log.info("Preferred backoff instance invalid; not attempting a connection.");return}if(Date.now()-this._backoffStartTime.preferred>t){this._log.info("Max preferred backoff attempt time exceeded; falling back to primary backoff."),this._preferredUri=null,this._backoff.primary.backoff();return}if("string"!=typeof this._preferredUri){this._log.info("Preferred URI cleared; falling back to primary backoff."),this._preferredUri=null,this._backoff.primary.backoff();return}this._connect(this._preferredUri,e+1)});let n={factor:2,jitter:.4,max:this._options.maxPrimaryDelayMs,min:this._uris&&this._uris.length>1?Math.floor(4001*Math.random())+1e3:100};this._log.info("Initializing primary transport backoff using config: ",n);let o=new $(n);return o.on("backoff",(e,t)=>{if(this.state===A.Closed){this._log.info("Primary backoff initiated but transport state is closed; not attempting a connection.");return}this._log.info(`Will attempt to reconnect WebSocket in ${t}ms`),0===e&&(this._backoffStartTime.primary=Date.now(),this._log.info(`Primary backoff start; ${this._backoffStartTime.primary}`))}),o.on("ready",(e,t)=>{if(this.state===A.Closed){this._log.info("Primary backoff ready but transport state is closed; not attempting a connection.");return}if(null===this._backoffStartTime.primary){this._log.info("Primary backoff start time invalid; not attempting a connection.");return}if(Date.now()-this._backoffStartTime.primary>this._options.maxPrimaryDurationMs){this._log.info("Max primary backoff attempt time exceeded; not attempting a connection.");return}this._connect(this._uris[this._uriIndex],e+1)}),{preferred:s,primary:o}}get uri(){return this._connectedUri}}eV.defaultConstructorOptions={WebSocket:eH,connectTimeoutMs:5e3,maxPreferredDelayMs:1e3,maxPreferredDurationMs:15e3,maxPrimaryDelayMs:2e4,maxPrimaryDurationMs:1/0,maxRetryAfterDelayMs:6e4,maxRetryAfterDurationMs:75e3};class eB extends j.EventEmitter{constructor(e,t,i){if(super(),!(this instanceof eB))return new eB(e,t,i);let s={TransportFactory:eV};for(let e in i=i||{},s)e in i||(i[e]=s[e]);this.options=i,this.token=e||"",this.status="disconnected",this.gateway=null,this.region=null,this._messageQueue=[],this._preferredUri=null,this._uris=t,this._handleTransportClose=this._handleTransportClose.bind(this),this._handleTransportError=this._handleTransportError.bind(this),this._handleTransportMessage=this._handleTransportMessage.bind(this),this._handleTransportOpen=this._handleTransportOpen.bind(this),this._log=new Z("PStream"),this.on("error",()=>{this._log.warn("Unexpected error handled in pstream")});let n=this;return this.addListener("ready",()=>{n.status="ready"}),this.addListener("offline",()=>{n.status="offline"}),this.addListener("close",()=>{n._log.info('Received "close" from server. Destroying PStream...'),n._destroy()}),this.transport=new this.options.TransportFactory(this._uris,{backoffMaxMs:this.options.backoffMaxMs,maxPreferredDurationMs:this.options.maxPreferredDurationMs}),Object.defineProperties(this,{uri:{enumerable:!0,get(){return this.transport.uri}}}),this.transport.on("close",this._handleTransportClose),this.transport.on("error",this._handleTransportError),this.transport.on("message",this._handleTransportMessage),this.transport.on("open",this._handleTransportOpen),this.transport.open(),this}}eB.prototype._handleTransportClose=function(){this.emit("transportClose"),"disconnected"!==this.status&&("offline"!==this.status&&this.emit("offline",this),this.status="disconnected")},eB.prototype._handleTransportError=function(e){if(!e){this.emit("error",{error:{code:31e3,message:"Websocket closed without a provided reason",twilioError:ne
1w x.ConnectionDisconnected}});return}this.emit("error",void 0!==e.code?{error:e}:e)},eB.prototype._handleTransportMessage=function(e){if(!e||!e.data||"string"!=typeof e.data)return;let{type:t,payload:i={}}=JSON.parse(e.data);this.gateway=i.gateway||this.gateway,this.region=i.region||this.region,"error"===t&&i.error&&(i.error.twilioError=new x.ConnectionError),this.emit(t,i)},eB.prototype._handleTransportOpen=function(){this.status="connected",this.setToken(this.token),this.emit("transportOpen"),this._messageQueue.splice(0,this._messageQueue.length).forEach(e=>this._publish(...e))},eB.toString=()=>"[Twilio.PStream class]",eB.prototype.toString=()=>"[Twilio.PStream instance]",eB.prototype.setToken=function(e){this._log.info("Setting token and publishing listen"),this.token=e;let t=0,i=this.options.maxPreferredDurationMs;this._log.info(`maxPreferredDurationMs:${i}`),"number"==typeof i&&i>=0&&(t=Math.min(Math.ceil(i/1e3),30)),this._log.info(`reconnectTimeout:${t}`);let s={browserinfo:function(){let e="undefined"!=typeof navigator?navigator:{};return{browser:{platform:e.platform||"unknown",userAgent:e.userAgent||"unknown"},p:"browser",plugin:"rtc",v:K}}(),reconnectTimeout:t,token:e};this._publish("listen",s)},eB.prototype.sendMessage=function(e,t,i="application/json",s,n){this._publish("message",{callsid:e,content:t,contenttype:i,messagetype:s,voiceeventsid:n},!0)},eB.prototype.register=function(e){this._publish("register",{media:e},!0)},eB.prototype.invite=function(e,t,i){this._publish("invite",{callsid:t,sdp:e,twilio:i?{params:i}:{}},!0)},eB.prototype.reconnect=function(e,t,i){this._publish("invite",{callsid:t,reconnect:i,sdp:e,twilio:{}},!0)},eB.prototype.answer=function(e,t){this._publish("answer",{sdp:e,callsid:t},!0)},eB.prototype.dtmf=function(e,t){this._publish("dtmf",{callsid:e,dtmf:t},!0)},eB.prototype.hangup=function(e,t){this._publish("hangup",t?{callsid:e,message:t}:{callsid:e},!0)},eB.prototype.reject=function(e){this._publish("reject",{callsid:e},!0)},eB.prototype.reinvite=function(e,t){this._publish("reinvite",{sdp:e,callsid:t},!1)},eB.prototype._destroy=function(){this.transport.removeListener("close",this._handleTransportClose),this.transport.removeListener("error",this._handleTransportError),this.transport.removeListener("message",this._handleTransportMessage),this.transport.removeListener("open",this._handleTransportOpen),this.transport.close(),this.emit("offline",this)},eB.prototype.destroy=function(){return this._log.info("PStream.destroy() called..."),this._destroy(),this},eB.prototype.updatePreferredURI=function(e){this._preferredUri=e,this.transport.updatePreferredURI(e)},eB.prototype.updateURIs=function(e){this._uris=e,this.transport.updateURIs(this._uris)},eB.prototype.publish=function(e,t){return this._publish(e,t,!0)},eB.prototype._publish=function(e,t,i){let s=JSON.stringify({payload:t,type:e,version:"1.6"});!this.transport.send(s)&&(this.emit("error",{error:{code:31009,message:"No transport available to send or receive messages",twilioError:new k.TransportError}}),i&&this._messageQueue.push([e,t,!0]))},(c=R||(R={})).Sydney="sydney",c.SaoPaulo="sao-paulo",c.Dublin="dublin",c.Frankfurt="frankfurt",c.Tokyo="tokyo",c.Singapore="singapore",c.Ashburn="ashburn",c.Umatilla="umatilla",c.Roaming="roaming",c.AshburnIx="ashburn-ix",c.SanJoseIx="san-jose-ix",c.LondonIx="london-ix",c.FrankfurtIx="frankfurt-ix",c.SingaporeIx="singapore-ix",c.SydneyIx="sydney-ix",c.TokyoIx="tokyo-ix",(l=O||(O={})).Au1="au1",l.Au1Ix="au1-ix",l.Br1="br1",l.De1="de1",l.De1Ix="de1-ix",l.Gll="gll",l.Ie1="ie1",l.Ie1Ix="ie1-ix",l.Ie1Tnx="ie1-tnx",l.Jp1="jp1",l.Jp1Ix="jp1-ix",l.Sg1="sg1",l.Sg1Ix="sg1-ix",l.Sg1Tnx="sg1-tnx",l.Us1="us1",l.Us1Ix="us1-ix",l.Us1Tnx="us1-tnx",l.Us2="us2",l.Us2Ix="us2-ix",l.Us2Tnx="us2-tnx";let eq={ASIAPAC_SINGAPORE:O.Sg1,ASIAPAC_SYDNEY:O.Au1,ASIAPAC_TOKYO:O.Jp1,EU_FRANKFURT:O.De1,EU_IRELAND:O.Ie1,SOUTH_AMERICA_SAO_PAULO:O.Br1,US_EAST_VIRGINIA:O.Us1,US_WEST_OREGON:O.Us2},eG={[O.Au1]:R.Sydney,[O.Br1]:R.SaoPaulo,[O.Ie1]:R.Dublin,[O.De1]:R.Frankfurt,[O.Jp1]:R.Tokyo,[O.Sg1]:R.Singapore,[O.Us1]:R.Ashburn,[O.Us2]:R.Umatilla,[O.Gll]:R.Roaming,[O.Us1Ix]:R.AshburnIx,[O.Us2Ix]:R.SanJoseIx,[O.Ie1Ix]:R.LondonIx,[O.De1Ix]:R.FrankfurtIx,[O.Sg1Ix]:R.SingaporeIx,[O.Au1Ix]:R.SydneyIx,[O.Jp1Ix]:R.TokyoIx,[O.Us1Tnx]:R.AshburnIx,[O.Us2Tnx]:R.AshburnIx,[O.Ie1Tnx]:R.LondonIx,[O.Sg1Tnx]:R.SingaporeIx},ez=R.Roaming;function eJ(e){return`voice-js.${e}.twilio.com`}function eQ(e){return e?`eventgw.${e}.twilio.com`:"eventgw.twilio.com"}function eK(e){return`wss://${e}/signal`}function eX(e){if(e&&"string"!=typeof e&&!Array.isArray(e))throw new B("If `edge` is provided, it must be of type `string` or an array of str
1ings.");return e?(Array.isArray(e)?e:[e]).map(e=>eJ(e)):[eJ(ez)]}let eY={0:"PCMU",8:"PCMA"};function eZ(e,t){if("number"!=typeof t||t<6e3||t>51e4)return e;let i=/a=rtpmap:(\d+) opus/m.exec(e),s=i&&i.length?i[1]:111,n=RegExp(`a=fmtp:${s}`);return e.split("\n").map(e=>n.test(e)?e+`;maxaveragebitrate=${t}`:e).join("\n")}function e0(e,t){let i=e.replace(/\r\n\r\n$/,"\r\n").split("\r\nm=").slice(1).map(e=>`m=${e}`).filter(e=>{let t=RegExp("m=.*","gm"),i=RegExp("a=.*","gm");return t.test(e)&&i.test(e)});return[e.split("\r\nm=")[0]].concat(i.map(e=>{if(!/^m=(audio|video)/.test(e))return e;let i=e.match(/^m=(audio|video)/)[1],s=Array.from((function(e){let t=e.split("\r\n")[0].match(/([0-9]+)/g);return t?t.slice(1).map(e=>parseInt(e,10)):[]})(e).reduce((t,i)=>{let s=RegExp(`a=rtpmap:${i} ([^/]+)`),n=e.match(s),o=n?n[1].toLowerCase():eY[i]?eY[i].toLowerCase():"";return t.set(i,o)},new Map)).reduce((e,t)=>{let i=t[0],s=t[1],n=e.get(s)||[];return e.set(s,n.concat(i))},new Map),n=function(e,t){let i=ep(t=t.map(e=>e.toLowerCase()),t=>e.get(t)||[]),s=ep(er(Array.from(e.keys()),t),t=>e.get(t));return i.concat(s)}(s,t),o=function(e,t){let i=t.split("\r\n"),s=i[0],n=i.slice(1);return[s=s.replace(/([0-9]+\s?)+$/,e.join(" "))].concat(n).join("\r\n")}(n,e),r=s.get("pcma")||[],a=s.get("pcmu")||[];return("audio"===i?new Set(r.concat(a)):new Set).has(n[0])?o.replace(/\r\nb=(AS|TIAS):([0-9]+)/g,""):o})).join("\r\n")}function e1(e){if(this.log=new Z("RTCPC"),"undefined"==typeof window){this.log.info("No RTCPeerConnection implementation available. The window object was not found.");return}e&&e.RTCPeerConnection?this.RTCPeerConnection=e.RTCPeerConnection:"function"==typeof window.RTCPeerConnection?this.RTCPeerConnection=window.RTCPeerConnection:"function"==typeof window.webkitRTCPeerConnection?this.RTCPeerConnection=webkitRTCPeerConnection:"function"==typeof window.mozRTCPeerConnection?(this.RTCPeerConnection=mozRTCPeerConnection,window.RTCSessionDescription=mozRTCSessionDescription,window.RTCIceCandidate=mozRTCIceCandidate):this.log.info("No RTCPeerConnection implementation available")}function e3(e,t,i,s){return function(){let n=Array.prototype.slice.call(arguments);return new Promise(i=>{let o=e.apply(t,n);if(!s){i(o);return}if("object"==typeof o&&"function"==typeof o.then)i(o);else throw Error()}).catch(()=>new Promise((s,o)=>{e.apply(t,i?[s,o].concat(n):n.concat([s,o]))}))}}function e2(e,t){return e3(e,t,!1,!1)}function e4(e,t,i){if(!e||!t)throw new B("Audiohelper, and pstream are required arguments");if(!(this instanceof e4))return new e4(e,t,i);function s(){this._log.warn("Unexpected noop call in peerconnection")}this._log=new Z("PeerConnection"),this.onaudio=s,this.onopen=s,this.onerror=s,this.onclose=s,this.ondisconnected=s,this.onfailed=s,this.onconnected=s,this.onreconnected=s,this.onsignalingstatechange=s,this.ondtlstransportstatechange=s,this.onicegatheringfailure=s,this.onicegatheringstatechange=s,this.oniceconnectionstatechange=s,this.onpcconnectionstatechange=s,this.onicecandidate=s,this.onselectedcandidatepairchange=s,this.onvolume=s,this.version=null,this.pstream=t,this.stream=null,this.sinkIds=new Set(["default"]),this.outputs=new Map,this.status="connecting",this.callSid=null,this.isMuted=!1;let n="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);return this._isSinkSupported=!!n&&"undefined"!=typeof HTMLAudioElement&&HTMLAudioElement.prototype.setSinkId,this._audioContext=n&&e._audioContext,this._audioHelper=e,this._audioProcessorEventObserver=e._getAudioProcessorEventObserver(),this._hasIceCandidates=!1,this._hasIceGatheringFailures=!1,this._iceGatheringTimeoutId=null,this._masterAudio=null,this._masterAudioDeviceId=null,this._mediaStreamSource=null,this._dtmfSender=null,this._dtmfSenderUnsupported=!1,this._callEvents=[],this._nextTimeToPublish=Date.now(),this._onAnswerOrRinging=s,this._onHangup=s,this._remoteStream=null,this._shouldManageStream=!0,this._iceState="new",this.options=i=i||{},this.navigator=i.navigator||("undefined"!=typeof navigator?navigator:null),this.util=i.util||M,this.codecPreferences=i.codecPreferences,this._onAudioProcessorAdded=e=>{this._handleAudioProcessorEvent(e,!0)},this._onAudioProcessorRemoved=e=>{this._handleAudioProcessorEvent(e,!1)},this._audioProcessorEventObserver.on("add",this._onAudioProcessorAdded),this._audioProcessorEventObserver.on("remove",this._onAudioProcessorRemoved),this}function e5(e,t){let i;return t?i=new t:"undefined"!=typeof MediaStream?i=new MediaStream:i=new webkitMediaStream,e.getAudioTracks().forEac
1h(i.addTrack,i),i}function e6(e,t,i){return i._maybeCreateRemoteProcessedStream(t).then(t=>{if(void 0!==e.srcObject)e.srcObject=t;else if(void 0!==e.mozSrcObject)e.mozSrcObject=t;else{if(void 0===e.src)return Promise.reject();let i=e.options.window||window;e.src=(i.URL||i.webkitURL).createObjectURL(t)}return Promise.resolve()})}function e7(e,t){return(t=t||{}).util=t.util||M,t.navigator=t.navigator||("undefined"!=typeof navigator?navigator:null),new Promise((i,s)=>{if(!t.navigator)throw new G("getUserMedia is not supported");switch("function"){case typeof(t.navigator.mediaDevices&&t.navigator.mediaDevices.getUserMedia):return i(t.navigator.mediaDevices.getUserMedia(e));case typeof t.navigator.webkitGetUserMedia:return t.navigator.webkitGetUserMedia(e,i,s);case typeof t.navigator.mozGetUserMedia:return t.navigator.mozGetUserMedia(e,i,s);case typeof t.navigator.getUserMedia:return t.navigator.getUserMedia(e,i,s);default:throw new G("getUserMedia is not supported")}}).catch(e=>{throw t.util.isFirefox()&&"NotReadableError"===e.name?new G("Firefox does not currently support opening multiple audio input trackssimultaneously, even across different tabs.\nRelated Bugzilla thread: https://bugzilla.mozilla.org/show_bug.cgi?id=1299324"):e})}function e8(){return`KX${function(){if("object"!=typeof window)throw new G("This platform is not supported.");let{crypto:e}=window;if("object"!=typeof e)throw new G("The `crypto` module is not available on this platform.");if("function"!=typeof e.getRandomValues)throw new G("The function `crypto.getRandomValues` is not available on this platform.");if("function"!=typeof window.Uint8Array)throw new G("The `Uint8Array` module is not available on this platform.");return e.getRandomValues(new window.Uint8Array(16)).reduce((e,t)=>`${e}${t.toString(16).padStart(2,"0")}`,"")}()}`}e1.prototype.create=function(e){this.pc=new this.RTCPeerConnection(e)},e1.prototype.createModernConstraints=e=>{if(void 0===e)return null;let t=Object.assign({},e);return"undefined"==typeof webkitRTCPeerConnection||ed()?(void 0!==e.audio&&(t.offerToReceiveAudio=e.audio),void 0!==e.video&&(t.offerToReceiveVideo=e.video)):(t.mandatory={},void 0!==e.audio&&(t.mandatory.OfferToReceiveAudio=e.audio),void 0!==e.video&&(t.mandatory.OfferToReceiveVideo=e.video)),delete t.audio,delete t.video,t},e1.prototype.createOffer=function(e,t,i,s){return t=this.createModernConstraints(t),e3(this.pc.createOffer,this.pc,!0,!0)(t).then(t=>{if(!this.pc)return Promise.resolve();let i=eZ(t.sdp,e);return e2(this.pc.setLocalDescription,this.pc)(new RTCSessionDescription({sdp:i,type:"offer"}))}).then(i,s)},e1.prototype.createAnswer=function(e,t,i,s){return t=this.createModernConstraints(t),e3(this.pc.createAnswer,this.pc,!0,!0)(t).then(t=>{if(!this.pc)return Promise.resolve();let i=eZ(t.sdp,e);return e2(this.pc.setLocalDescription,this.pc)(new RTCSessionDescription({sdp:i,type:"answer"}))}).then(i,s)},e1.prototype.processSDP=function(e,t,i,s,n,o){let r=new RTCSessionDescription({sdp:i=e0(i,t),type:"offer"});return e2(this.pc.setRemoteDescription,this.pc)(r).then(()=>{this.createAnswer(e,s,n,o)})},e1.prototype.getSDP=function(){return this.pc.localDescription.sdp},e1.prototype.processAnswer=function(e,t,i,s){return this.pc?(t=e0(t,e),e2(this.pc.setRemoteDescription,this.pc)(new RTCSessionDescription({sdp:t,type:"answer"})).then(i,s)):Promise.resolve()},e1.test=()=>{if("object"==typeof navigator){let e=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.getUserMedia;if(ed(navigator))return!1;if(e&&"function"==typeof window.RTCPeerConnection||e&&"function"==typeof window.webkitRTCPeerConnection)return!0;if(e&&"function"==typeof window.mozRTCPeerConnection){try{let e=new window.mozRTCPeerConnection;if("function"!=typeof e.getLocalStreams)return!1}catch(e){return!1}return!0}if("undefined"!=typeof RTCIceGatherer)return!0}return!1},e4.prototype.uri=function(){return this._uri},e4.prototype.openDefaultDeviceWithConstraints=function(e){return this._audioHelper._openDefaultDeviceWithConstraints(e).then(this._setInputTracksFromStream.bind(this,!1))},e4.prototype.setInputTracksFromStream=function(e){let t=this;return this._setInputTracksFromStream(!0,e).then(()=>{t._shouldManageStream=!1})},e4.prototype._createAnalyser=(e,t)=>{t=Object.assign({fftSize:32,smoothingTimeConstant:.3},t);let i=e.createAnalyser();for(let e in t)i[e]=t[e];return i},e4.prototype._setVolumeHandler=function(e){this.onvolume=e},e4.prototype._startPollingVolume=function(){if(!this._audioContext||!this.stream||!this._remoteStream)return;let e=this._audioContext,t=new Uint8Array((this._inputAnalyser=this._createAnalyser(e)).frequencyBinCount);this._inputAnalyser2=this._createAnalyser(e,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0});let i=new Uint8Array((this._outputAnalyser=this._createAnalyser(e)).frequencyBinCount);this._outputAnalyser2=this._createAnalyser(e,{maxDecibels:0,minDecibels:-127,smoothingTimeConstant:0}),this._updateInputStreamSource(this.stream),this._updateOutputStreamSource(this._remoteStream);let s=this;setTimeout(function e(){if(!s._audioContext)return;if("closed"===s.status){s._inputAnalyser.disconnect(),s._outputAnalyser.disconnect(),s._inputAnalyser2.disconnect(),s._outputAnalyser2.disconnect();return}s._inputAnalyser.getByteFrequencyData(t);let n=s.util.average(t);s._inputAnalyser2.getByteFrequencyData(t);let o=s.util.average(t);s._outputAnalyser.getByteFrequencyData(i);let r=s.util.average(i);s._outputAnalyser2.getByteFrequencyData(i);let a=s.util.average(i);s.onvolume(n/255,r/255,o,a),setTimeout(e,50)},50)},e4.prototype._stopStream=function(){this._shouldManageStream&&this._audioHelper._stopDefaultInputDeviceStream()},e4.prototype._updateInputStreamSource=function(e){this._inputStreamSource&&this._inputStreamSource.disconnect();try{this._inputStreamSource=this._audioContext.createMediaStreamSource(e),this._inputStreamSource.connect(this._inputAnalyser),this._inputStreamSource.connect(this._inputAnalyser2)}catch(e){this._log.warn("Unable to update input MediaStreamSource",e),this._inputStreamSource=null}},e4.prototype._updateOutputStreamSource=function(e){this._outputStreamSource&&this._outputStreamSource.disconnect();try{this._outputStreamSource=this._audioContext.createMediaStreamSource(e),this._outputStreamSource.connect(this._outputAnalyser),this._outputStreamSource.connect(this._outputAnalyser2)}catch(e){this._log.warn("Unable to update output MediaStreamSource",e),this._outputStreamSource=null}},e4.prototype._setInputTracksFromStream=function(e,t){if(!t)return Promise.reject(new B("Can not set input stream to null while in a call"));if(!t.getAudioTracks().length)return Promise.reject(new B("Supplied input stream has no audio tracks"));let i=this.stream,s=()=>(this.mute(this.isMuted),Promise.resolve(this.stream));return i?(this._shouldManageStream&&this._stopStream(),this._sender||(this._sender=this.version.pc.getSenders()[0]),this._sender.replaceTrack(t.getAudioTracks()[0]).then(()=>(this._updateInputStreamSource(t),this.stream=e?e5(t,this.options.MediaStream):t,s()))):(this.stream=e?e5(t,this.options.MediaStream):t,s())},e4.prototype._onInputDevicesChanged=function(){this.stream&&this.stream.getAudioTracks().every(e=>"ended"===e.readyState)&&this._shouldManageStream&&this.openDefaultDeviceWithConstraints({audio:!0})},e4.prototype._onIceGatheringFailure=function(e){this._hasIceGatheringFailures=!0,this.onicegatheringfailure(e)},e4.prototype._onMediaConnectionStateChange=function(e){let t;let i=this._iceState;if(i!==e&&("connected"===e||"disconnected"===e||"failed"===e))switch(this._iceState=e,e){case"connected":"disconnected"===i||"failed"===i?(t="ICE liveliness check 
1succeeded. Connection with Twilio restored",this._log.info(t),this.onreconnected(t)):(t="Media connection established.",this._log.info(t),this.onconnected(t)),this._stopIceGatheringTimeout(),this._hasIceGatheringFailures=!1;break;case"disconnected":t="ICE liveliness check failed. May be having trouble connecting to Twilio",this._log.warn(t),this.ondisconnected(t);break;case"failed":t="Connection with Twilio was interrupted.",this._log.warn(t),this.onfailed(t)}},e4.prototype._setSinkIds=function(e){return this._isSinkSupported?(this.sinkIds=new Set(e.forEach?e:[e]),this.version?this._updateAudioOutputs():Promise.resolve()):Promise.reject(new G("Audio output selection is not supported by this browser"))},e4.prototype._startIceGatheringTimeout=function(){this._stopIceGatheringTimeout(),this._iceGatheringTimeoutId=setTimeout(()=>{this._onIceGatheringFailure("timeout")},15e3)},e4.prototype._stopIceGatheringTimeout=function(){clearInterval(this._iceGatheringTimeoutId)},e4.prototype._updateAudioOutputs=function(){let e=Array.from(this.sinkIds).filter(function(e){return!this.outputs.has(e)},this),t=Array.from(this.outputs.keys()).filter(function(e){return!this.sinkIds.has(e)},this),i=this;return Promise.all(e.map(this._createAudioOutput,this)).then(()=>Promise.all(t.map(i._removeAudioOutput,i)))},e4.prototype._createAudio=function(e){let t=new Audio(e);return this.onaudio(t),t},e4.prototype._createAudioOutput=function(e){let t=null;this._mediaStreamSource&&(t=this._audioContext.createMediaStreamDestination(),this._mediaStreamSource.connect(t));let i=this._createAudio();e6(i,t&&t.stream?t.stream:this.pcStream,this._audioHelper).catch(()=>this._log.error("Error attaching stream to element (_createAudioOutput)."));let s=this;return i.setSinkId(e).then(()=>i.play()).then(()=>{s.outputs.set(e,{audio:i,dest:t})})},e4.prototype._removeAudioOutputs=function(){return this._masterAudio&&void 0!==this._masterAudioDeviceId&&(this._disableOutput(this,this._masterAudioDeviceId),this.outputs.delete(this._masterAudioDeviceId),this._masterAudioDeviceId=null,this._masterAudio.paused||this._masterAudio.pause(),void 0!==this._masterAudio.srcObject?this._masterAudio.srcObject=null:this._masterAudio.src="",this._masterAudio=null),Array.from(this.outputs.keys()).map(this._removeAudioOutput,this)},e4.prototype._disableOutput=function(e,t){let i=e.outputs.get(t);i&&(i.audio&&(i.audio.pause(),i.audio.src=""),i.dest&&i.dest.disconnect())},e4.prototype._reassignMasterOutput=function(e,t){let i=e.outputs.get(t);e.outputs.delete(t);let s=this,n=Array.from(e.outputs.keys())[0],o="string"==typeof n?n:"default";return i.audio.setSinkId(o).then(()=>{s._disableOutput(e,o),e.outputs.set(o,i),e._masterAudioDeviceId=o}).catch(function(){e.outputs.set(t,i),s._log.info("Could not reassign master output. Attempted to roll back.")})},e4.prototype._removeAudioOutput=function(e){return this._masterAudioDeviceId===e?this._reassignMasterOutput(this,e):(this._disableOutput(this,e),this.outputs.delete(e),Promise.resolve())},e4.prototype._onAddTrack=function(e,t){let i=e._masterAudio=this._createAudio();e6(i,t,this._audioHelper).then(()=>i.play()).catch(()=>e._log.error("Error attaching stream to element (_onAddTrack)."));let s=Array.from(e.outputs.keys())[0],n="string"==typeof s?s:"default";e._masterAudioDeviceId=n,e.outputs.set(n,{audio:i});try{e._mediaStreamSource=e._audioContext.createMediaStreamSource(t)}catch(e){this._log.warn("Unable to create a MediaStreamSource from onAddTrack",e),this._mediaStreamSource=null}e.pcStream=t,e._updateAudioOutputs()},e4.prototype._fallbackOnAddTrack=function(e,t){let i=document&&document.createElement("audio");e6(i,t,this._audioHelper).then(()=>i.play()).catch(()=>e._log.error("Error attaching stream to element (_fallbackOnAddTrack).")),e.outputs.set("default",{audio:i})},e4.prototype._setEncodingParameters=function(e){if(!e||!this._sender||"function"!=typeof this._sender.getParameters||"function"!=typeof this._sender.setParameters)return;let t=this._sender.getParameters();(t.priority||t.encodings&&t.encodings.length)&&(t.priority="high",t.encodings&&t.encodings.length&&t.encodings.forEac
1h(e=>{e.priority="high",e.networkPriority="high"}),this._sender.setParameters(t))},e4.prototype._setupPeerConnection=function(e){var t,i;let s=this,n=new(this.options.rtcpcFactory||e1)({RTCPeerConnection:this.options.RTCPeerConnection});n.create(e),t=n.pc,i=this.stream,"function"==typeof t.addTrack?i.getAudioTracks().forEach(e=>{t.addTrack(e,i)}):t.addStream(i);let o=RTCRtpReceiver.getCapabilities("audio").codecs;this._log.debug("sorting codecs",o,this.codecPreferences);let r=eg(o,this.codecPreferences),[a]=n.pc.getTransceivers();this._log.debug("setting sorted codecs",r),a.setCodecPreferences(r);let c="ontrack"in n.pc?"ontrack":"onaddstream";return n.pc[c]=e=>{let t=s._remoteStream=e.stream||e.streams[0];"function"==typeof n.pc.getSenders&&(this._sender=n.pc.getSenders()[0]),s._isSinkSupported?s._onAddTrack(s,t):s._fallbackOnAddTrack(s,t),s._startPollingVolume()},n},e4.prototype._maybeSetIceAggressiveNomination=function(e){return this.options.forceAggressiveIceNomination&&ec(window,window.navigator)?e.split("\n").filter(e=>-1===e.indexOf("a=ice-lite")).join("\n"):e},e4.prototype._setupChannel=function(){let e=this.version.pc;this.version.pc.onopen=()=>{this.status="open",this.onopen()},this.version.pc.onstatechange=()=>{this.version.pc&&"stable"===this.version.pc.readyState&&(this.status="open",this.onopen())},this.version.pc.onsignalingstatechange=()=>{let t=e.signalingState;this._log.info(`signalingState is "${t}"`),this.version.pc&&"stable"===this.version.pc.signalingState&&(this.status="open",this.onopen()),this.onsignalingstatechange(e.signalingState)},e.onconnectionstatechange=t=>{let i=e.connectionState;if(!i&&t&&t.target){let e=t.target;i=e.connectionState||e.connectionState_,this._log.info(`pc.connectionState not detected. Using target PC. State=${i}`)}i?this._log.info(`pc.connectionState is "${i}"`):this._log.warn(`onconnectionstatechange detected but state is "${i}"`),this.onpcconnectionstatechange(i),this._onMediaConnectionStateChange(i)},e.onicecandidate=e=>{let{candidate:t}=e;t&&(this._hasIceCandidates=!0,this.onicecandidate(t),this._setupRTCIceTransportListener()),this._log.info(`ICE Candidate: ${JSON.stringify(t)}`)},e.onicegatheringstatechange=()=>{let t=e.iceGatheringState;"gathering"===t?this._startIceGatheringTimeout():"complete"===t&&(this._stopIceGatheringTimeout(),this._hasIceCandidates||this._onIceGatheringFailure("none"),this._hasIceCandidates&&this._hasIceGatheringFailures&&this._startIceGatheringTimeout()),this._log.info(`pc.iceGatheringState is "${e.iceGatheringState}"`),this.onicegatheringstatechange(t)},e.oniceconnectionstatechange=()=>{this._log.info(`pc.iceConnectionState is "${e.iceConnectionState}"`),this.oniceconnectionstatechange(e.iceConnectionState),this._onMediaConnectionStateChange(e.iceConnectionState)}},e4.prototype._initializeMediaStream=function(e){return"open"!==this.status&&("disconnected"===this.pstream.status?(this.onerror
1({info:{code:31e3,message:"Cannot establish connection. Client is disconnected",twilioError:new x.ConnectionDisconnected}}),this.close(),!1):(this.version=this._setupPeerConnection(e),this._setupChannel(),!0))},e4.prototype._removeReconnectionListeners=function(){this.pstream&&(this.pstream.removeListener("answer",this._onAnswerOrRinging),this.pstream.removeListener("hangup",this._onHangup))},e4.prototype._setupRTCDtlsTransportListener=function(){let e=this.getRTCDtlsTransport();if(!e||e.onstatechange)return;let t=()=>{this._log.info(`dtlsTransportState is "${e.state}"`),this.ondtlstransportstatechange(e.state)};t(),e.onstatechange=t},e4.prototype._setupRTCIceTransportListener=function(){let e=this._getRTCIceTransport();e&&!e.onselectedcandidatepairchange&&(e.onselectedcandidatepairchange=()=>this.onselectedcandidatepairchange(e.getSelectedCandidatePair()))},e4.prototype.iceRestart=function(){this._log.info("Attempting to restart ICE..."),this._hasIceCandidates=!1,this.version.createOffer(this.options.maxAverageBitrate,{iceRestart:!0}).then(()=>{this._removeReconnectionListeners(),this._onAnswerOrRinging=e=>{if(this._removeReconnectionListeners(),!e.sdp||"have-local-offer"!==this.version.pc.signalingState){let t=`Invalid state or param during ICE Restart:hasSdp:${!!e.sdp}, signalingState:${this.version.pc.signalingState}`;this._log.warn(t);return}let t=this._maybeSetIceAggressiveNomination(e.sdp);this._answerSdp=t,"closed"!==this.status&&this.version.processAnswer(this.codecPreferences,t,null,e=>{let t=e&&e.message?e.message:e;this._log.error(`Failed to process answer during ICE Restart. Error: ${t}`)})},this._onHangup=()=>{this._log.info("Received hangup during ICE Restart"),this._removeReconnectionListeners()},this.pstream.on("answer",this._onAnswerOrRinging),this.pstream.on("hangup",this._onHangup),this.pstream.reinvite(this.version.getSDP(),this.callSid)}).catch(e=>{let t=e&&e.message?e.message:e;this._log.error(`Failed to createOffer during ICE Restart. Error: ${t}`),this.onfailed(t)})},e4.prototype.makeOutgoingCall=function(e,t,i,s,n){if(!this._initializeMediaStream(s))return;let o=this;function r(){o.options&&o._setEncodingParameters(o.options.dscp),n(o.version.pc)}function a(e){let t=e.message||e;o.onerror({info:{code:31e3,message:`Error processing answer: ${t}`,twilioError:new D.ClientRemoteDescFailed}})}this.callSid=i,this._onAnswerOrRinging=e=>{if(!e.sdp)return;let t=this._maybeSetIceAggressiveNomination(e.sdp);o._answerSdp=t,"closed"!==o.status&&o.version.processAnswer(this.codecPreferences,t,r,a),o.pstream.removeListener("answer",o._onAnswerOrRinging),o.pstream.removeListener("ringing",o._onAnswerOrRinging)},this.pstream.on("answer",this._onAnswerOrRinging),this.pstream.on("ringing",this._onAnswerOrRinging),this.version.createOffer(this.options.maxAverageBitrate,{audio:!0},function(){"closed"!==o.status&&(t?o.pstream.reconnect(o.version.getSDP(),o.callSid,t):o.pstream.invite(o.version.getSDP(),o.callSid,e),o._setupRTCDtlsTransportListener())},function(e){let t=e.message||e;o.onerror({info:{code:31e3,message:`Error creating the offer: ${t}`,twilioError:new D.ClientLocalDescFailed}})})},e4.prototype.answerIncomingCall=function(e,t,i,s){if(!this._initializeMediaStream(i))return;t=this._maybeSetIceAggressiveNomination(t),this._answerSdp=t.replace(/^a=setup:actpass$/gm,"a=setup:passive"),this.callSid=e;let n=this;this.version.processSDP(this.options.maxAverageBitrate,this.codecPreferences,t,{audio:!0},function(){"closed"!==n.status&&(n.pstream.answer(n.version.getSDP(),e),n.options&&n._setEncodingParameters(n.options.dscp),s(n.version.pc),n._setupRTCDtlsTransportListener())},function(e){let t=e.message||e;n.onerror({info:{code:31e3,message:`Error creating the answer: ${t}`,twilioError:new D.ClientRemoteDescFailed}})})},e4.prototype.close=function(){this.version&&this.version.pc&&("closed"!==this.version.pc.signalingState&&this.version.pc.close(),this.version.pc=null),this.stream&&(this.mute(!1),this._stopStream()),this.stream=null,this._removeReconnectionListeners(),this._stopIceGatheringTimeout(),this._audioHelper._destroyRemoteProcessedStream(),this._audioProcessorEventObserver.removeListener("add",this._onAudioProcessorAdded),this._audioProcessorEventObserver.removeListener("remove",this._onAudioProcessorRemoved),Promise.all(this._removeAudioOutputs()).catch(()=>{}),this._mediaStreamSource&&this._mediaStreamSource.disconnect(),this._inputAnalyser&&this._inputAnalyser.disconnect(),this._outputAnalyser&&this._outputAnalyser.disconnect(),this._inputAnalyser2&&this._inputAnalyser2.disconnect(),this._outputAnalyser2&&this._outputAnalyser2.disconnect(),this.status="closed",this.onclose()},e4.prototype.reject=function(e){this.callSid=e},e4.prototype.ignore=function(e){this.callSid=e},e4.prototype.mute=function(e){this.isMuted=e,this.stream&&(this._sender&&this._sender.track?this._sender.track.enabled=!e:("function"==typeof this.stream.getAudioTracks?this.stream.getAudioTracks():this.stream.audioTracks).forEac
1h(t=>{t.enabled=!e}))},e4.prototype.getOrCreateDTMFSender=function(){if(this._dtmfSender||this._dtmfSenderUnsupported)return this._dtmfSender||null;let e=this,t=this.version.pc;if(!t)return this._log.warn("No RTCPeerConnection available to call createDTMFSender on"),null;if("function"==typeof t.getSenders&&("function"==typeof RTCDTMFSender||"function"==typeof RTCDtmfSender)){let e=t.getSenders().find(e=>e.dtmf);if(e)return this._log.info("Using RTCRtpSender#dtmf"),this._dtmfSender=e.dtmf,this._dtmfSender}if("function"==typeof t.createDTMFSender&&"function"==typeof t.getLocalStreams){let i=t.getLocalStreams().map(t=>{let i=e._getAudioTracks(t);return i&&i[0]})[0];return i?(this._log.info("Creating RTCDTMFSender"),this._dtmfSender=t.createDTMFSender(i),this._dtmfSender):(this._log.warn("No local audio MediaStreamTrack available on the RTCPeerConnection to pass to createDTMFSender"),null)}return this._log.info("RTCPeerConnection does not support RTCDTMFSender"),this._dtmfSenderUnsupported=!0,null},e4.prototype.getRTCDtlsTransport=function(){let e=this.version&&this.version.pc&&"function"==typeof this.version.pc.getSenders&&this.version.pc.getSenders()[0];return e&&e.transport||null},e4.prototype._canStopMediaStreamTrack=()=>"function"==typeof MediaStreamTrack.prototype.stop,e4.prototype._getAudioTracks=e=>"function"==typeof e.getAudioTracks?e.getAudioTracks():e.audioTracks,e4.prototype._getRTCIceTransport=function(){let e=this.getRTCDtlsTransport();return e&&e.iceTransport||null},e4.protocol=e1.test()?new e1:null,e4.prototype._handleAudioProcessorEvent=function(e,t){if(!e||!this._remoteStream)return;let i=null;this._masterAudio?(this._log.info("Setting audio source for master audio."),i=this._masterAudio):(this._log.info("No master audio. Setting audio source for default audio output."),i=this.outputs.get("default").audio),e6(i,this._remoteStream,this._audioHelper).then(()=>{this._log.info(t?"Successfully updated audio source with processed stream":"Successfully reverted audio source to original stream"),i.paused&&(this._log.info("Resuming audio playback"),i.play())}).catch(()=>{this._log.error(t?"Failed to update audio source":"Failed to revert audio source")})},e4.enabled=e1.test();class e9{constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}reject(e){this._reject(e)}resolve(e){this._resolve(e)}}class te{constructor(){this._operations=[]}enqueue(e){let t=!!this._operations.length,i=new e9;return this._operations.push({deferred:i,callback:e}),t||this._processQueue(),i.promise}_processQueue(){return F(this,void 0,void 0,function*(){for(;this._operations.length;){let e,t,i;let{deferred:s,callback:n}=this._operations[0];try{e=yield n(),i=!0}catch(e){t=e}this._operations.shift(),i?s.resolve(e):s.reject(t)}})}}class tt{get reject(){return this._reject}get resolve(){return this._resolve}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class ti{constructor(){this._eventEmitter=new j.EventEmitter}addEventListener(e,t){return this._eventEmitter.addListener(e,t)}dispatchEvent(e,...t){return this._eventEmitter.emit(e,...t)}removeEventListener(e,t){return this._eventEmitter.removeListener(e,t)}}class ts extends ti{get destination(){return this._destination}get loop(){return this._loop}set loop(e){let t=this;e||!this.loop||this.paused||this._audioNode.addEventListener("ended",function e(){t._audioNode.removeEventListener("ended",e),t.pause()}),this._loop=e}get muted(){return 0===this._gainNode.gain.value}set muted(e){this._gainNode.gain.value=e?0:1}get paused(){return null===this._audioNode}get src(){return this._src}set src(e){this._load(e)}get srcObject(){return this._audioElement.srcObject}set srcObject(e){this._audioElement.srcObject=e}get sinkId(){return this._sinkId}constructor(e,t={},i={}){super(),this._audioNode=null,this._loop=!1,this._pendingPlayDeferreds=[],this._sinkId="default",this._src="","string"!=typeof t&&(i=t),this._audioContext=e,this._audioElement=new(i.AudioFactory||Audio),this._bufferPromise=this._createPlayDeferred().promise,this._destination=this._audioContext.destination,this._gainNode=this._audioContext.createGain(),this._gainNode.connect(this._destination),this._XMLHttpRequest=i.XMLHttpRequestFactory||XMLHttpRequest,this.addEventListener("canplaythrough",()=>{this._resolvePlayDeferreds()}),"string"==typeof t&&(this.src=t)}load(){this._load(this._src)}pause(){this.paused||(this._audioElement.pause(),this._audioNode.stop(),this._audioNode.disconnect(this._gainNode),this._audioNode=null,this._rejectPlayDeferreds(Error("The play() request was interrupted by a call to pause().")))}play(){return F(this,void 0,void 0,function*(){if(!this.paused){if(yield this._bufferPromise,!this.paused)return;throw Error("The play() request was interrupted by a call to pause().")}this._audioNode=this._audioContext.createBufferSource(),this._audioNode.loop=this.loop,this._audioNode.addEventListener("ended",()=>{this._audioNode&&this._audioNode.loop||this.dispatchEvent("ended")});let e=yield this._bufferPromise;if(this.paused)throw Error("The play() request was interrupted by a call to pause().");if(this._audioNode.buffer=e,this._audioNode.connect(this._gainNode),this._audioNode.start(),this._audioElement.srcObject)return this._audioElement.play()})}setSinkId(e){return F(this,void 0,void 0,function*(){if("function"!=typeof this._audioElement.setSinkId)throw Error("This browser does not support setSinkId.");if(e!==this.sinkId){if("default"===e){this.paused||this._gainNode.disconnect(this._destination),this._audioElement.srcObject=null,this._destination=this._audioContext.destination,this._gainNode.connect(this._destination),this._sinkId=e;return}yield this._audioElement.setSinkId(e),this._audioElement.srcObject||(this._gainNode.disconnect(this._audioContext.destination),this._destination=this._audioContext.createMediaStreamDestination(),this._audioElement.srcObject=this._destination.stream,this._sinkId=e,this._gainNode.connect(this._destination))}})}_createPlayDeferred(){let e=new tt;return this._pendingPlayDeferreds.push(e),e}_load(e){this._src&&this._src!==e&&this.pause(),this._src=e,this._bufferPromise=new Promise((t,i)=>F(this,void 0,void 0,function*(){if(!e)return this._createPlayDeferred().promise;let i=yield function(e,t,i){return F(this,void 0,void 0,function*(){let s=new t;s.open("GET",i,!0),s.responseType="arraybuffer";let n=yield new Promise(e=>{s.addEventListener("load",e),s.send()});try{return e.decodeAudioData(n.target.response)}catch(t){return new Promise(t=>{e.decodeAudioData(n.target.response,t)})}})}(this._audioContext,this._XMLHttpRequest,e);this.dispatchEvent("canplaythrough"),t(i)}))}
1_rejectPlayDeferreds(e){let t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({reject:t})=>t(e))}_resolvePlayDeferreds(e){let t=this._pendingPlayDeferreds;t.splice(0,t.length).forEach(({resolve:t})=>t(e))}}function tn(e,t,i){if(!(this instanceof tn))return new tn(e,t,i);if(!e||!t)throw new B("name and url are required arguments");(i=Object.assign({AudioFactory:"undefined"!=typeof Audio?Audio:null,maxDuration:0,shouldLoop:!1},i)).AudioPlayer=i.audioContext?ts.bind(ts,i.audioContext):i.AudioFactory,Object.defineProperties(this,{_Audio:{value:i.AudioPlayer},_activeEls:{value:new Map},_isSinkSupported:{value:null!==i.AudioFactory&&"function"==typeof i.AudioFactory.prototype.setSinkId},_maxDuration:{value:i.maxDuration},_maxDurationTimeout:{value:null,writable:!0},_operations:{value:new te},_playPromise:{value:null,writable:!0},_shouldLoop:{value:i.shouldLoop},_sinkIds:{value:["default"]},isPlaying:{enumerable:!0,get(){return!!this._playPromise}},name:{enumerable:!0,value:e},url:{enumerable:!0,value:t}}),this._Audio&&this._play(!0,!1)}function to(e){e&&(e.pause(),e.src="",e.srcObject=null,e.load())}tn.prototype._playAudioElement=function(e,t,i){let s=this._activeEls.get(e);if(!s)throw new B(`sinkId: "${e}" doesn't have an audio element`);return s.muted=!!t,s.loop=!!i,s.play().then(()=>s).catch(t=>{throw to(s),this._activeEls.delete(e),t})},tn.prototype._play=function(e,t){this.isPlaying&&this._stop(),this._maxDuration>0&&(this._maxDurationTimeout=setTimeout(this._stop.bind(this),this._maxDuration)),t="boolean"==typeof t?t:this._shouldLoop;let i=this;return this._playPromise=Promise.all(this._sinkIds.map(function(s){if(!i._Audio)return Promise.resolve();let n=i._activeEls.get(s);return n?i._playAudioElement(s,e,t):("function"==typeof(n=new i._Audio(i.url)).setAttribute&&n.setAttribute("crossorigin","anonymous"),new Promise(e=>{n.addEventListener("canplaythrough",e)}).then(()=>(i._isSinkSupported?n.setSinkId(s):Promise.resolve()).then(function(){return(i._activeEls.set(s,n),i._playPromise)?i._playAudioElement(s,e,t):Promise.resolve()})))}))},tn.prototype._stop=function(){this._activeEls.forEach((e,t)=>{this._sinkIds.includes(t)?(e.pause(),e.currentTime=0):(to(e),this._activeEls.delete(t))}),clearTimeout(this._maxDurationTimeout),this._playPromise=null,this._maxDurationTimeout=null},tn.prototype.setSinkIds=function(e){this._isSinkSupported&&(e=e.forEach?e:[e],[].splice.apply(this._sinkIds,[0,this._sinkIds.length].concat(e)))},tn.prototype.stop=function(){this._operations.enqueue(()=>(this._stop(),Promise.resolve()))},tn.prototype.play=function(){return this._operations.enqueue(()=>this._play())};class tr extends j.EventEmitter{static get audioContext(){return tr._audioContext}static get extension(){let e,t;let i="undefined"!=typeof document?document.createElement("audio"):{canPlayType:!1};try{e=i.canPlayType&&!!i.canPlayType("audio/mpeg").replace(/no/,"")}catch(t){e=!1}try{t=i.canPlayType&&!!i.canPlayType("audio/ogg;codecs='vorbis'").replace(/no/,"")}catch(e){t=!1}return t&&!e?"ogg":"mp3"}static get isSupported(){return e1.test()}static get packageName(){return Q}static runPreflight(e,t){return new eW(e,Object.assign({audioContext:tr._getOrCreateAudioContext()},t))}static toString(){return"[Twilio.Device class]"}static get version(){return K}static _getOrCreateAudioContext(){return tr._audioContext||("undefined"!=typeof AudioContext?tr._audioContext=new AudioContext:"undefined"!=typeof webkitAudioContext&&(tr._audioContext=new webkitAudioContext)),tr._audioContext}constructor(e,t={}){if(super(),this._activeCall=null,this._audio=null,this._audioProcessorEventObserver=null,this._callInputStream=null,this._calls=[],this._callSinkIds=["default"],this._chunderURIs=[],this._defaultOptions={allowIncomingWhileBusy:!1,closeProtection:!1,codecPreferences:[tf.Codec.PCMU,tf.Codec.Opus],dscp:!0,enableImprovedSignalingErrorPrecision:!1,forceAggressiveIceNomination:!1,logLevel:N.levels.ERROR,maxCallSignalingTimeoutMs:0,preflight:!1,sounds:{},tokenRefreshMs:1e4,voiceEventSidGenerator:e8},this._edge=null,this._home=null,this._identity=null,this._log=new Z("Device"),this._makeCallPromise=null,this._options={},this._preferredURI=null,this._publisher=null,this._region=null,this._regTimer=null,this._shouldReRegister=!1,this._soundcache=new Map,this._state=tr.State.Unregistered,this._stateEventMapping={[tr.State.Destroyed]:tr.EventName.Destroyed,[tr.State.Unregistered]:tr.EventName.Unregistered,[tr.State.Registering]:tr.EventName.Registering,[tr.State.Registered]:tr.EventName.Registered},this._stream=null,this._streamConnectedPromise=null,this._tokenWillExpireTimeout=null,this._createDefaultPayload=e=>{let t={aggressive_nomination:this._options.forceAggressiveIceNomination,browser_extension:this._isBrowserExtension,dscp:!!this._options.dscp,ice_restart_enabled:!0,platform:"undefined"!=typeof RTCIceGatherer?"ORTC":"WebRTC",sdk_version:K};function i(e,i){i&&(t[e]=i)}if(e){let s=e.parameters.CallSid;i("call_sid",/^TJ/.test(s)?void 0:s),i("temp_call_sid",e.outboundConnectionId),i("audio_codec",e.codec),t.direction=e.direction}return i("gateway",this._stream&&this._stream.gateway),i("region",this._stream&&this._stream.region),t},this._onSignalingClose=()=>{this._stream=null,this._streamConnectedPromise=null},this._onSignalingConnected=e=>{var t;let i=eq[e.region]||null;if(this._edge=e.edge||eG[i]||e.region,this._region=i||e.region,this._home=e.home,null===(t=this._publisher)||void 0===t||t.setHost(eQ(e.home)),e.token&&(this._identity=e.token.identity,"number"==typeof e.token.ttl&&"number"==typeof this._options.tokenRefreshMs)){let t=Math.max(0,1e3*e.token.ttl-this._options.tokenRefreshMs);this._tokenWillExpireTimeout=setTimeout(()=>
1{this._log.debug("#tokenWillExpire"),this.emit("tokenWillExpire",this),this._tokenWillExpireTimeout&&(clearTimeout(this._tokenWillExpireTimeout),this._tokenWillExpireTimeout=null)},t)}let s=this._getChunderws()||eX(this._edge);if(s.length>0){let[e]=s;this._preferredURI=eK(e)}else this._log.warn("Could not parse a preferred URI from the stream#connected event.");this._shouldReRegister&&this.register()},this._onSignalingError=e=>{if("object"!=typeof e){this._log.warn("Invalid signaling error payload",e);return}let{error:t,callsid:i,voiceeventsid:s}=e;if("object"!=typeof t||s){this._log.warn("Ignoring signaling error payload",{originalError:t,voiceeventsid:s});return}let n="string"==typeof i&&this._findCall(i)||void 0,{code:o,message:r}=t,{twilioError:a}=t;if("number"==typeof o){if(31201===o)a=new w.AuthenticationFailed(t);else if(31204===o)a=new w.AccessTokenInvalid(t);else if(31205===o)this._stopRegistrationTimer(),a=new w.AccessTokenExpired(t);else{let e=V(!!this._options.enableImprovedSignalingErrorPrecision,o);void 0!==e&&(a=new e(t))}}a||(this._log.error("Unknown signaling error: ",t),a=new k.UnknownError(r,t)),this._log.error("Received error: ",a),this._log.debug("#error",t),this.emit(tr.EventName.Error,a,n)},this._onSignalingInvite=e=>F(this,void 0,void 0,function*(){var t;let i;let s=!!this._activeCall;if(s&&!this._options.allowIncomingWhileBusy){this._log.info("Device busy; ignoring incoming invite");return}if(!e.callsid||!e.sdp){this._log.debug("#error",e),this.emit(tr.EventName.Error,new E.BadRequest("Malformed invite from gateway"));return}let n=e.parameters||{};n.CallSid=n.CallSid||e.callsid;let o=Object.assign({},eu(n.Params));this._makeCallPromise=this._makeCall(o,{callParameters:n,enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,offerSdp:e.sdp,reconnectToken:e.reconnect,voiceEventSidGenerator:this._options.voiceEventSidGenerator});try{i=yield this._makeCallPromise}finally{this._makeCallPromise=null}this._calls.push(i),i.once("accept",()=>{this._soundcache.get(tr.SoundName.Incoming).stop(),this._publishNetworkChange()});let r=(null===(t=this._audio)||void 0===t?void 0:t.incoming())&&!s?()=>this._soundcache.get(tr.SoundName.Incoming).play():()=>Promise.resolve();this._showIncomingCall(i,r)}),this._onSignalingOffline=()=>{this._log.info("Stream is offline"),this._edge=null,this._region=null,this._shouldReRegister=this.state!==tr.State.Unregistered,this._setState(tr.State.Unregistered)},this._onSignalingReady=()=>{this._log.info("Stream is ready"),this._setState(tr.State.Registered)},this._publishNetworkChange=()=>{this._activeCall&&this._networkInformation&&this._publisher.info("network-information","network-change",{connection_type:this._networkInformation.type,downlink:this._networkInformation.downlink,downlinkMax:this._networkInformation.downlinkMax,effective_type:this._networkInformation.effectiveType,rtt:this._networkInformation.rtt},this._activeCall)},this._updateInputStream=e=>{let t=this._activeCall;return t&&!e?Promise.reject(new q("Cannot unset input device while a call is in progress.")):(this._callInputStream=e,t?t._setInputTracksFromStream(e):Promise.resolve())},this._updateSinkIds=(e,t)=>("ringtone"===e?this._updateRingtoneSinkIds(t):this._updateSpeakerSinkIds(t)).then(()=>{this._publisher.info("audio",`${e}-devices-set`,{audio_device_ids:t},this._activeCall)},i=>{throw this._publisher.error("audio",`${e}-devices-set-failed`,{audio_device_ids:t,message:i.message},this._activeCall),i}),this._setupLoglevel(t.logLevel),this._logOptions("constructor",t),this.updateToken(e),ed())throw new G("Microsoft Edge Legacy (https://support.microsoft.com/en-us/help/4533505/what-is-microsoft-edge-legacy) is deprecated and will not be able to connect to Twilio to make or receive calls after September 1st, 2020. Please see this documentation for a list of supported browsers https://www.twilio.com/docs/voice/client/javascript#supported-browsers");if(!tr.isSupported&&t.ignoreBrowserSupport){if(window&&window.location&&"http:"===window.location.protocol)throw new G("twilio.js wasn't able to find WebRTC browser support.           This is most likely because this page is served over http rather than https,           which does not support WebRTC in many browsers. Please load this page over https and           try again.");throw new G("twilio.js 1.3+ SDKs require WebRTC browser support.         For more information, see <https://www.twilio.com/docs/api/client/twilio-js>.         If you have any questions about this announcement, please contact         Twil
1io Support at <[email protected]>.")}let i=globalThis,s=i.msBrowser||i.browser||i.chrome;if(this._isBrowserExtension=!!s&&!!s.runtime&&!!s.runtime.id||!!i.safari&&!!i.safari.extension,this._isBrowserExtension&&this._log.info("Running as browser extension."),navigator){let e=navigator;this._networkInformation=e.connection||e.mozConnection||e.webkitConnection}this._networkInformation&&"function"==typeof this._networkInformation.addEventListener&&this._networkInformation.addEventListener("change",this._publishNetworkChange),tr._getOrCreateAudioContext(),tr._audioContext&&!tr._dialtonePlayer&&(tr._dialtonePlayer=new ew(tr._audioContext)),this._boundDestroy=this.destroy.bind(this),this._boundConfirmClose=this._confirmClose.bind(this),"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("pagehide",this._boundDestroy),this.updateOptions(t)}get audio(){return this._audio}connect(){return F(this,arguments,void 0,function*(e={}){let t,i,s,n;if(this._log.debug(".connect",JSON.stringify(e)),this._throwIfDestroyed(),this._activeCall)throw new q("A Call is already active");if(e.connectToken){try{let n=JSON.parse(decodeURIComponent(atob(e.connectToken)));t=n.customParameters,i=n.parameters,s=n.signalingReconnectToken}catch(e){throw new B("Cannot parse connectToken")}if(!i||!i.CallSid||!s)throw new B("Invalid connectToken")}let o=!1,r={},a={enableImprovedSignalingErrorPrecision:!!this._options.enableImprovedSignalingErrorPrecision,rtcConfiguration:e.rtcConfiguration,voiceEventSidGenerator:this._options.voiceEventSidGenerator};s&&i?(o=!0,a.callParameters=i,a.reconnectCallSid=i.CallSid,a.reconnectToken=s,r=t||r):r=e.params||r,this._makeCallPromise=this._makeCall(r,a,o);try{n=this._activeCall=yield this._makeCallPromise}finally{this._makeCallPromise=null}return this._calls.splice(0).forEach(e=>e.ignore()),this._soundcache.get(tr.SoundName.Incoming).stop(),n.accept({rtcConstraints:e.rtcConstraints}),this._publishNetworkChange(),n})}get calls(){return this._calls}destroy(){var e;this._log.debug(".destroy"),this._log.debug("Rejecting any incoming calls"),this._calls.slice(0).forEach(e=>e.reject()),this.disconnectAll(),this._stopRegistrationTimer(),this._destroyStream(),this._destroyAudioHelper(),null===(e=this._audioProcessorEventObserver)||void 0===e||e.destroy(),this._destroyPublisher(),this._networkInformation&&"function"==typeof this._networkInformation.removeEventListener&&this._networkInformation.removeEventListener("change",this._publishNetworkChange),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.removeEventListener("pagehide",this._boundDestroy)),this._setState(tr.State.Destroyed),j.EventEmitter.prototype.removeAllListeners.call(this)}disconnectAll(){this._log.debug(".disconnectAll"),this._calls.splice(0).forEach(e=>e.disconnect()),this._activeCall&&this._activeCall.disconnect()}get edge(){return this._edge}get home(){return this._home}get identity(){return this._identity}get isBusy(){return!!this._activeCall}register(){return F(this,void 0,void 0,function*(){if(this._log.debug(".register"),this.state!==tr.State.Unregistered)throw new q(`Attempt to register when device is in state "${this.state}". Must be "${tr.State.Unregistered}".`);this._shouldReRegister=!1,this._setState(tr.State.Registering),yield this._streamConnectedPromise||this._setupStream(),yield this._sendPresence(!0),yield em(this,tr.State.Registered,tr.State.Unregistered)})}get state(){return this._state}get token(){return this._token}toString(){return"[Twilio.Device instance]"}unregister(){return F(this,void 0,void 0,function*(){if(this._log.debug(".unregister"),this.state!==tr.State.Registered)throw new q(`Attempt to unregister when device is in state "${this.state}". Must be "${tr.State.Registered}".`);this._shouldReRegister=!1;let e=yield this._streamConnectedPromise,t=new Promise(t=>{e.on("offline",t)});yield this._sendPresence(!1),yield t})}updateOptions(e={}){if(this._logOptions("updateOptions",e),this.state===tr.State.Destroyed)throw new q(`Attempt to "updateOptions" when device is in state "${this.state}".`);this._options=Object.assign(Object.assign(Object.assign({},this._defaultOptions),this._options),e);let t=new Set(this._chunderURIs),i=this._chunderURIs=(this._getChunderws()||eX(this._options.edge)).map(eK),s=t.size!==i.length;if(!s){for(let e of i)if(!t.has(e)){s=!0;break}}if(this.isBusy&&s)throw new q("Cannot change Edge while on an active 
1Call");for(let e of(this._setupLoglevel(this._options.logLevel),Object.keys(tr._defaultSounds))){let t=tr._defaultSounds[e],i=`${X}/${t.filename}.${tr.extension}?cache=${K}`,s=this._options.sounds&&this._options.sounds[e]||i,n=new(this._options.Sound||tn)(e,s,{audioContext:this._options.disableAudioContextSounds?null:tr.audioContext,maxDuration:t.maxDuration,shouldLoop:t.shouldLoop});this._soundcache.set(e,n)}this._setupAudioHelper(),this._setupPublisher(),s&&this._streamConnectedPromise&&this._setupStream(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&this._options.closeProtection&&(window.removeEventListener("beforeunload",this._boundConfirmClose),window.addEventListener("beforeunload",this._boundConfirmClose))}updateToken(e){if(this._log.debug(".updateToken"),this.state===tr.State.Destroyed)throw new q(`Attempt to "updateToken" when device is in state "${this.state}".`);if("string"!=typeof e)throw new B('Parameter "token" must be of type "string".');this._token=e,this._stream&&this._stream.setToken(this._token),this._publisher&&this._publisher.setToken(this._token)}_confirmClose(e){if(!this._activeCall)return"";let t=this._options.closeProtection||!1,i="string"!=typeof t?"A call is currently in-progress. Leaving or reloading this page will end the call.":t;return(e||window.event).returnValue=i,i}_destroyAudioHelper(){this._audio&&(this._audio._destroy(),this._audio=null)}_destroyPublisher(){this._publisher&&(this._publisher=null)}_destroyStream(){this._stream&&(this._stream.removeListener("close",this._onSignalingClose),this._stream.removeListener("connected",this._onSignalingConnected),this._stream.removeListener("error",this._onSignalingError),this._stream.removeListener("invite",this._onSignalingInvite),this._stream.removeListener("offline",this._onSignalingOffline),this._stream.removeListener("ready",this._onSignalingReady),this._stream.destroy(),this._stream=null),this._onSignalingOffline(),this._streamConnectedPromise=null}_findCall(e){return this._calls.find(t=>t.parameters.CallSid===e||t.outboundConnectionId===e)||null}_getChunderws(){return"string"==typeof this._options.chunderw?[this._options.chunderw]:Array.isArray(this._options.chunderw)?this._options.chunderw:null}_logOptions(e,t={}){let i=["allowIncomingWhileBusy","appName","appVersion","closeProtection","codecPreferences","disableAudioContextSounds","dscp","edge","enableImprovedSignalingErrorPrecision","forceAggressiveIceNomination","logLevel","maxAverageBitrate","maxCallSignalingTimeoutMs","sounds","tokenRefreshMs"],s=["RTCPeerConnection","enumerateDevices","getUserMedia","MediaStream"];if("object"==typeof t){let n=Object.assign({},t);Object.keys(n).forEach(e=>{i.includes(e)||s.includes(e)||delete n[e],s.includes(e)&&(n[e]=!0)}),this._log.debug(`.${e}`,JSON.stringify(n))}}_makeCall(e,t){return F(this,arguments,void 0,function*(e,t,i=!1){var s;let n=null===(s=this._audio)||void 0===s?void 0:s._getInputDevicePromise();n&&(this._log.debug("inputDevicePromise detected, waiting..."),yield n,this._log.debug("inputDevicePromise resolved"));let o={audioHelper:this._audio,onIgnore:()=>{this._soundcache.get(tr.SoundName.Incoming).stop()},pstream:yield this._streamConnectedPromise||this._setupStream(),publisher:this._publisher,soundcache:this._soundcache};t=Object.assign({MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,beforeAccept:e=>{this._activeCall&&this._activeCall!==e&&(this._activeCall.disconnect(),this._removeCall(this._activeCall))},codecPreferences:this._options.codecPreferences,customSounds:this._options.sounds,dialtonePlayer:tr._dialtonePlayer,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,getInputStream:()=>this._options.fileInputStream||this._callInputStream,getSinkIds:()=>this._callSinkIds,maxAverageBitrate:this._options.maxAverageBitrate,preflight:this._options.preflight,rtcConstraints:this._options.rtcConstraints,shouldPlayDisconnect:()=>{var e;return null===(e=this._audio)||void 0===e?void 0:e.disconnect()},twimlParams:e,voiceEventSidGenerator:this._options.voiceEventSidGenerator},t);let r=()=>{if(!this._stream){this._log.warn("UnsetPreferredUri called without a stream");return}null===this._activeCall&&0===this._calls.length&&this._stream.updatePreferredURI(null)},a=new(this._options.Call||tf)(o,t);return this._publisher.info("settings","init",{MediaStream:!!this._options.MediaStream,RTCPeerConnection:!!this._options.RTCPeerConnection,enumerateDevices:!!this._options.enumerateDevices,getUserMedia:!!this._options.getUserMedia},a),a.once("accept",()=>{var e,t,s,n,o;this._stream.updatePreferredURI(this._preferredURI),this._removeCall(a),this._activeCall=a,this._audio&&this._audio._maybeStartPollingVolume(),a.direction===tf.CallDirection.Outgoing&&(null===(e=this._audio)||void 0===e?void 0:e.outgoing())&&!i&&this._soundcache.get(tr.SoundName.Outgoing).play();let r={edge:this._edge||this._region};this._options.edge&&(r.selected_edge=Array.isArray(this._options.edge)?this._options.edge:[this._options.edge]),this._publisher.info("settings","edge",r,a),(null===(t=this._audio)||void 0===t?void 0:t.localProcessedStream)&&(null===(s=this._audioProcessorEventObserver)||void 0===s||s.emit("enabled",!1)),(null===(n=this._audio)||void 0===n?void 0:n.remoteProcessedStream)&&(null===(o=this._audioProcessorEventObserver)||void 0===o||o.emit("enabled",!0))}),a.addListener("error",e=>{"closed"===a.status()&&(this._removeCall(a),r()),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),a.once("cancel",()=>{this._log.info(`Canceled: ${a.parameters.CallSid}`),this._removeCall(a),r(),this._audio&&this._audio._maybeStopPollingVolume(),this._maybeStopIncomingSound()}),a.once("disconnect",()=>{this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(a),r(),this._maybeStopIncomingSound()}),a.once("reject",()=>{this._log.info(`Rejected: ${a.parameters.CallSid}`),this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(a),r(),this._maybeStopIncomingSound()}),a.on("transportClose",()=>{a.status()===tf.State.Pending&&(this._audio&&this._audio._maybeStopPollingVolume(),this._removeCall(a),this._maybeStopIncomingSound())}),a})}_maybeStopIncomingSound(){this._calls.length||this._soundcache.get(tr.SoundName.Incoming).stop()}_removeCall(e){this._activeCall===e&&(this._activeCall=null,this._makeCallPromise=null);for(let t=this._calls.length-1;t>=0;t--)e===this._calls[t]&&this._calls.splice(t,1)}_sendPresence(e){return F(this,void 0,void 0,function*(){let t=yield this._streamConnectedPromise;t&&(t.register({audio:e}),e?this._startRegistrationTimer():this._stopRegistrationTimer())})}_setState(e){if(e===this.state)return;this._state=e;let t=this._stateEventMapping[e];this._log.debug(`#${t}
1`),this.emit(t)}_setupAudioHelper(){this._audioProcessorEventObserver||(this._audioProcessorEventObserver=new eb,this._audioProcessorEventObserver.on("event",({name:e,group:t,isRemote:i})=>{this._publisher.info(t,e,{is_remote:i},this._activeCall)}));let e={audioContext:tr.audioContext,audioProcessorEventObserver:this._audioProcessorEventObserver,beforeSetInputDevice:()=>this._makeCallPromise?(this._log.debug("beforeSetInputDevice pause detected"),this._makeCallPromise):(this._log.debug("beforeSetInputDevice pause not detected, setting default"),Promise.resolve()),enumerateDevices:this._options.enumerateDevices,getUserMedia:this._options.getUserMedia||e7};if(this._audio){this._log.info("Found existing audio helper; updating options..."),this._audio._updateUserOptions(e);return}this._audio=new(this._options.AudioHelper||ey)(this._updateSinkIds,this._updateInputStream,e),this._audio.on("deviceChange",e=>{let t=this._activeCall,i=e.map(e=>e.deviceId);this._publisher.info("audio","device-change",{lost_active_device_ids:i},t),t&&t._mediaHandler._onInputDevicesChanged()})}_setupLoglevel(e){let t="number"==typeof e||"string"==typeof e?e:N.levels.ERROR;this._log.setDefaultLevel(t),this._log.info("Set logger default level to",t)}_setupPublisher(){this._publisher&&(this._log.info("Found existing publisher; destroying..."),this._destroyPublisher());let e={defaultPayload:this._createDefaultPayload,metadata:{app_name:this._options.appName,app_version:this._options.appVersion}};return this._options.eventgw&&(e.host=this._options.eventgw),this._home&&(e.host=eQ(this._home)),this._publisher=new(this._options.Publisher||eE)("twilio-js-sdk",this.token,e),!1===this._options.publishEvents?this._publisher.disable():this._publisher.on("error",e=>{this._log.warn("Cannot connect to insights.",e)}),this._publisher}_setupStream(){return this._stream&&(this._log.info("Found existing stream; destroying..."),this._destroyStream()),this._log.info("Setting up VSP"),this._stream=new(this._options.PStream||eB)(this.token,this._chunderURIs,{backoffMaxMs:this._options.backoffMaxMs,maxPreferredDurationMs:this._options.maxCallSignalingTimeoutMs}),this._stream.addListener("close",this._onSignalingClose),this._stream.addListener("connected",this._onSignalingConnected),this._stream.addListener("error",this._onSignalingError),this._stream.addListener("invite",this._onSignalingInvite),this._stream.addListener("offline",this._onSignalingOffline),this._stream.addListener("ready",this._onSignalingReady),this._streamConnectedPromise=em(this._stream,"connected","close").then(()=>this._stream)}_showIncomingCall(e,t){let i;return Promise.race([t(),new Promise((e,t)=>{i=setTimeout(()=>{t(Error("Playing incoming ringtone took too long; it might not play. Continuing execution..."))},2e3)})]).catch(e=>{this._log.warn(e.message)}).then(()=>{clearTimeout(i),this._log.debug("#incoming",JSON.stringify({customParameters:e.customParameters,parameters:e.parameters})),this.emit(tr.EventName.Incoming,e)})}_startRegistrationTimer(){this._stopRegistrationTimer(),this._regTimer=setTimeout(()=>{this._sendPresence(!0)},3e4)}_stopRegistrationTimer(){this._regTimer&&clearTimeout(this._regTimer)}_throwIfDestroyed(){if(this.state===tr.State.Destroyed)throw new q("Device has been destroyed.")}_updateRingtoneSinkIds(e){return Promise.resolve(this._soundcache.get(tr.SoundName.Incoming).setSinkIds(e))}_updateSpeakerSinkIds(e){Array.from(this._soundcache.entries()).filter(e=>e[0]!==tr.SoundName.Incoming).forEach(t=>t[1].setSinkIds(e)),this._callSinkIds=e;let t=this._activeCall;return t?t._setSinkIds(e):Promise.resolve()}}tr._defaultSounds={disconnect:{filename:"disconnect",maxDuration:3e3},dtmf0:{filename:"dtmf-0",maxDuration:1e3},dtmf1:{filename:"dtmf-1",maxDuration:1e3},dtmf2:{filename:"dtmf-2",maxDuration:1e3},dtmf3:{filename:"dtmf-3",maxDuration:1e3},dtmf4:{filename:"dtmf-4",maxDuration:1e3},dtmf5:{filename:"dtmf-5",maxDuration:1e3},dtmf6:{filename:"dtmf-6",maxDuration:1e3},dtmf7:{filename:"dtmf-7",maxDuration:1e3},dtmf8:{filename:"dtmf-8",maxDuration:1e3},dtmf9:{filename:"dtmf-9",maxDuration:1e3},dtmfh:{filename:"dtmf-hash",maxDuration:1e3},dtmfs:{filename:"dtmf-star",maxDuration:1e3},incoming:{filename:"incoming",shouldLoop:!0},outgoing:{filename:"outgoing",maxDuration:3e3}},(h=(d=tr||(tr={})).EventName||(d.EventName={})).Error="error",h.Incoming="incoming",h.Destroyed="destroyed",h.Unregistered="unregistered",h.Registering="registering",h.Registered="registered",h.TokenWillExpire="tokenWillExpire",(u=d.State||(d.State={})).Destroyed="destroyed",u.Unregistered="unregistered",u.Registering="registering",u.Registered="registered",(p=d.SoundName||(d.SoundName={})).Incoming="incoming",p.Outgoing="outgoing",p.Disconnect="disconnect",p.Dtmf0="dtmf0",p.Dtmf1="dtmf1",p.Dtmf2="dtmf2",p.Dtmf3="dtmf3",p.Dtmf4="dtmf4",p.Dtmf5="dtmf5",p.Dtmf6="dtmf6",p.Dtmf7="dtmf7",p.Dtmf8="dtmf8",p.Dtmf9="dtmf9",p.DtmfS="dtmfs",p.DtmfH="dtmfh";class ta{constructor(e,t=!1){let i;this.deleted=!1;let s=e.candidate.split("network-cost ");s[1]&&(i=parseInt(s[1],10)),this.candidateType=e.type,this.ip=e.ip||e.address,this.isRemote=t,this.networkCost=i,this.port=e.port,this.priority=e.priority,this.protocol=e.protocol,this.relatedAddress=e.relatedAddress,this.relatedPort=e.relatedPort,this.tcpType=e.tcpType,this.transportId=e.sdpMid}toPayload(){return{candidate_type:this.candidateType,deleted:this.deleted,ip:this.ip,is_remote:this.isRemote,"network-cost":this.networkCost,port:this.port,priority:this.priority,protocol:this.protocol,related_address:this.relatedAddress,related_port:this.relatedPort,tcp_type:this.tcpType,transport_id:this.transportId}}}function tc(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)&&e>=0}var tl={calculate:function(e,t,i){if("number"!=typeof e||"number"!=typeof t||"number"!=typeof i||!tc(e)||!tc(t)||!tc(i))return null;let s=e+2*t+10,n=0;switch(!0){case s<160:n=94.768-s/40;break;case s<1e3:n=94.768-(s-120)/10}return 1+.035*(n=!0==i<=n/2.5?Math.max(n-2.5*i,6.52):0)+7e-6*n*(n-60)
1*(100-n)},isNonNegativeNumber:tc};let td={audioInputLevel:{minStandardDeviation:327.67,sampleCount:10},audioOutputLevel:{minStandardDeviation:327.67,sampleCount:10},bytesReceived:{clearCount:2,min:1,raiseCount:3,sampleCount:3},bytesSent:{clearCount:2,min:1,raiseCount:3,sampleCount:3},jitter:{max:30},mos:{min:3},packetsLostFraction:[{max:1},{clearValue:1,maxAverage:3,sampleCount:7}],rtt:{max:400}};class th extends j.EventEmitter{constructor(e){super(),this._activeWarnings=new Map,this._currentStreaks=new Map,this._inputVolumes=[],this._outputVolumes=[],this._sampleBuffer=[],this._supplementalSampleBuffers={audioInputLevel:[],audioOutputLevel:[]},this._warningsEnabled=!0,e=e||{},this._getRTCStats=e.getRTCStats||eF,this._mos=e.Mos||tl,this._peerConnection=e.peerConnection,this._thresholds=Object.assign(Object.assign({},td),e.thresholds);let t=Object.values(this._thresholds).map(e=>e.sampleCount).filter(e=>!!e);this._maxSampleCount=Math.max(5,...t),this._peerConnection&&this.enable(this._peerConnection)}addVolumes(e,t){this._inputVolumes.push(e),this._outputVolumes.push(t)}disable(){return this._sampleInterval&&(clearInterval(this._sampleInterval),delete this._sampleInterval),this}disableWarnings(){return this._warningsEnabled&&this._activeWarnings.clear(),this._warningsEnabled=!1,this}enable(e){if(e){if(this._peerConnection&&e!==this._peerConnection)throw new B("Attempted to replace an existing PeerConnection in StatsMonitor.enable");this._peerConnection=e}if(!this._peerConnection)throw new B("Can not enable StatsMonitor without a PeerConnection");return this._sampleInterval=this._sampleInterval||setInterval(this._fetchSample.bind(this),1e3),this}enableWarnings(){return this._warningsEnabled=!0,this}hasActiveWarning(e,t){let i=`${e}:${t}`;return!!this._activeWarnings.get(i)}_addSample(e){let t=this._sampleBuffer;t.push(e),t.length>this._maxSampleCount&&t.splice(0,t.length-this._maxSampleCount)}_clearWarning(e,t,i){let s=`${e}:${t}`,n=this._activeWarnings.get(s);!n||Date.now()-n.timeRaised<5e3||(this._activeWarnings.delete(s),this.emit("warning-cleared",Object.assign(Object.assign({},i),{name:e,threshold:{name:t,value:this._thresholds[e][t]}})))}_createSample(e,t){let i=t&&t.totals.bytesSent||0,s=t&&t.totals.bytesReceived||0,n=t&&t.totals.packetsSent||0,o=t&&t.totals.packetsReceived||0,r=t&&t.totals.packetsLost||0,a=e.bytesSent-i,c=e.bytesReceived-s,l=e.packetsSent-n,d=e.packetsReceived-o,h=e.packetsLost-r,u=d+h,p=u>0?h/u*100:0,m=e.packetsReceived+e.packetsLost,g=m>0?e.packetsLost/m*100:100,_="number"!=typeof e.rtt&&t?t.rtt:e.rtt,f=this._inputVolumes.splice(0);this._supplementalSampleBuffers.audioInputLevel.push(f);let v=this._outputVolumes.splice(0);return this._supplementalSampleBuffers.audioOutputLevel.push(v),{audioInputLevel:Math.round(eo(f)),audioOutputLevel:Math.round(eo(v)),bytesReceived:c,bytesSent:a,codecName:e.codecName,jitter:e.jitter,mos:this._mos.calculate(_,e.jitter,t&&p),packetsLost:h,packetsLostFraction:p,packetsReceived:d,packetsSent:l,rtt:_,timestamp:e.timestamp,totals:{bytesReceived:e.bytesReceived,bytesSent:e.bytesSent,packetsLost:e.packetsLost,packetsLostFraction:g,packetsReceived:e.packetsReceived,packetsSent:e.packetsSent}}}_fetchSample(){this._getSample().then(e=>{this._addSample(e),this._raiseWarnings(),this.emit("sample",e)}).catch(e=>{this.disable(),this.emit("error",e)})}_getSample(){return this._getRTCStats(this._peerConnection).then(e=>{let t=null;return this._sampleBuffer.length&&(t=this._sampleBuffer[this._sampleBuffer.length-1]),this._createSample(e,t)})}_raiseWarning(e,t,i){let s;let n=`${e}:${t}`;if(this._activeWarnings.has(n))return;this._activeWarnings.set(n,{timeRaised:Date.now()});let o=this._thresholds[e];if(Array.isArray(o)){let e=o.find(e=>t in e);e&&(s=e[t])}else s=this._thresholds[e][t];this.emit("warning",Object.assign(Object.assign({},i),{name:e,threshold:{name:t,value:s}}))}_raiseWarnings(){this._warningsEnabled&&Object.keys(this._thresholds).forEach(e=>this._raiseWarningsForStat(e))}_raiseWarningsForStat(e){(Array.isArray(this._thresholds[e])?this._thresholds[e]:[this._thresholds[e]]).forEac
1h(t=>{var i,s;let n;let o=this._sampleBuffer,r=t.clearCount||0,a=t.raiseCount||3,c=t.sampleCount||this._maxSampleCount,l=o.slice(-c),d=l.map(t=>t[e]);if(!d.some(e=>null==e)){if("number"==typeof t.max&&(i=t.max,(n=d.reduce((e,t)=>e+=t>i?1:0,0))>=a?this._raiseWarning(e,"max",{values:d,samples:l}):n<=r&&this._clearWarning(e,"max",{values:d,samples:l})),"number"==typeof t.min&&(s=t.min,(n=d.reduce((e,t)=>e+=t<s?1:0,0))>=a?this._raiseWarning(e,"min",{values:d,samples:l}):n<=r&&this._clearWarning(e,"min",{values:d,samples:l})),"number"==typeof t.maxDuration&&o.length>1){let i=(l=o.slice(-2))[0][e],s=l[1][e],n=this._currentStreaks.get(e)||0,r=i===s?n+1:0;this._currentStreaks.set(e,r),r>=t.maxDuration?this._raiseWarning(e,"maxDuration",{value:r}):0===r&&this._clearWarning(e,"maxDuration",{value:n})}if("number"==typeof t.minStandardDeviation){let i=this._supplementalSampleBuffers[e];if(!i||i.length<t.sampleCount)return;i.length>t.sampleCount&&i.splice(0,i.length-t.sampleCount);let s=function(e){if(e.length<=0)return null;let t=e.reduce((e,t)=>e+t,0)/e.length,i=e.map(e=>Math.pow(e-t,2));return Math.sqrt(i.reduce((e,t)=>e+t,0)/i.length)}(i.slice(-c).reduce((e,t)=>[...e,...t],[]));if("number"!=typeof s)return;s<t.minStandardDeviation?this._raiseWarning(e,"minStandardDeviation",{value:s}):this._clearWarning(e,"minStandardDeviation",{value:s})}[["maxAverage",(e,t)=>e>t],["minAverage",(e,t)=>e<t]].forEach(([i,s])=>{if("number"==typeof t[i]&&d.length>=c){let n=eo(d);s(n,t[i])?this._raiseWarning(e,i,{values:d,samples:l}):s(n,t.clearValue||t[i])||this._clearWarning(e,i,{values:d,samples:l})}})}})}}let tu={factor:1.1,jitter:.5,max:3e4,min:1},tp={disconnect:!0,info:{code:31003,message:"Connection with Twilio was interrupted.",twilioError:new D.ConnectionError}},tm={packetsLostFraction:{max:"packet-loss",maxAverage:"packets-lost-fraction"}},tg={audioInputLevel:"audio-input-level",audioOutputLevel:"audio-output-level",bytesReceived:"bytes-received",bytesSent:"bytes-sent",jitter:"jitter",mos:"mos",rtt:"rtt"},t_={max:"high-",maxAverage:"high-",maxDuration:"constant-",min:"low-",minStandardDeviation:"constant-"};class tf extends j.EventEmitter{get direction(){return this._direction}get codec(){return this._codec}get connectToken(){let e=this._signalingReconnectToken,t=this.parameters&&this.parameters.CallSid?this.parameters.CallSid:void 0;if(e&&t)return btoa(encodeURIComponent(JSON.stringify({customParameters:this.customParameters&&"function"==typeof this.customParameters.keys?Array.from(this.customParameters.keys()).reduce((e,t)=>(e[t]=this.customParameters.get(t),e),{}):{},parameters:this.parameters||{},signalingReconnectToken:e})))}constructor(e,t){super(),this.parameters={},this._inputVolumeStreak=0,this._isAnswered=!1,this._isCancelled=!1,this._isRejected=!1,this._latestInputVolume=0,this._latestOutputVolume=0,this._log=new Z("Call"),this._mediaStatus=tf.State.Pending,this._messages=new Map,this._metricsSamples=[],this._options={MediaHandler:e4,MediaStream:null,enableImprovedSignalingErrorPrecision:!1,offerSdp:null,shouldPlayDisconnect:()=>!0,voiceEventSidGenerator:e8},this._outputVolumeStreak=0,this._shouldSendHangup=!0,this._signalingStatus=tf.State.Pending,this._soundcache=new Map,this._status=tf.State.Pending,this._wasConnected=!1,this.toString=()=>"[Twilio.Call instance]",this._emitWarning=(e,t,i,s,n,o)=>{let r=`${e}warning${n?"-cleared":"-raised"}`;if("constant-audio-input-level"===t&&this.isMuted())return;let a=n?"info":"warning";"constant-audio-output-level"===t&&(a="info");let c={threshold:i};if(s&&(s instanceof Array?c.values=s.map(e=>"number"==typeof e?Math.round(100*e)/100:s):c.value=s),this._publisher.post(a,r,t,{data:c},this),"constant-audio-output-level"!==t){let e=n?"warning-cleared":"warning";this._log.debug(`#${e}`,t),this.emit(e,t,o&&!n?o:null)}},this._onAck=e=>{let{acktype:t,callsid:i,voiceeventsid:s}=e;if(this.parameters.CallSid!==i){this._log.warn(`Received ack from a different callsid: ${i}`);return}"message"===t&&this._onMessageSent(s)},this._onAnswer=e=>{"string"==typeof e.reconnect&&(this._signalingReconnectToken=e.reconnect),this._isAnswered&&this._status!==tf.State.Reconnecting||(this._setCallSid(e),this._isAnswered=!0,this._maybeTransitionToOpen())},this._onCancel=e=>{let t=e.callsid;this.parameters.CallSid===t&&(this._isCancelled=!0,this._publisher.info("connection","cancel",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=tf.State.Closed,this._log.debug("#cancel"),this.emit
1("cancel"),this._pstream.removeListener("cancel",this._onCancel))},this._onConnected=()=>{this._log.info("Received connected from pstream"),this._signalingReconnectToken&&this._mediaHandler.version&&this._pstream.reconnect(this._mediaHandler.version.getSDP(),this.parameters.CallSid,this._signalingReconnectToken)},this._onHangup=e=>{if(this.status()!==tf.State.Closed){if(e.callsid&&(this.parameters.CallSid||this.outboundConnectionId)){if(e.callsid!==this.parameters.CallSid&&e.callsid!==this.outboundConnectionId)return}else if(e.callsid)return;if(this._log.info("Received HANGUP from gateway"),e.error){let t=e.error.code,i=V(this._options.enableImprovedSignalingErrorPrecision,t),s=void 0!==i?new i(e.error.message):new k.ConnectionError("Error sent from gateway in HANGUP",e.error);this._log.error("Received an error from the gateway:",s),this._log.debug("#error",s),this.emit("error",s)}this._shouldSendHangup=!1,this._publisher.info("connection","disconnected-by-remote",null,this),this._disconnect(null,!0),this._cleanupEventListeners()}},this._onMediaFailure=e=>{let{ConnectionDisconnected:t,ConnectionFailed:i,IceGatheringFailed:s,LowBytes:n}=tf.MediaFailure,o=e===i||e===s;if(!ec(window,window.navigator)&&e===i)return this._mediaHandler.onerror(tp);if(this._mediaStatus===tf.State.Reconnecting){if(o){if(Date.now()-this._mediaReconnectStartTime>tu.max)return this._log.warn("Exceeded max ICE retries"),this._mediaHandler.onerror(tp);try{this._mediaReconnectBackoff.backoff()}catch(e){if(!(e.message&&"Backoff in progress."===e.message))throw e}}return}let r=this._mediaHandler.version.pc,a=r&&"disconnected"===r.iceConnectionState,c=this._monitor.hasActiveWarning("bytesSent","min")||this._monitor.hasActiveWarning("bytesReceived","min");if(e===n&&a||e===t&&c||o){let e=new D.ConnectionError("Media connection failed.");this._log.warn("ICE Connection disconnected."),this._publisher.warn("connection","error",e,this),this._publisher.info("connection","reconnecting",null,this),this._mediaReconnectStartTime=Date.now(),this._status=tf.State.Reconnecting,this._mediaStatus=tf.State.Reconnecting,this._mediaReconnectBackoff.reset(),this._mediaReconnectBackoff.backoff(),this._log.debug("#reconnecting"),this.emit("reconnecting",e)}},this._onMediaReconnected=()=>{this._mediaStatus===tf.State.Reconnecting&&(this._log.info("ICE Connection reestablished."),this._mediaStatus=tf.State.Open,this._signalingStatus===tf.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=tf.State.Open))},this._onMessageReceived=e=>{let{callsid:t,content:i,contenttype:s,messagetype:n,voiceeventsid:o}=e;if(this.parameters.CallSid!==t){this._log.warn(`Received a message from a different callsid: ${t}`);return}let r={content:i,contentType:s,messageType:n,voiceEventSid:o};this._publisher.info("call-message",n,{content_type:s,event_type:"received",voice_event_sid:o},this),this._log.debug("#messageReceived",JSON.stringify(r)),this.emit("messageReceived",r)},this._onMessageSent=e=>{if(!this._messages.has(e)){this._log.warn(`Received a messageSent with a voiceEventSid that doesn't exists: ${e}`);return}let t=this._messages.get(e);this._messages.delete(e),this._publisher.info("call-message",null==t?void 0:t.messageType,{content_type:null==t?void 0:t.contentType,event_type:"sent",voice_event_sid:e},this),this._log.debug("#messageSent",JSON.stringify(t)),this.emit("messageSent",t)},this._onRinging=e=>{if(this._setCallSid(e),this._status!==tf.State.Connecting&&this._status!==tf.State.Ringing)return;let t=!!e.sdp;this._status=tf.State.Ringing,this._publisher.info("connection","outgoing-ringing",{hasEarlyMedia:t},this),this._log.debug("#ringing"),this.emit("ringing",t)},this._onRTCSample=e=>{let t=Object.assign(Object.assign({},e),{inputVolume:this._latestInputVolume,outputVolume:this._latestOutputVolume});this._codec=t.codecName,this._metricsSamples.push(t),this._metricsSamples.length>=10&&this._publishMetrics(),this.emit("sample",e)},this._onSignalingError=e=>{let{callsid:t,voiceeventsid:i,error:s}=e;if(this.parameters.CallSid!==t){this._log.warn(`Received an error from a different callsid: ${t}`);return}if(i&&this._messages.has(i)){let t;this._messages.delete(i),this._log.warn("Received an error while sending a message.",e),this._publisher.error("call-message","error",{code:s.code,message:s.message,voice_event_sid:i},this);let n=V(!!this._options.enableImprovedSignalingErrorPrecision,s.c
1ode);void 0!==n&&(t=new n(s)),t||(this._log.error("Unknown Call Message Error: ",s),t=new k.UnknownError(s.message,s)),this._log.debug("#error",s,t),this.emit("error",t)}},this._onSignalingReconnected=()=>{this._signalingStatus===tf.State.Reconnecting&&(this._log.info("Signaling Connection reestablished."),this._signalingStatus=tf.State.Open,this._mediaStatus===tf.State.Open&&(this._publisher.info("connection","reconnected",null,this),this._log.debug("#reconnected"),this.emit("reconnected"),this._status=tf.State.Open))},this._onTransportClose=()=>{this._log.error("Received transportClose from pstream"),this._log.debug("#transportClose"),this.emit("transportClose"),this._signalingReconnectToken?(this._status=tf.State.Reconnecting,this._signalingStatus=tf.State.Reconnecting,this._publisher.info("connection","reconnecting",null,this),this._log.debug("#reconnecting"),this.emit("reconnecting",new x.ConnectionDisconnected)):(this._status=tf.State.Closed,this._signalingStatus=tf.State.Closed)},this._reemitWarning=(e,t)=>{let i;let s=/^audio/.test(e.name)?"audio-level-":"network-quality-",n=t_[e.threshold.name];e.name in tm?i=tm[e.name][e.threshold.name]:e.name in tg&&(i=tg[e.name]);let o=n+i;this._emitWarning(s,o,e.threshold.value,e.values||e.value,t,e)},this._reemitWarningCleared=e=>{this._reemitWarning(e,!0)},this._soundcache=e.soundcache,"function"==typeof e.onIgnore&&(this._onIgnore=e.onIgnore);let i=t&&t.twimlParams||{};this.customParameters=new Map(Object.entries(i).map(([e,t])=>[e,String(t)])),Object.assign(this._options,t),this._options.callParameters&&(this.parameters=this._options.callParameters),this._options.reconnectToken&&(this._signalingReconnectToken=this._options.reconnectToken),this._voiceEventSidGenerator=this._options.voiceEventSidGenerator||e8,this._direction=this.parameters.CallSid&&!this._options.reconnectCallSid?tf.CallDirection.Incoming:tf.CallDirection.Outgoing,this.parameters?this.callerInfo=this.parameters.StirStatus?{isVerified:"TN-Validation-Passed-A"===this.parameters.StirStatus}:null:this.callerInfo=null,this._mediaReconnectBackoff=new $(tu),this._mediaReconnectBackoff.on("ready",()=>this._mediaHandler.iceRestart()),this.outboundConnectionId="TJSxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});let s=this._publisher=e.publisher;this._direction===tf.CallDirection.Incoming?s.info("connection","incoming",null,this):s.info("connection","outgoing",{preflight:this._options.preflight,reconnect:!!this._options.reconnectCallSid},this);let n=this._monitor=new(this._options.StatsMonitor||th);n.on("sample",this._onRTCSample),n.disableWarnings(),setTimeout(()=>n.enableWarnings(),5e3),n.on("warning",(e,t)=>{("bytesSent"===e.name||"bytesReceived"===e.name)&&this._onMediaFailure(tf.MediaFailure.LowBytes),this._reemitWarning(e,t)}),n.on("warning-cleared",e=>{this._reemitWarningCleared(e)}),this._mediaHandler=new this._options.MediaHandler(e.audioHelper,e.pstream,{MediaStream:this._options.MediaStream,RTCPeerConnection:this._options.RTCPeerConnection,codecPreferences:this._options.codecPreferences,dscp:this._options.dscp,forceAggressiveIceNomination:this._options.forceAggressiveIceNomination,maxAverageBitrate:this._options.maxAverageBitrate}),this.on("volume",(e,t)=>{this._inputVolumeStreak=this._checkVolume(e,this._inputVolumeStreak,this._latestInputVolume,"input"),this._outputVolumeStreak=this._checkVolume(t,this._outputVolumeStreak,this._latestOutputVolume,"output"),this._latestInputVolume=e,this._latestOutputVolume=t}),this._mediaHandler.onaudio=e=>{this._log.debug("#audio"),this.emit("audio",e)},this._mediaHandler.onvolume=(e,t,i,s)=>{n.addVolumes(i/255*32767,s/255*32767),this.emit("volume",e,t)},this._mediaHandler.ondtlstransportstatechange=e=>{this._publisher.post("failed"===e?"error":"debug","dtls-transport-state",e,null,this)},this._mediaHandler.onpcconnectionstatechange=e=>{let t="debug",i=this._mediaHandler.getRTCDtlsTransport();"failed"===e&&(t=i&&"failed"===i.state?"error":"warning"),this._publisher.post(t,"pc-connection-state",e,null,this)},this._mediaHandler.onicecandidate=e=>{let t=new ta(e).toPayload();this._publisher.debug("ice-candidate","ice-candidate",t,this)},this._mediaHandler.onselectedcandidatepairchange=e=>{let t=new ta(e.local).toPayload(),i=new ta(e.remote,!0).toPayload();this._publisher.debug("ice-candidate","selected-ice-candidate-pair",{local_candidate:t,remote_candidate:i},this)},this._mediaHandler.oniceconnectionstatechange=e=>{this._publisher.post("failed"===e?"error":"debug","ice-connection-state",e,null,this)},this._mediaHandler.onicegatheringfailure=e=>{this._publisher.warn("ice-gathering-state",e,null,this),this._onMediaFailure(tf.MediaFailure.IceGatheringFailed)},this._mediaHandler.onicegatheringstatechange=e=>{this._publisher.debug("ice-gathering-state",e,null,this)},this._mediaHandler.onsignalingstatechange=e=>{this._publisher.debug("signaling-state",e,null,this)},this._mediaHandler.ondisconnected=e=>{this._log.warn(e),this._publisher.warn("network-quality-warning-raised","ice-connectivity-lost",{message:e},this),this._log.debug("#warning","ice-connectivity-lost"),this.emit
1("warning","ice-connectivity-lost"),this._onMediaFailure(tf.MediaFailure.ConnectionDisconnected)},this._mediaHandler.onfailed=e=>{this._onMediaFailure(tf.MediaFailure.ConnectionFailed)},this._mediaHandler.onconnected=()=>{this._status===tf.State.Reconnecting&&this._onMediaReconnected()},this._mediaHandler.onreconnected=e=>{this._log.info(e),this._publisher.info("network-quality-warning-cleared","ice-connectivity-lost",{message:e},this),this._log.debug("#warning-cleared","ice-connectivity-lost"),this.emit("warning-cleared","ice-connectivity-lost"),this._onMediaReconnected()},this._mediaHandler.onerror=e=>{!0===e.disconnect&&this._disconnect(e.info&&e.info.message);let t=e.info.twilioError||new k.UnknownError(e.info.message);this._log.error("Received an error from MediaStream:",e),this._log.debug("#error",t),this.emit("error",t)},this._mediaHandler.onopen=()=>{this._status!==tf.State.Open&&this._status!==tf.State.Reconnecting&&(this._status===tf.State.Ringing||this._status===tf.State.Connecting?(this.mute(this._mediaHandler.isMuted),this._mediaStatus=tf.State.Open,this._maybeTransitionToOpen()):this._mediaHandler.close())},this._mediaHandler.onclose=()=>{this._status=tf.State.Closed,this._options.shouldPlayDisconnect&&this._options.shouldPlayDisconnect()&&!this._isCancelled&&!this._isRejected&&this._soundcache.get(tr.SoundName.Disconnect).play(),n.disable(),this._publishMetrics(),this._isCancelled||this._isRejected||(this._log.debug("#disconnect"),this.emit("disconnect",this))},this._pstream=e.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",e=>{this._publisher.error("connection","error",{code:e.code,message:e.message},this),this._pstream&&"disconnected"===this._pstream.status&&this._cleanupEventListeners()}),this.on("disconnect",()=>{this._cleanupEventListeners()})}_setInputTracksFromStream(e){return this._mediaHandler.setInputTracksFromStream(e)}_setSinkIds(e){return this._mediaHandler._setSinkIds(e)}accept(e){if(this._log.debug(".accept",e),this._status!==tf.State.Pending){this._log.debug(`.accept noop. status is '${this._status}'`);return}let t=(e=e||{}).rtcConfiguration||this._options.rtcConfiguration,i=e.rtcConstraints||this._options.rtcConstraints||{},s={audio:void 0===i.audio||i.audio};this._status=tf.State.Connecting;let n=()=>{if(this._status!==tf.State.Connecting){this._cleanupEventListeners(),this._mediaHandler.close();return}let e=e=>{let t=this._direction===tf.CallDirection.Incoming?"accepted-by-local":"accepted-by-remote";this._publisher.info("connection",t,null,this);let{codecName:i,codecParams:s}=function(e){let[,t,i]=/a=rtpmap:(\d+) (\S+)/m.exec(e)||[null,"",""],[,s]=RegExp(`a=fmtp:${t} (\\S+)`,"m").exec(e)||[null,""];return{codecName:i,codecParams:s}}(this._mediaHandler.version.getSDP());this._publisher.info("settings","codec",{codec_params:s,selected_codec:i},this),this._monitor.enable(e)},i="function"==typeof this._options.getSinkIds&&this._options.getSinkIds();if(Array.isArray(i)&&this._mediaHandler._setSinkIds(i).catch(()=>{}),this._pstream.addListener("hangup",this._onHangup),this._direction===tf.CallDirection.Incoming)this._isAnswered=!0,this._pstream.on("answer",this._onAnswer),this._mediaHandler.answerIncomingCall(this.parameters.CallSid,this._options.offerSdp,t,e);else{let i=Array.from(this.customParameters.entries()).map(e=>`${encodeURIComponent(e[0])}=${encodeURIComponent(e[1])}`).join("&");this._pstream.on("answer",this._onAnswer),this._mediaHandler.makeOutgoingCall(i,this._signalingReconnectToken,this._options.reconnectCallSid||this.outboundConnectionId,t,e)}};this._options.beforeAccept&&this._options.beforeAccept(this);let o="function"==typeof this._options.getInputStream&&this._options.getInputStream();(o?this._mediaHandler.setInputTracksFromStream(o):this._mediaHandler.openDefaultDeviceWithConstraints(s)).then(()=>{this._publisher.info("get-user-media","succeeded",{data:{audioConstraints:s}},this),n()},e=>{let t;31208===e.code||-1!==["PermissionDeniedError","NotAllowedError"].indexOf(e.name)?(t=new P.PermissionDeniedError,this._publisher.error("get-user-media","denied",{data:{audioConstraints:s,error:e}},this)):(t=new P.AcquisitionFailedError,this._publisher.error("get-user-media","failed",{data:{audioConstraints:s,error:e}},this)),this._disconnect(),this._log.debug("#error",e),this.emit
1("error",t)})}disconnect(){this._log.debug(".disconnect"),this._disconnect()}getLocalStream(){return this._mediaHandler&&this._mediaHandler.stream}getRemoteStream(){return this._mediaHandler&&this._mediaHandler._remoteStream}ignore(){if(this._log.debug(".ignore"),this._status!==tf.State.Pending){this._log.debug(`.ignore noop. status is '${this._status}'`);return}this._status=tf.State.Closed,this._mediaHandler.ignore(this.parameters.CallSid),this._publisher.info("connection","ignored-by-local",null,this),this._onIgnore&&this._onIgnore()}isMuted(){return this._mediaHandler.isMuted}mute(e=!0){this._log.debug(".mute",e);let t=this._mediaHandler.isMuted;this._mediaHandler.mute(e);let i=this._mediaHandler.isMuted;t!==i&&(this._publisher.info("connection",i?"muted":"unmuted",null,this),this._log.debug("#mute",i),this.emit("mute",i,this))}postFeedback(e,t){if(null==e)return this._postFeedbackDeclined();if(!Object.values(tf.FeedbackScore).includes(e))throw new B(`Feedback score must be one of: ${Object.values(tf.FeedbackScore)}`);if(null!=t&&!Object.values(tf.FeedbackIssue).includes(t))throw new B(`Feedback issue must be one of: ${Object.values(tf.FeedbackIssue)}`);return this._publisher.info("feedback","received",{issue_name:t,quality_score:e},this,!0)}reject(){if(this._log.debug(".reject"),this._status!==tf.State.Pending){this._log.debug(`.reject noop. status is '${this._status}'`);return}this._isRejected=!0,this._pstream.reject(this.parameters.CallSid),this._mediaHandler.reject(this.parameters.CallSid),this._publisher.info("connection","rejected-by-local",null,this),this._cleanupEventListeners(),this._mediaHandler.close(),this._status=tf.State.Closed,this._log.debug("#reject"),this.emit("reject")}sendDigits(e){if(this._log.debug(".sendDigits",e),e.match(/[^0-9*#w]/))throw new B("Illegal character passed into sendDigits");let t=this._options.customSounds||{},i=[];e.split("").forEach(e=>{let t="w"!==e?`dtmf${e}`:"";"dtmf*"===t&&(t="dtmfs"),"dtmf#"===t&&(t="dtmfh"),i.push(t)});let s=()=>{let e=i.shift();e&&(this._options.dialtonePlayer&&!t[e]?this._options.dialtonePlayer.play(e):this._soundcache.get(e).play()),i.length&&setTimeout(()=>s(),200)};s();let n=this._mediaHandler.getOrCreateDTMFSender();if(n){if(!("canInsertDTMF"in n)||n.canInsertDTMF){this._log.info("Sending digits using RTCDTMFSender"),function e(t){if(!t.length)return;let i=t.shift();i&&i.length&&n.insertDTMF(i,160,70),setTimeout(e.bind(null,t),500)}(e.split("w"));return}this._log.info("RTCDTMFSender cannot insert DTMF")}if(this._log.info("Sending digits over PStream"),null!==this._pstream&&"disconnected"!==this._pstream.status)this._pstream.dtmf(this.parameters.CallSid,e);else{let e=new k.ConnectionError("Could not send DTMF: Signaling channel is disconnected");this._log.debug("#error",e),this.emit("error",e)}}sendMessage(e){this._log.debug(".sendMessage",JSON.stringify(e));let{content:t,contentType:i,messageType:s}=e;if(null==t)throw new B("`content` is empty");if("string"!=typeof s)throw new B("`messageType` must be a string.");if(0===s.length)throw new B("`messageType` must be a non-empty string.");if(null===this._pstream)throw new q("Could not send CallMessage; Signaling channel is disconnected");let n=this.parameters.CallSid;if(void 0===this.parameters.CallSid)throw new q("Could not send CallMessage; Call has no CallSid");let o=this._voiceEventSidGenerator();return this._messages.set(o,{content:t,contentType:i,messageType:s,voiceEventSid:o}),this._pstream.sendMessage(n,t,i,s,o),o}status(){return this._status}_checkVolume(e,t,i,s){let n=0;return i===e&&(n=t),n>=10?this._emitWarning("audio-level-",`constant-audio-${s}-level`,10,n,!1):t>=10&&this._emitWarning("audio-level-",`constant-audio-${s}-level`,10,n,!0),n}_cleanupEventListeners(){let e=()=>{this._pstream&&(this._pstream.removeListener("ack",this._onAck),this._pstream.removeListener("answer",this._onAnswer),this._pstream.removeListener("cancel",this._onCancel),this._pstream.removeListener("error",this._onSignalingError),this._pstream.removeListener("hangup",this._onHangup),this._pstream.removeListener("ringing",this._onRinging),this._pstream.removeListener("transportClose",this._onTransportClose),this._pstream.removeListener("connected",this._onConnected),this._pstream.removeListener("message",this._onMessageReceived))};e(),setTimeout(e,0)}_createMetricPayload(){let e={call_sid:this.parameters.CallSid,dscp:!!this._options.dscp,sdk_version:K};return this._options.gateway&&(e.gateway=this._options.gateway),e.direction=this._direction,e}_disconnect(e,t){if(e="string"==typeof e?e:null,this._status===tf.State.Open||this._status===tf.State.Connecting||this._status===tf.State.Reconnecting||this._status===tf.State.Ringing){if(this._log.info("Disconnecting..."),null!==this._pstream&&"disconnected"!==this._pstream.status&&this._shouldSe
1ndHangup){let t=this.parameters.CallSid||this.outboundConnectionId;t&&this._pstream.hangup(t,e)}this._cleanupEventListeners(),this._mediaHandler.close(),t||this._publisher.info("connection","disconnected-by-local",null,this)}}_maybeTransitionToOpen(){this._wasConnected,this._isAnswered&&(this._onSignalingReconnected(),this._signalingStatus=tf.State.Open,this._mediaHandler&&"open"===this._mediaHandler.status&&(this._status=tf.State.Open,this._wasConnected||(this._wasConnected=!0,this._log.debug("#accept"),this.emit("accept",this))))}_postFeedbackDeclined(){return this._publisher.info("feedback","received-none",null,this,!0)}_publishMetrics(){0!==this._metricsSamples.length&&this._publisher.postMetrics("quality-metrics-samples","metrics-sample",this._metricsSamples.splice(0),this._createMetricPayload(),this).catch(e=>{this._log.warn("Unable to post metrics to Insights. Received error:",e)})}_setCallSid(e){let t=e.callsid;t&&(this.parameters.CallSid=t,this._mediaHandler.callSid=t)}}tf.toString=()=>"[Twilio.Call class]",(g=(m=tf||(tf={})).State||(m.State={})).Closed="closed",g.Connecting="connecting",g.Open="open",g.Pending="pending",g.Reconnecting="reconnecting",g.Ringing="ringing",(_=m.FeedbackIssue||(m.FeedbackIssue={})).AudioLatency="audio-latency",_.ChoppyAudio="choppy-audio",_.DroppedCall="dropped-call",_.Echo="echo",_.NoisyCall="noisy-call",_.OneWayAudio="one-way-audio",(f=m.FeedbackScore||(m.FeedbackScore={}))[f.One=1]="One",f[f.Two=2]="Two",f[f.Three=3]="Three",f[f.Four=4]="Four",f[f.Five=5]="Five",(v=m.CallDirection||(m.CallDirection={})).Incoming="INCOMING",v.Outgoing="OUTGOING",(y=m.Codec||(m.Codec={})).Opus="opus",y.PCMU="pcmu",(b=m.IceGatheringFailureReason||(m.IceGatheringFailureReason={})).None="none",b.Timeout="timeout",(S=m.MediaFailure||(m.MediaFailure={})).ConnectionDisconnected="ConnectionDisconnected",S.ConnectionFailed="ConnectionFailed",S.IceGatheringFailed="IceGatheringFailed",S.LowBytes="LowBytes"},17187:function(e){"use strict";var t,i="object"==typeof Reflect?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise(function(i,s){var n;function o(i){e.removeListener(t,r),s(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",o),i([].slice.call(arguments))}g(e,t,r,{once:!0}),"error"!==t&&(n={once:!0},"function"==typeof e.on&&g(e,"error",o,n))})},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var r=10;function a(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function l(e,t,i,s){if(a(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),r=o[t]),void 0===r)r=o[t]=i,++e._eventsCount;else if("function"==typeof r?r=o[t]=s?[i,r]:[r,i]:s?r.unshift(i):r.push(i),(n=c(e))>0&&r.length>n&&!r.warned){r.warned=!0;var n,o,r,l=Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=r.length,console&&console.warn&&console.warn(l)}return e}function d(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,i){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=d.bind(s);return n.listener=i,s.wrapFn=n,n}function u(e,t,i){var s=e._events;if(void 0===s)return[];var n=s[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):m(n,n.length)}function p(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function m(e,t){for(var i=Array(t),s=0;s<t;++s)i[s]=e[s];return i}function g(e,t,i,s){if("function"==typeof e.on)s.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function n(o){s.once&&e.removeEventListener(t,n),i(o)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),o.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return c(this)},o.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,o=this._events;if(void 0!==o)n=n&&void 0===o.error;else if(!n)return!1;if(n){if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var r,a=Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else for(var l=c.length,d=m(c,l),i=0;i<l;++i)s(d[i],this,t);return!0},o.prototype.addListener=function(e,t){return l(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return l(this,e,t,!0)},o.prototype.once=function(e,t){return a(t),this.on(e,h(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,h(this,e,t)),this},o.prototype.removeListener=function(e,t){var i,s,n,o,r;if(a(t),void 0===(s=this._events)||void 0===(i=s[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit
1("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,o=i.length-1;o>=0;o--)if(i[o]===t||i[o].listener===t){r=i[o].listener,n=o;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,n),1===i.length&&(s[e]=i[0]),void 0!==s.removeListener&&this.emit("removeListener",e,r||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,i,s;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var n,o=Object.keys(i);for(s=0;s<o.length;++s)"removeListener"!==(n=o[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},o.prototype.listeners=function(e){return u(this,e,!0)},o.prototype.rawListeners=function(e){return u(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},2043:function(e,t,i){var s,n;void 0!==(n="function"==typeof(s=function(){"use strict";var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],n={},o=null;function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),n=0;n<s.length;n++){var o=s[n];this[o]=n<i?e:this.methodFactory(o,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(s,n,o){var c;return"debug"===(c=s)&&(c="log"),typeof console!==t&&("trace"===c&&i?a:void 0!==console[c]?r(console,c):void 0!==console.log?r(console,"log"):e)||l.apply(this,arguments)}function h(e,i){var r,a,l,h=this,u="loglevel";function p(){var e;if(typeof window!==t&&u){try{e=window.localStorage[u]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=encodeURIComponent(u),n=i.indexOf(s+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n+s.length+1))[1])}catch(e){}return void 0===h.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==h.levels[t.toUpperCase()]&&(t=h.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=h.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?u+=":"+e:"symbol"==typeof e&&(u=void 0),h.name=e,h.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},h.methodFactory=i||d,h.getLevel=function(){return null!=l?l:null!=a?a:r},h.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&u){try{window.localStorage[u]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"="+i+";"}catch(e){}}}(l),c.call(h)},h.setDefaultLevel=function(e){a=m(e),p()||h.setLevel(e,!1)},h.resetLevel=function(){l=null,function(){if(typeof window!==t&&u){try{window.localStorage.removeItem(u)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(h)},h.enableAll=function(e){h.setLevel(h.levels.TRACE,e)},h.disableAll=function(e){h.setLevel(h.levels.SILENT,e)},h.rebuild=function(){if(o!==h&&(r=m(o.getLevel())),c.call(h),o===h)for(var e in n)n[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(l=m(g)),c.call(h)}(o=new h).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=n[e];return t||(t=n[e]=new h(e,o.methodFactory)),t};var u=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=u),o},o.getLoggers=function(){return n},o.default=o,o})?s.call(t,i,t,e):s)&&(e.exports=n)}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.