@telnyx/webrtc 2.25.17-beta.2 → 2.25.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/bundle.js +1 -1
- package/lib/bundle.mjs +1 -1
- package/lib/packages/js/src/Modules/Verto/BaseSession.d.ts +7 -2
- package/lib/packages/js/src/Modules/Verto/messages/verto/AnonymousLogin.d.ts +1 -1
- package/lib/packages/js/src/Modules/Verto/messages/verto/Login.d.ts +1 -1
- package/lib/packages/js/src/Modules/Verto/services/Connection.d.ts +0 -1
- package/lib/packages/js/src/Modules/Verto/util/constants/index.d.ts +2 -2
- package/lib/packages/js/src/Modules/Verto/util/interfaces.d.ts +13 -5
- package/lib/packages/js/src/Modules/Verto/webrtc/BaseCall.d.ts +4 -5
- package/lib/packages/js/src/Modules/Verto/webrtc/Peer.d.ts +2 -2
- package/lib/packages/js/src/Modules/Verto/webrtc/VertoHandler.d.ts +0 -2
- package/lib/packages/js/src/Modules/Verto/webrtc/constants.d.ts +3 -0
- package/lib/packages/js/src/Modules/Verto/webrtc/interfaces.d.ts +20 -5
- package/lib/packages/js/src/index.d.ts +2 -1
- package/lib/packages/js/src/utils/interfaces.d.ts +0 -2
- package/package.json +2 -2
- package/lib/packages/js/src/Modules/Verto/util/LogCollector.d.ts +0 -29
- package/lib/packages/js/src/Modules/Verto/webrtc/CallReportCollector.d.ts +0 -91
package/lib/bundle.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function t(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function s(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||function(e,t){var i=t||0,n=o;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(r)}const c="wss://rtc.telnyx.com",d={urls:"stun:stun.l.google.com:19302"},l=[{urls:"stun:stun.telnyx.com:3478"},d,{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],u=[{urls:"stun:stundev.telnyx.com:3478"},d,{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var h;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"}(h||(h={}));var p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function g(e,t){return e(t={exports:{}},t.exports),t.exports}var v=g((function(e){var t,i;t=p,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function s(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 o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,i){for(var s=0;s<n.length;s++){var o=n[s];this[o]=s<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(r.call(this,i,n),this[e].apply(this,arguments))}}function c(n,r,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?s(console,n):void 0!==console.log?s(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,s){var o,a=this;i=null==i?"WARN":i;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(i,s){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==s&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=i),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=i():t.log=i()}));const f={debug:0,info:1,warn:2,error:3};class m{constructor(e={}){var t,i,n;this.buffer=[],this.isCapturing=!1,this.options={enabled:null!==(t=e.enabled)&&void 0!==t&&t,level:null!==(i=e.level)&&void 0!==i?i:"debug",maxEntries:null!==(n=e.maxEntries)&&void 0!==n?n:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,t,i){if(!this.isCapturing||!this.options.enabled)return;if(f[e]<f[this.options.level])return;const n=Object.assign({timestamp:(new Date).toISOString(),level:e,message:t},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(n),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let b=null;function y(){return b}function _(e){b=e}const S=v.getLogger("telnyx"),C={trace:0,debug:1,info:2,warn:3,error:4},w=C.info,I=S.methodFactory;S.methodFactory=(e,t,i)=>{const n=I(e,t,i);return function(...t){if(C[e]>=w){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=y();if(null==i?void 0:i.isActive()){const[n,...s]=t,o="string"==typeof n?n:JSON.stringify(n);let r;s.length>0&&(r=1===s.length&&"object"==typeof s[0]&&null!==s[0]?s[0]:{args:s}),i.addEntry(e,o,r)}}},S.setLevel("debug");const k=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){S.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},E=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},T=e=>e instanceof Function||"function"==typeof e,R=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,x=/^(ws|wss):\/\//,A=(e,t=null)=>{const{result:i={},error:n}=e;if(n)return{error:n};const{result:s=null}=i;if(null===s)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?A(a,r):{result:s}},O=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),L=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),P=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),D=e=>{var t,i,n,s,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(s=null===(n=null==e?void 0:e.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};function M({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?N(n,e):n,i=s})),resolve:t,reject:i}}const N=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},j="telnyx-voice-sdk-id";function $(){return sessionStorage.getItem(j)}var U,F,B;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(j)})),function(e){e.Offer="offer",e.Answer="answer"}(U||(U={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(F||(F={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.Candidate="telnyx_rtc.candidate",e.EndOfCandidates="telnyx_rtc.endOfCandidates",e.Display="telnyx_rtc.display",e.Media="telnyx_rtc.media",e.Event="telnyx_rtc.event",e.Bye="telnyx_rtc.bye",e.Punt="telnyx_rtc.punt",e.Broadcast="telnyx_rtc.broadcast",e.Subscribe="telnyx_rtc.subscribe",e.Unsubscribe="telnyx_rtc.unsubscribe",e.ClientReady="telnyx_rtc.clientReady",e.Modify="telnyx_rtc.modify",e.Ringing="telnyx_rtc.ringing",e.GatewayState="telnyx_rtc.gatewayState",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(B||(B={}));const V={generic:"event",[B.Display]:"participantData",[B.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},G={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1};var H,q,W,J,K;!function(e){e[e.New=0]="New",e[e.Requesting=1]="Requesting",e[e.Trying=2]="Trying",e[e.Recovering=3]="Recovering",e[e.Ringing=4]="Ringing",e[e.Answering=5]="Answering",e[e.Early=6]="Early",e[e.Active=7]="Active",e[e.Held=8]="Held",e[e.Hangup=9]="Hangup",e[e.Destroy=10]="Destroy",e[e.Purge=11]="Purge"}(H||(H={})),function(e){e.Participant="participant",e.Moderator="moderator"}(q||(q={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(W||(W={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(J||(J={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(K||(K={}));const z="GLOBAL",Q={},Y=(e,t)=>`${e}|${t}`,X=(e,t=z)=>Y(e,t)in Q,Z=(e,t,i=z)=>{const n=Y(e,i);n in Q||(Q[n]=[]),Q[n].push(t)},ee=(e,t,i=z)=>{const n=function(s){te(e,n,i),t(s)};return n.prototype.targetRef=t,Z(e,n,i)},te=(e,t,i=z)=>{if(!X(e,i))return!1;const n=Y(e,i);if(T(t)){for(let e=Q[n].length-1;e>=0;e--){const i=Q[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&Q[n].splice(e,1)}}else Q[n]=[];return 0===Q[n].length&&delete Q[n],!0},ie=(e,t,i=z,n=!0)=>{const s=n&&i!==z;if(!X(e,i))return s&&ie(e,t),!1;const o=Y(e,i),r=Q[o].length;if(!r)return s&&ie(e,t),!1;for(let e=r-1;e>=0;e--)Q[o][e](t);return s&&ie(e,t),!0},ne=e=>{const t=Y(e,"");Object.keys(Q).filter((e=>0===e.indexOf(t))).forEach((e=>delete Q[e]))};let se="undefined"!=typeof WebSocket?WebSocket:null;const oe=0,re=1,ae=2,ce=3;class de{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=c,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this.upDur=null,this.downDur=null;const{host:t,env:i,region:n,trickleIce:s,useCanaryRtcServer:o}=e.options;i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":c),t&&(this._host=(e=>`${x.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host=this._host.replace(/rtc(dev)?/,`${n}.rtc$1`)),(s||o)&&(this._useCanaryRtcServer=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===re}get connecting(){return this._wsClient&&this._wsClient.readyState===oe}get closing(){return this._wsClient&&this._wsClient.readyState===ae}get closed(){return this._wsClient&&this._wsClient.readyState===ce}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let t=$();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),S.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this._wsClient=new se(e.toString()),this._wsClient.onopen=e=>ie(h.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>ie(h.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>ie(h.SocketError,{error:e,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const n=E(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(s=n.voice_sdk_id,sessionStorage.setItem(j,s)),this._unsetTimer(n.id),S.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),K[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!ie(n.id,n)){const e=D(n);ie(h.SocketMessage,n,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(n)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,i=new Promise(((e,i)=>{if(t.hasOwnProperty("result"))return e();ee(t.id,(t=>{const{result:n,error:s}=A(t);return s?i(s):e(n)}))}));return S.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}close(){this._wsClient&&(T(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),ie(h.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else S.warn("Unknown message from socket",e)}}class le{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const ue={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class he extends le{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in ue)e&&i.hasOwnProperty(e)&&(i[ue[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class pe extends he{constructor(e){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class ge{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(D(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new pe($());this.pendingRequestId=e.request.id,this.gatewayStateTask=M({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[K.REGISTER,K.REGED].includes(t)})),this.session=e,this.gatewayStateTask=M({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ve extends he{constructor(e){super(),this.method=B.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class fe{constructor(e){if(this.options=e,this.uuid=a(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");S.setLevel(e.debug?"debug":"info"),this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new de(this),this.registerAgent=new ge(this)}get __logger(){return S}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*O(2,6)}execute(e){return this._idle?new Promise((t=>this._executeQueue.push({resolve:t,msg:e}))):this.connected?this.connection.send(e):new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return L(this.options)||P(this.options)}broadcast(e){}disconnect(){return t(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),S.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return Z(e,t,this.uuid),this}off(e,t){return te(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new de(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||this.connection.connect(),S.debug("Session connected. Connection initiated if not already alive. Auto-reconnect enabled.")}))}_handleLoginError(e){ie(h.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&ne(this.relayProtocol);for(const e in this.subscriptions)ne(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>this.connect()),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],te(e,null,t)):(delete this.subscriptions[e],ne(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},T(t)&&Z(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(h.SocketOpen,this._onSocketOpen),this.on(h.SocketClose,this.onNetworkClose),this.on(h.SocketError,this.onNetworkClose),this.on(h.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(h.SocketOpen,this._onSocketOpen),this.off(h.SocketClose,this.onNetworkClose),this.off(h.SocketError,this.onNetworkClose),this.off(h.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(S.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new ve($()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){S.debug("Ping received"),this._pong=!0}static on(e,t){Z(e,t)}static off(e){te(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const me=e=>navigator.mediaDevices.getUserMedia(e),be=e=>e&&e instanceof MediaStream,ye=(e,t)=>{const i=R(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},_e=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=R(e);if(null===t)return S.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return S.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),Se=e=>{e&&"live"===e.readyState&&e.stop()},Ce=e=>{be(e)&&e.getTracks().forEach(Se),e=null},we=i=>t(void 0,void 0,void 0,(function*(){S.info("RTCService.getUserMedia",i);const{audio:t,video:n}=i;if(!t&&!n)return null;try{return yield me(i)}catch(t){if(S.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const n=(t=>{const{audio:i,video:n}=t;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(i);if(n){S.warn("Device not found or not readable, falling back to default device");try{return yield me(n)}catch(e){throw S.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),Ie=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===J.AudioIn||e===J.AudioOut,video:!e||e===J.Video}))(e)).catch((e=>(S.error(e),null)));if(n){if(Ce(n),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),ke=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Ee=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield Ie(n,!0);for(let n=0;n<t.length;n++){const{deviceId:s,label:o}=t[n];if(e===s||i===o)return s}return null})),Te=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},Re=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=xe(e);return i.includes(t)||n.includes(t)},xe=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Ae=(e,t=null,i=null)=>{if(!be(e))return null;let n=[];switch(t){case"audio":n=e.getAudioTracks();break;case"video":n=e.getVideoTracks();break;default:n=e.getTracks()}n.forEach((e=>{switch(i){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Oe=e=>{Ae(e,"audio",!0)},Le=e=>{Ae(e,"audio",!1)},Pe=e=>{Ae(e,"audio",null)},De=e=>((e,t=null)=>{if(!be(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some((e=>e.enabled))})(e,"audio");function Me(){try{const{browserInfo:e,name:t,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),i=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:i,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!we}}catch(e){return e.message}}var Ne;function je(e,t){const i=document.getElementById(t);if(i)return i;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function $e(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{S.error("playAudio",t),e._playFulfilled=!0})))}function Ue(e){e&&(e._playFulfilled?(e.pause(),e.currentTime=0):e._promise&&e._promise.then?e._promise.then((()=>{e.pause(),e.currentTime=0})):setTimeout((()=>{e.pause(),e.currentTime=0}),1e3))}!function(e){e.not_supported="not supported",e.full="full",e.partial="partial"}(Ne||(Ne={}));var Fe="2.25.17-beta.2",Be=Fe;class Ve extends he{constructor(e,t,i,n,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:i,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:Be,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class Ge extends he{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class He extends he{toString(){return B.Invite}}class qe extends he{toString(){return B.Answer}}class We extends he{toString(){return B.Attach}}class Je extends he{toString(){return B.Bye}}class Ke extends he{toString(){return B.Candidate}}class ze extends he{toString(){return B.EndOfCandidates}}class Qe extends he{toString(){return B.Modify}}class Ye extends he{toString(){return B.Info}}class Xe extends he{toString(){return B.Broadcast}}class Ze extends he{toString(){return B.Subscribe}}class et extends he{toString(){return B.Unsubscribe}}class tt extends le{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}class it{constructor(e,t){this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.MAX_BUFFER_SIZE=360,this.options=e,this.logCollectorOptions=t||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(e){return new m(e)}(this.logCollectorOptions),this.logCollector.start(),_(this.logCollector))}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,S.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.isActive())&&void 0!==i&&i}),this.intervalId=setInterval((()=>{this._collectStats()}),this.options.interval))}stop(){var e,t;this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&this._collectStats();const i=null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==t?t:0;this.logCollector&&this.logCollector.stop(),S.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}postReport(e,i,n,s){var o,r,a;return t(this,void 0,void 0,(function*(){if(!this.options.enabled||0===this.statsBuffer.length)return;const t=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),c=Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:null===(r=this.callEndTime)||void 0===r?void 0:r.toISOString()}),stats:this.statsBuffer},t&&t.length>0?{logs:t}:{});try{const o=new URL(n),r=`${o.protocol.replace(/^ws/,"http")}//${o.host}/call_report`;S.info("CallReportCollector: Posting report",{endpoint:r,intervals:this.statsBuffer.length,logEntries:null!==(a=null==t?void 0:t.length)&&void 0!==a?a:0,callId:e.callId});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.callId};s&&(d["x-voice-sdk-id"]=s);const l=yield fetch(r,{method:"POST",headers:d,body:JSON.stringify(c)});if(l.ok)S.info("CallReportCollector: Successfully posted report");else{const e=yield l.text();S.error("CallReportCollector: Failed to post report",{status:l.status,error:e})}}catch(e){S.error("CallReportCollector: Error posting report",{error:e})}}))}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,t;return null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogs())&&void 0!==t?t:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),y()===this.logCollector&&_(null),this.logCollector=null)}_collectStats(){return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const e=yield this.peerConnection.getStats(),t=new Date;let i=null,n=null,s=null;if(e.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(i=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(n=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(s=e)}})),i){const n=this._getTrackAudioLevel(e,i.trackId);if(null!==n&&this.intervalAudioLevels.outbound.push(n),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(i.bytesSent||0)-this.previousStats.outboundBytes,n=(i.timestamp||t.getTime())-this.previousStats.timestamp;if(n>0){const t=8*e*1e3/n;this.intervalBitrates.outbound.push(t)}}this.previousStats.outboundBytes=i.bytesSent}if(n){const i=this._getTrackAudioLevel(e,n.trackId);if(null!==i&&this.intervalAudioLevels.inbound.push(i),void 0!==n.jitter&&this.intervalJitters.push(1e3*n.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(n.bytesReceived||0)-this.previousStats.inboundBytes,i=(n.timestamp||t.getTime())-this.previousStats.timestamp;if(i>0){const t=8*e*1e3/i;this.intervalBitrates.inbound.push(t)}}this.previousStats.inboundBytes=n.bytesReceived}s&&void 0!==s.currentRoundTripTime&&this.intervalRTTs.push(s.currentRoundTripTime),this.previousStats.timestamp=t.getTime();if(t.getTime()-this.intervalStartTime.getTime()>=this.options.interval){const e=this._createStatsEntry(this.intervalStartTime,t,i,n,s);this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),S.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.intervalStartTime=t,this._resetIntervalAccumulators()}}catch(e){S.error("CallReportCollector: Error collecting stats",{error:e})}}))}_createStatsEntry(e,t,i,n,s){const o={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(o.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),n&&(o.audio.inbound={packetsReceived:n.packetsReceived,bytesReceived:n.bytesReceived,packetsLost:n.packetsLost,packetsDiscarded:n.packetsDiscarded,jitterBufferDelay:n.jitterBufferDelay,jitterBufferEmittedCount:n.jitterBufferEmittedCount,totalSamplesReceived:n.totalSamplesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),s&&(o.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived}),o}_getTrackAudioLevel(e,t){if(!t)return null;const i=e.get(t);return i&&i.audioLevel||null}_average(e){if(0===e.length)return;const t=e.reduce(((e,t)=>e+t),0);return parseFloat((t/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}var nt,st=g((function(e,t){var i;function n(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,i,s){var r,a,c;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]):(a=e._events=new n,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[i,c]:[c,i]:s?c.unshift(i):c.push(i),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(d)}}else c=a[t]=i,++e._eventsCount;return e}function a(e,t,i){function n(){e.removeListener(t,n),s||(s=!0,i.apply(e,arguments))}var s=!1;return n.listener=i,n}function c(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function d(e,t){for(var i=Array(t);t--;)i[t]=e[t];return i}Object.defineProperty(t,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,i,n,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(i=r[e]))return!1;var u="function"==typeof i;switch(n=arguments.length){case 1:!function(e,t,i){if(t)e.call(i);else for(var n=e.length,s=d(e,n),o=0;o<n;++o)s[o].call(i)}(i,u,this);break;case 2:!function(e,t,i,n){if(t)e.call(i,n);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(i,n)}(i,u,this,arguments[1]);break;case 3:!function(e,t,i,n,s){if(t)e.call(i,n,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(i,n,s)}(i,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,i,n,s,o){if(t)e.call(i,n,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(i,n,s,o)}(i,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(n-1),o=1;o<n;o++)s[o-1]=arguments[o];!function(e,t,i,n){if(t)e.apply(i,n);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(i,n)}(i,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(i=s[e]))return this;if(i===t||i.listener&&i.listener===t)0==--this._eventsCount?this._events=new n:(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(o=-1,r=i.length;0<r--;)if(i[r]===t||i[r].listener&&i[r].listener===t){a=i[r].listener,o=r;break}if(0>o)return this;if(1===i.length){if(i[0]=void 0,0==--this._eventsCount)return this._events=new n,this;delete s[e]}else!function(e,t){for(var i=t,n=i+1,s=e.length;n<s;i+=1,n+=1)e[i]=e[n];e.pop()}(i,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,i;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=new n,this._eventsCount=0):i[e]&&(0==--this._eventsCount?this._events=new n:delete i[e]),this;if(0===arguments.length){for(var s,o=Object.keys(i),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,i,n=this._events;return n?i=(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(t):[]:i=[],i},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var l,u=new Uint8Array(16);function h(){if(!l&&!(l="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],v=0;256>v;++v)g.push((v+256).toString(16).substr(1));function f(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,i=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(i))throw TypeError("Stringified UUID is invalid");return i}function m(e,t,i){var n=(e=e||{}).random||(e.rng||h)();if(n[6]=64|15&n[6],n[8]=128|63&n[8],t){i=i||0;for(var s=0;16>s;++s)t[i+s]=n[s];return t}return f(n)}function b(e,t){if(!e||!t)return{};const i={...e};if(i.localCandidateId){const e=t.get(i.localCandidateId);i.local={...e}}if(i.remoteCandidateId){const e=t.get(i.remoteCandidateId);i.remote={...e}}return i}function y(e,t,i){return 8*function(e,t,i){const n=e[i],s=t?t[i]:null;return null===n||null===s?null:(n-s)/(e.timestamp-t.timestamp)*1e3}(e,t,i)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,i){t[i]=e})),t}function S(e,t,i={}){if(!e)return null;let n={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};i.remote&&(n.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const i=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(i))continue;if(t.codecId){const i=e.get(t.codecId);i&&(s.clockRate=i.clockRate,s.mimeType=i.mimeType,s.payloadType=i.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let i=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(i))if(t.id.includes("Video"))i="video";else{if(!t.id.includes("Audio"))continue;i="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":n.connection.dataChannelsClosed=t.dataChannelsClosed,n.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!i.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=b(t,e)}}n.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!i.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}n.remote[s].outbound.push({...t,...o});break}}if(!n.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(n.connection=b(t,e));return n=function(e,t){return t?(e.audio.inbound.map((e=>{let i=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e):e}(n,t),n}let C,w={},I=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:i}=e;let{connectionId:n,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!i)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[i]){if(n&&n in this.peersToMonitor[i])throw new Error(`We are already monitoring connection with id ${n}.`);for(let e in this.peersToMonitor[i]){const n=this.peersToMonitor[i][e];if(n.pc===t)throw new Error(`We are already monitoring peer with id ${i}.`);"closed"===n.pc.connectionState&&this.removeConnection({pc:n.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),n||(n=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:i,connectionId:n,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:i,connectionId:n,pc:t,remote:s}),{connectionId:n}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:i,pc:n}=e;if(!n&&!i)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(i){if("string"!=typeof i)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)i in this.peersToMonitor[e]&&(n=this.peersToMonitor[e][i].pc,t=e)}else if(n){if(!(n instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===n&&(i=s,t=e)}if(!n||!i)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(i,n),delete this.peersToMonitor[t][i],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:i}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let i=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,i)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),I.forEach((e=>{this.removeTrackEventListeners(e)})),I=[],this.shouldWrapGetUserMedia&&C&&(navigator.mediaDevices.getUserMedia=C)}monitorPeer(e){let{peerId:t,connectionId:i,pc:n,remote:s}=e;if(!n)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:n,connectionId:i,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(i in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${i}`);this.peersToMonitor[t][i]=o}else this.peersToMonitor[t]={[i]:o};this.addPeerConnectionEventListeners(t,i,n),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let i=[];for(const e in t)for(const n in t[e]){const s=t[e][n],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,n,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=_(o),d={remote:s.options.remote},l=S(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:n,timeTaken:a-t,data:l};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),i.push(u),s.stats.parsed=l}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return i}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const i=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,i)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,i){const n=this.isConnectionClosed(i);if(n){this.removeConnection({pc:i});let n="closed"===i.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:n,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return n}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),C=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),C.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var i=t[e];this.statsToMonitor.includes(i.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,i,n)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",n),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:n.candidate})},track:(e,t,i,n)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,n);const s=n.track,o=n.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:n.track.kind+":"+n.track.id+" "+n.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:i.signalingState,localDescription:i.localDescription,remoteDescription:i.remoteDescription}})},iceconnectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceConnectionState})},icegatheringstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceGatheringState})},icecandidateerror:(e,t,i,n)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:n.errorCode}})},connectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.connectionState})},negotiationneeded:(e,t,i)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,i,n)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,n),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:n.channel})}}}addPeerConnectionEventListeners(e,t,i){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),w[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{w[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,w[t][n],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),I.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){w[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{w[e.id][t]=i[t].bind(this),e.addEventListener(t,w[e.id][t])})),w[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in w){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,w[e.id][t])})),clearInterval(w[e.id].readyState),delete w[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in w&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,w[e][i],!1)})),delete w[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),i=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=i.bind(navigator.mediaDevices)}}}}));(nt=st)&&nt.__esModule&&Object.prototype.hasOwnProperty.call(nt,"default")&&nt.default;var ot=st.WebRTCStats;function rt(e){const{packetsLost:t,packetsReceived:i,jitter:n,rtt:s}=e,o=function(e){const{jitter:t,rtt:i}=e,n=t+i/2;return.024*n+.11*(n-177.3)*(n>177.3?1:0)}({rtt:s,jitter:n}),r=function(e){const{packetsLost:t,packetsReceived:i}=e,n=t/(i+t)*100;return 20*Math.log(1+n)}({packetsLost:t,packetsReceived:i}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function at(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class ct extends le{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class dt extends le{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class lt extends le{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function ut(e,t){var i,n;return{errorCode:e.errorCode,errorText:e.errorText,url:e.url,address:e.address,port:e.port,connectionState:t.connectionState,iceConnectionState:t.iceConnectionState,iceGatheringState:t.iceGatheringState,signalingState:t.signalingState,localDescriptionType:null===(i=t.localDescription)||void 0===i?void 0:i.type,remoteDescriptionType:null===(n=t.remoteDescription)||void 0===n?void 0:n.type}}function ht(e,i){const n=a();let s=!1;const o=new ot({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=i=>t(this,void 0,void 0,(function*(){"stats"===i.event&&ie(h.StatsFrame,function({data:e}){var t,i,n,s,o,r,a,c;const{audio:d,remote:l}=e,{audio:u}=l,h=null!==(i=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==i?i:1/0,p=null!==(s=null===(n=u.inbound[0])||void 0===n?void 0:n.roundTripTime)&&void 0!==s?s:1/0,g=null!==(r=null===(o=d.inbound[0])||void 0===o?void 0:o.packetsReceived)&&void 0!==r?r:-1,v=null!==(c=null===(a=d.inbound[0])||void 0===a?void 0:a.packetsLost)&&void 0!==c?c:-1,f=rt({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:at(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(i),e.uuid),yield e.execute(new lt(n,i))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){s?S.debug(`[${i}] Stats reporter already running, skipping start`):(yield e.execute(new ct(n,i)),o.on("timeline",r),yield new Promise((e=>setTimeout(e,500))),o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0)})),stop:r=>t(this,void 0,void 0,(function*(){if(!s)return void S.debug(`[${i}] Stats reporter already stopped, skipping stop`);const t=o.getTimeline();if(ie(h.StatsReport,t,e.uuid),"file"===r){!function(e,t){const i=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(n)}(t,`webrtc-stats-${n}-${Date.now()}`)}yield e.execute(new dt(n,i)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const pt=(e,t)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==n&&delete o.memberID;const a={type:V.conferenceUpdate,call:e.calls[s],canvasInfo:gt(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:W.LayerInfo},a);ie(h.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:W.LayoutInfo},a);ie(h.Notification,t,e.uuid);break}}},gt=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return E(t)};class vt{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=e=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(S.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){const i=()=>t(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,i){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:i,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,i=null==e?void 0:e.transport;i&&(t.dtlsState=i.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const i=yield e.getStats();i.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,i.forEach((i=>{"local-candidate"===i.type&&i.id===e.localCandidateId&&(t.localCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType}),"remote-candidate"===i.type&&i.id===e.remoteCandidateId&&(t.remoteCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){S.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}!this._restartedIceOnConnectionStateFailed&&"failed"===e&&this._session.hasAutoReconnect()&&(yield this.instance.restartIce(),this._restartedIceOnConnectionStateFailed=!0,S.debug("Peer connection state failed. ICE restarted.")),window.removeEventListener("online",i)}));navigator.onLine?i():window.addEventListener("online",i)}"failed"===e&&ie(h.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=e,this._isTrickleIce()&&("connecting"===e&&performance.mark("peer-connection-connecting"),"connected"===e&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))})),this._handleIceConnectionStateChange=e=>{S.debug(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=e=>{S.debug(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},S.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===U.Offer}get isAnswer(){return this.type===U.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get keepConnectionAliveOnSocketClose(){return this.options.keepConnectionAliveOnSocketClose||this._session.options.keepConnectionAliveOnSocketClose}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return t(this,void 0,void 0,(function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))}))}_logTransceivers(){S.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{S.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),S.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),t=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),n=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("invite-send","new-call-start","sdp-send-start"),o=performance.measure("total-duration","peer-creation-start","sdp-send-end"),r=e=>`${e.toFixed(2)}ms`;return{"New Call":{duration:r(e.duration)},"Peer Creation":{duration:r(t.duration)},"ICE Gathering":{duration:r(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:r(s.duration)},"SDP Send":{duration:r(n.duration)},"Total Duration":{duration:r(o.duration)}}}handleSignalingStateChangeEvent(e){switch(S.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":ie(h.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(S.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){S.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?S.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:n}=this.options;this.options.remoteStream=t,!1===n&&ye(i,this.options.remoteStream)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:U.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>(ie(h.MediaError,e,this.options.id),null))),this.options.mutedMicOnStart&&be(this.options.localStream)&&(S.info("Muting local audio tracks on start"),Le(this.options.localStream)),performance.mark("peer-creation-end")}))}init(){var e;return t(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=ht(this._session,this.options.id),yield null===(e=this.statsReporter)||void 0===e?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:t,localStream:i=null,screenShare:n=!1}=this.options;if(be(i)){const e=i.getAudioTracks();let s=[...e];if(S.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{S.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],S.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{S.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=(e=>{const t=[],i=[];return e&&0!==e.length?(e.forEach((e=>{const n=e.mimeType.toLocaleLowerCase();n.startsWith("audio/")?t.push(e):n.startsWith("video/")&&i.push(e)})),{audioCodecs:t,videoCodecs:i}):{audioCodecs:t,videoCodecs:i}})(this.options.preferred_codecs);if(this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[i]};s.forEach((t=>{"audio"===t.kind&&(this.options.userVariables.microphoneLabel=t.label),"video"===t.kind&&(this.options.userVariables.cameraLabel=t.label);const i=this.instance.addTransceiver(t,e);"audio"===t.kind&&o.length>0&&this._setCodecs(i,o),"video"===t.kind&&r.length>0&&this._setCodecs(i,r)}))}else"function"==typeof this.instance.addTrack?(s.forEach((e=>{"audio"===e.kind&&(this.options.userVariables.microphoneLabel=e.label),"video"===e.kind&&(this.options.userVariables.cameraLabel=e.label),this.instance.addTrack(e,i)})),this.instance.getTransceivers().forEach((e=>{"audio"===e.receiver.track.kind&&o.length>0&&this._setCodecs(e,o),"video"===e.receiver.track.kind&&r.length>0&&this._setCodecs(e,r)}))):this.instance.addStream(i);!1===n&&ye(t,i)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()}))}_getSenderByKind(e){return this.instance.getSenders().find((({track:t})=>t&&t.kind===e))}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);S.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio,this._constraints.offerToReceiveVideo=Boolean(this.options.video),S.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){S.error("Peer _createOffer error:",e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){S.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return S.debug("Skipping negotiation, state:",this.instance.signalingState),S.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:U.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){S.error("Peer _createAnswer error:",e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){yield this.instance.setLocalDescription(e)}))}_sdpReady(){T(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(be(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:n=!1,camId:s}=i;const{micLabel:o="",camLabel:r=""}=i;return t&&(t=yield Ee(t,o,J.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield Ee(s,r,J.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return we(e)}))}_isOffer(){return this.type===U.Offer}_isAnswer(){return this.type===U.Answer}_isTrickleIce(){return!0===this.options.trickleIce}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:t,iceServers:i}=this.options,n={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:t?"relay":"all"};return S.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?S.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(S.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):S.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){null!==this._sleepWakeupIntervalId&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)}))}}const ft=Be;class mt{constructor(e,t){this.session=e,this._callReportCollector=null,this.id="",this.state=H[H.New],this.prevState="",this.channels=[],this.role=q.Participant,this.extension=null,this._state=H.New,this._prevState=H.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=e=>{const t=e<0||!this._lastSerno||this._lastSerno&&e===this._lastSerno+1;return t&&e>=0&&(this._lastSerno=e),t},this._doStats=()=>{this.peer&&this.peer.instance&&0!==this._statsBindings.length&&this.peer.instance.getStats().then((e=>{e.forEach((e=>{this._statsBindings.forEach((t=>{if(t.callback){if(t.constraints)for(var i in t.constraints)if(t.constraints.hasOwnProperty(i)&&t.constraints[i]!==e[i])return;t.callback(e)}}))}))}))};const{iceServers:i,speaker:n,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,options:l,mediaConstraints:{audio:u,video:h},ringtoneFile:p,ringbackFile:g}=e;this.options=Object.assign({},G,{audio:u,video:h,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:i,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:n,ringtoneFile:p,ringbackFile:g,debug:l.debug,debugOutput:l.debugOutput,trickleIce:l.trickleIce,prefetchIceCandidates:l.prefetchIceCandidates,forceRelayCandidate:l.forceRelayCandidate,keepConnectionAliveOnSocketClose:l.keepConnectionAliveOnSocketClose,mutedMicOnStart:l.mutedMicOnStart},t),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=je(this.options.ringtoneFile,"_ringtone"),this._ringback=je(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),t=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),n=performance.measure("total-duration","peer-creation-start","sdp-send-end"),s=e=>`${e.toFixed(2)}ms`;return{"Peer Creation":{duration:s(e.duration)},"ICE Gathering":{duration:s(t.duration)},"SDP Send":{duration:s(i.duration)},"Total Duration":{duration:s(n.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return!De(this.options.localStream)}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=F.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new vt(U.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1}))}answer(e={}){var i;return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=F.Inbound,(null===(i=null==e?void 0:e.customHeaders)||void 0===i?void 0:i.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new vt(U.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1}))}playRingtone(){$e(this._ringtone)}stopRingtone(){Ue(this._ringtone)}playRingback(){$e(this._ringback)}stopRingback(){Ue(this._ringback)}hangup(e,t){var i,n,s;let o=e||{},r=!1!==t;this.cause=o.cause||"NORMAL_CLEARING",this.causeCode=o.causeCode||16,this.sipCode=o.sipCode||null,this.sipReason=o.sipReason||null,this.sipCallId=o.sip_call_id||null,this.options.customHeaders=[...null!==(i=this.options.customHeaders)&&void 0!==i?i:[],...null!==(s=null===(n=null==o?void 0:o.dialogParams)||void 0===n?void 0:n.customHeaders)&&void 0!==s?s:[]],this.setState(H.Hangup);const a=()=>{var e;return S.debug(`[${this.id}] Closing peer from hangup`),null===(e=this.peer)||void 0===e||e.close(),this.setState(H.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new Je({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{S.error("telnyx_rtc.bye failed!",e),ie(h.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new Qe({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Qe({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Qe({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Ye({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const i={from:this.session.options.login,to:e,body:t},n=new Ye({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Le(this.options.localStream)}unmuteAudio(){Oe(this.options.localStream)}toggleAudioMute(){Pe(this.options.localStream)}setAudioInDevice(e,i=this.options.mutedMicOnStart){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const t=yield me({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];s.enabled=!i,n.replaceTrack(s),this.options.micId=e;const{localStream:o}=this.options;o.getAudioTracks().forEach((e=>e.stop())),o.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Ae(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ae(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ae(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(i){const t=yield me({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;ye(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Le(this.options.remoteStream)}undeaf(){Oe(this.options.remoteStream)}toggleDeaf(){Pe(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void S.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:t}=this.peer,n=t.getSenders();if(!n)return void S.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const s=n.find((({track:{kind:e}})=>e===i));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),S.info("Parameters: ",t),S.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{S.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>S.error(e)))}else S.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const i={callback:e,constraints:t};if(this._statsBindings.push(i),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){var t;switch(this._prevState=this._state,this._state=e,this.state=H[this._state].toLowerCase(),this.prevState=H[this._prevState].toLowerCase(),S.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:V.callUpdate,call:this}),e){case H.Purge:S.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case H.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&_e(e,t)}),0),this._callReportCollector&&(null===(t=this.peer)||void 0===t?void 0:t.instance)&&this._callReportCollector.start(this.peer.instance);break;case H.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case B.Answer:if(this.gotAnswer=!0,this._state>=H.Active)return;this._state>=H.Early&&this.setState(H.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case B.Media:if(this._state>=H.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case B.Display:case B.Attach:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===F.Inbound?F.Outbound:F.Inbound,r={type:V[t],call:this,displayName:e,displayNumber:n,displayDirection:o};ie(h.Notification,r,this.id)||ie(h.Notification,r,this.session.uuid);break}case B.Candidate:this._addIceCandidate(i);break;case B.Info:case B.Event:{const e=Object.assign(Object.assign({},i),{type:V.generic,call:this});ie(h.Notification,e,this.id)||ie(h.Notification,e,this.session.uuid);break}case B.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case B.Bye:const e=i.client_state||i.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,i){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return S.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:W.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},k(n[e][1])));this._dispatchConferenceUpdate({action:W.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:W.Add,callId:s,index:o},k(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:W.Modify,callId:s,index:o},k(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:W.Delete,callId:s,index:o},k(n)));break;case"clear":this._dispatchConferenceUpdate({action:W.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:n,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:n,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:W.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{S.error("ConfChat subscription error:",e)}));Re(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,pt(this.session,t);else S.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{S.error("ConfInfo subscription error:",e)}));Re(i,e)&&this._addChannel(e)}))}_confControl(e,t={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(H.Active):this.setState(H.Held),!0}_handleChangeHoldStateError(e){return S.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const t=new RTCSessionDescription({sdp:e,type:U.Answer});yield this.peer.instance.setRemoteDescription(t).then((()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(H.Early),this.gotAnswer&&this.setState(H.Active)})).catch((e=>{S.error("Call setRemoteDescription Error: ",e),this.hangup()}))}))}_requestAnotherLocalDescription(){T(this.peer.onSdpReadyTwice)?ie(h.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:n,type:s}=e;if(-1===n.indexOf("candidate"))return S.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(i=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===i||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,"User-Agent":`Web-${ft}`};switch(s){case U.Offer:this.setState(H.Requesting),o=new He(r);break;case U.Answer:this.setState(H.Answering),o=!0===this.options.attach?new We(r):new qe(r);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===U.Offer?this.setState(H.Trying):this.setState(H.Active)})).catch((e=>{S.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})).finally((()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()}))}_onTrickleIceSdp(e){if(!e)return S.error("No SDP data provided"),this.hangup({},!1);const{sdp:t,type:i}=e;let n=null;const s={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ft}`};switch(i){case U.Offer:this.setState(H.Requesting),n=new He(s);break;case U.Answer:this.setState(H.Answering),n=!0===this.options.attach?new We(s):new qe(s);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(n).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===U.Offer?this.setState(H.Trying):this.setState(H.Active)})).catch((e=>{S.error(`${this.id} - Sending ${i} error:`,e),this.hangup()})).finally((()=>{performance.mark("sdp-send-end")}))}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?S.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(S.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Ke({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(t)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return S.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const t=this.peer.instance.addIceCandidate(e);Promise.resolve(t).then((()=>{S.debug("Successfully added ICE candidate:",e)})).catch((t=>{S.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new ze({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.onicecandidateerror=t=>{var i;if(S.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=ut(t,e);this.peer.statsReporter.reportIceCandidateError(i)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:i,screenShare:n}=this.options;!1===n&&ye(t,i)}))}_registerTrickleIcePeerEvents(e){e.onicecandidate=e=>{this._onTrickleIce(e)},e.onicegatheringstatechange=t=>{S.debug("ICE gathering state changed:",e.iceGatheringState),"complete"===e.iceGatheringState&&S.debug("Finished gathering candidates")},e.onicecandidateerror=t=>{var i;if(S.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=ut(t,e);this.peer.statsReporter.reportIceCandidateError(i)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:i,screenShare:n}=this.options;!1===n&&ye(t,i)}))}_onMediaError(e){this._dispatchNotification({type:V.userMediaError,error:e}),S.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:V.peerConnectionFailureError,error:e}),S.error("Peer connection failure error, call is not recoverable. Handling reconnection according to keepConnectionAliveOnSocketClose option")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:V.signalingStateClosed},e)),S.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:V.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(ie(h.Notification,e,this.id,!1)||ie(h.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:i,onNotification:n}=this.options;var s;this.options.id=e?e.toString():a(),this.id=this.options.id,t&&(s=t,0!==Object.keys(s).length)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Z(h.MediaError,this._onMediaError,this.id),Z(h.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Z(h.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),T(n)&&Z(h.Notification,n.bind(this),this.id);const o=!1!==this.session.options.enableCallReports,r=this.session.options.callReportInterval||5e3,c=this.session.options.debugLogLevel||"debug",d=this.session.options.debugLogMaxEntries||1e3;o&&(this._callReportCollector=new it({enabled:!0,interval:r},{enabled:!0,level:c,maxEntries:d})),this.setState(H.New),S.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),S.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:i}=this.options;Ce(t),Ce(i),te(h.MediaError,null,this.id),te(h.PeerConnectionFailureError,null,this.id),te(h.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport()}_postCallReport(){var e;if(!this._callReportCollector)return void S.warn("Call report collector not initialized");this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return void S.debug("Cannot post call report: call_report_id not available");const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===F.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ft},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void S.error("Cannot post call report: connection host not available");const s=$()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{S.error("Failed to post call report",{error:e})})).finally((()=>{var e;null===(e=this._callReportCollector)||void 0===e||e.cleanup()}))}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),S.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),S.debug("Stats stopped")}}mt.setStateTelnyx=e=>{if(e){switch(e._state){case H.Requesting:case H.Recovering:case H.Trying:case H.Early:e.state="connecting";break;case H.Active:e.state="active";break;case H.Held:e.state="held";break;case H.Hangup:case H.Destroy:e.state="done";break;case H.Answering:e.state="ringing";break;case H.New:e.state="new"}return e}};class bt extends mt{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new tt(e,t))}hangup(e={},t=!0){this.screenShare instanceof bt&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(this,void 0,void 0,(function*(){const t=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:n,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:n,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new bt(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof bt&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&_e(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);S.setLevel(2),this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const i=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],n=["id","type","timestamp"];e.forEach((e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((i=>{n.includes(i)||(t+=`\t${i}: ${e[i]}\n`)})))})),S.info(t)}))),2e3)}}class yt extends fe{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield we({audio:e,video:i});return Ce(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(H.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((t,i)=>{if(ee(h.SpeedTest,(i=>{const{upDur:n,downDur:s}=i,o=s?8*e/(s/1e3)/1024:0;t({upDur:n,downDur:s,upKps:(n?8*e/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let n=e/1024;e%1024&&n++;const s=".".repeat(1024);for(let e=0;e<n;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return Ie().catch((e=>(ie(h.MediaError,e,this.uuid),[])))}getVideoDevices(){return Ie(J.Video).catch((e=>(ie(h.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Ie(J.AudioIn).catch((e=>(ie(h.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return Ie(J.AudioOut).catch((e=>(S.error("getAudioOutDevices",e),ie(h.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return Ee(e,t,i)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],i=yield we({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<ke.length;e++){const[i,s]=ke[e];(yield n.applyConstraints({width:{exact:i},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${i}x${s}`,width:i,height:s})}return Ce(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=i,o=e(i,["micId","micLabel"]);return Te(o),this._audioConstraints=yield((e,i,n,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||i)){const t=yield Ee(e,i,n).catch((e=>null));t&&(s.deviceId={exact:t})}return s})))(n,s,"audioinput",o),this.micId=n,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const e="development"===this.options.env;this._iceServers=e?u:l}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=R(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=R(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const n=new Xe({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ze({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=xe(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,n,e))),s}))}vertoUnsubscribe({nodeId:e,channels:i=[]}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new et({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=xe(n);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),n}))}_setupNetworkListeners(){"undefined"!=typeof window&&(this._onlineHandler=()=>{this._wasOffline&&(S.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,S.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){"undefined"!=typeof window&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return bt.setStateTelnyx(e)}}class _t{constructor(e,t){this.code=t,this.message=e}}class St extends he{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:i,target_version_id:n,userVariables:s,sessionId:o,reconnection:r}=e,a={target_type:t,target_id:i,userVariables:s,reconnection:r,"User-Agent":{sdkVersion:Be,data:navigator.userAgent}};o&&(a.sessid=o),n&&(a.target_version_id=n),this.buildRequest({method:this.method,params:a})}}const Ct=Be;class wt{constructor(e){this.session=e,this.handleLogin=()=>t(this,void 0,void 0,(function*(){const{login:e,password:t,passwd:i,login_token:n,userVariables:s}=this.session.options,o=new Ve(e,t||i,n,this.session.sessionid,s,!!$()),r=yield this.session.execute(o).catch(this.session.handleLoginError);r&&(this.session.sessionid=r.sessid)})),this.handleAnonymousLogin=()=>t(this,void 0,void 0,(function*(){const{anonymous_login:e}=this.session.options,t=new St({target_id:e.target_id,target_type:e.target_type,target_version_id:e.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!$()}),i=yield this.session.execute(t).catch(this.session.handleLoginError);i&&(this.session.sessionid=i.sessid)}))}_ack(e,t){const i=new Ge(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*O(2,6)}handleMessage(e){var i,n,s,o,r,a;const{session:c}=this,{id:d,method:l,params:u={},voice_sdk_id:p}=e,g=null==u?void 0:u.callID,v=null==u?void 0:u.eventChannel,f=null==u?void 0:u.eventType,m=l===B.Attach,b=l===B.Punt;let y=!1,_=!1;if("channelPvtData"===f)return this._handlePvtEvent(u.pvtData);if(g&&c.calls.hasOwnProperty(g)){if(!m)return c.calls[g].handleMessage(e),void this._ack(d,l);{const e=c.calls[g];_=null===(i=e.peer)||void 0===i?void 0:i.restartedIceOnConnectionStateFailed,y=(c.options.keepConnectionAliveOnSocketClose||e.options.keepConnectionAliveOnSocketClose)&&Boolean(null===(n=e.peer)||void 0===n?void 0:n.instance)&&!e.signalingStateClosed&&!_,y?S.info(`[${(new Date).toISOString()}][${g}] re-attaching call due to ATTACH and keepConnectionAliveOnSocketClose`):(e.signalingStateClosed?S.info(`[${(new Date).toISOString()}][${g}] Hanging up the and recreating call due to ATTACH - signalingState is closed`):_&&S.info(`[${(new Date).toISOString()}][${g}] Hanging up the call due to ATTACH - connection had restarted ICE on connection state failed`),e.hangup({},_),S.debug(`[${(new Date).toISOString()}][${g}] Call hangup bye message ${_?"executed":"not executed"}`))}}if(b&&c.options.keepConnectionAliveOnSocketClose)return S.info(`[${(new Date).toISOString()}][${g}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),this.session.socketDisconnect(),void this._ack(d,l);const C=(e=!0)=>{var t,i,n,s,o,r;const a={audio:!0,video:c.options.video,remoteSdp:u.sdp,destinationNumber:u.callee_id_number,remoteCallerName:u.caller_id_name,remoteCallerNumber:u.caller_id_number,callerName:u.callee_id_name,callerNumber:u.callee_id_number,attach:m,mediaSettings:u.mediaSettings,debug:null!==(t=c.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=c.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:null!==(n=c.options.trickleIce)&&void 0!==n&&n,prefetchIceCandidates:null!==(s=c.options.prefetchIceCandidates)&&void 0!==s&&s,forceRelayCandidate:null!==(o=c.options.forceRelayCandidate)&&void 0!==o&&o,keepConnectionAliveOnSocketClose:null!==(r=c.options.keepConnectionAliveOnSocketClose)&&void 0!==r&&r};e&&(a.id=g),u.telnyx_call_control_id&&(a.telnyxCallControlId=u.telnyx_call_control_id),u.telnyx_session_id&&(a.telnyxSessionId=u.telnyx_session_id),u.telnyx_leg_id&&(a.telnyxLegId=u.telnyx_leg_id),u.client_state&&(a.clientState=u.client_state),u.dialogParams&&u.dialogParams.custom_headers&&u.dialogParams.custom_headers.length&&(a.customHeaders=u.dialogParams.custom_headers);const d=new bt(c,a);return d.nodeId=this.nodeId,d},w=new pe(p),I=new ve(p);switch(l){case B.Ping:this.session.setPingReceived(),this.session.execute(I).then((()=>{wt.receivedAuthenticationRequired=0})).catch((e=>t(this,void 0,void 0,(function*(){e.code===this.session.authenticationRequiredErrorCode&&wt.receivedAuthenticationRequired>=0&&(wt.receivedAuthenticationRequired+=1,wt.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(S.warn("Ping failed twice with Authentication Required. Re-logging in..."),L(this.session.options)?this.handleLogin():P(this.session.options)&&this.handleAnonymousLogin(),wt.receivedAuthenticationRequired=-1))}))));break;case B.Punt:c.disconnect();break;case B.Invite:{const e=C();e.playRingtone(),e.setState(H.Ringing),e.direction=F.Inbound,this._ack(d,l);break}case B.Attach:{if(y)return this.session.execute(new We({sessid:this.session.sessionid,sdp:this.session.calls[g].peer.instance.localDescription.sdp,dialogParams:this.session.calls[g].options,"User-Agent":`Web-${Ct}`})),void(null===(s=this.session.calls[g].peer)||void 0===s||s.restartStatsReporter());if(S.info(`[${(new Date).toISOString()}][${g}] Re-creating call instance.`),null===(o=this.session.calls[g])||void 0===o?void 0:o.creatingPeer)return void S.debug(`[${(new Date).toISOString()}][${g}] Call is already creating a peer, skip recreating call instance.`);let t;this.session.autoRecoverCalls?_?(S.debug(`[${(new Date).toISOString()}][${g}] Call had restarted ICE on connection state failed. Re-inviting to become active leg. due to keepConnectionAliveOnSocketClose.`),t=C(!1),t.invite()):(S.debug(`[${(new Date).toISOString()}][${g}] Call is not in an unrecoverable state. Answering.`),t=C(),t.answer()):(t=C(),t.setState(H.Recovering)),t.handleMessage(e);break}case B.Event:case"webrtc.event":if(!v)return void S.error("Verto received an unknown event:",u);const i=c.relayProtocol,n=v.split(".")[0];c._existsSubscription(i,v)?ie(i,u,v):v===c.sessionid?this._handleSessionEvent(u.eventData):c._existsSubscription(i,n)?ie(i,u,n):c.calls.hasOwnProperty(v)?c.calls[v].handleMessage(e):ie(h.Notification,u,c.uuid);break;case B.Info:u.type=V.generic,ie(h.Notification,u,c.uuid);break;case B.ClientReady:this.session.execute(w);break;default:{const t=D(e);if(t){switch(t){case K.REGISTER:case K.REGED:if(c.connection.previousGatewayState!==K.REGED&&c.connection.previousGatewayState!==K.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),wt.retriedRegister=0;const t=null===(a=null===(r=null==e?void 0:e.result)||void 0===r?void 0:r.params)||void 0===a?void 0:a.call_report_id;t&&(c.callReportId=t,S.debug("Captured call_report_id from REGED:",t)),u.type=V.vertoClientReady,ie(h.Ready,u,c.uuid),c.options.trickleIce&&(S.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new Ke({candidate:""})).catch((e=>{e.code===this.session.invalidMethodErrorCode?(S.warn("Trickle ICE is not supported by the server, disabling it."),S.debug("Trickle ICE check error:",JSON.stringify(e,null,2)),c.options.trickleIce=!1):S.debug("Trickle ICE check:",JSON.stringify(e,null,2))})))}break;case K.UNREGED:case K.NOREG:if(wt.retriedRegister+=1,5===wt.retriedRegister){wt.retriedRegister=0,ie(h.Error,{error:new _t("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:c.sessionid},c.uuid);break}setTimeout((()=>{this.session.execute(w)}),this.reconnectDelay());break;case K.FAILED:case K.FAIL_WAIT:if(c.connection.previousGatewayState!==K.FAILED&&c.connection.previousGatewayState!==K.FAIL_WAIT){if(!this.session.hasAutoReconnect()){wt.retriedConnect=0,ie(h.Error,{error:new _t("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:c.sessionid},c.uuid);break}if(wt.retriedConnect+=1,5===wt.retriedConnect){wt.retriedConnect=0,ie(h.Error,{error:new Error("Connection Retry Failed"),sessionId:c.sessionid},c.uuid);break}setTimeout((()=>{if(S.debug(`Reconnecting... Retry ${wt.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(c.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return S.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();S.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:S.warn("GatewayState message unknown method:",e)}break}S.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const i=Object.keys(this.session.calls);if("bootObj"!==e.action)return i.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>i.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(n){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},n={nodeId:this.nodeId,channels:[s],handler:({data:n})=>{const r=u||this._retrieveCallId(n,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(n,e).then((e=>{"INVALID_PACKET"===e&&i()}))}}},r=yield t.vertoSubscribe(n).catch((e=>{S.error("liveArray subscription error:",e)}));Re(r,s)&&i();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(i,s)){const{callId:n=null}=t.subscriptions[i][s];if(e=t.calls[n]||null,null!==n){const i={type:V.conferenceUpdate,action:W.Leave,conferenceName:o,participantId:Number(d),role:l};ie(h.Notification,i,n,!1)||ie(h.Notification,i,t.uuid),null===e&&te(h.Notification,null,n)}}const n=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:n}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{S.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":pt(this.session,e);break;case"logo-info":{const t={type:V.conferenceUpdate,action:W.LogoInfo,logo:e.logoURL};ie(h.Notification,t,this.session.uuid);break}}}}wt.retriedConnect=0,wt.retriedRegister=0,wt.receivedAuthenticationRequired=0;class It extends yt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:i,login_token:n,userVariables:s,autoReconnect:o=!0}=this.options,r=new Ve(e,t||i,n,this.sessionid,s,!!$()),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid)})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{anonymous_login:e}=this.options,t=new St({target_id:e.target_id,target_type:e.target_type,target_version_id:e.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!$()}),i=yield this.execute(t).catch(this._handleLoginError);i&&(this.sessionid=i.sessid)})),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(S.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return L(this.options)||P(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const t=new bt(this,e);return t.invite(),performance.mark("new-call-end"),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!P(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return L(this.options)?this.handleLoginOnSocketOpen():P(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){new wt(this).handleMessage(e)}}class kt extends It{constructor(e){super(e),S.info(`SDK version: ${Fe}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Me()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ne.full},{browserName:"Firefox",features:["audio"],supported:Ne.partial},{browserName:"Safari",supported:Ne.not_supported},{browserName:"Edge",supported:Ne.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ne.not_supported},{browserName:"Firefox",supported:Ne.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ne.full},{browserName:"Edge",supported:Ne.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ne.full},{browserName:"Firefox",features:["audio"],supported:Ne.partial},{browserName:"Safari",supported:Ne.not_supported},{browserName:"Edge",supported:Ne.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ne.full},{browserName:"Firefox",features:["audio"],supported:Ne.partial},{browserName:"Safari",features:["video","audio"],supported:Ne.full},{browserName:"Edge",features:["audio"],supported:Ne.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ne.full},{browserName:"Firefox",features:["audio"],supported:Ne.partial},{browserName:"Safari",supported:Ne.not_supported},{browserName:"Edge",features:["audio"],supported:Ne.partial}]}]}}class Et{static run(e){return t(this,void 0,void 0,(function*(){const t=M({}),i=M({}),n=new kt(e.credentials);yield n.connect(),n.on(h.Ready,t.resolve),n.on(h.Error,t.reject),n.on(h.MediaError,t.reject),n.on(h.MediaError,t.reject),n.on(h.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),Z(h.StatsReport,(e=>{i.resolve(Et.mapReport(e))})),yield t.promise,yield n.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield i.promise;return yield n.disconnect(),s}))}static mapReport(e){var t,i,n,s,o,r,a,c,d,l,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let f=0,m=1/0,b=-1/0,y=0,_=1/0,S=-1/0,C=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=1;const s=null!==(i=e.remote.audio.inbound[0].jitter)&&void 0!==i?i:0,o=null!==(n=e.remote.audio.inbound[0].roundTripTime)&&void 0!==n?n:0;y+=s,C+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),_=Math.min(_,o)}));const w=C/f,I=y/f,k=v[v.length-1],E=rt({jitter:1e3*I,rtt:1e3*w,packetsReceived:null!==(n=null===(i=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===i?void 0:i.packetsReceived)&&void 0!==n?n:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:E,jitter:{average:I,max:b,min:m},rtt:{average:w,max:S,min:_},quality:at(E)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=k.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=k.remote.audio.inbound)||void 0===l?void 0:l[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}export{bt as Call,Et as PreCallDiagnosis,h as SwEvent,kt as TelnyxRTC};
|
|
1
|
+
function e(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),i=new Uint8Array(16);function s(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(i)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[i+a]=r[a];return t||function(e,t){var n=t||0,i=o;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(r)}const c="wss://rtc.telnyx.com",d={urls:"stun:stun.l.google.com:19302"},l=[{urls:"stun:stun.telnyx.com:3478"},d,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],u=[{urls:"stun:stundev.telnyx.com:3478"},d,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var h;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"}(h||(h={}));var p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function g(e,t){return e(t={exports:{}},t.exports),t.exports}var v=g((function(e){var t,n;t=p,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=n),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=n():t.log=n()}));const f=v.getLogger("telnyx"),m=f.methodFactory;f.methodFactory=(e,t,n)=>{const i=m(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},f.setLevel("info");const b=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){f.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},y=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},_=e=>e instanceof Function||"function"==typeof e,S=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,w=/^(ws|wss):\/\//,C=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?C(a,r):{result:s}},I=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),k=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),E=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),T=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};function R({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?x(i,e):i,n=s})),resolve:t,reject:n}}const x=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},O="telnyx-voice-sdk-id";function A(){return sessionStorage.getItem(O)}var P,L,M;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(O)})),function(e){e.Offer="offer",e.Answer="answer"}(P||(P={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(L||(L={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.Candidate="telnyx_rtc.candidate",e.EndOfCandidates="telnyx_rtc.endOfCandidates",e.Display="telnyx_rtc.display",e.Media="telnyx_rtc.media",e.Event="telnyx_rtc.event",e.Bye="telnyx_rtc.bye",e.Punt="telnyx_rtc.punt",e.Broadcast="telnyx_rtc.broadcast",e.Subscribe="telnyx_rtc.subscribe",e.Unsubscribe="telnyx_rtc.unsubscribe",e.ClientReady="telnyx_rtc.clientReady",e.Modify="telnyx_rtc.modify",e.Ringing="telnyx_rtc.ringing",e.GatewayState="telnyx_rtc.gatewayState",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(M||(M={}));const D={generic:"event",[M.Display]:"participantData",[M.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},N={invalidCredentialsOptions:"InvalidCredentialsOptions"},U={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1};var j,$,F,V,G;!function(e){e[e.New=0]="New",e[e.Requesting=1]="Requesting",e[e.Trying=2]="Trying",e[e.Recovering=3]="Recovering",e[e.Ringing=4]="Ringing",e[e.Answering=5]="Answering",e[e.Early=6]="Early",e[e.Active=7]="Active",e[e.Held=8]="Held",e[e.Hangup=9]="Hangup",e[e.Destroy=10]="Destroy",e[e.Purge=11]="Purge"}(j||(j={})),function(e){e.Participant="participant",e.Moderator="moderator"}($||($={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(F||(F={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(V||(V={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(G||(G={}));const B="GLOBAL",H={},q=(e,t)=>`${e}|${t}`,W=(e,t=B)=>q(e,t)in H,K=(e,t,n=B)=>{const i=q(e,n);i in H||(H[i]=[]),H[i].push(t)},J=(e,t,n=B)=>{const i=function(s){z(e,i,n),t(s)};return i.prototype.targetRef=t,K(e,i,n)},z=(e,t,n=B)=>{if(!W(e,n))return!1;const i=q(e,n);if(_(t)){for(let e=H[i].length-1;e>=0;e--){const n=H[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&H[i].splice(e,1)}}else H[i]=[];return 0===H[i].length&&delete H[i],!0},Y=(e,t,n=B,i=!0)=>{const s=i&&n!==B;if(!W(e,n))return s&&Y(e,t),!1;const o=q(e,n),r=H[o].length;if(!r)return s&&Y(e,t),!1;for(let e=r-1;e>=0;e--)H[o][e](t);return s&&Y(e,t),!0},Q=e=>{const t=q(e,"");Object.keys(H).filter((e=>0===e.indexOf(t))).forEach((e=>delete H[e]))};let X="undefined"!=typeof WebSocket?WebSocket:null;const Z=0,ee=1,te=2,ne=3;class ie{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=c,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this.upDur=null,this.downDur=null;const{host:t,env:n,region:i,useCanaryRtcServer:s}=e.options;n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":c),t&&(this._host=(e=>`${w.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host=this._host.replace(/rtc(dev)?/,`${i}.rtc$1`)),s&&(this._useCanaryRtcServer=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===ee}get connecting(){return this._wsClient&&this._wsClient.readyState===Z}get closing(){return this._wsClient&&this._wsClient.readyState===te}get closed(){return this._wsClient&&this._wsClient.readyState===ne}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let t=A();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),f.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this._wsClient=new X(e.toString()),this._wsClient.onopen=e=>Y(h.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>Y(h.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>Y(h.SocketError,{error:e,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=y(e.data);var s;if("string"!=typeof i){if(i.voice_sdk_id&&(s=i.voice_sdk_id,sessionStorage.setItem(O,s)),this._unsetTimer(i.id),f.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),G[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!Y(i.id,i)){const e=T(i);Y(h.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();J(t.id,(t=>{const{result:i,error:s}=C(t);return s?n(s):e(i)}))}));return f.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(_(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),Y(h.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else f.warn("Unknown message from socket",e)}}class se{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const oe={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class re extends se{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in oe)e&&n.hasOwnProperty(e)&&(n[oe[e]]=n[e],delete n[e]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class ae extends re{constructor(e){super(),this.method=M.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class ce{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(T(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new ae(A());this.pendingRequestId=e.request.id,this.gatewayStateTask=R({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[G.REGISTER,G.REGED].includes(t)})),this.session=e,this.gatewayStateTask=R({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class de extends re{constructor(e){super(),this.method=M.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var le="2.25.18",ue=le;class he extends re{constructor(e,t,n,i,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:n,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:ue,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class pe extends re{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class ge extends re{toString(){return M.Invite}}class ve extends re{toString(){return M.Answer}}class fe extends re{toString(){return M.Attach}}class me extends re{toString(){return M.Bye}}class be extends re{toString(){return M.Candidate}}class ye extends re{toString(){return M.EndOfCandidates}}class _e extends re{toString(){return M.Modify}}class Se extends re{toString(){return M.Info}}class we extends re{toString(){return M.Broadcast}}class Ce extends re{toString(){return M.Subscribe}}class Ie extends re{toString(){return M.Unsubscribe}}class ke extends re{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:n,target_version_id:i,userVariables:s,sessionId:o,reconnection:r}=e,a={target_type:t,target_id:n,userVariables:s,reconnection:r,"User-Agent":{sdkVersion:ue,data:navigator.userAgent}};o&&(a.sessid=o),i&&(a.target_version_id=i),this.buildRequest({method:this.method,params:a})}}class Ee{constructor(e){if(this.options=e,this.uuid=a(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");f.setLevel(e.debug?"debug":"info"),this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new ie(this),this.registerAgent=new ce(this)}get __logger(){return f}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*I(2,6)}execute(e){return this._idle?new Promise((t=>this._executeQueue.push({resolve:t,msg:e}))):this.connected?this.connection.send(e):new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),f.debug("Calling connect from execute since not currently connected."),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return k(this.options)||E(this.options)}broadcast(e){}disconnect(){return t(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),f.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return K(e,t,this.uuid),this}off(e,t){return z(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(f.debug("No existing connection found, creating a new one."),this.connection=new ie(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(f.debug("Initiating connection to the server..."),this.connection.connect()),f.debug("Connect method called. Connection initiated.")}))}_handleLoginError(e){Y(h.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return t(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(e&&(void 0!==e.login&&(this.options.login=e.login),void 0!==e.password&&(this.options.password=e.password),void 0!==e.passwd&&(this.options.passwd=e.passwd),void 0!==e.login_token&&(this.options.login_token=e.login_token),void 0!==e.userVariables&&(this.options.userVariables=e.userVariables),void 0!==e.anonymous_login&&(this.options.anonymous_login=e.anonymous_login)),k(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(E(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const e="Invalid login options provided for authentication.";return f.error(e),void Y(h.Error,{error:new Error(e),type:N.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:n,onError:i}){return t(this,void 0,void 0,(function*(){let t;t="login"===e?new he(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!A()):new ke({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!A()});const s=yield this.execute(t).catch((e=>{this._handleLoginError(e),i&&i(e)}));s&&(this.sessionid=s.sessid,n&&n())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&Q(this.relayProtocol);for(const e in this.subscriptions)Q(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{f.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],z(e,null,t)):(delete this.subscriptions[e],Q(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},_(t)&&K(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(h.SocketOpen,this._onSocketOpen),this.on(h.SocketClose,this.onNetworkClose),this.on(h.SocketError,this.onNetworkClose),this.on(h.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(h.SocketOpen,this._onSocketOpen),this.off(h.SocketClose,this.onNetworkClose),this.off(h.SocketError,this.onNetworkClose),this.off(h.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(f.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new de(A()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){f.debug("Ping received"),this._pong=!0}static on(e,t){K(e,t)}static off(e){z(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Te=e=>navigator.mediaDevices.getUserMedia(e),Re=e=>e&&e instanceof MediaStream,xe=(e,t)=>{const n=S(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},Oe=(e,n)=>t(void 0,void 0,void 0,(function*(){const t=S(e);if(null===t)return f.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof n)return f.info(`Invalid speaker deviceId: '${n}'`),!1;try{return yield t.setSinkId(n),!0}catch(e){return!1}})),Ae=e=>{e&&"live"===e.readyState&&e.stop()},Pe=e=>{Re(e)&&e.getTracks().forEach(Ae),e=null},Le=n=>t(void 0,void 0,void 0,(function*(){f.info("RTCService.getUserMedia",n);const{audio:t,video:i}=n;if(!t&&!i)return null;try{return yield Te(n)}catch(t){if(f.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const i=(t=>{const{audio:n,video:i}=t;let s=!1,o=n,r=i;if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(n);if(i){f.warn("Device not found or not readable, falling back to default device");try{return yield Te(i)}catch(e){throw f.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),Me=(e=null,n=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===V.AudioIn||e===V.AudioOut,video:!e||e===V.Video}))(e)).catch((e=>(f.error(e),null)));if(i){if(Pe(i),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===n)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),De=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Ne=(e,n,i)=>t(void 0,void 0,void 0,(function*(){const t=yield Me(i,!0);for(let i=0;i<t.length;i++){const{deviceId:s,label:o}=t[i];if(e===s||n===o)return s}return null})),Ue=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},je=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=$e(e);return n.includes(t)||i.includes(t)},$e=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},Fe=(e,t=null,n=null)=>{if(!Re(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Ve=e=>{Fe(e,"audio",!0)},Ge=e=>{Fe(e,"audio",!1)},Be=e=>{Fe(e,"audio",null)},He=e=>((e,t=null)=>{if(!Re(e))return null;let n=[];switch(t){case"audio":n=e.getAudioTracks();break;case"video":n=e.getVideoTracks();break;default:n=e.getTracks()}return n.some((e=>e.enabled))})(e,"audio");function qe(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!Le}}catch(e){return e.message}}var We;function Ke(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Je(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{f.error("playAudio",t),e._playFulfilled=!0})))}function ze(e){e&&(e._playFulfilled?(e.pause(),e.currentTime=0):e._promise&&e._promise.then?e._promise.then((()=>{e.pause(),e.currentTime=0})):setTimeout((()=>{e.pause(),e.currentTime=0}),1e3))}!function(e){e.not_supported="not supported",e.full="full",e.partial="partial"}(We||(We={}));class Ye extends se{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}var Qe,Xe=g((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(d)}}else c=a[t]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,n,i,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var l,u=new Uint8Array(16);function h(){if(!l&&!(l="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],v=0;256>v;++v)g.push((v+256).toString(16).substr(1));function f(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n}function m(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return f(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function S(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let w,C={},I=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:n}=e;let{connectionId:i,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),I.forEach((e=>{this.removeTrackEventListeners(e)})),I=[],this.shouldWrapGetUserMedia&&w&&(navigator.mediaDevices.getUserMedia=w)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=_(o),d={remote:s.options.remote},l=S(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,timeTaken:a-t,data:l};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),n.push(u),s.stats.parsed=l}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),w=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),w.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),C[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{C[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,C[t][i],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),I.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){C[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{C[e.id][t]=n[t].bind(this),e.addEventListener(t,C[e.id][t])})),C[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in C){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,C[e.id][t])})),clearInterval(C[e.id].readyState),delete C[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in C&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,C[e][n],!1)})),delete C[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=n.bind(navigator.mediaDevices)}}}}));(Qe=Xe)&&Qe.__esModule&&Object.prototype.hasOwnProperty.call(Qe,"default")&&Qe.default;var Ze=Xe.WebRTCStats;function et(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(e){const{jitter:t,rtt:n}=e,i=t+n/2;return.024*i+.11*(i-177.3)*(i>177.3?1:0)}({rtt:s,jitter:i}),r=function(e){const{packetsLost:t,packetsReceived:n}=e,i=t/(n+t)*100;return 20*Math.log(1+i)}({packetsLost:t,packetsReceived:n}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function tt(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class nt extends se{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class it extends se{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class st extends se{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function ot(e,t){var n,i;return{errorCode:e.errorCode,errorText:e.errorText,url:e.url,address:e.address,port:e.port,connectionState:t.connectionState,iceConnectionState:t.iceConnectionState,iceGatheringState:t.iceGatheringState,signalingState:t.signalingState,localDescriptionType:null===(n=t.localDescription)||void 0===n?void 0:n.type,remoteDescriptionType:null===(i=t.remoteDescription)||void 0===i?void 0:i.type}}function rt(e,n){const i=a();let s=!1;const o=new Ze({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=n=>t(this,void 0,void 0,(function*(){"stats"===n.event&&Y(h.StatsFrame,function({data:e}){var t,n,i,s,o,r,a,c;const{audio:d,remote:l}=e,{audio:u}=l,h=null!==(n=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==n?n:1/0,p=null!==(s=null===(i=u.inbound[0])||void 0===i?void 0:i.roundTripTime)&&void 0!==s?s:1/0,g=null!==(r=null===(o=d.inbound[0])||void 0===o?void 0:o.packetsReceived)&&void 0!==r?r:-1,v=null!==(c=null===(a=d.inbound[0])||void 0===a?void 0:a.packetsLost)&&void 0!==c?c:-1,f=et({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:tt(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(n),e.uuid),yield e.execute(new st(i,n))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)f.debug(`[${n}] Stats reporter already running, skipping start`);else{yield e.execute(new nt(i,n)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){f.error(`[${n}] Failed to start stats reporter:`,e),o.removeAllPeers(),o.destroy()}}})),stop:r=>t(this,void 0,void 0,(function*(){const t=o.getTimeline();if(Y(h.StatsReport,t,e.uuid),"file"===r){!function(e,t){const n=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(i)}(t,`webrtc-stats-${i}-${Date.now()}`)}yield e.execute(new it(i,n)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const at=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:D.conferenceUpdate,call:e.calls[s],canvasInfo:ct(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:F.LayerInfo},a);Y(h.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:F.LayoutInfo},a);Y(h.Notification,t,e.uuid);break}}},ct=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return y(t)};class dt{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(f.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){const e=()=>t(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,n){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:n,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},i=e.getTransceivers();if(i.length>0){const e=i[0].sender,n=null==e?void 0:e.transport;n&&(t.dtlsState=n.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const n=yield e.getStats();n.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,n.forEach((n=>{"local-candidate"===n.type&&n.id===e.localCandidateId&&(t.localCandidateType=n.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:n.address,port:n.port,protocol:n.protocol,candidateType:n.candidateType}),"remote-candidate"===n.type&&n.id===e.remoteCandidateId&&(t.remoteCandidateType=n.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:n.address,port:n.port,protocol:n.protocol,candidateType:n.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){f.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}window.removeEventListener("online",e)}));navigator.onLine?e():window.addEventListener("online",e)}"failed"===e&&Y(h.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=e,this._isTrickleIce()&&("connecting"===e&&performance.mark("peer-connection-connecting"),"connected"===e&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))})),this._handleIceConnectionStateChange=()=>{f.debug(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{f.debug(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},f.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===P.Offer}get isAnswer(){return this.type===P.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return"connected"===this.instance.connectionState&&"connected"===this.instance.iceConnectionState&&"closed"!==this.instance.signalingState}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return t(this,void 0,void 0,(function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))}))}_logTransceivers(){f.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{f.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),f.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),t=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),n=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("invite-send","new-call-start","sdp-send-start"),o=performance.measure("total-duration","peer-creation-start","sdp-send-end"),r=e=>`${e.toFixed(2)}ms`;return{"New Call":{duration:r(e.duration)},"Peer Creation":{duration:r(t.duration)},"ICE Gathering":{duration:r(n.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:r(s.duration)},"SDP Send":{duration:r(i.duration)},"Total Duration":{duration:r(o.duration)}}}handleSignalingStateChangeEvent(){switch(f.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":Y(h.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(f.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){f.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?f.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;this.options.remoteStream=t,!1===i&&xe(n,this.options.remoteStream)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:P.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>(Y(h.MediaError,e,this.options.id),null))),this.options.mutedMicOnStart&&Re(this.options.localStream)&&(f.info("Muting local audio tracks on start"),Ge(this.options.localStream)),performance.mark("peer-creation-end")}))}init(){var e;return t(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=rt(this._session,this.options.id),yield null===(e=this.statsReporter)||void 0===e?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:t,localStream:n=null,screenShare:i=!1}=this.options;if(Re(n)){const e=n.getAudioTracks();let s=[...e];if(f.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{f.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=n.getVideoTracks();s=[...e,...t],f.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{f.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=(e=>{const t=[],n=[];return e&&0!==e.length?(e.forEach((e=>{const i=e.mimeType.toLocaleLowerCase();i.startsWith("audio/")?t.push(e):i.startsWith("video/")&&n.push(e)})),{audioCodecs:t,videoCodecs:n}):{audioCodecs:t,videoCodecs:n}})(this.options.preferred_codecs);if(this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[n]};s.forEach((t=>{"audio"===t.kind&&(this.options.userVariables.microphoneLabel=t.label),"video"===t.kind&&(this.options.userVariables.cameraLabel=t.label);const n=this.instance.addTransceiver(t,e);"audio"===t.kind&&o.length>0&&this._setCodecs(n,o),"video"===t.kind&&r.length>0&&this._setCodecs(n,r)}))}else"function"==typeof this.instance.addTrack?(s.forEach((e=>{"audio"===e.kind&&(this.options.userVariables.microphoneLabel=e.label),"video"===e.kind&&(this.options.userVariables.cameraLabel=e.label),this.instance.addTrack(e,n)})),this.instance.getTransceivers().forEach((e=>{"audio"===e.receiver.track.kind&&o.length>0&&this._setCodecs(e,o),"video"===e.receiver.track.kind&&r.length>0&&this._setCodecs(e,r)}))):this.instance.addStream(n);!1===i&&xe(t,n)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()}))}_getSenderByKind(e){return this.instance.getSenders().find((({track:t})=>t&&t.kind===e))}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);f.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio,this._constraints.offerToReceiveVideo=Boolean(this.options.video),f.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){f.error("Peer _createOffer error:",e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){f.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return f.debug("Skipping negotiation, state:",this.instance.signalingState),f.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:P.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){f.error("Peer _createAnswer error:",e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){yield this.instance.setLocalDescription(e)}))}_sdpReady(){_(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(Re(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:i=!1,camId:s}=n;const{micLabel:o="",camLabel:r=""}=n;return t&&(t=yield Ne(t,o,V.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield Ne(s,r,V.Video).catch((e=>null)),s&&("boolean"==typeof i&&(i={}),i.deviceId={exact:s})),{audio:e,video:i}})));var n;return Le(e)}))}_isOffer(){return this.type===P.Offer}_isAnswer(){return this.type===P.Answer}_isTrickleIce(){return!0===this.options.trickleIce}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:t,iceServers:n}=this.options,i={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:t?"relay":"all"};return f.info("RTC config",i),i}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?f.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(f.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):f.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){null!==this._sleepWakeupIntervalId&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)}))}}const lt=ue;class ut{constructor(e,t,n=!1){this.session=e,this._isRecovering=n,this.id="",this.state=j[j.New],this.prevState="",this.channels=[],this.role=$.Participant,this.extension=null,this._state=j.New,this._prevState=j.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=e=>{const t=e<0||!this._lastSerno||this._lastSerno&&e===this._lastSerno+1;return t&&e>=0&&(this._lastSerno=e),t},this._doStats=()=>{this.peer&&this.peer.instance&&0!==this._statsBindings.length&&this.peer.instance.getStats().then((e=>{e.forEach((e=>{this._statsBindings.forEach((t=>{if(t.callback){if(t.constraints)for(const n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:d,remoteElement:l,options:u,mediaConstraints:{audio:h,video:p},ringtoneFile:g,ringbackFile:v}=e;this.options=Object.assign({},U,{audio:h,video:p,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:i,localElement:d,remoteElement:l,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:g,ringbackFile:v,debug:u.debug,debugOutput:u.debugOutput,trickleIce:u.trickleIce,prefetchIceCandidates:u.prefetchIceCandidates,forceRelayCandidate:u.forceRelayCandidate,keepConnectionAliveOnSocketClose:u.keepConnectionAliveOnSocketClose,mutedMicOnStart:u.mutedMicOnStart},t),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=Ke(this.options.ringtoneFile,"_ringtone"),this._ringback=Ke(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),t=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),n=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),i=performance.measure("total-duration","peer-creation-start","sdp-send-end"),s=e=>`${e.toFixed(2)}ms`;return{"Peer Creation":{duration:s(e.duration)},"ICE Gathering":{duration:s(t.duration)},"SDP Send":{duration:s(n.duration)},"Total Duration":{duration:s(i.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return!He(this.options.localStream)}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=L.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new dt(P.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1}))}answer(e={}){var n;return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=L.Inbound,(null===(n=null==e?void 0:e.customHeaders)||void 0===n?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new dt(P.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1}))}playRingtone(){Je(this._ringtone)}stopRingtone(){ze(this._ringtone)}playRingback(){Je(this._ringback)}stopRingback(){ze(this._ringback)}hangup(e,t){var n,i,s;const o=e||{},r=!1!==t;if(this.cause=o.cause||"NORMAL_CLEARING",this.causeCode=o.causeCode||16,this.sipCode=o.sipCode||null,this.sipReason=o.sipReason||null,this.sipCallId=o.sip_call_id||null,this.options.customHeaders=[...null!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(s=null===(i=null==o?void 0:o.dialogParams)||void 0===i?void 0:i.customHeaders)&&void 0!==s?s:[]],o.isRecovering)return this._isRecovering=!0,this.setState(j.Recovering),void this._finalize();this.setState(j.Hangup);const a=()=>{var e;f.debug(`[${this.id}] Closing peer from hangup`),null===(e=this.peer)||void 0===e||e.close(),this.setState(j.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new me({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(e).catch((e=>{f.error("telnyx_rtc.bye failed!",e),Y(h.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new _e({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new _e({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new _e({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Se({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new Se({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){Ge(this.options.localStream)}unmuteAudio(){Ve(this.options.localStream)}toggleAudioMute(){Be(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(i){const t=yield Te({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];s.enabled=!n,i.replaceTrack(s),this.options.micId=e;const{localStream:o}=this.options;o.getAudioTracks().forEach((e=>e.stop())),o.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Fe(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Fe(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Fe(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield Te({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);const{localElement:s,localStream:o}=this.options;xe(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ge(this.options.remoteStream)}undeaf(){Ve(this.options.remoteStream)}toggleDeaf(){Be(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void f.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:t}=this.peer,i=t.getSenders();if(!i)return void f.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const s=i.find((({track:{kind:e}})=>e===n));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),f.info("Parameters: ",t),f.info("Setting max ","audio"===n?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{f.info("audio"===n?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>f.error(e)))}else f.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=j[this._state].toLowerCase(),this.prevState=j[this._prevState].toLowerCase(),f.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:D.callUpdate,call:this}),e){case j.Purge:f.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case j.Active:this._isRecovering&&(this._isRecovering=!1,f.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&Oe(e,t)}),0);break;case j.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case M.Answer:if(this.gotAnswer=!0,this._state>=j.Active)return;this._state>=j.Early&&this.setState(j.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case M.Media:if(this._state>=j.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case M.Display:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===L.Inbound?L.Outbound:L.Inbound,r={type:D[t],call:this,displayName:e,displayNumber:i,displayDirection:o};Y(h.Notification,r,this.id)||Y(h.Notification,r,this.session.uuid);break}case M.Candidate:this._addIceCandidate(n);break;case M.Info:case M.Event:{const e=Object.assign(Object.assign({},n),{type:D.generic,call:this});Y(h.Notification,e,this.id)||Y(h.Notification,e,this.session.uuid);break}case M.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case M.Bye:const e=n.client_state||n.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,n){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return f.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:i,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=n;this._dispatchConferenceUpdate({action:F.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},b(i[e][1])));this._dispatchConferenceUpdate({action:F.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:F.Add,callId:s,index:o},b(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:F.Modify,callId:s,index:o},b(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:F.Delete,callId:s,index:o},b(i)));break;case"clear":this._dispatchConferenceUpdate({action:F.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:i,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:F.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{f.error("ConfChat subscription error:",e)}));je(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,at(this.session,t);else f.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{f.error("ConfInfo subscription error:",e)}));je(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(j.Active):this.setState(j.Held),!0}_handleChangeHoldStateError(e){return f.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const t=new RTCSessionDescription({sdp:e,type:P.Answer});yield this.peer.instance.setRemoteDescription(t).then((()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(j.Early),this.gotAnswer&&this.setState(j.Active)})).catch((e=>{f.error("Call setRemoteDescription Error: ",e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}))}))}_requestAnotherLocalDescription(){_(this.peer.onSdpReadyTwice)?Y(h.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return f.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${lt}`};switch(s){case P.Offer:this.setState(j.Requesting),o=new ge(r);break;case P.Answer:this._isRecovering||this.setState(j.Answering),o=!0===this.options.attach?new fe(r):new ve(r);break;default:return f.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===P.Offer?this.setState(j.Trying):this.setState(j.Active)})).catch((e=>{f.error(`${this.id} - Sending ${s} error:`,e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})).finally((()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()}))}_onTrickleIceSdp(e){if(!e)return f.error("No SDP data provided"),this.hangup({},!1);const{sdp:t,type:n}=e;let i=null;const s={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${lt}`};switch(n){case P.Offer:this.setState(j.Requesting),i=new ge(s);break;case P.Answer:this._isRecovering||this.setState(j.Answering),i=!0===this.options.attach?new fe(s):new ve(s);break;default:return f.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(i).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,n===P.Offer?this.setState(j.Trying):this.setState(j.Active)})).catch((e=>{f.error(`${this.id} - Sending ${n} error:`,e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})).finally((()=>{performance.mark("sdp-send-end")}))}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?f.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(f.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new be({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(t)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return f.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const t=this.peer.instance.addIceCandidate(e);Promise.resolve(t).then((()=>{f.debug("Successfully added ICE candidate:",e)})).catch((t=>{f.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new ye({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.onicecandidateerror=t=>{var n;if(f.debug("ICE candidate error:",t),null===(n=this.peer)||void 0===n?void 0:n.statsReporter){const n=ot(t,e);this.peer.statsReporter.reportIceCandidateError(n)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&xe(t,n)}))}_registerTrickleIcePeerEvents(e){e.onicecandidate=e=>{this._onTrickleIce(e)},e.onicegatheringstatechange=t=>{f.debug("ICE gathering state changed:",e.iceGatheringState),"complete"===e.iceGatheringState&&f.debug("Finished gathering candidates")},e.onicecandidateerror=t=>{var n;if(f.debug("ICE candidate error:",t),null===(n=this.peer)||void 0===n?void 0:n.statsReporter){const n=ot(t,e);this.peer.statsReporter.reportIceCandidateError(n)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&xe(t,n)}))}_onMediaError(e){this._dispatchNotification({type:D.userMediaError,error:e}),f.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:D.peerConnectionFailureError,error:e}),f.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:D.signalingStateClosed},e)),f.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:D.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(Y(h.Notification,e,this.id,!1)||Y(h.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:n,onNotification:i}=this.options;var s;this.options.id=e?e.toString():a(),this.id=this.options.id,t&&(s=t,0!==Object.keys(s).length)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,K(h.MediaError,this._onMediaError,this.id),K(h.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),K(h.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),_(i)&&K(h.Notification,i.bind(this),this.id),this._isRecovering?this.setState(j.Recovering):this.setState(j.New),f.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),f.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:n}=this.options;Pe(t),Pe(n),z(h.MediaError,null,this.id),z(h.PeerConnectionFailureError,null,this.id),z(h.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),f.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),f.debug("Stats stopped")}}ut.setStateTelnyx=e=>{if(e){switch(e._state){case j.Recovering:e.state="recovering";break;case j.Requesting:case j.Trying:case j.Early:e.state="connecting";break;case j.Active:e.state="active";break;case j.Held:e.state="held";break;case j.Hangup:case j.Destroy:e.state="done";break;case j.Answering:e.state="ringing";break;case j.New:e.state="new"}return e}};class ht extends ut{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new Ye(e,t))}hangup(e={},t=!0){this.screenShare instanceof ht&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new ht(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof ht&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&Oe(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);f.setLevel(2),this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),f.info(t)}))),2e3)}}class pt extends Ee{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,n=!0){return t(this,void 0,void 0,(function*(){try{const t=yield Le({audio:e,video:n});return Pe(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(j.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((t,n)=>{if(J(h.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return Me().catch((e=>(Y(h.MediaError,e,this.uuid),[])))}getVideoDevices(){return Me(V.Video).catch((e=>(Y(h.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Me(V.AudioIn).catch((e=>(Y(h.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return Me(V.AudioOut).catch((e=>(f.error("getAudioOutDevices",e),Y(h.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return Ne(e,t,n)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],n=yield Le({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<De.length;e++){const[n,s]=De[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return Pe(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{micId:i,micLabel:s}=n,o=e(n,["micId","micLabel"]);return Ue(o),this._audioConstraints=yield((e,n,i,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||n)){const t=yield Ne(e,n,i).catch((e=>null));t&&(s.deviceId={exact:t})}return s})))(i,s,"audioinput",o),this.micId=i,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const e="development"===this.options.env;this._iceServers=e?u:l}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=S(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=S(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new we({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ce({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=$e(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:n=[]}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ie({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const i=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=$e(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}_setupNetworkListeners(){"undefined"!=typeof window&&(this._onlineHandler=()=>{this._wasOffline&&(f.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,f.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){"undefined"!=typeof window&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return ht.setStateTelnyx(e)}}class gt{constructor(e,t){this.code=t,this.message=e}}class vt{constructor(e){this.session=e}_ack(e,t){const n=new pe(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*I(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,c=null==r?void 0:r.callID,d=null==r?void 0:r.eventChannel,l=null==r?void 0:r.eventType,u=i.calls[c],p=null===(n=null==u?void 0:u.peer)||void 0===n?void 0:n.isConnectionHealthy();if("channelPvtData"===l)return this._handlePvtEvent(r.pvtData);const g=(e=!1)=>{var t,n,s,a,d,l;const u={audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:o===M.Attach,mediaSettings:r.mediaSettings,debug:null!==(t=i.options.debug)&&void 0!==t&&t,debugOutput:null!==(n=i.options.debugOutput)&&void 0!==n?n:"socket",trickleIce:null!==(s=i.options.trickleIce)&&void 0!==s&&s,prefetchIceCandidates:null!==(a=i.options.prefetchIceCandidates)&&void 0!==a&&a,forceRelayCandidate:null!==(d=i.options.forceRelayCandidate)&&void 0!==d&&d,keepConnectionAliveOnSocketClose:null!==(l=i.options.keepConnectionAliveOnSocketClose)&&void 0!==l&&l};c&&(u.id=c),r.telnyx_call_control_id&&(u.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(u.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(u.telnyxLegId=r.telnyx_leg_id),r.client_state&&(u.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(u.customHeaders=r.dialogParams.custom_headers);const h=new ht(i,u,e);return h.nodeId=this.nodeId,h},v=new ae(a),m=new de(a);switch(o){case M.Answer:case M.Display:case M.Candidate:case M.Ringing:case M.Bye:case M.Media:if(!c||!u)return void f.error(`Received ${o} for non existing call:`,r);u.handleMessage(e),this._ack(s,o);break;case M.Ping:this.session.setPingReceived(),this.session.execute(m).then((()=>{vt.receivedAuthenticationRequired=0})).catch((e=>t(this,void 0,void 0,(function*(){e.code===this.session.authenticationRequiredErrorCode&&vt.receivedAuthenticationRequired>=0&&(vt.receivedAuthenticationRequired+=1,vt.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(f.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),vt.receivedAuthenticationRequired=-1))}))));break;case M.Punt:i.options.keepConnectionAliveOnSocketClose&&p?(f.info(`[${(new Date).toISOString()}][${c}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),i.socketDisconnect(),this._ack(s,o)):i.disconnect();break;case M.Invite:{const e=g();e.playRingtone(),e.setState(j.Ringing),e.direction=L.Inbound,this._ack(s,o);break}case M.Attach:{if(!u){return g().answer(),void this._ack(s,o)}const e=!!u;f.info(`[${(new Date).toISOString()}][${c}] closing existing call on ATTACH.`),u.hangup({isRecovering:e},!1),f.info(`[${(new Date).toISOString()}][${c}] Attach: Creating new call for recovery`);g(e).answer(),this._ack(s,o);break}case M.Event:case"webrtc.event":if(!d)return void f.error("Verto received an unknown event:",r);const n=i.relayProtocol,a=d.split(".")[0];i._existsSubscription(n,d)?Y(n,r,d):d===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(n,a)?Y(n,r,a):i.calls.hasOwnProperty(d)?i.calls[d].handleMessage(e):Y(h.Notification,r,i.uuid);break;case M.Info:r.type=D.generic,Y(h.Notification,r,i.uuid);break;case M.ClientReady:this.session.execute(v);break;default:{const t=T(e);if(t){switch(t){case G.REGISTER:case G.REGED:i.connection.previousGatewayState!==G.REGED&&i.connection.previousGatewayState!==G.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),vt.retriedRegister=0,r.type=D.vertoClientReady,Y(h.Ready,r,i.uuid));break;case G.UNREGED:case G.NOREG:if(vt.retriedRegister+=1,5===vt.retriedRegister){vt.retriedRegister=0,Y(h.Error,{error:new gt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout((()=>{this.session.execute(v)}),this.reconnectDelay());break;case G.FAILED:case G.FAIL_WAIT:if(i.connection.previousGatewayState!==G.FAILED&&i.connection.previousGatewayState!==G.FAIL_WAIT){if(!this.session.hasAutoReconnect()){vt.retriedConnect=0,Y(h.Error,{error:new gt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(vt.retriedConnect+=1,5===vt.retriedConnect){vt.retriedConnect=0,Y(h.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout((()=>{if(f.debug(`Reconnecting... Retry ${vt.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(i.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return f.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();f.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:f.warn("GatewayState message unknown method:",e)}break}f.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=u||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{f.error("liveArray subscription error:",e)}));je(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:D.conferenceUpdate,action:F.Leave,conferenceName:o,participantId:Number(d),role:l};Y(h.Notification,n,i,!1)||Y(h.Notification,n,t.uuid),null===e&&z(h.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{f.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":at(this.session,e);break;case"logo-info":{const t={type:D.conferenceUpdate,action:F.LogoInfo,logo:e.logoURL};Y(h.Notification,t,this.session.uuid);break}}}}vt.retriedConnect=0,vt.retriedRegister=0,vt.receivedAuthenticationRequired=0;class ft extends pt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(f.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return k(this.options)||E(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const t=new ht(this,e);return t.invite(),performance.mark("new-call-end"),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!E(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return k(this.options)?this.handleLoginOnSocketOpen():E(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){new vt(this).handleMessage(e)}}class mt extends ft{constructor(e){super(e),f.info(`SDK version: ${le}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return qe()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:We.full},{browserName:"Firefox",features:["audio"],supported:We.partial},{browserName:"Safari",supported:We.not_supported},{browserName:"Edge",supported:We.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:We.not_supported},{browserName:"Firefox",supported:We.not_supported},{browserName:"Safari",features:["video","audio"],supported:We.full},{browserName:"Edge",supported:We.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:We.full},{browserName:"Firefox",features:["audio"],supported:We.partial},{browserName:"Safari",supported:We.not_supported},{browserName:"Edge",supported:We.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:We.full},{browserName:"Firefox",features:["audio"],supported:We.partial},{browserName:"Safari",features:["video","audio"],supported:We.full},{browserName:"Edge",features:["audio"],supported:We.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:We.full},{browserName:"Firefox",features:["audio"],supported:We.partial},{browserName:"Safari",supported:We.not_supported},{browserName:"Edge",features:["audio"],supported:We.partial}]}]}}class bt{static run(e){return t(this,void 0,void 0,(function*(){const t=R({}),n=R({}),i=new mt(e.credentials);yield i.connect(),i.on(h.Ready,t.resolve),i.on(h.Error,t.reject),i.on(h.MediaError,t.reject),i.on(h.MediaError,t.reject),i.on(h.Notification,(e=>{e.call&&e.call.sipCode>=400&&n.reject(new Error(e.call.sipReason))})),K(h.StatsReport,(e=>{n.resolve(bt.mapReport(e))})),yield t.promise,yield i.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield n.promise;return yield i.disconnect(),s}))}static mapReport(e){var t,n,i,s,o,r,a,c,d,l,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let f=0,m=1/0,b=-1/0,y=0,_=1/0,S=-1/0,w=0;v.forEach((e=>{var t,n,i;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=1;const s=null!==(n=e.remote.audio.inbound[0].jitter)&&void 0!==n?n:0,o=null!==(i=e.remote.audio.inbound[0].roundTripTime)&&void 0!==i?i:0;y+=s,w+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),_=Math.min(_,o)}));const C=w/f,I=y/f,k=v[v.length-1],E=et({jitter:1e3*I,rtt:1e3*C,packetsReceived:null!==(i=null===(n=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===n?void 0:n.packetsReceived)&&void 0!==i?i:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:E,jitter:{average:I,max:b,min:m},rtt:{average:C,max:S,min:_},quality:tt(E)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=k.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=k.remote.audio.inbound)||void 0===l?void 0:l[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}export{ht as Call,N as ERROR_TYPE,D as NOTIFICATION_TYPE,bt as PreCallDiagnosis,h as SwEvent,mt as TelnyxRTC};
|