@telnyx/webrtc 2.6.1 → 2.6.2

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 CHANGED
@@ -12,4 +12,4 @@
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */function t(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(i[s[n]]=e[s[n]])}return i}function i(e,t,i,s){return new(i||(i=Promise))((function(n,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}var s="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 o(){if(!s)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(n)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,i){var s=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var n=(e=e||{}).random||(e.rng||o)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t)for(var a=0;a<16;++a)t[s+a]=n[a];return t||function(e,t){var i=t||0,s=r;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(n)}var d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var l=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t,i;t=d,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function n(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(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?o:void 0!==console[s]?n(console,s):void 0!==console.log?n(console,"log"):e)}function a(t,i){for(var n=0;n<s.length;n++){var o=s[n];this[o]=n<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function c(e,i,s){return function(){typeof console!==t&&(a.call(this,i,s),this[e].apply(this,arguments))}}function d(e,t,i){return r(e)||c.apply(this,arguments)}function l(e,i,n){var o,r=this,c="loglevel";function l(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(c)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=n||d,r.getLevel=function(){return o},r.setLevel=function(i,n){if("string"==typeof i&&void 0!==r.levels[i.toUpperCase()]&&(i=r.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+i+";"}catch(e){}}}(i),a.call(r,i,e),typeof console===t&&i<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){l()||r.setLevel(e,!1)},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=l();null==u&&(u=null==i?"WARN":i),r.setLevel(u,!1)}var u=new l,h={};u.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=h[e];return t||(t=h[e]=new l(e,u.getLevel(),u.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=p),u},u.getLoggers=function(){return h},u.default=u,u},e.exports?e.exports=i():t.log=i()}));const u=()=>(new Date).toISOString().replace("T"," ").replace("Z",""),h=l.getLogger("telnyx"),p=h.methodFactory;h.methodFactory=(e,t,i)=>{const s=p(e,t,i);return function(){const e=[u(),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},h.setLevel(h.getLevel());const g="sessId",f="wss://rtc.telnyx.com:14938",m={urls:"stun:stun.telnyx.com:3478"},v={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var b;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(b||(b={}));const y=e=>0===Object.keys(e).length,_=e=>"@telnyx:"+e,w=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){h.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,media:a,participantData:r}},S=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},I=e=>e instanceof Function||"function"==typeof e,C=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,E=/^(ws|wss):\/\//,k=(e,t=null)=>{const{result:i={},error:s}=e;if(s)return{error:s};const{result:n=null}=i;if(null===n)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=n;return o&&"200"!==o?{error:n}:a?k(a,r):{result:n}},x=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),N="GLOBAL",R={},A=(e,t)=>`${e}|${t}`,T=(e,t=N)=>A(e,t)in R,O=(e,t,i=N)=>{const s=A(e,i);s in R||(R[s]=[]),R[s].push(t)},D=(e,t,i=N)=>{const s=function(n){L(e,s,i),t(n)};return s.prototype.targetRef=t,O(e,s,i)},L=(e,t,i=N)=>{if(!T(e,i))return!1;const s=A(e,i);if(I(t)){for(let e=R[s].length-1;e>=0;e--){const i=R[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&R[s].splice(e,1)}}else R[s]=[];return 0===R[s].length&&delete R[s],!0},P=(e,t,i=N,s=!0)=>{const n=s&&i!==N;if(!T(e,i))return n&&P(e,t),!1;const o=A(e,i),r=R[o].length;if(!r)return n&&P(e,t),!1;for(let e=r-1;e>=0;e--)R[o][e](t);return n&&P(e,t),!0},M=e=>{const t=A(e,"");Object.keys(R).filter(e=>0===e.indexOf(t)).forEach(e=>delete R[e])};var U,V,j;!function(e){e.Offer="offer",e.Answer="answer"}(U||(U={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(V||(V={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",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"}(j||(j={}));const B={generic:"event",[j.Display]:"participantData",[j.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},F={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var $,G,H,W,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"}($||($={})),function(e){e.Participant="participant",e.Moderator="moderator"}(G||(G={})),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"}(H||(H={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(W||(W={})),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={}));let q="undefined"!=typeof WebSocket?WebSocket:null;const J=0,z=1,Q=2,Y=3;class X{constructor(e){this.session=e,this._wsClient=null,this._host=f,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${E.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com:14938":f)}get connected(){return this._wsClient&&this._wsClient.readyState===z}get connecting(){return this._wsClient&&this._wsClient.readyState===J}get closing(){return this._wsClient&&this._wsClient.readyState===Q}get closed(){return this._wsClient&&this._wsClient.readyState===Y}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new q(this._host),this._wsClient.onopen=e=>P(b.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>P(b.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>P(b.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=S(e.data);"string"!=typeof s?(this._unsetTimer(s.id),h.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),!K[""+(null===(i=null===(t=null==s?void 0:s.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)]&&P(s.id,s)||P(b.SocketMessage,s,this.session.uuid)):this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,i=new Promise((e,i)=>{if(t.hasOwnProperty("result"))return e();D(t.id,t=>{const{result:s,error:n}=k(t);return n?i(n):e(s)}),this._setTimer(t.id)});return h.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}close(){this._wsClient&&(I(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_setTimer(e){this._timers[e]=setTimeout(()=>{P(e,{error:{code:this.session.timeoutErrorCode,message:"Timeout"}}),this._unsetTimer(e)},1e4)}_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)),P(b.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else h.warn("Unknown message from socket",e)}}const Z=()=>"undefined"==typeof window&&"undefined"!=typeof process,ee=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){if(Z())return null;const i=window[e].getItem(_(t));return S(i)})))("sessionStorage",e),te=(e,t)=>((e,t,s)=>i(void 0,void 0,void 0,(function*(){if(Z())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(_(t),s)})))("sessionStorage",e,t),ie=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){return Z()?null:window[e].removeItem(_(t))})))("sessionStorage",e);const se=e=>navigator.mediaDevices.getUserMedia(e),ne=e=>e&&e instanceof MediaStream,oe=(e,t)=>{const i=C(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},re=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=C(e);if(null===i)return h.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return h.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),ae=e=>{e&&"live"===e.readyState&&e.stop()},ce=e=>{ne(e)&&e.getTracks().forEach(ae),e=null},de=e=>i(void 0,void 0,void 0,(function*(){h.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield se(e)}catch(e){throw h.error("getUserMedia error: ",e),e}})),le=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=yield navigator.mediaDevices.enumerateDevices().catch(e=>(console.error("enumerateDevices",e),[]));e&&(i=i.filter(t=>t.kind===e));if(!(i.length&&i.every(e=>e.deviceId&&e.label))){const t=yield se(((e=null)=>({audio:!e||e===W.AudioIn||e===W.AudioOut,video:!e||e===W.Video}))(e));return ce(t),le(e)}if(!0===t)return i;const s=[];return i=i.filter(({kind:e,groupId:t})=>{if(!t)return!0;const i=`${e}-${t}`;return!s.includes(i)&&(s.push(i),!0)}),i})),ue=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],he=(e,t,s)=>i(void 0,void 0,void 0,(function*(){const i=yield le(s,!0);for(let s=0;s<i.length;s++){const{deviceId:n,label:o}=i[s];if(e===n||t===o)return n}return null})),pe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]})},ge=(e,t,s,n)=>i(void 0,void 0,void 0,(function*(){const{deviceId:i}=n;if(void 0===i&&(e||t)){const i=yield he(e,t,s).catch(e=>null);i&&(n.deviceId={exact:i})}return n})),fe=e=>{const t="\r\n",i=e.split(t),s=i.findIndex(e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e));if(s<0)return e;const n=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),i=e.match(t);return i&&2==i.length?i[1]:null})(i[s]),o=new RegExp("a=fmtp:"+n),r=i.findIndex(e=>o.test(e));return r>=0?/stereo=1;/.test(i[r])||(i[r]+="; stereo=1; sprop-stereo=1"):i[s]+=`\r\na=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},me=e=>/^m=audio/.test(e),ve=e=>/^m=video/.test(e),be=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(me)<s.findIndex(ve))return e;const n=e.split(i),o=n.findIndex(me),r=n.findIndex(ve),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},ye=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=_e(e);return i.includes(t)||s.includes(t)},_e=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(i=>{t[i]=e[i+"Channels"]||[]}),t},we=(e,t=null,i=null)=>{if(!ne(e))return null;let s=[];switch(t){case"audio":s=e.getAudioTracks();break;case"video":s=e.getVideoTracks();break;default:s=e.getTracks()}s.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}})},Se=e=>{we(e,"audio",!0)},Ie=e=>{we(e,"audio",!1)},Ce=e=>{we(e,"audio",null)};function Ee(){try{const{browserInfo:e,name:t,version:i,supportAudio:s,supportVideo:n}=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:s,supportWebRTCVideo:n,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!de}}catch(e){return e.message}}var ke;function xe(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 Ne(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then(()=>{e._playFulfilled=!0}).catch(t=>{console.error("playAudio",t),e._playFulfilled=!0}))}function Re(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"}(ke||(ke={}));const Ae={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number"};class Te extends class{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Ae)e&&i.hasOwnProperty(e)&&(i[Ae[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Oe extends Te{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{}};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class De extends Te{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Le extends Te{toString(){return j.Invite}}class Pe extends Te{toString(){return j.Answer}}class Me extends Te{toString(){return j.Attach}}class Ue extends Te{toString(){return j.Bye}}class Ve extends Te{toString(){return j.Modify}}class je extends Te{toString(){return j.Info}}class Be extends Te{toString(){return j.Broadcast}}class Fe extends Te{toString(){return j.Subscribe}}class $e extends Te{toString(){return j.Unsubscribe}}class Ge{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,h.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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._init()}get isOffer(){return this.type===U.Offer}get isAnswer(){return this.type===U.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){h.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,t)=>{h.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),h.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(h.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){h.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:n}=this.options;n=t,!1===s&&oe(i,n)}createPeerConnection(){return i(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("addstream",e=>{this.options.remoteStream=e.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(e=>(P(b.MediaError,e,this.options.id),null))}))}_init(){return i(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:i=!1}=this.options;if(ne(t)){const s=t.getAudioTracks();h.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(h.info("Local video tracks: ",n),this.isOffer&&"function"==typeof this.instance.addTransceiver){s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTransceiver(e,{direction:"sendrecv",streams:[t]})});const e={direction:"sendrecv",streams:[t]};console.debug("Applying video transceiverParams",e),n.forEach(t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)})}else"function"==typeof this.instance.addTrack?(s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)}),n.forEach(e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)})):this.instance.addStream(t);!1===i&&((e=>{const t=C(e);t&&(t.muted=!0)})(e),oe(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);h.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),h.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>h.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=fe(e.sdp)),this.instance.localDescription&&(e.sdp=be(e.sdp,this.instance.localDescription.sdp));const t=e;return h.info("REMOTE SDP \n","Type: "+e.type,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return i(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:U.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:n,mediaSettings:o}=this.options;return t&&(e.sdp=fe(e.sdp)),i&&s&&n&&(e.sdp=((e,t,i,s)=>{const n=e.split("\r\n");return n.forEach((e,o)=>{/^a=fmtp:\d*/.test(e)?n[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${i};x-google-start-bitrate=${s}`:/^a=mid:(1|video)/.test(e)&&(n[o]+="\r\nb=AS:"+t)}),n.join("\r\n")})(e.sdp,i,s,n)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let i="AS",s=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(i="TIAS",s=1e3*(t>>>0));return-1===e.indexOf("b="+i+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+i+":"+s+"\r\n"):e.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+s+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){I(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(ne(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,i(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:i}=t;const{micLabel:s=""}=t;i&&(i=yield he(i,s,W.AudioIn).catch(e=>null),i&&("boolean"==typeof e&&(e={}),e.deviceId={exact:i}));let{video:n=!1,camId:o}=t;const{camLabel:r=""}=t;return o&&(o=yield he(o,r,W.Video).catch(e=>null),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var t;return de(e)}))}_isOffer(){return this.type===U.Offer}_isAnswer(){return this.type===U.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return h.info("RTC config",t),t}}const He=(e,t)=>{const{contentType:i,canvasType:s,callID:n,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==s&&delete o.memberID;const a={type:B.conferenceUpdate,call:e.calls[n],canvasInfo:We(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:H.LayerInfo},a);P(b.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:H.LayoutInfo},a);P(b.Notification,t,e.uuid);break}}},We=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return S(t)};var Ke="2.6.1";const qe=Ke;class Je{constructor(e,t){this.session=e,this.id="",this.state=$[$.New],this.prevState="",this.channels=[],this.role=G.Participant,this.extension=null,this._state=$.New,this._prevState=$.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._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:s,micId:n,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},F,{audio:l,video:u,iceServers:i,localElement:c,remoteElement:d,micId:n,micLabel:o,camId:r,camLabel:a,speakerId:s,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=xe(this.options.ringtoneFile,"_ringtone"),this._ringback=xe(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}invite(){this.direction=V.Outbound,this.peer=new Ge(U.Offer,this.options),this._registerPeerEvents()}answer(){this.stopRingtone(),this.direction=V.Inbound,this.peer=new Ge(U.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Re(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Re(this._ringback)}hangup(e,t){let i=e||{},s=!1!==t;this.cause=i.cause||"NORMAL_CLEARING",this.causeCode=i.causeCode||16,this.sipCode=i.sipCode||null,this.sipReason=i.sipReason||null,this.sipCallId=i.sip_call_id||null,this.setState($.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState($.Destroy)};if(this.stopRingtone(),s){const e=new Ue({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch(e=>h.error("telnyl_rtc.bye failed!",e)).then(n.bind(this))}else n()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new Ve({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Ve({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Ve({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 Ve({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 Ve({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 je({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},s=new je({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ie(this.options.localStream)}unmuteAudio(){Se(this.options.localStream)}toggleAudioMute(){Ce(this.options.localStream)}setAudioInDevice(e){return i(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 se({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];i.replaceTrack(s),this.options.micId=e;const{localStream:n}=this.options;n.getAudioTracks().forEach(e=>e.stop()),n.getVideoTracks().forEach(e=>t.addTrack(e)),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,we(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,we(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,we(e,"video",null)}setVideoDevice(e){return i(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 se({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;oe(n,t),this.options.camId=e,o.getAudioTracks().forEach(e=>t.addTrack(e)),o.getVideoTracks().forEach(e=>e.stop()),this.options.localStream=t}}))}deaf(){Ie(this.options.remoteStream)}undeaf(){Se(this.options.remoteStream)}toggleDeaf(){Ce(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(this,void 0,void 0,(function*(){if(!this||!this.peer)return void h.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:i}=this.peer,s=i.getSenders();if(!s)return void h.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 n=s.find(({track:{kind:e}})=>e===t);if(n){const i=n.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),h.info("Parameters: ",i),h.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield n.setParameters(i).then(()=>{h.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())}).catch(e=>console.error(e))}else h.error("Could not set bandwidth (reason: no "+t+" 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){switch(this._prevState=this._state,this._state=e,this.state=$[this._state].toLowerCase(),this.prevState=$[this._prevState].toLowerCase(),h.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case $.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case $.Active:setTimeout(()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&re(e,t)},0);break;case $.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case j.Answer:if(this.gotAnswer=!0,this._state>=$.Active)return;this._state>=$.Early&&this.setState($.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case j.Media:if(this._state>=$.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case j.Display:case j.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===V.Inbound?V.Outbound:V.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:s,displayDirection:o};P(b.Notification,r,this.id)||P(b.Notification,r,this.session.uuid);break}case j.Info:case j.Event:{const e=Object.assign(Object.assign({},i),{type:B.generic,call:this});P(b.Notification,e,this.id)||P(b.Notification,e,this.session.uuid);break}case j.Ringing:this.playRingback();break;case j.Bye:this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,t){return i(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return h.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:n=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:i,modChannel:n,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:H.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i)),n&&a===G.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},w(s[e][1])));this._dispatchConferenceUpdate({action:H.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:H.Add,callId:n,index:o},w(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:H.Modify,callId:n,index:o},w(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:H.Delete,callId:n,index:o},w(s)));break;case"clear":this._dispatchConferenceUpdate({action:H.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:n,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 i(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:s,message:n,type:o}=e.data;this._dispatchConferenceUpdate({action:H.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch(e=>{h.error("ConfChat subscription error:",e)});ye(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 i(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;switch(t.contentType){case"layout-info":t.callID=this.id,He(this.session,t);break;default:h.error("Conference-Info unknown contentType",e)}}},i=yield this.session.vertoSubscribe(t).catch(e=>{h.error("ConfInfo subscription error:",e)});ye(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})}_subscribeConferenceModerator(e){return i(this,void 0,void 0,(function*(){const t=(t,i=null,s=null)=>{const n=parseInt(i)||null;this._confControl(e,{command:t,id:n,value:s})},i=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&y(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;switch(t["conf-command"]){case"list-videoLayouts":if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:H.LayoutList,layouts:JSON.parse(e)})}break;default:this._dispatchConferenceUpdate({action:H.ModCmdResponse,command:t["conf-command"],response:t.response})}}},n=yield this.session.vertoSubscribe(s).catch(e=>{h.error("ConfMod subscription error:",e)});ye(n,e)&&(this.role=G.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{i(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,s)=>{i();t("vid-layout",null,s?[e,s]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{i(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{i(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{i(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,s)=>{i(),t("vid-banner",e,encodeURI(s))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,i)=>{t("transfer",e,i)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState($.Active):this.setState($.Held),!0}_handleChangeHoldStateError(e){return h.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=be(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=fe(t));const i={sdp:t,type:U.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState($.Early),this.gotAnswer&&this.setState($.Active)}).catch(e=>{h.error("Call setRemoteDescription Error: ",e),this.hangup()})}_requestAnotherLocalDescription(){I(this.peer.onSdpReadyTwice)?P(b.Error,new Error("SDP without candidates for the second time!"),this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:t,type:i}=e;if(-1===t.indexOf("candidate"))return h.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();this.peer.instance.removeEventListener("icecandidate",this._onIce);let s=null;const n={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,"User-Agent":"Web-"+qe};switch(i){case U.Offer:this.setState($.Requesting),s=new Le(n);break;case U.Answer:this.setState($.Answering),s=!0===this.options.attach?new Me(n):new Pe(n);break;default:return h.error(this.id+" - Unknown local SDP type:",e),this.hangup({},!1)}this._execute(s).then(e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===U.Offer?this.setState($.Trying):this.setState($.Active)}).catch(e=>{h.error(`${this.id} - Sending ${i} error:`,e),this.hangup()})}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(t.localDescription),1e3)),e.candidate?h.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},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:s}=this.options;!1===s&&oe(t,i)})}_onMediaError(e){this._dispatchNotification({type:B.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:B.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(P(b.Notification,e,this.id,!1)||P(b.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:s}=this.options;e||(this.options.id=c()),this.id=this.options.id,t&&!y(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(b.MediaError,this._onMediaError,this.id),I(s)&&O(b.Notification,s.bind(this),this.id),this.setState($.New),h.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ce(e),ce(t),L(b.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),h.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),h.info("Stats stopped")}}Je.setStateTelnyx=e=>{if(e){switch(e._state){case $.Requesting:case $.Recovering:case $.Trying:case $.Early:e.state="connecting";break;case $.Active:e.state="active";break;case $.Held:e.state="held";break;case $.Hangup:case $.Destroy:e.state="done";break;case $.Answering:e.state="ringing";break;case $.New:e.state="new"}return e}};class ze extends Je{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof ze&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return i(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:s,remoteCallerNumber:n,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:this.extension+"-screen",remoteCallerName:s,remoteCallerNumber:n+"-screen",callerName:o+" (Screen)",callerNumber:r+" (Screen)"},e);return this.screenShare=new ze(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof ze&&this.screenShare.hangup()}setAudioOutDevice(e){return i(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&re(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);h.setLevel(2),this._statsInterval=window.setInterval(()=>i(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"],s=["id","type","timestamp"];e.forEach(e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach(i=>{s.includes(i)||(t+=`\t${i}: ${e[i]}\n`)}))}),h.info(t)})),2e3)}}class Qe extends Te{constructor(){super(),this.method=j.GatewayState;this.buildRequest({method:this.method,params:{}})}}class Ye{constructor(e,t){this.code=t,this.message=e}}class Xe{constructor(e){this.session=e}_ack(e,t){const i=new De(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}handleMessage(e){const{session:t}=this,{id:i,method:s,params:n={}}=e,o=null==n?void 0:n.callID,r=null==n?void 0:n.eventChannel,a=null==n?void 0:n.eventType,c=s===j.Attach;if("channelPvtData"===a)return this._handlePvtEvent(n.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(i,s);t.calls[o].hangup({},!1)}const d=()=>{const e={id:o,remoteSdp:n.sdp,destinationNumber:n.callee_id_number,remoteCallerName:n.caller_id_name,remoteCallerNumber:n.caller_id_number,callerName:n.callee_id_name,callerNumber:n.callee_id_number,attach:c,mediaSettings:n.mediaSettings};n.telnyx_call_control_id&&(e.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(e.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(e.telnyxLegId=n.telnyx_leg_id),n.client_state&&(e.clientState=n.client_state);const i=new ze(t,e);return i.nodeId=this.nodeId,i},l=new Qe;switch(s){case j.Punt:t.disconnect();break;case j.Invite:{const e=d();e.playRingtone(),e.setState($.Ringing),this._ack(i,s);break}case j.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState($.Recovering),t.handleMessage(e);break}case j.Event:case"webrtc.event":if(!r)return void h.error("Verto received an unknown event:",n);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?P(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?P(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):P(b.Notification,n,t.uuid);break;case j.Info:n.type=B.generic,P(b.Notification,n,t.uuid);break;case j.ClientReady:this.session.execute(l);break;default:{const i=e&&e.result&&e.result.params&&e.result.params.state?e.result.params.state:"",s=e&&e.params&&e.params.state?e.params.state:"",o=i||s;if(o){switch(o){case K.REGED:Xe.retriedRegister=0,n.type=B.vertoClientReady,P(b.Ready,n,t.uuid);break;case K.UNREGED:case K.NOREG:if(Xe.retriedRegister+=1,5===Xe.retriedRegister){Xe.retriedRegister=0,P(b.Error,new Ye("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout(()=>{this.session.execute(l)},500);break;case K.FAILED:case K.FAIL_WAIT:if(!this.session.hasAutoReconnect()){Xe.retriedConnect=0,P(b.Error,new Ye("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(Xe.retriedConnect+=1,5===Xe.retriedConnect){Xe.retriedConnect=0,P(b.Error,n,t.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},500);break;default:h.warn("GatewayState message unknown method:",e)}break}h.warn("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 i(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:s,laChannel:n,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(s){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:n,data:{liveArray:{command:"bootstrap",context:n,name:o}}})},s={nodeId:this.nodeId,channels:[n],handler:({data:s})=>{const r=u||this._retrieveCallId(s,n);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(n),a.extension=o,a.handleConferenceUpdate(s,e).then(e=>{"INVALID_PACKET"===e&&i()})}}},r=yield t.vertoSubscribe(s).catch(e=>{h.error("liveArray subscription error:",e)});ye(r,n)&&i();break}case"conference-liveArray-part":{let e=null;if(n&&t._existsSubscription(i,n)){const{callId:s=null}=t.subscriptions[i][n];if(e=t.calls[s]||null,null!==s){const i={type:B.conferenceUpdate,action:H.Leave,conferenceName:o,participantId:Number(d),role:l};P(b.Notification,i,s,!1)||P(b.Notification,i,t.uuid),null===e&&L(b.Notification,null,s)}}const s=[n,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then(({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter(e=>!t.includes(e)))}).catch(e=>{h.error("liveArray unsubscribe error:",e)});break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":He(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:H.LogoInfo,logo:e.logoURL};P(b.Notification,t,this.session.uuid);break}}}}Xe.retriedConnect=0,Xe.retriedRegister=0;e.TelnyxRTC=class extends class extends class extends class{constructor(e){if(this.options=e,this.uuid=c(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketCloseOrError=this._onSocketCloseOrError.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new X(this)}get __logger(){return h}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*(e=6,t=2,Math.floor(Math.random()*(t-e+1)+e));var e,t}execute(e){return this._idle?new Promise(t=>this._executeQueue.push({resolve:t,msg:e})):this.connected?this.connection.send(e).catch(e=>{throw e.code&&e.code===this.timeoutErrorCode&&this._closeConnection(),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 x(this.options)}broadcast(e){}disconnect(){return i(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield ie(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return O(e,t,this.uuid),this}off(e,t){return L(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(this.connection=new X(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){P(b.Error,e,this.uuid)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){h.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&M(this.relayProtocol);for(const e in this.subscriptions)M(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],L(e,null,t)):(delete this.subscriptions[e],M(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},I(t)&&O(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(b.SocketOpen,this._onSocketOpen),this.on(b.SocketClose,this._onSocketCloseOrError),this.on(b.SocketError,this._onSocketCloseOrError),this.on(b.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(b.SocketOpen,this._onSocketOpen),this.off(b.SocketClose,this._onSocketCloseOrError),this.off(b.SocketError,this._onSocketCloseOrError),this.off(b.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()}_keepAlive(){if(!0===this._doKeepAlive){if(!1===this._pong)return this._closeConnection();this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),1e4)}}static on(e,t){O(e,t)}static off(e){L(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return i(this,void 0,void 0,(function*(){this.sessionid=yield ee(g),e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield de({audio:e,video:t});return ce(i),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return i(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach(e=>this.calls[e].setState($.Purge)),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise((t,i)=>{if(D(b.SpeedTest,i=>{const{upDur:s,downDur:n}=i,o=n?8*e/(n/1e3)/1024:0;t({upDur:s,downDur:n,upKps:(s?8*e/(s/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 s=e/1024;e%1024&&s++;const n=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw("#SPB "+n);this.executeRaw("#SPE")})}getDevices(){return le().catch(e=>(P(b.MediaError,e,this.uuid),[]))}getVideoDevices(){return le(W.Video).catch(e=>(P(b.MediaError,e,this.uuid),[]))}getAudioInDevices(){return le(W.AudioIn).catch(e=>(P(b.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return le(W.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),P(b.MediaError,e,this.uuid),[]))}validateDeviceId(e,t,i){return he(e,t,i)}getDeviceResolutions(e){return i(this,void 0,void 0,(function*(){try{return yield(e=>i(void 0,void 0,void 0,(function*(){const t=[],i=yield de({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<ue.length;e++){const[i,n]=ue[e];(yield s.applyConstraints({width:{exact:i},height:{exact:n}}).then(()=>!0).catch(()=>!1))&&t.push({resolution:`${i}x${n}`,width:i,height:n})}return ce(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:s}=e,n=t(e,["micId","micLabel"]);return pe(n),this._audioConstraints=yield ge(i,s,"audioinput",n),this.micId=i,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:i,camLabel:s}=e,n=t(e,["camId","camLabel"]);return pe(n),this._videoConstraints=yield ge(i,s,"videoinput",n),this.camId=i,this.camLabel=s,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){this._iceServers="boolean"==typeof e?e?[{urls:["stun:stun.l.google.com:19302"]}]:[]:e||[v,m]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=C(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=C(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error("Invalid channel for broadcast: "+t);const s=new Be({sessid:this.sessionid,eventChannel:t,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(e=>e)}vertoSubscribe({nodeId:e,channels:t=[],handler:s}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter(e=>e&&!this._existsSubscription(this.relayProtocol,e))).length)return{};const i=new Fe({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=_e(n);return o.length&&o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),r.forEach(e=>this._addSubscription(this.relayProtocol,s,e)),n}))}vertoUnsubscribe({nodeId:e,channels:t=[]}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter(e=>e&&this._existsSubscription(this.relayProtocol,e))).length)return{};const i=new $e({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:n=[],notSubscribed:o=[]}=_e(s);return n.forEach(e=>this._removeSubscription(this.relayProtocol,e)),o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),s}))}static telnyxStateCall(e){return ze.setStateTelnyx(e)}}{constructor(){super(...arguments),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990}validateOptions(){return x(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new ze(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:i,login_token:s,userVariables:n,autoReconnect:o=!0}=this.options,r=new Oe(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,te(g,this.sessionid))}))}_onSocketMessage(e){new Xe(this).handleMessage(e)}}{constructor(e){super(e),console.log("SDK version: 2.6.1")}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ee()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ke.not_supported},{browserName:"Firefox",supported:ke.not_supported},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",features:["audio"],supported:ke.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",features:["audio"],supported:ke.partial}]}]}},Object.defineProperty(e,"__esModule",{value:!0})}));
15
+ ***************************************************************************** */function t(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(i[s[n]]=e[s[n]])}return i}function i(e,t,i,s){return new(i||(i=Promise))((function(n,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}var s="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 o(){if(!s)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(n)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,i){var s=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var n=(e=e||{}).random||(e.rng||o)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t)for(var a=0;a<16;++a)t[s+a]=n[a];return t||function(e,t){var i=t||0,s=r;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(n)}var d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var l=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t,i;t=d,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function n(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(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?o:void 0!==console[s]?n(console,s):void 0!==console.log?n(console,"log"):e)}function a(t,i){for(var n=0;n<s.length;n++){var o=s[n];this[o]=n<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function c(e,i,s){return function(){typeof console!==t&&(a.call(this,i,s),this[e].apply(this,arguments))}}function d(e,t,i){return r(e)||c.apply(this,arguments)}function l(e,i,n){var o,r=this,c="loglevel";function l(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(c)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=n||d,r.getLevel=function(){return o},r.setLevel=function(i,n){if("string"==typeof i&&void 0!==r.levels[i.toUpperCase()]&&(i=r.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+i+";"}catch(e){}}}(i),a.call(r,i,e),typeof console===t&&i<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){l()||r.setLevel(e,!1)},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=l();null==u&&(u=null==i?"WARN":i),r.setLevel(u,!1)}var u=new l,h={};u.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=h[e];return t||(t=h[e]=new l(e,u.getLevel(),u.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=p),u},u.getLoggers=function(){return h},u.default=u,u},e.exports?e.exports=i():t.log=i()}));const u=()=>(new Date).toISOString().replace("T"," ").replace("Z",""),h=l.getLogger("telnyx"),p=h.methodFactory;h.methodFactory=(e,t,i)=>{const s=p(e,t,i);return function(){const e=[u(),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},h.setLevel(h.getLevel());const g="sessId",f="wss://rtc.telnyx.com:14938",m={urls:"stun:stun.telnyx.com:3478"},v={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var b;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(b||(b={}));const y=e=>0===Object.keys(e).length,_=e=>"@telnyx:"+e,w=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){h.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,media:a,participantData:r}},S=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},I=e=>e instanceof Function||"function"==typeof e,C=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,E=/^(ws|wss):\/\//,k=(e,t=null)=>{const{result:i={},error:s}=e;if(s)return{error:s};const{result:n=null}=i;if(null===n)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=n;return o&&"200"!==o?{error:n}:a?k(a,r):{result:n}},x=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),N="GLOBAL",R={},A=(e,t)=>`${e}|${t}`,T=(e,t=N)=>A(e,t)in R,O=(e,t,i=N)=>{const s=A(e,i);s in R||(R[s]=[]),R[s].push(t)},D=(e,t,i=N)=>{const s=function(n){L(e,s,i),t(n)};return s.prototype.targetRef=t,O(e,s,i)},L=(e,t,i=N)=>{if(!T(e,i))return!1;const s=A(e,i);if(I(t)){for(let e=R[s].length-1;e>=0;e--){const i=R[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&R[s].splice(e,1)}}else R[s]=[];return 0===R[s].length&&delete R[s],!0},P=(e,t,i=N,s=!0)=>{const n=s&&i!==N;if(!T(e,i))return n&&P(e,t),!1;const o=A(e,i),r=R[o].length;if(!r)return n&&P(e,t),!1;for(let e=r-1;e>=0;e--)R[o][e](t);return n&&P(e,t),!0},M=e=>{const t=A(e,"");Object.keys(R).filter(e=>0===e.indexOf(t)).forEach(e=>delete R[e])};var U,V,j;!function(e){e.Offer="offer",e.Answer="answer"}(U||(U={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(V||(V={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",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"}(j||(j={}));const B={generic:"event",[j.Display]:"participantData",[j.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},F={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var $,G,H,W,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"}($||($={})),function(e){e.Participant="participant",e.Moderator="moderator"}(G||(G={})),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"}(H||(H={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(W||(W={})),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={}));let q="undefined"!=typeof WebSocket?WebSocket:null;const J=0,z=1,Q=2,Y=3;class X{constructor(e){this.session=e,this._wsClient=null,this._host=f,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${E.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com:14938":f)}get connected(){return this._wsClient&&this._wsClient.readyState===z}get connecting(){return this._wsClient&&this._wsClient.readyState===J}get closing(){return this._wsClient&&this._wsClient.readyState===Q}get closed(){return this._wsClient&&this._wsClient.readyState===Y}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new q(this._host),this._wsClient.onopen=e=>P(b.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>P(b.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>P(b.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=S(e.data);"string"!=typeof s?(this._unsetTimer(s.id),h.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),!K[""+(null===(i=null===(t=null==s?void 0:s.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)]&&P(s.id,s)||P(b.SocketMessage,s,this.session.uuid)):this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,i=new Promise((e,i)=>{if(t.hasOwnProperty("result"))return e();D(t.id,t=>{const{result:s,error:n}=k(t);return n?i(n):e(s)}),this._setTimer(t.id)});return h.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}close(){this._wsClient&&(I(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_setTimer(e){this._timers[e]=setTimeout(()=>{P(e,{error:{code:this.session.timeoutErrorCode,message:"Timeout"}}),this._unsetTimer(e)},1e4)}_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)),P(b.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else h.warn("Unknown message from socket",e)}}const Z=()=>"undefined"==typeof window&&"undefined"!=typeof process,ee=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){if(Z())return null;const i=window[e].getItem(_(t));return S(i)})))("sessionStorage",e),te=(e,t)=>((e,t,s)=>i(void 0,void 0,void 0,(function*(){if(Z())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(_(t),s)})))("sessionStorage",e,t),ie=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){return Z()?null:window[e].removeItem(_(t))})))("sessionStorage",e);const se=e=>navigator.mediaDevices.getUserMedia(e),ne=e=>e&&e instanceof MediaStream,oe=(e,t)=>{const i=C(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},re=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=C(e);if(null===i)return h.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return h.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),ae=e=>{e&&"live"===e.readyState&&e.stop()},ce=e=>{ne(e)&&e.getTracks().forEach(ae),e=null},de=e=>i(void 0,void 0,void 0,(function*(){h.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield se(e)}catch(e){throw h.error("getUserMedia error: ",e),e}})),le=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=yield navigator.mediaDevices.enumerateDevices().catch(e=>(console.error("enumerateDevices",e),[]));e&&(i=i.filter(t=>t.kind===e));if(!(i.length&&i.every(e=>e.deviceId&&e.label))){const t=yield se(((e=null)=>({audio:!e||e===W.AudioIn||e===W.AudioOut,video:!e||e===W.Video}))(e));return ce(t),le(e)}if(!0===t)return i;const s=[];return i=i.filter(({kind:e,groupId:t})=>{if(!t)return!0;const i=`${e}-${t}`;return!s.includes(i)&&(s.push(i),!0)}),i})),ue=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],he=(e,t,s)=>i(void 0,void 0,void 0,(function*(){const i=yield le(s,!0);for(let s=0;s<i.length;s++){const{deviceId:n,label:o}=i[s];if(e===n||t===o)return n}return null})),pe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]})},ge=(e,t,s,n)=>i(void 0,void 0,void 0,(function*(){const{deviceId:i}=n;if(void 0===i&&(e||t)){const i=yield he(e,t,s).catch(e=>null);i&&(n.deviceId={exact:i})}return n})),fe=e=>{const t="\r\n",i=e.split(t),s=i.findIndex(e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e));if(s<0)return e;const n=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),i=e.match(t);return i&&2==i.length?i[1]:null})(i[s]),o=new RegExp("a=fmtp:"+n),r=i.findIndex(e=>o.test(e));return r>=0?/stereo=1;/.test(i[r])||(i[r]+="; stereo=1; sprop-stereo=1"):i[s]+=`\r\na=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},me=e=>/^m=audio/.test(e),ve=e=>/^m=video/.test(e),be=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(me)<s.findIndex(ve))return e;const n=e.split(i),o=n.findIndex(me),r=n.findIndex(ve),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},ye=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=_e(e);return i.includes(t)||s.includes(t)},_e=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(i=>{t[i]=e[i+"Channels"]||[]}),t},we=(e,t=null,i=null)=>{if(!ne(e))return null;let s=[];switch(t){case"audio":s=e.getAudioTracks();break;case"video":s=e.getVideoTracks();break;default:s=e.getTracks()}s.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}})},Se=e=>{we(e,"audio",!0)},Ie=e=>{we(e,"audio",!1)},Ce=e=>{we(e,"audio",null)};function Ee(){try{const{browserInfo:e,name:t,version:i,supportAudio:s,supportVideo:n}=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:s,supportWebRTCVideo:n,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!de}}catch(e){return e.message}}var ke;function xe(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 Ne(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then(()=>{e._playFulfilled=!0}).catch(t=>{console.error("playAudio",t),e._playFulfilled=!0}))}function Re(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"}(ke||(ke={}));const Ae={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number"};class Te extends class{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Ae)e&&i.hasOwnProperty(e)&&(i[Ae[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Oe extends Te{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{}};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class De extends Te{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Le extends Te{toString(){return j.Invite}}class Pe extends Te{toString(){return j.Answer}}class Me extends Te{toString(){return j.Attach}}class Ue extends Te{toString(){return j.Bye}}class Ve extends Te{toString(){return j.Modify}}class je extends Te{toString(){return j.Info}}class Be extends Te{toString(){return j.Broadcast}}class Fe extends Te{toString(){return j.Subscribe}}class $e extends Te{toString(){return j.Unsubscribe}}class Ge{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,h.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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._init()}get isOffer(){return this.type===U.Offer}get isAnswer(){return this.type===U.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){h.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,t)=>{h.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),h.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(h.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){h.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:n}=this.options;n=t,!1===s&&oe(i,n)}createPeerConnection(){return i(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("addstream",e=>{this.options.remoteStream=e.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(e=>(P(b.MediaError,e,this.options.id),null))}))}_init(){return i(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:i=!1}=this.options;if(ne(t)){const s=t.getAudioTracks();h.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(h.info("Local video tracks: ",n),this.isOffer&&"function"==typeof this.instance.addTransceiver){s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTransceiver(e,{direction:"sendrecv",streams:[t]})});const e={direction:"sendrecv",streams:[t]};console.debug("Applying video transceiverParams",e),n.forEach(t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)})}else"function"==typeof this.instance.addTrack?(s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)}),n.forEach(e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)})):this.instance.addStream(t);!1===i&&((e=>{const t=C(e);t&&(t.muted=!0)})(e),oe(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);h.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),h.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>h.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=fe(e.sdp)),this.instance.localDescription&&(e.sdp=be(e.sdp,this.instance.localDescription.sdp));const t=e;return h.info("REMOTE SDP \n","Type: "+e.type,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return i(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:U.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:n,mediaSettings:o}=this.options;return t&&(e.sdp=fe(e.sdp)),i&&s&&n&&(e.sdp=((e,t,i,s)=>{const n=e.split("\r\n");return n.forEach((e,o)=>{/^a=fmtp:\d*/.test(e)?n[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${i};x-google-start-bitrate=${s}`:/^a=mid:(1|video)/.test(e)&&(n[o]+="\r\nb=AS:"+t)}),n.join("\r\n")})(e.sdp,i,s,n)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let i="AS",s=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(i="TIAS",s=1e3*(t>>>0));return-1===e.indexOf("b="+i+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+i+":"+s+"\r\n"):e.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+s+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){I(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(ne(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,i(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:i}=t;const{micLabel:s=""}=t;i&&(i=yield he(i,s,W.AudioIn).catch(e=>null),i&&("boolean"==typeof e&&(e={}),e.deviceId={exact:i}));let{video:n=!1,camId:o}=t;const{camLabel:r=""}=t;return o&&(o=yield he(o,r,W.Video).catch(e=>null),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var t;return de(e)}))}_isOffer(){return this.type===U.Offer}_isAnswer(){return this.type===U.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return h.info("RTC config",t),t}}const He=(e,t)=>{const{contentType:i,canvasType:s,callID:n,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==s&&delete o.memberID;const a={type:B.conferenceUpdate,call:e.calls[n],canvasInfo:We(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:H.LayerInfo},a);P(b.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:H.LayoutInfo},a);P(b.Notification,t,e.uuid);break}}},We=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return S(t)};var Ke="2.6.2";const qe=Ke;class Je{constructor(e,t){this.session=e,this.id="",this.state=$[$.New],this.prevState="",this.channels=[],this.role=G.Participant,this.extension=null,this._state=$.New,this._prevState=$.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._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:s,micId:n,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},F,{audio:l,video:u,iceServers:i,localElement:c,remoteElement:d,micId:n,micLabel:o,camId:r,camLabel:a,speakerId:s,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=xe(this.options.ringtoneFile,"_ringtone"),this._ringback=xe(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}invite(){this.direction=V.Outbound,this.peer=new Ge(U.Offer,this.options),this._registerPeerEvents()}answer(){this.stopRingtone(),this.direction=V.Inbound,this.peer=new Ge(U.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Re(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Re(this._ringback)}hangup(e,t){let i=e||{},s=!1!==t;this.cause=i.cause||"NORMAL_CLEARING",this.causeCode=i.causeCode||16,this.sipCode=i.sipCode||null,this.sipReason=i.sipReason||null,this.sipCallId=i.sip_call_id||null,this.setState($.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState($.Destroy)};if(this.stopRingtone(),s){const e=new Ue({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch(e=>{h.error("telnyl_rtc.bye failed!",e),P(b.Error,e,this.session.uuid)}).then(n.bind(this))}else n()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new Ve({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Ve({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Ve({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 Ve({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 Ve({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 je({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},s=new je({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ie(this.options.localStream)}unmuteAudio(){Se(this.options.localStream)}toggleAudioMute(){Ce(this.options.localStream)}setAudioInDevice(e){return i(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 se({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];i.replaceTrack(s),this.options.micId=e;const{localStream:n}=this.options;n.getAudioTracks().forEach(e=>e.stop()),n.getVideoTracks().forEach(e=>t.addTrack(e)),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,we(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,we(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,we(e,"video",null)}setVideoDevice(e){return i(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 se({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;oe(n,t),this.options.camId=e,o.getAudioTracks().forEach(e=>t.addTrack(e)),o.getVideoTracks().forEach(e=>e.stop()),this.options.localStream=t}}))}deaf(){Ie(this.options.remoteStream)}undeaf(){Se(this.options.remoteStream)}toggleDeaf(){Ce(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(this,void 0,void 0,(function*(){if(!this||!this.peer)return void h.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:i}=this.peer,s=i.getSenders();if(!s)return void h.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 n=s.find(({track:{kind:e}})=>e===t);if(n){const i=n.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),h.info("Parameters: ",i),h.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield n.setParameters(i).then(()=>{h.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())}).catch(e=>console.error(e))}else h.error("Could not set bandwidth (reason: no "+t+" 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){switch(this._prevState=this._state,this._state=e,this.state=$[this._state].toLowerCase(),this.prevState=$[this._prevState].toLowerCase(),h.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case $.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case $.Active:setTimeout(()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&re(e,t)},0);break;case $.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case j.Answer:if(this.gotAnswer=!0,this._state>=$.Active)return;this._state>=$.Early&&this.setState($.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case j.Media:if(this._state>=$.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case j.Display:case j.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===V.Inbound?V.Outbound:V.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:s,displayDirection:o};P(b.Notification,r,this.id)||P(b.Notification,r,this.session.uuid);break}case j.Info:case j.Event:{const e=Object.assign(Object.assign({},i),{type:B.generic,call:this});P(b.Notification,e,this.id)||P(b.Notification,e,this.session.uuid);break}case j.Ringing:this.playRingback();break;case j.Bye:this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,t){return i(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return h.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:n=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:i,modChannel:n,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:H.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i)),n&&a===G.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},w(s[e][1])));this._dispatchConferenceUpdate({action:H.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:H.Add,callId:n,index:o},w(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:H.Modify,callId:n,index:o},w(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:H.Delete,callId:n,index:o},w(s)));break;case"clear":this._dispatchConferenceUpdate({action:H.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:n,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 i(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:s,message:n,type:o}=e.data;this._dispatchConferenceUpdate({action:H.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch(e=>{h.error("ConfChat subscription error:",e)});ye(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 i(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;switch(t.contentType){case"layout-info":t.callID=this.id,He(this.session,t);break;default:h.error("Conference-Info unknown contentType",e)}}},i=yield this.session.vertoSubscribe(t).catch(e=>{h.error("ConfInfo subscription error:",e)});ye(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})}_subscribeConferenceModerator(e){return i(this,void 0,void 0,(function*(){const t=(t,i=null,s=null)=>{const n=parseInt(i)||null;this._confControl(e,{command:t,id:n,value:s})},i=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&y(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;switch(t["conf-command"]){case"list-videoLayouts":if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:H.LayoutList,layouts:JSON.parse(e)})}break;default:this._dispatchConferenceUpdate({action:H.ModCmdResponse,command:t["conf-command"],response:t.response})}}},n=yield this.session.vertoSubscribe(s).catch(e=>{h.error("ConfMod subscription error:",e)});ye(n,e)&&(this.role=G.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{i(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,s)=>{i();t("vid-layout",null,s?[e,s]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{i(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{i(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{i(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,s)=>{i(),t("vid-banner",e,encodeURI(s))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,i)=>{t("transfer",e,i)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState($.Active):this.setState($.Held),!0}_handleChangeHoldStateError(e){return h.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=be(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=fe(t));const i={sdp:t,type:U.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState($.Early),this.gotAnswer&&this.setState($.Active)}).catch(e=>{h.error("Call setRemoteDescription Error: ",e),this.hangup()})}_requestAnotherLocalDescription(){I(this.peer.onSdpReadyTwice)?P(b.Error,new Error("SDP without candidates for the second time!"),this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:t,type:i}=e;if(-1===t.indexOf("candidate"))return h.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();this.peer.instance.removeEventListener("icecandidate",this._onIce);let s=null;const n={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,"User-Agent":"Web-"+qe};switch(i){case U.Offer:this.setState($.Requesting),s=new Le(n);break;case U.Answer:this.setState($.Answering),s=!0===this.options.attach?new Me(n):new Pe(n);break;default:return h.error(this.id+" - Unknown local SDP type:",e),this.hangup({},!1)}this._execute(s).then(e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===U.Offer?this.setState($.Trying):this.setState($.Active)}).catch(e=>{h.error(`${this.id} - Sending ${i} error:`,e),this.hangup()})}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(t.localDescription),1e3)),e.candidate?h.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},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:s}=this.options;!1===s&&oe(t,i)})}_onMediaError(e){this._dispatchNotification({type:B.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:B.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(P(b.Notification,e,this.id,!1)||P(b.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:s}=this.options;e||(this.options.id=c()),this.id=this.options.id,t&&!y(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(b.MediaError,this._onMediaError,this.id),I(s)&&O(b.Notification,s.bind(this),this.id),this.setState($.New),h.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ce(e),ce(t),L(b.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),h.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),h.info("Stats stopped")}}Je.setStateTelnyx=e=>{if(e){switch(e._state){case $.Requesting:case $.Recovering:case $.Trying:case $.Early:e.state="connecting";break;case $.Active:e.state="active";break;case $.Held:e.state="held";break;case $.Hangup:case $.Destroy:e.state="done";break;case $.Answering:e.state="ringing";break;case $.New:e.state="new"}return e}};class ze extends Je{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof ze&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return i(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:s,remoteCallerNumber:n,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:this.extension+"-screen",remoteCallerName:s,remoteCallerNumber:n+"-screen",callerName:o+" (Screen)",callerNumber:r+" (Screen)"},e);return this.screenShare=new ze(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof ze&&this.screenShare.hangup()}setAudioOutDevice(e){return i(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&re(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);h.setLevel(2),this._statsInterval=window.setInterval(()=>i(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"],s=["id","type","timestamp"];e.forEach(e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach(i=>{s.includes(i)||(t+=`\t${i}: ${e[i]}\n`)}))}),h.info(t)})),2e3)}}class Qe extends Te{constructor(){super(),this.method=j.GatewayState;this.buildRequest({method:this.method,params:{}})}}class Ye{constructor(e,t){this.code=t,this.message=e}}class Xe{constructor(e){this.session=e}_ack(e,t){const i=new De(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}handleMessage(e){const{session:t}=this,{id:i,method:s,params:n={}}=e,o=null==n?void 0:n.callID,r=null==n?void 0:n.eventChannel,a=null==n?void 0:n.eventType,c=s===j.Attach;if("channelPvtData"===a)return this._handlePvtEvent(n.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(i,s);t.calls[o].hangup({},!1)}const d=()=>{const e={id:o,remoteSdp:n.sdp,destinationNumber:n.callee_id_number,remoteCallerName:n.caller_id_name,remoteCallerNumber:n.caller_id_number,callerName:n.callee_id_name,callerNumber:n.callee_id_number,attach:c,mediaSettings:n.mediaSettings};n.telnyx_call_control_id&&(e.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(e.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(e.telnyxLegId=n.telnyx_leg_id),n.client_state&&(e.clientState=n.client_state);const i=new ze(t,e);return i.nodeId=this.nodeId,i},l=new Qe;switch(s){case j.Punt:t.disconnect();break;case j.Invite:{const e=d();e.playRingtone(),e.setState($.Ringing),this._ack(i,s);break}case j.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState($.Recovering),t.handleMessage(e);break}case j.Event:case"webrtc.event":if(!r)return void h.error("Verto received an unknown event:",n);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?P(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?P(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):P(b.Notification,n,t.uuid);break;case j.Info:n.type=B.generic,P(b.Notification,n,t.uuid);break;case j.ClientReady:this.session.execute(l);break;default:{const i=e&&e.result&&e.result.params&&e.result.params.state?e.result.params.state:"",s=e&&e.params&&e.params.state?e.params.state:"",o=i||s;if(o){switch(o){case K.REGED:Xe.retriedRegister=0,n.type=B.vertoClientReady,P(b.Ready,n,t.uuid);break;case K.UNREGED:case K.NOREG:if(Xe.retriedRegister+=1,5===Xe.retriedRegister){Xe.retriedRegister=0,P(b.Error,new Ye("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout(()=>{this.session.execute(l)},500);break;case K.FAILED:case K.FAIL_WAIT:if(!this.session.hasAutoReconnect()){Xe.retriedConnect=0,P(b.Error,new Ye("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(Xe.retriedConnect+=1,5===Xe.retriedConnect){Xe.retriedConnect=0,P(b.Error,n,t.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},500);break;default:h.warn("GatewayState message unknown method:",e)}break}h.warn("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 i(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:s,laChannel:n,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(s){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:n,data:{liveArray:{command:"bootstrap",context:n,name:o}}})},s={nodeId:this.nodeId,channels:[n],handler:({data:s})=>{const r=u||this._retrieveCallId(s,n);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(n),a.extension=o,a.handleConferenceUpdate(s,e).then(e=>{"INVALID_PACKET"===e&&i()})}}},r=yield t.vertoSubscribe(s).catch(e=>{h.error("liveArray subscription error:",e)});ye(r,n)&&i();break}case"conference-liveArray-part":{let e=null;if(n&&t._existsSubscription(i,n)){const{callId:s=null}=t.subscriptions[i][n];if(e=t.calls[s]||null,null!==s){const i={type:B.conferenceUpdate,action:H.Leave,conferenceName:o,participantId:Number(d),role:l};P(b.Notification,i,s,!1)||P(b.Notification,i,t.uuid),null===e&&L(b.Notification,null,s)}}const s=[n,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then(({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter(e=>!t.includes(e)))}).catch(e=>{h.error("liveArray unsubscribe error:",e)});break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":He(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:H.LogoInfo,logo:e.logoURL};P(b.Notification,t,this.session.uuid);break}}}}Xe.retriedConnect=0,Xe.retriedRegister=0;e.TelnyxRTC=class extends class extends class extends class{constructor(e){if(this.options=e,this.uuid=c(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketCloseOrError=this._onSocketCloseOrError.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new X(this)}get __logger(){return h}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*(e=6,t=2,Math.floor(Math.random()*(t-e+1)+e));var e,t}execute(e){return this._idle?new Promise(t=>this._executeQueue.push({resolve:t,msg:e})):this.connected?this.connection.send(e).catch(e=>{throw e.code&&e.code===this.timeoutErrorCode&&this._closeConnection(),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 x(this.options)}broadcast(e){}disconnect(){return i(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield ie(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return O(e,t,this.uuid),this}off(e,t){return L(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(this.connection=new X(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){P(b.Error,e,this.uuid)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){h.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&M(this.relayProtocol);for(const e in this.subscriptions)M(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],L(e,null,t)):(delete this.subscriptions[e],M(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},I(t)&&O(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(b.SocketOpen,this._onSocketOpen),this.on(b.SocketClose,this._onSocketCloseOrError),this.on(b.SocketError,this._onSocketCloseOrError),this.on(b.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(b.SocketOpen,this._onSocketOpen),this.off(b.SocketClose,this._onSocketCloseOrError),this.off(b.SocketError,this._onSocketCloseOrError),this.off(b.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()}_keepAlive(){if(!0===this._doKeepAlive){if(!1===this._pong)return this._closeConnection();this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),1e4)}}static on(e,t){O(e,t)}static off(e){L(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return i(this,void 0,void 0,(function*(){this.sessionid=yield ee(g),e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield de({audio:e,video:t});return ce(i),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return i(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach(e=>this.calls[e].setState($.Purge)),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise((t,i)=>{if(D(b.SpeedTest,i=>{const{upDur:s,downDur:n}=i,o=n?8*e/(n/1e3)/1024:0;t({upDur:s,downDur:n,upKps:(s?8*e/(s/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 s=e/1024;e%1024&&s++;const n=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw("#SPB "+n);this.executeRaw("#SPE")})}getDevices(){return le().catch(e=>(P(b.MediaError,e,this.uuid),[]))}getVideoDevices(){return le(W.Video).catch(e=>(P(b.MediaError,e,this.uuid),[]))}getAudioInDevices(){return le(W.AudioIn).catch(e=>(P(b.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return le(W.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),P(b.MediaError,e,this.uuid),[]))}validateDeviceId(e,t,i){return he(e,t,i)}getDeviceResolutions(e){return i(this,void 0,void 0,(function*(){try{return yield(e=>i(void 0,void 0,void 0,(function*(){const t=[],i=yield de({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<ue.length;e++){const[i,n]=ue[e];(yield s.applyConstraints({width:{exact:i},height:{exact:n}}).then(()=>!0).catch(()=>!1))&&t.push({resolution:`${i}x${n}`,width:i,height:n})}return ce(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:s}=e,n=t(e,["micId","micLabel"]);return pe(n),this._audioConstraints=yield ge(i,s,"audioinput",n),this.micId=i,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:i,camLabel:s}=e,n=t(e,["camId","camLabel"]);return pe(n),this._videoConstraints=yield ge(i,s,"videoinput",n),this.camId=i,this.camLabel=s,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){this._iceServers="boolean"==typeof e?e?[{urls:["stun:stun.l.google.com:19302"]}]:[]:e||[v,m]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=C(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=C(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error("Invalid channel for broadcast: "+t);const s=new Be({sessid:this.sessionid,eventChannel:t,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(e=>e)}vertoSubscribe({nodeId:e,channels:t=[],handler:s}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter(e=>e&&!this._existsSubscription(this.relayProtocol,e))).length)return{};const i=new Fe({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=_e(n);return o.length&&o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),r.forEach(e=>this._addSubscription(this.relayProtocol,s,e)),n}))}vertoUnsubscribe({nodeId:e,channels:t=[]}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter(e=>e&&this._existsSubscription(this.relayProtocol,e))).length)return{};const i=new $e({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:n=[],notSubscribed:o=[]}=_e(s);return n.forEach(e=>this._removeSubscription(this.relayProtocol,e)),o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),s}))}static telnyxStateCall(e){return ze.setStateTelnyx(e)}}{constructor(){super(...arguments),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990}validateOptions(){return x(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new ze(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:i,login_token:s,userVariables:n,autoReconnect:o=!0}=this.options,r=new Oe(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,te(g,this.sessionid))}))}_onSocketMessage(e){new Xe(this).handleMessage(e)}}{constructor(e){super(e),console.log("SDK version: 2.6.2")}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ee()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ke.not_supported},{browserName:"Firefox",supported:ke.not_supported},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",features:["audio"],supported:ke.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",features:["audio"],supported:ke.partial}]}]}},Object.defineProperty(e,"__esModule",{value:!0})}));
package/lib/bundle.mjs CHANGED
@@ -12,4 +12,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
14
  ***************************************************************************** */
15
- function e(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(i[s[n]]=e[s[n]])}return i}function t(e,t,i,s){return new(i||(i=Promise))((function(n,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),s=new Uint8Array(16);function n(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var s=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||n)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[s+a]=r[a];return t||function(e,t){var i=t||0,s=o;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(r)}var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var l=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t,i;t=c,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function n(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(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?o:void 0!==console[s]?n(console,s):void 0!==console.log?n(console,"log"):e)}function a(t,i){for(var n=0;n<s.length;n++){var o=s[n];this[o]=n<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function c(e,i,s){return function(){typeof console!==t&&(a.call(this,i,s),this[e].apply(this,arguments))}}function l(e,t,i){return r(e)||c.apply(this,arguments)}function d(e,i,n){var o,r=this,c="loglevel";function d(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(c)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=n||l,r.getLevel=function(){return o},r.setLevel=function(i,n){if("string"==typeof i&&void 0!==r.levels[i.toUpperCase()]&&(i=r.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+i+";"}catch(e){}}}(i),a.call(r,i,e),typeof console===t&&i<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){d()||r.setLevel(e,!1)},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=d();null==u&&(u=null==i?"WARN":i),r.setLevel(u,!1)}var u=new d,h={};u.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=h[e];return t||(t=h[e]=new d(e,u.getLevel(),u.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=p),u},u.getLoggers=function(){return h},u.default=u,u},e.exports?e.exports=i():t.log=i()}));const d=()=>(new Date).toISOString().replace("T"," ").replace("Z",""),u=l.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,i)=>{const s=h(e,t,i);return function(){const e=[d(),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},u.setLevel(u.getLevel());const p={urls:"stun:stun.telnyx.com:3478"},g={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var f;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(f||(f={}));const m=e=>0===Object.keys(e).length,v=e=>"@telnyx:"+e,b=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){u.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,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,w=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,S=/^(ws|wss):\/\//,I=(e,t=null)=>{const{result:i={},error:s}=e;if(s)return{error:s};const{result:n=null}=i;if(null===n)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=n;return o&&"200"!==o?{error:n}:a?I(a,r):{result:n}},C=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),E={},k=(e,t)=>`${e}|${t}`,x=(e,t="GLOBAL")=>k(e,t)in E,A=(e,t,i="GLOBAL")=>{const s=k(e,i);s in E||(E[s]=[]),E[s].push(t)},N=(e,t,i="GLOBAL")=>{const s=function(n){R(e,s,i),t(n)};return s.prototype.targetRef=t,A(e,s,i)},R=(e,t,i="GLOBAL")=>{if(!x(e,i))return!1;const s=k(e,i);if(_(t)){for(let e=E[s].length-1;e>=0;e--){const i=E[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&E[s].splice(e,1)}}else E[s]=[];return 0===E[s].length&&delete E[s],!0},T=(e,t,i="GLOBAL",s=!0)=>{const n=s&&"GLOBAL"!==i;if(!x(e,i))return n&&T(e,t),!1;const o=k(e,i),r=E[o].length;if(!r)return n&&T(e,t),!1;for(let e=r-1;e>=0;e--)E[o][e](t);return n&&T(e,t),!0},O=e=>{const t=k(e,"");Object.keys(E).filter(e=>0===e.indexOf(t)).forEach(e=>delete E[e])};var D,L,P;!function(e){e.Offer="offer",e.Answer="answer"}(D||(D={})),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.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"}(P||(P={}));const M={generic:"event",[P.Display]:"participantData",[P.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},U={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var B,V,j,F,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"}(B||(B={})),function(e){e.Participant="participant",e.Moderator="moderator"}(V||(V={})),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"}(j||(j={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(F||(F={})),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={}));let $="undefined"!=typeof WebSocket?WebSocket:null;const H=0,K=1,W=2,q=3;class J{constructor(e){this.session=e,this._wsClient=null,this._host="wss://rtc.telnyx.com:14938",this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${S.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com:14938":"wss://rtc.telnyx.com:14938")}get connected(){return this._wsClient&&this._wsClient.readyState===K}get connecting(){return this._wsClient&&this._wsClient.readyState===H}get closing(){return this._wsClient&&this._wsClient.readyState===W}get closed(){return this._wsClient&&this._wsClient.readyState===q}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new $(this._host),this._wsClient.onopen=e=>T(f.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>T(f.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>T(f.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=y(e.data);"string"!=typeof s?(this._unsetTimer(s.id),u.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),!G[""+(null===(i=null===(t=null==s?void 0:s.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)]&&T(s.id,s)||T(f.SocketMessage,s,this.session.uuid)):this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,i=new Promise((e,i)=>{if(t.hasOwnProperty("result"))return e();N(t.id,t=>{const{result:s,error:n}=I(t);return n?i(n):e(s)}),this._setTimer(t.id)});return u.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}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]}_setTimer(e){this._timers[e]=setTimeout(()=>{T(e,{error:{code:this.session.timeoutErrorCode,message:"Timeout"}}),this._unsetTimer(e)},1e4)}_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)),T(f.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}const z=()=>"undefined"==typeof window&&"undefined"!=typeof process,Q=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){if(z())return null;const t=window[e].getItem(v(i));return y(t)})))("sessionStorage",e),Y=(e,i)=>((e,i,s)=>t(void 0,void 0,void 0,(function*(){if(z())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(v(i),s)})))("sessionStorage",e,i),X=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){return z()?null:window[e].removeItem(v(i))})))("sessionStorage",e);const Z=e=>navigator.mediaDevices.getUserMedia(e),ee=e=>e&&e instanceof MediaStream,te=(e,t)=>{const i=w(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ie=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=w(e);if(null===t)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return u.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()},ne=e=>{ee(e)&&e.getTracks().forEach(se),e=null},oe=e=>t(void 0,void 0,void 0,(function*(){u.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield Z(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),re=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=yield navigator.mediaDevices.enumerateDevices().catch(e=>(console.error("enumerateDevices",e),[]));e&&(t=t.filter(t=>t.kind===e));if(!(t.length&&t.every(e=>e.deviceId&&e.label))){const t=yield Z(((e=null)=>({audio:!e||e===F.AudioIn||e===F.AudioOut,video:!e||e===F.Video}))(e));return ne(t),re(e)}if(!0===i)return t;const s=[];return t=t.filter(({kind:e,groupId:t})=>{if(!t)return!0;const i=`${e}-${t}`;return!s.includes(i)&&(s.push(i),!0)}),t})),ae=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ce=(e,i,s)=>t(void 0,void 0,void 0,(function*(){const t=yield re(s,!0);for(let s=0;s<t.length;s++){const{deviceId:n,label:o}=t[s];if(e===n||i===o)return n}return null})),le=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]})},de=(e,i,s,n)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=n;if(void 0===t&&(e||i)){const t=yield ce(e,i,s).catch(e=>null);t&&(n.deviceId={exact:t})}return n})),ue=e=>{const t="\r\n",i=e.split(t),s=i.findIndex(e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e));if(s<0)return e;const n=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),i=e.match(t);return i&&2==i.length?i[1]:null})(i[s]),o=new RegExp("a=fmtp:"+n),r=i.findIndex(e=>o.test(e));return r>=0?/stereo=1;/.test(i[r])||(i[r]+="; stereo=1; sprop-stereo=1"):i[s]+=`\r\na=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},he=e=>/^m=audio/.test(e),pe=e=>/^m=video/.test(e),ge=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(he)<s.findIndex(pe))return e;const n=e.split(i),o=n.findIndex(he),r=n.findIndex(pe),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},fe=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=me(e);return i.includes(t)||s.includes(t)},me=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(i=>{t[i]=e[i+"Channels"]||[]}),t},ve=(e,t=null,i=null)=>{if(!ee(e))return null;let s=[];switch(t){case"audio":s=e.getAudioTracks();break;case"video":s=e.getVideoTracks();break;default:s=e.getTracks()}s.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}})},be=e=>{ve(e,"audio",!0)},ye=e=>{ve(e,"audio",!1)},_e=e=>{ve(e,"audio",null)};function we(){try{const{browserInfo:e,name:t,version:i,supportAudio:s,supportVideo:n}=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,l=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:i,supportWebRTC:!!(o&&r&&a&&c&&l),supportWebRTCAudio:s,supportWebRTCVideo:n,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!oe}}catch(e){return e.message}}var Se;function Ie(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 Ce(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then(()=>{e._playFulfilled=!0}).catch(t=>{console.error("playAudio",t),e._playFulfilled=!0}))}function Ee(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"}(Se||(Se={}));const ke={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number"};class xe extends class{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in ke)e&&i.hasOwnProperty(e)&&(i[ke[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class Ae extends xe{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{}};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class Ne extends xe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Re extends xe{toString(){return P.Invite}}class Te extends xe{toString(){return P.Answer}}class Oe extends xe{toString(){return P.Attach}}class De extends xe{toString(){return P.Bye}}class Le extends xe{toString(){return P.Modify}}class Pe extends xe{toString(){return P.Info}}class Me extends xe{toString(){return P.Broadcast}}class Ue extends xe{toString(){return P.Subscribe}}class Be extends xe{toString(){return P.Unsubscribe}}class Ve{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,u.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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._init()}get isOffer(){return this.type===D.Offer}get isAnswer(){return this.type===D.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){u.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,t)=>{u.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),u.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(u.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){u.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:n}=this.options;n=t,!1===s&&te(i,n)}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("addstream",e=>{this.options.remoteStream=e.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(e=>(T(f.MediaError,e,this.options.id),null))}))}_init(){return t(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:i=!1}=this.options;if(ee(t)){const s=t.getAudioTracks();u.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(u.info("Local video tracks: ",n),this.isOffer&&"function"==typeof this.instance.addTransceiver){s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTransceiver(e,{direction:"sendrecv",streams:[t]})});const e={direction:"sendrecv",streams:[t]};console.debug("Applying video transceiverParams",e),n.forEach(t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)})}else"function"==typeof this.instance.addTrack?(s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)}),n.forEach(e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)})):this.instance.addStream(t);!1===i&&((e=>{const t=w(e);t&&(t.muted=!0)})(e),te(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);u.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),u.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>u.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=ue(e.sdp)),this.instance.localDescription&&(e.sdp=ge(e.sdp,this.instance.localDescription.sdp));const t=e;return u.info("REMOTE SDP \n","Type: "+e.type,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return t(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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:D.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:D.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:n,mediaSettings:o}=this.options;return t&&(e.sdp=ue(e.sdp)),i&&s&&n&&(e.sdp=((e,t,i,s)=>{const n=e.split("\r\n");return n.forEach((e,o)=>{/^a=fmtp:\d*/.test(e)?n[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${i};x-google-start-bitrate=${s}`:/^a=mid:(1|video)/.test(e)&&(n[o]+="\r\nb=AS:"+t)}),n.join("\r\n")})(e.sdp,i,s,n)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let i="AS",s=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(i="TIAS",s=1e3*(t>>>0));return-1===e.indexOf("b="+i+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+i+":"+s+"\r\n"):e.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+s+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){_(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(ee(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}=i;const{micLabel:s=""}=i;t&&(t=yield ce(t,s,F.AudioIn).catch(e=>null),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t}));let{video:n=!1,camId:o}=i;const{camLabel:r=""}=i;return o&&(o=yield ce(o,r,F.Video).catch(e=>null),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var i;return oe(e)}))}_isOffer(){return this.type===D.Offer}_isAnswer(){return this.type===D.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return u.info("RTC config",t),t}}const je=(e,t)=>{const{contentType:i,canvasType:s,callID:n,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==s&&delete o.memberID;const a={type:M.conferenceUpdate,call:e.calls[n],canvasInfo:Fe(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:j.LayerInfo},a);T(f.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:j.LayoutInfo},a);T(f.Notification,t,e.uuid);break}}},Fe=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return y(t)};const Ge="2.6.1";class $e{constructor(e,t){this.session=e,this.id="",this.state=B[B.New],this.prevState="",this.channels=[],this.role=V.Participant,this.extension=null,this._state=B.New,this._prevState=B.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._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:s,micId:n,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:l,mediaConstraints:{audio:d,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},U,{audio:d,video:u,iceServers:i,localElement:c,remoteElement:l,micId:n,micLabel:o,camId:r,camLabel:a,speakerId:s,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=Ie(this.options.ringtoneFile,"_ringtone"),this._ringback=Ie(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}invite(){this.direction=L.Outbound,this.peer=new Ve(D.Offer,this.options),this._registerPeerEvents()}answer(){this.stopRingtone(),this.direction=L.Inbound,this.peer=new Ve(D.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ce(this._ringtone)}stopRingtone(){Ee(this._ringtone)}playRingback(){Ce(this._ringback)}stopRingback(){Ee(this._ringback)}hangup(e,t){let i=e||{},s=!1!==t;this.cause=i.cause||"NORMAL_CLEARING",this.causeCode=i.causeCode||16,this.sipCode=i.sipCode||null,this.sipReason=i.sipReason||null,this.sipCallId=i.sip_call_id||null,this.setState(B.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(B.Destroy)};if(this.stopRingtone(),s){const e=new De({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch(e=>u.error("telnyl_rtc.bye failed!",e)).then(n.bind(this))}else n()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new Le({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Le({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Le({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 Le({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 Le({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 Pe({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},s=new Pe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){ye(this.options.localStream)}unmuteAudio(){be(this.options.localStream)}toggleAudioMute(){_e(this.options.localStream)}setAudioInDevice(e){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 Z({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];i.replaceTrack(s),this.options.micId=e;const{localStream:n}=this.options;n.getAudioTracks().forEach(e=>e.stop()),n.getVideoTracks().forEach(e=>t.addTrack(e)),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,ve(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,ve(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,ve(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 Z({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;te(n,t),this.options.camId=e,o.getAudioTracks().forEach(e=>t.addTrack(e)),o.getVideoTracks().forEach(e=>e.stop()),this.options.localStream=t}}))}deaf(){ye(this.options.remoteStream)}undeaf(){be(this.options.remoteStream)}toggleDeaf(){_e(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void u.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,s=t.getSenders();if(!s)return void u.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 n=s.find(({track:{kind:e}})=>e===i);if(n){const t=n.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),u.info("Parameters: ",t),u.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield n.setParameters(t).then(()=>{u.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())}).catch(e=>console.error(e))}else u.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){switch(this._prevState=this._state,this._state=e,this.state=B[this._state].toLowerCase(),this.prevState=B[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:M.callUpdate,call:this}),e){case B.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case B.Active:setTimeout(()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ie(e,t)},0);break;case B.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case P.Answer:if(this.gotAnswer=!0,this._state>=B.Active)return;this._state>=B.Early&&this.setState(B.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case P.Media:if(this._state>=B.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case P.Display:case P.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===L.Inbound?L.Outbound:L.Inbound,r={type:M[t],call:this,displayName:e,displayNumber:s,displayDirection:o};T(f.Notification,r,this.id)||T(f.Notification,r,this.session.uuid);break}case P.Info:case P.Event:{const e=Object.assign(Object.assign({},i),{type:M.generic,call:this});T(f.Notification,e,this.id)||T(f.Notification,e,this.session.uuid);break}case P.Ringing:this.playRingback();break;case P.Bye: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 u.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:s,hashKey:n=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:n,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:j.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),n&&a===V.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},b(s[e][1])));this._dispatchConferenceUpdate({action:j.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:j.Add,callId:n,index:o},b(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:j.Modify,callId:n,index:o},b(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:j.Delete,callId:n,index:o},b(s)));break;case"clear":this._dispatchConferenceUpdate({action:j.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:s,callId:n,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:s,message:n,type:o}=e.data;this._dispatchConferenceUpdate({action:j.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch(e=>{u.error("ConfChat subscription error:",e)});fe(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;switch(t.contentType){case"layout-info":t.callID=this.id,je(this.session,t);break;default:u.error("Conference-Info unknown contentType",e)}}},i=yield this.session.vertoSubscribe(t).catch(e=>{u.error("ConfInfo subscription error:",e)});fe(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})}_subscribeConferenceModerator(e){return t(this,void 0,void 0,(function*(){const t=(t,i=null,s=null)=>{const n=parseInt(i)||null;this._confControl(e,{command:t,id:n,value:s})},i=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&m(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;switch(t["conf-command"]){case"list-videoLayouts":if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:j.LayoutList,layouts:JSON.parse(e)})}break;default:this._dispatchConferenceUpdate({action:j.ModCmdResponse,command:t["conf-command"],response:t.response})}}},n=yield this.session.vertoSubscribe(s).catch(e=>{u.error("ConfMod subscription error:",e)});fe(n,e)&&(this.role=V.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{i(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,s)=>{i();t("vid-layout",null,s?[e,s]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{i(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{i(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{i(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,s)=>{i(),t("vid-banner",e,encodeURI(s))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,i)=>{t("transfer",e,i)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(B.Active):this.setState(B.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=ge(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=ue(t));const i={sdp:t,type:D.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState(B.Early),this.gotAnswer&&this.setState(B.Active)}).catch(e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()})}_requestAnotherLocalDescription(){_(this.peer.onSdpReadyTwice)?T(f.Error,new Error("SDP without candidates for the second time!"),this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:t,type:i}=e;if(-1===t.indexOf("candidate"))return u.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();this.peer.instance.removeEventListener("icecandidate",this._onIce);let s=null;const n={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,"User-Agent":"Web-"+Ge};switch(i){case D.Offer:this.setState(B.Requesting),s=new Re(n);break;case D.Answer:this.setState(B.Answering),s=!0===this.options.attach?new Oe(n):new Te(n);break;default:return u.error(this.id+" - Unknown local SDP type:",e),this.hangup({},!1)}this._execute(s).then(e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===D.Offer?this.setState(B.Trying):this.setState(B.Active)}).catch(e=>{u.error(`${this.id} - Sending ${i} error:`,e),this.hangup()})}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(t.localDescription),1e3)),e.candidate?u.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},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:s}=this.options;!1===s&&te(t,i)})}_onMediaError(e){this._dispatchNotification({type:M.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:M.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(T(f.Notification,e,this.id,!1)||T(f.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:s}=this.options;e||(this.options.id=a()),this.id=this.options.id,t&&!m(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,A(f.MediaError,this._onMediaError,this.id),_(s)&&A(f.Notification,s.bind(this),this.id),this.setState(B.New),u.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ne(e),ne(t),R(f.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),u.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),u.info("Stats stopped")}}$e.setStateTelnyx=e=>{if(e){switch(e._state){case B.Requesting:case B.Recovering:case B.Trying:case B.Early:e.state="connecting";break;case B.Active:e.state="active";break;case B.Held:e.state="held";break;case B.Hangup:case B.Destroy:e.state="done";break;case B.Answering:e.state="ringing";break;case B.New:e.state="new"}return e}};class He extends $e{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof He&&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:s,remoteCallerNumber:n,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:this.extension+"-screen",remoteCallerName:s,remoteCallerNumber:n+"-screen",callerName:o+" (Screen)",callerNumber:r+" (Screen)"},e);return this.screenShare=new He(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof He&&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)&&ie(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);u.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"],s=["id","type","timestamp"];e.forEach(e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach(i=>{s.includes(i)||(t+=`\t${i}: ${e[i]}\n`)}))}),u.info(t)})),2e3)}}class Ke extends xe{constructor(){super(),this.method=P.GatewayState;this.buildRequest({method:this.method,params:{}})}}class We{constructor(e,t){this.code=t,this.message=e}}class qe{constructor(e){this.session=e}_ack(e,t){const i=new Ne(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}handleMessage(e){const{session:t}=this,{id:i,method:s,params:n={}}=e,o=null==n?void 0:n.callID,r=null==n?void 0:n.eventChannel,a=null==n?void 0:n.eventType,c=s===P.Attach;if("channelPvtData"===a)return this._handlePvtEvent(n.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(i,s);t.calls[o].hangup({},!1)}const l=()=>{const e={id:o,remoteSdp:n.sdp,destinationNumber:n.callee_id_number,remoteCallerName:n.caller_id_name,remoteCallerNumber:n.caller_id_number,callerName:n.callee_id_name,callerNumber:n.callee_id_number,attach:c,mediaSettings:n.mediaSettings};n.telnyx_call_control_id&&(e.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(e.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(e.telnyxLegId=n.telnyx_leg_id),n.client_state&&(e.clientState=n.client_state);const i=new He(t,e);return i.nodeId=this.nodeId,i},d=new Ke;switch(s){case P.Punt:t.disconnect();break;case P.Invite:{const e=l();e.playRingtone(),e.setState(B.Ringing),this._ack(i,s);break}case P.Attach:{const t=l();this.session.autoRecoverCalls?t.answer():t.setState(B.Recovering),t.handleMessage(e);break}case P.Event:case"webrtc.event":if(!r)return void u.error("Verto received an unknown event:",n);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?T(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?T(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):T(f.Notification,n,t.uuid);break;case P.Info:n.type=M.generic,T(f.Notification,n,t.uuid);break;case P.ClientReady:this.session.execute(d);break;default:{const i=e&&e.result&&e.result.params&&e.result.params.state?e.result.params.state:"",s=e&&e.params&&e.params.state?e.params.state:"",o=i||s;if(o){switch(o){case G.REGED:qe.retriedRegister=0,n.type=M.vertoClientReady,T(f.Ready,n,t.uuid);break;case G.UNREGED:case G.NOREG:if(qe.retriedRegister+=1,5===qe.retriedRegister){qe.retriedRegister=0,T(f.Error,new We("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout(()=>{this.session.execute(d)},500);break;case G.FAILED:case G.FAIL_WAIT:if(!this.session.hasAutoReconnect()){qe.retriedConnect=0,T(f.Error,new We("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(qe.retriedConnect+=1,5===qe.retriedConnect){qe.retriedConnect=0,T(f.Error,n,t.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},500);break;default:u.warn("GatewayState message unknown method:",e)}break}u.warn("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:s,laChannel:n,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:l,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:n,data:{liveArray:{command:"bootstrap",context:n,name:o}}})},s={nodeId:this.nodeId,channels:[n],handler:({data:s})=>{const r=h||this._retrieveCallId(s,n);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(n),a.extension=o,a.handleConferenceUpdate(s,e).then(e=>{"INVALID_PACKET"===e&&i()})}}},r=yield t.vertoSubscribe(s).catch(e=>{u.error("liveArray subscription error:",e)});fe(r,n)&&i();break}case"conference-liveArray-part":{let e=null;if(n&&t._existsSubscription(i,n)){const{callId:s=null}=t.subscriptions[i][n];if(e=t.calls[s]||null,null!==s){const i={type:M.conferenceUpdate,action:j.Leave,conferenceName:o,participantId:Number(l),role:d};T(f.Notification,i,s,!1)||T(f.Notification,i,t.uuid),null===e&&R(f.Notification,null,s)}}const s=[n,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then(({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter(e=>!t.includes(e)))}).catch(e=>{u.error("liveArray unsubscribe error:",e)});break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":je(this.session,e);break;case"logo-info":{const t={type:M.conferenceUpdate,action:j.LogoInfo,logo:e.logoURL};T(f.Notification,t,this.session.uuid);break}}}}qe.retriedConnect=0,qe.retriedRegister=0;class Je extends class extends class extends class{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.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketCloseOrError=this._onSocketCloseOrError.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new J(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*(e=6,t=2,Math.floor(Math.random()*(t-e+1)+e));var e,t}execute(e){return this._idle?new Promise(t=>this._executeQueue.push({resolve:t,msg:e})):this.connected?this.connection.send(e).catch(e=>{throw e.code&&e.code===this.timeoutErrorCode&&this._closeConnection(),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 C(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 X(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return A(e,t,this.uuid),this}off(e,t){return R(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new J(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){T(f.Error,e,this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){u.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&O(this.relayProtocol);for(const e in this.subscriptions)O(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],R(e,null,t)):(delete this.subscriptions[e],O(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},_(t)&&A(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(f.SocketOpen,this._onSocketOpen),this.on(f.SocketClose,this._onSocketCloseOrError),this.on(f.SocketError,this._onSocketCloseOrError),this.on(f.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(f.SocketOpen,this._onSocketOpen),this.off(f.SocketClose,this._onSocketCloseOrError),this.off(f.SocketError,this._onSocketCloseOrError),this.off(f.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()}_keepAlive(){if(!0===this._doKeepAlive){if(!1===this._pong)return this._closeConnection();this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),1e4)}}static on(e,t){A(e,t)}static off(e){R(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){this.sessionid=yield Q("sessId"),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield oe({audio:e,video:i});return ne(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(B.Purge)),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise((t,i)=>{if(N(f.SpeedTest,i=>{const{upDur:s,downDur:n}=i,o=n?8*e/(n/1e3)/1024:0;t({upDur:s,downDur:n,upKps:(s?8*e/(s/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 s=e/1024;e%1024&&s++;const n=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw("#SPB "+n);this.executeRaw("#SPE")})}getDevices(){return re().catch(e=>(T(f.MediaError,e,this.uuid),[]))}getVideoDevices(){return re(F.Video).catch(e=>(T(f.MediaError,e,this.uuid),[]))}getAudioInDevices(){return re(F.AudioIn).catch(e=>(T(f.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return re(F.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),T(f.MediaError,e,this.uuid),[]))}validateDeviceId(e,t,i){return ce(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 oe({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<ae.length;e++){const[i,n]=ae[e];(yield s.applyConstraints({width:{exact:i},height:{exact:n}}).then(()=>!0).catch(()=>!1))&&t.push({resolution:`${i}x${n}`,width:i,height:n})}return ne(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:t,micLabel:s}=i,n=e(i,["micId","micLabel"]);return le(n),this._audioConstraints=yield de(t,s,"audioinput",n),this.micId=t,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{camId:t,camLabel:s}=i,n=e(i,["camId","camLabel"]);return le(n),this._videoConstraints=yield de(t,s,"videoinput",n),this.camId=t,this.camLabel=s,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){this._iceServers="boolean"==typeof e?e?[{urls:["stun:stun.l.google.com:19302"]}]:[]:e||[g,p]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=w(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=w(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error("Invalid channel for broadcast: "+t);const s=new Me({sessid:this.sessionid,eventChannel:t,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(e=>e)}vertoSubscribe({nodeId:e,channels:i=[],handler:s}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter(e=>e&&!this._existsSubscription(this.relayProtocol,e))).length)return{};const t=new Ue({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=me(n);return o.length&&o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),r.forEach(e=>this._addSubscription(this.relayProtocol,s,e)),n}))}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 Be({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unsubscribed:n=[],notSubscribed:o=[]}=me(s);return n.forEach(e=>this._removeSubscription(this.relayProtocol,e)),o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),s}))}static telnyxStateCall(e){return He.setStateTelnyx(e)}}{constructor(){super(...arguments),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990}validateOptions(){return C(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new He(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:i,login_token:s,userVariables:n,autoReconnect:o=!0}=this.options,r=new Ae(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,Y("sessId",this.sessionid))}))}_onSocketMessage(e){new qe(this).handleMessage(e)}}{constructor(e){super(e),console.log("SDK version: 2.6.1")}newCall(e){return super.newCall(e)}static webRTCInfo(){return we()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Se.not_supported},{browserName:"Firefox",supported:Se.not_supported},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",features:["audio"],supported:Se.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",features:["audio"],supported:Se.partial}]}]}}export{Je as TelnyxRTC};
15
+ function e(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(i[s[n]]=e[s[n]])}return i}function t(e,t,i,s){return new(i||(i=Promise))((function(n,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),s=new Uint8Array(16);function n(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var s=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||n)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[s+a]=r[a];return t||function(e,t){var i=t||0,s=o;return[s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],"-",s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]],s[e[i++]]].join("")}(r)}var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var d=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t,i;t=c,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function n(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(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?o:void 0!==console[s]?n(console,s):void 0!==console.log?n(console,"log"):e)}function a(t,i){for(var n=0;n<s.length;n++){var o=s[n];this[o]=n<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function c(e,i,s){return function(){typeof console!==t&&(a.call(this,i,s),this[e].apply(this,arguments))}}function d(e,t,i){return r(e)||c.apply(this,arguments)}function l(e,i,n){var o,r=this,c="loglevel";function l(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(c)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===r.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),r.name=e,r.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},r.methodFactory=n||d,r.getLevel=function(){return o},r.setLevel=function(i,n){if("string"==typeof i&&void 0!==r.levels[i.toUpperCase()]&&(i=r.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=r.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+i+";"}catch(e){}}}(i),a.call(r,i,e),typeof console===t&&i<r.levels.SILENT)return"No console available for logging"},r.setDefaultLevel=function(e){l()||r.setLevel(e,!1)},r.enableAll=function(e){r.setLevel(r.levels.TRACE,e)},r.disableAll=function(e){r.setLevel(r.levels.SILENT,e)};var u=l();null==u&&(u=null==i?"WARN":i),r.setLevel(u,!1)}var u=new l,h={};u.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=h[e];return t||(t=h[e]=new l(e,u.getLevel(),u.methodFactory)),t};var p=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=p),u},u.getLoggers=function(){return h},u.default=u,u},e.exports?e.exports=i():t.log=i()}));const l=()=>(new Date).toISOString().replace("T"," ").replace("Z",""),u=d.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,i)=>{const s=h(e,t,i);return function(){const e=[l(),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},u.setLevel(u.getLevel());const p={urls:"stun:stun.telnyx.com:3478"},g={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var f;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(f||(f={}));const m=e=>0===Object.keys(e).length,v=e=>"@telnyx:"+e,b=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){u.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,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,w=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,S=/^(ws|wss):\/\//,I=(e,t=null)=>{const{result:i={},error:s}=e;if(s)return{error:s};const{result:n=null}=i;if(null===n)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=n;return o&&"200"!==o?{error:n}:a?I(a,r):{result:n}},C=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),E={},k=(e,t)=>`${e}|${t}`,x=(e,t="GLOBAL")=>k(e,t)in E,A=(e,t,i="GLOBAL")=>{const s=k(e,i);s in E||(E[s]=[]),E[s].push(t)},N=(e,t,i="GLOBAL")=>{const s=function(n){R(e,s,i),t(n)};return s.prototype.targetRef=t,A(e,s,i)},R=(e,t,i="GLOBAL")=>{if(!x(e,i))return!1;const s=k(e,i);if(_(t)){for(let e=E[s].length-1;e>=0;e--){const i=E[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&E[s].splice(e,1)}}else E[s]=[];return 0===E[s].length&&delete E[s],!0},T=(e,t,i="GLOBAL",s=!0)=>{const n=s&&"GLOBAL"!==i;if(!x(e,i))return n&&T(e,t),!1;const o=k(e,i),r=E[o].length;if(!r)return n&&T(e,t),!1;for(let e=r-1;e>=0;e--)E[o][e](t);return n&&T(e,t),!0},O=e=>{const t=k(e,"");Object.keys(E).filter(e=>0===e.indexOf(t)).forEach(e=>delete E[e])};var D,L,P;!function(e){e.Offer="offer",e.Answer="answer"}(D||(D={})),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.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"}(P||(P={}));const M={generic:"event",[P.Display]:"participantData",[P.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},U={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var B,V,j,F,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"}(B||(B={})),function(e){e.Participant="participant",e.Moderator="moderator"}(V||(V={})),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"}(j||(j={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(F||(F={})),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={}));let $="undefined"!=typeof WebSocket?WebSocket:null;const H=0,K=1,W=2,q=3;class J{constructor(e){this.session=e,this._wsClient=null,this._host="wss://rtc.telnyx.com:14938",this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${S.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com:14938":"wss://rtc.telnyx.com:14938")}get connected(){return this._wsClient&&this._wsClient.readyState===K}get connecting(){return this._wsClient&&this._wsClient.readyState===H}get closing(){return this._wsClient&&this._wsClient.readyState===W}get closed(){return this._wsClient&&this._wsClient.readyState===q}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new $(this._host),this._wsClient.onopen=e=>T(f.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>T(f.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>T(f.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=y(e.data);"string"!=typeof s?(this._unsetTimer(s.id),u.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),!G[""+(null===(i=null===(t=null==s?void 0:s.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)]&&T(s.id,s)||T(f.SocketMessage,s,this.session.uuid)):this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,i=new Promise((e,i)=>{if(t.hasOwnProperty("result"))return e();N(t.id,t=>{const{result:s,error:n}=I(t);return n?i(n):e(s)}),this._setTimer(t.id)});return u.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}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]}_setTimer(e){this._timers[e]=setTimeout(()=>{T(e,{error:{code:this.session.timeoutErrorCode,message:"Timeout"}}),this._unsetTimer(e)},1e4)}_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)),T(f.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}const z=()=>"undefined"==typeof window&&"undefined"!=typeof process,Q=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){if(z())return null;const t=window[e].getItem(v(i));return y(t)})))("sessionStorage",e),Y=(e,i)=>((e,i,s)=>t(void 0,void 0,void 0,(function*(){if(z())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(v(i),s)})))("sessionStorage",e,i),X=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){return z()?null:window[e].removeItem(v(i))})))("sessionStorage",e);const Z=e=>navigator.mediaDevices.getUserMedia(e),ee=e=>e&&e instanceof MediaStream,te=(e,t)=>{const i=w(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ie=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=w(e);if(null===t)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return u.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()},ne=e=>{ee(e)&&e.getTracks().forEach(se),e=null},oe=e=>t(void 0,void 0,void 0,(function*(){u.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield Z(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),re=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=yield navigator.mediaDevices.enumerateDevices().catch(e=>(console.error("enumerateDevices",e),[]));e&&(t=t.filter(t=>t.kind===e));if(!(t.length&&t.every(e=>e.deviceId&&e.label))){const t=yield Z(((e=null)=>({audio:!e||e===F.AudioIn||e===F.AudioOut,video:!e||e===F.Video}))(e));return ne(t),re(e)}if(!0===i)return t;const s=[];return t=t.filter(({kind:e,groupId:t})=>{if(!t)return!0;const i=`${e}-${t}`;return!s.includes(i)&&(s.push(i),!0)}),t})),ae=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ce=(e,i,s)=>t(void 0,void 0,void 0,(function*(){const t=yield re(s,!0);for(let s=0;s<t.length;s++){const{deviceId:n,label:o}=t[s];if(e===n||i===o)return n}return null})),de=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]})},le=(e,i,s,n)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=n;if(void 0===t&&(e||i)){const t=yield ce(e,i,s).catch(e=>null);t&&(n.deviceId={exact:t})}return n})),ue=e=>{const t="\r\n",i=e.split(t),s=i.findIndex(e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e));if(s<0)return e;const n=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),i=e.match(t);return i&&2==i.length?i[1]:null})(i[s]),o=new RegExp("a=fmtp:"+n),r=i.findIndex(e=>o.test(e));return r>=0?/stereo=1;/.test(i[r])||(i[r]+="; stereo=1; sprop-stereo=1"):i[s]+=`\r\na=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},he=e=>/^m=audio/.test(e),pe=e=>/^m=video/.test(e),ge=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(he)<s.findIndex(pe))return e;const n=e.split(i),o=n.findIndex(he),r=n.findIndex(pe),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},fe=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=me(e);return i.includes(t)||s.includes(t)},me=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(i=>{t[i]=e[i+"Channels"]||[]}),t},ve=(e,t=null,i=null)=>{if(!ee(e))return null;let s=[];switch(t){case"audio":s=e.getAudioTracks();break;case"video":s=e.getVideoTracks();break;default:s=e.getTracks()}s.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}})},be=e=>{ve(e,"audio",!0)},ye=e=>{ve(e,"audio",!1)},_e=e=>{ve(e,"audio",null)};function we(){try{const{browserInfo:e,name:t,version:i,supportAudio:s,supportVideo:n}=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:s,supportWebRTCVideo:n,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!oe}}catch(e){return e.message}}var Se;function Ie(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 Ce(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then(()=>{e._playFulfilled=!0}).catch(t=>{console.error("playAudio",t),e._playFulfilled=!0}))}function Ee(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"}(Se||(Se={}));const ke={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number"};class xe extends class{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in ke)e&&i.hasOwnProperty(e)&&(i[ke[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class Ae extends xe{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{}};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class Ne extends xe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Re extends xe{toString(){return P.Invite}}class Te extends xe{toString(){return P.Answer}}class Oe extends xe{toString(){return P.Attach}}class De extends xe{toString(){return P.Bye}}class Le extends xe{toString(){return P.Modify}}class Pe extends xe{toString(){return P.Info}}class Me extends xe{toString(){return P.Broadcast}}class Ue extends xe{toString(){return P.Subscribe}}class Be extends xe{toString(){return P.Unsubscribe}}class Ve{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,u.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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._init()}get isOffer(){return this.type===D.Offer}get isAnswer(){return this.type===D.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){u.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,t)=>{u.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),u.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(u.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){u.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:n}=this.options;n=t,!1===s&&te(i,n)}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("addstream",e=>{this.options.remoteStream=e.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(e=>(T(f.MediaError,e,this.options.id),null))}))}_init(){return t(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:i=!1}=this.options;if(ee(t)){const s=t.getAudioTracks();u.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(u.info("Local video tracks: ",n),this.isOffer&&"function"==typeof this.instance.addTransceiver){s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTransceiver(e,{direction:"sendrecv",streams:[t]})});const e={direction:"sendrecv",streams:[t]};console.debug("Applying video transceiverParams",e),n.forEach(t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)})}else"function"==typeof this.instance.addTrack?(s.forEach(e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)}),n.forEach(e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)})):this.instance.addStream(t);!1===i&&((e=>{const t=w(e);t&&(t.muted=!0)})(e),te(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);u.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),u.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>u.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=ue(e.sdp)),this.instance.localDescription&&(e.sdp=ge(e.sdp,this.instance.localDescription.sdp));const t=e;return u.info("REMOTE SDP \n","Type: "+e.type,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return t(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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:D.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:D.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:n,mediaSettings:o}=this.options;return t&&(e.sdp=ue(e.sdp)),i&&s&&n&&(e.sdp=((e,t,i,s)=>{const n=e.split("\r\n");return n.forEach((e,o)=>{/^a=fmtp:\d*/.test(e)?n[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${i};x-google-start-bitrate=${s}`:/^a=mid:(1|video)/.test(e)&&(n[o]+="\r\nb=AS:"+t)}),n.join("\r\n")})(e.sdp,i,s,n)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let i="AS",s=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(i="TIAS",s=1e3*(t>>>0));return-1===e.indexOf("b="+i+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+i+":"+s+"\r\n"):e.replace(new RegExp("b="+i+":.*\r\n"),"b="+i+":"+s+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){_(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(ee(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}=i;const{micLabel:s=""}=i;t&&(t=yield ce(t,s,F.AudioIn).catch(e=>null),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t}));let{video:n=!1,camId:o}=i;const{camLabel:r=""}=i;return o&&(o=yield ce(o,r,F.Video).catch(e=>null),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var i;return oe(e)}))}_isOffer(){return this.type===D.Offer}_isAnswer(){return this.type===D.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return u.info("RTC config",t),t}}const je=(e,t)=>{const{contentType:i,canvasType:s,callID:n,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==s&&delete o.memberID;const a={type:M.conferenceUpdate,call:e.calls[n],canvasInfo:Fe(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:j.LayerInfo},a);T(f.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:j.LayoutInfo},a);T(f.Notification,t,e.uuid);break}}},Fe=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return y(t)};const Ge="2.6.2";class $e{constructor(e,t){this.session=e,this.id="",this.state=B[B.New],this.prevState="",this.channels=[],this.role=V.Participant,this.extension=null,this._state=B.New,this._prevState=B.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._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:s,micId:n,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},U,{audio:l,video:u,iceServers:i,localElement:c,remoteElement:d,micId:n,micLabel:o,camId:r,camLabel:a,speakerId:s,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=Ie(this.options.ringtoneFile,"_ringtone"),this._ringback=Ie(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}invite(){this.direction=L.Outbound,this.peer=new Ve(D.Offer,this.options),this._registerPeerEvents()}answer(){this.stopRingtone(),this.direction=L.Inbound,this.peer=new Ve(D.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ce(this._ringtone)}stopRingtone(){Ee(this._ringtone)}playRingback(){Ce(this._ringback)}stopRingback(){Ee(this._ringback)}hangup(e,t){let i=e||{},s=!1!==t;this.cause=i.cause||"NORMAL_CLEARING",this.causeCode=i.causeCode||16,this.sipCode=i.sipCode||null,this.sipReason=i.sipReason||null,this.sipCallId=i.sip_call_id||null,this.setState(B.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(B.Destroy)};if(this.stopRingtone(),s){const e=new De({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch(e=>{u.error("telnyl_rtc.bye failed!",e),T(f.Error,e,this.session.uuid)}).then(n.bind(this))}else n()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new Le({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Le({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Le({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 Le({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 Le({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 Pe({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},s=new Pe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){ye(this.options.localStream)}unmuteAudio(){be(this.options.localStream)}toggleAudioMute(){_e(this.options.localStream)}setAudioInDevice(e){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 Z({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];i.replaceTrack(s),this.options.micId=e;const{localStream:n}=this.options;n.getAudioTracks().forEach(e=>e.stop()),n.getVideoTracks().forEach(e=>t.addTrack(e)),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,ve(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,ve(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,ve(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 Z({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;te(n,t),this.options.camId=e,o.getAudioTracks().forEach(e=>t.addTrack(e)),o.getVideoTracks().forEach(e=>e.stop()),this.options.localStream=t}}))}deaf(){ye(this.options.remoteStream)}undeaf(){be(this.options.remoteStream)}toggleDeaf(){_e(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void u.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,s=t.getSenders();if(!s)return void u.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 n=s.find(({track:{kind:e}})=>e===i);if(n){const t=n.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),u.info("Parameters: ",t),u.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield n.setParameters(t).then(()=>{u.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())}).catch(e=>console.error(e))}else u.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){switch(this._prevState=this._state,this._state=e,this.state=B[this._state].toLowerCase(),this.prevState=B[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:M.callUpdate,call:this}),e){case B.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case B.Active:setTimeout(()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ie(e,t)},0);break;case B.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case P.Answer:if(this.gotAnswer=!0,this._state>=B.Active)return;this._state>=B.Early&&this.setState(B.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case P.Media:if(this._state>=B.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case P.Display:case P.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===L.Inbound?L.Outbound:L.Inbound,r={type:M[t],call:this,displayName:e,displayNumber:s,displayDirection:o};T(f.Notification,r,this.id)||T(f.Notification,r,this.session.uuid);break}case P.Info:case P.Event:{const e=Object.assign(Object.assign({},i),{type:M.generic,call:this});T(f.Notification,e,this.id)||T(f.Notification,e,this.session.uuid);break}case P.Ringing:this.playRingback();break;case P.Bye: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 u.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:s,hashKey:n=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:n,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:j.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),n&&a===V.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},b(s[e][1])));this._dispatchConferenceUpdate({action:j.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:j.Add,callId:n,index:o},b(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:j.Modify,callId:n,index:o},b(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:j.Delete,callId:n,index:o},b(s)));break;case"clear":this._dispatchConferenceUpdate({action:j.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:s,callId:n,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:s,message:n,type:o}=e.data;this._dispatchConferenceUpdate({action:j.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch(e=>{u.error("ConfChat subscription error:",e)});fe(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;switch(t.contentType){case"layout-info":t.callID=this.id,je(this.session,t);break;default:u.error("Conference-Info unknown contentType",e)}}},i=yield this.session.vertoSubscribe(t).catch(e=>{u.error("ConfInfo subscription error:",e)});fe(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})}_subscribeConferenceModerator(e){return t(this,void 0,void 0,(function*(){const t=(t,i=null,s=null)=>{const n=parseInt(i)||null;this._confControl(e,{command:t,id:n,value:s})},i=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&m(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;switch(t["conf-command"]){case"list-videoLayouts":if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:j.LayoutList,layouts:JSON.parse(e)})}break;default:this._dispatchConferenceUpdate({action:j.ModCmdResponse,command:t["conf-command"],response:t.response})}}},n=yield this.session.vertoSubscribe(s).catch(e=>{u.error("ConfMod subscription error:",e)});fe(n,e)&&(this.role=V.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{i(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,s)=>{i();t("vid-layout",null,s?[e,s]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{i(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{i(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{i(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,s)=>{i(),t("vid-banner",e,encodeURI(s))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,i)=>{t("transfer",e,i)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(B.Active):this.setState(B.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=ge(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=ue(t));const i={sdp:t,type:D.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState(B.Early),this.gotAnswer&&this.setState(B.Active)}).catch(e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()})}_requestAnotherLocalDescription(){_(this.peer.onSdpReadyTwice)?T(f.Error,new Error("SDP without candidates for the second time!"),this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:t,type:i}=e;if(-1===t.indexOf("candidate"))return u.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();this.peer.instance.removeEventListener("icecandidate",this._onIce);let s=null;const n={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,"User-Agent":"Web-"+Ge};switch(i){case D.Offer:this.setState(B.Requesting),s=new Re(n);break;case D.Answer:this.setState(B.Answering),s=!0===this.options.attach?new Oe(n):new Te(n);break;default:return u.error(this.id+" - Unknown local SDP type:",e),this.hangup({},!1)}this._execute(s).then(e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===D.Offer?this.setState(B.Trying):this.setState(B.Active)}).catch(e=>{u.error(`${this.id} - Sending ${i} error:`,e),this.hangup()})}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(t.localDescription),1e3)),e.candidate?u.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},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:s}=this.options;!1===s&&te(t,i)})}_onMediaError(e){this._dispatchNotification({type:M.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:M.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(T(f.Notification,e,this.id,!1)||T(f.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:s}=this.options;e||(this.options.id=a()),this.id=this.options.id,t&&!m(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,A(f.MediaError,this._onMediaError,this.id),_(s)&&A(f.Notification,s.bind(this),this.id),this.setState(B.New),u.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ne(e),ne(t),R(f.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),u.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),u.info("Stats stopped")}}$e.setStateTelnyx=e=>{if(e){switch(e._state){case B.Requesting:case B.Recovering:case B.Trying:case B.Early:e.state="connecting";break;case B.Active:e.state="active";break;case B.Held:e.state="held";break;case B.Hangup:case B.Destroy:e.state="done";break;case B.Answering:e.state="ringing";break;case B.New:e.state="new"}return e}};class He extends $e{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof He&&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:s,remoteCallerNumber:n,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:this.extension+"-screen",remoteCallerName:s,remoteCallerNumber:n+"-screen",callerName:o+" (Screen)",callerNumber:r+" (Screen)"},e);return this.screenShare=new He(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof He&&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)&&ie(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);u.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"],s=["id","type","timestamp"];e.forEach(e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach(i=>{s.includes(i)||(t+=`\t${i}: ${e[i]}\n`)}))}),u.info(t)})),2e3)}}class Ke extends xe{constructor(){super(),this.method=P.GatewayState;this.buildRequest({method:this.method,params:{}})}}class We{constructor(e,t){this.code=t,this.message=e}}class qe{constructor(e){this.session=e}_ack(e,t){const i=new Ne(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}handleMessage(e){const{session:t}=this,{id:i,method:s,params:n={}}=e,o=null==n?void 0:n.callID,r=null==n?void 0:n.eventChannel,a=null==n?void 0:n.eventType,c=s===P.Attach;if("channelPvtData"===a)return this._handlePvtEvent(n.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(i,s);t.calls[o].hangup({},!1)}const d=()=>{const e={id:o,remoteSdp:n.sdp,destinationNumber:n.callee_id_number,remoteCallerName:n.caller_id_name,remoteCallerNumber:n.caller_id_number,callerName:n.callee_id_name,callerNumber:n.callee_id_number,attach:c,mediaSettings:n.mediaSettings};n.telnyx_call_control_id&&(e.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(e.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(e.telnyxLegId=n.telnyx_leg_id),n.client_state&&(e.clientState=n.client_state);const i=new He(t,e);return i.nodeId=this.nodeId,i},l=new Ke;switch(s){case P.Punt:t.disconnect();break;case P.Invite:{const e=d();e.playRingtone(),e.setState(B.Ringing),this._ack(i,s);break}case P.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(B.Recovering),t.handleMessage(e);break}case P.Event:case"webrtc.event":if(!r)return void u.error("Verto received an unknown event:",n);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?T(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?T(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):T(f.Notification,n,t.uuid);break;case P.Info:n.type=M.generic,T(f.Notification,n,t.uuid);break;case P.ClientReady:this.session.execute(l);break;default:{const i=e&&e.result&&e.result.params&&e.result.params.state?e.result.params.state:"",s=e&&e.params&&e.params.state?e.params.state:"",o=i||s;if(o){switch(o){case G.REGED:qe.retriedRegister=0,n.type=M.vertoClientReady,T(f.Ready,n,t.uuid);break;case G.UNREGED:case G.NOREG:if(qe.retriedRegister+=1,5===qe.retriedRegister){qe.retriedRegister=0,T(f.Error,new We("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout(()=>{this.session.execute(l)},500);break;case G.FAILED:case G.FAIL_WAIT:if(!this.session.hasAutoReconnect()){qe.retriedConnect=0,T(f.Error,new We("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(qe.retriedConnect+=1,5===qe.retriedConnect){qe.retriedConnect=0,T(f.Error,n,t.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},500);break;default:u.warn("GatewayState message unknown method:",e)}break}u.warn("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:s,laChannel:n,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:h}=e;switch(s){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:n,data:{liveArray:{command:"bootstrap",context:n,name:o}}})},s={nodeId:this.nodeId,channels:[n],handler:({data:s})=>{const r=h||this._retrieveCallId(s,n);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(n),a.extension=o,a.handleConferenceUpdate(s,e).then(e=>{"INVALID_PACKET"===e&&i()})}}},r=yield t.vertoSubscribe(s).catch(e=>{u.error("liveArray subscription error:",e)});fe(r,n)&&i();break}case"conference-liveArray-part":{let e=null;if(n&&t._existsSubscription(i,n)){const{callId:s=null}=t.subscriptions[i][n];if(e=t.calls[s]||null,null!==s){const i={type:M.conferenceUpdate,action:j.Leave,conferenceName:o,participantId:Number(d),role:l};T(f.Notification,i,s,!1)||T(f.Notification,i,t.uuid),null===e&&R(f.Notification,null,s)}}const s=[n,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then(({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter(e=>!t.includes(e)))}).catch(e=>{u.error("liveArray unsubscribe error:",e)});break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":je(this.session,e);break;case"logo-info":{const t={type:M.conferenceUpdate,action:j.LogoInfo,logo:e.logoURL};T(f.Notification,t,this.session.uuid);break}}}}qe.retriedConnect=0,qe.retriedRegister=0;class Je extends class extends class extends class{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.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this._onSocketCloseOrError=this._onSocketCloseOrError.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new J(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*(e=6,t=2,Math.floor(Math.random()*(t-e+1)+e));var e,t}execute(e){return this._idle?new Promise(t=>this._executeQueue.push({resolve:t,msg:e})):this.connected?this.connection.send(e).catch(e=>{throw e.code&&e.code===this.timeoutErrorCode&&this._closeConnection(),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 C(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 X(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return A(e,t,this.uuid),this}off(e,t){return R(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new J(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){T(f.Error,e,this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){u.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&O(this.relayProtocol);for(const e in this.subscriptions)O(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],R(e,null,t)):(delete this.subscriptions[e],O(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},_(t)&&A(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(f.SocketOpen,this._onSocketOpen),this.on(f.SocketClose,this._onSocketCloseOrError),this.on(f.SocketError,this._onSocketCloseOrError),this.on(f.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(f.SocketOpen,this._onSocketOpen),this.off(f.SocketClose,this._onSocketCloseOrError),this.off(f.SocketError,this._onSocketCloseOrError),this.off(f.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()}_keepAlive(){if(!0===this._doKeepAlive){if(!1===this._pong)return this._closeConnection();this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),1e4)}}static on(e,t){A(e,t)}static off(e){R(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){this.sessionid=yield Q("sessId"),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield oe({audio:e,video:i});return ne(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(B.Purge)),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise((t,i)=>{if(N(f.SpeedTest,i=>{const{upDur:s,downDur:n}=i,o=n?8*e/(n/1e3)/1024:0;t({upDur:s,downDur:n,upKps:(s?8*e/(s/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 s=e/1024;e%1024&&s++;const n=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw("#SPB "+n);this.executeRaw("#SPE")})}getDevices(){return re().catch(e=>(T(f.MediaError,e,this.uuid),[]))}getVideoDevices(){return re(F.Video).catch(e=>(T(f.MediaError,e,this.uuid),[]))}getAudioInDevices(){return re(F.AudioIn).catch(e=>(T(f.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return re(F.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),T(f.MediaError,e,this.uuid),[]))}validateDeviceId(e,t,i){return ce(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 oe({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<ae.length;e++){const[i,n]=ae[e];(yield s.applyConstraints({width:{exact:i},height:{exact:n}}).then(()=>!0).catch(()=>!1))&&t.push({resolution:`${i}x${n}`,width:i,height:n})}return ne(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:t,micLabel:s}=i,n=e(i,["micId","micLabel"]);return de(n),this._audioConstraints=yield le(t,s,"audioinput",n),this.micId=t,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{camId:t,camLabel:s}=i,n=e(i,["camId","camLabel"]);return de(n),this._videoConstraints=yield le(t,s,"videoinput",n),this.camId=t,this.camLabel=s,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){this._iceServers="boolean"==typeof e?e?[{urls:["stun:stun.l.google.com:19302"]}]:[]:e||[g,p]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=w(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=w(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error("Invalid channel for broadcast: "+t);const s=new Me({sessid:this.sessionid,eventChannel:t,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(e=>e)}vertoSubscribe({nodeId:e,channels:i=[],handler:s}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter(e=>e&&!this._existsSubscription(this.relayProtocol,e))).length)return{};const t=new Ue({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=me(n);return o.length&&o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),r.forEach(e=>this._addSubscription(this.relayProtocol,s,e)),n}))}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 Be({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unsubscribed:n=[],notSubscribed:o=[]}=me(s);return n.forEach(e=>this._removeSubscription(this.relayProtocol,e)),o.forEach(e=>this._removeSubscription(this.relayProtocol,e)),s}))}static telnyxStateCall(e){return He.setStateTelnyx(e)}}{constructor(){super(...arguments),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990}validateOptions(){return C(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new He(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:i,login_token:s,userVariables:n,autoReconnect:o=!0}=this.options,r=new Ae(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,Y("sessId",this.sessionid))}))}_onSocketMessage(e){new qe(this).handleMessage(e)}}{constructor(e){super(e),console.log("SDK version: 2.6.2")}newCall(e){return super.newCall(e)}static webRTCInfo(){return we()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Se.not_supported},{browserName:"Firefox",supported:Se.not_supported},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",features:["audio"],supported:Se.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",features:["audio"],supported:Se.partial}]}]}}export{Je as TelnyxRTC};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telnyx/webrtc",
3
- "version": "2.6.1",
3
+ "version": "2.6.2",
4
4
  "description": "Telnyx WebRTC Client",
5
5
  "keywords": [
6
6
  "telnyx",
@@ -52,7 +52,7 @@
52
52
  "@typescript-eslint/eslint-plugin": "^3.6.1",
53
53
  "@typescript-eslint/parser": "^3.6.1",
54
54
  "core-js": "^3.8.3",
55
- "eslint": "^7.4.0",
55
+ "eslint": "^8.3.0",
56
56
  "eslint-config-airbnb-base": "^14.2.0",
57
57
  "eslint-plugin-import": "^2.22.1",
58
58
  "events": "^3.0.0",
@@ -60,7 +60,7 @@
60
60
  "lint-staged": "^10.2.11",
61
61
  "md-gum-polyfill": "^1.0.0",
62
62
  "prettier": "^2.1.2",
63
- "release-it": "^14.6.2",
63
+ "release-it": "^14.11.8",
64
64
  "rollup": "^1.19.4",
65
65
  "rollup-plugin-babel": "^4.3.3",
66
66
  "rollup-plugin-commonjs": "^10.0.2",