@telnyx/webrtc 2.10.2 → 2.11.0
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/CHANGELOG.md +13 -0
- package/lib/bundle.js +1 -1
- package/lib/bundle.mjs +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
## [2.11.0](https://github.com/team-telnyx/webrtc/compare/webrtc/v2.10.2...webrtc/v2.11.0) (2024-02-26)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* **TELAPPS-4794:** expose user agent on login ([#343](https://github.com/team-telnyx/webrtc/issues/343)) ([a8b9606](https://github.com/team-telnyx/webrtc/commit/a8b96068255c4cec50d43d737a85fea267f3b52a))
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
* **ENGDESK-23349:** bind telnyxids on ringing event for outbound calls ([#342](https://github.com/team-telnyx/webrtc/issues/342)) ([1b1df78](https://github.com/team-telnyx/webrtc/commit/1b1df782c3c4034d412be079b92019e661dbd5ce))
|
|
12
|
+
* **ENGDESK-28811:** call object direction is undefined upon receiving call ([#341](https://github.com/team-telnyx/webrtc/issues/341)) ([8ac5a3f](https://github.com/team-telnyx/webrtc/commit/8ac5a3f6626d67cde4cf14c541aa26085be19ae6))
|
|
13
|
+
|
|
1
14
|
### [2.10.2](https://github.com/team-telnyx/webrtc/compare/webrtc/v2.10.1...webrtc/v2.10.2) (2024-02-20)
|
|
2
15
|
|
|
3
16
|
|
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 l="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=l,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(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 a(e,i,s){return function(){typeof console!==t&&(r.call(this,i,s),this[e].apply(this,arguments))}}function c(s,r,c){return function(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)}(s)||a.apply(this,arguments)}function l(e,i,n){var o,a=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(l)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=n||c,a.getLevel=function(){return o},a.setLevel=function(i,n){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=i),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},e.exports?e.exports=i():t.log=i()}));const u=d.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,i)=>{const s=h(e,t,i);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},u.setLevel(u.getLevel());const p="sessId",g="wss://rtc.telnyx.com",f={urls:"stun:stun.telnyx.com:3478"},m={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var v;!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"}(v||(v={}));const b=e=>0===Object.keys(e).length,y=e=>`@telnyx:${e}`,_=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}},w=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},S=e=>e instanceof Function||"function"==typeof e,I=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,C=/^(ws|wss):\/\//,E=(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?E(a,r):{result:n}},k=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),x=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),R=e=>{var t,i,s,n,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(n=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===n?void 0:n.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c},N="GLOBAL",A={},T=(e,t)=>`${e}|${t}`,O=(e,t=N)=>T(e,t)in A,D=(e,t,i=N)=>{const s=T(e,i);s in A||(A[s]=[]),A[s].push(t)},L=(e,t,i=N)=>{const s=function(n){P(e,s,i),t(n)};return s.prototype.targetRef=t,D(e,s,i)},P=(e,t,i=N)=>{if(!O(e,i))return!1;const s=T(e,i);if(S(t)){for(let e=A[s].length-1;e>=0;e--){const i=A[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&A[s].splice(e,1)}}else A[s]=[];return 0===A[s].length&&delete A[s],!0},M=(e,t,i=N,s=!0)=>{const n=s&&i!==N;if(!O(e,i))return n&&M(e,t),!1;const o=T(e,i),r=A[o].length;if(!r)return n&&M(e,t),!1;for(let e=r-1;e>=0;e--)A[o][e](t);return n&&M(e,t),!0},U=e=>{const t=T(e,"");Object.keys(A).filter((e=>0===e.indexOf(t))).forEach((e=>delete A[e]))};var j,V,B;!function(e){e.Offer="offer",e.Answer="answer"}(j||(j={})),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",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(B||(B={}));const $={generic:"event",[B.Display]:"participantData",[B.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,q,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"}(G||(G={})),function(e){e.Participant="participant",e.Moderator="moderator"}(H||(H={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(W||(W={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(q||(q={})),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 J="undefined"!=typeof WebSocket?WebSocket:null;const z=0,Q=1,Y=2,X=3;class Z{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=g,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${C.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":g)}get connected(){return this._wsClient&&this._wsClient.readyState===Q}get connecting(){return this._wsClient&&this._wsClient.readyState===z}get closing(){return this._wsClient&&this._wsClient.readyState===Y}get closed(){return this._wsClient&&this._wsClient.readyState===X}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new J(this._host),this._wsClient.onopen=e=>M(v.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>M(v.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>M(v.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=w(e.data);if("string"!=typeof s){if(this._unsetTimer(s.id),u.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}`]||!M(s.id,s)){const e=R(s);M(v.SocketMessage,s,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else 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();L(t.id,(t=>{const{result:s,error:n}=E(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&&(S(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((()=>{M(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)),M(v.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}const ee=()=>"undefined"==typeof window&&"undefined"!=typeof process,te=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){if(ee())return null;const i=window[e].getItem(y(t));return w(i)})))("sessionStorage",e),ie=(e,t)=>((e,t,s)=>i(void 0,void 0,void 0,(function*(){if(ee())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(y(t),s)})))("sessionStorage",e,t),se=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){return ee()?null:window[e].removeItem(y(t))})))("sessionStorage",e);class ne{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 Z(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*k(2,6)}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 se(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return D(e,t,this.uuid),this}off(e,t){return P(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(this.connection=new Z(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){M(v.Error,e,this.uuid)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){u.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&U(this.relayProtocol);for(const e in this.subscriptions)U(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],P(e,null,t)):(delete this.subscriptions[e],U(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},S(t)&&D(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(v.SocketOpen,this._onSocketOpen),this.on(v.SocketClose,this._onSocketCloseOrError),this.on(v.SocketError,this._onSocketCloseOrError),this.on(v.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(v.SocketOpen,this._onSocketOpen),this.off(v.SocketClose,this._onSocketCloseOrError),this.off(v.SocketError,this._onSocketCloseOrError),this.off(v.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){D(e,t)}static off(e){P(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const oe=e=>navigator.mediaDevices.getUserMedia(e),re=e=>e&&e instanceof MediaStream,ae=(e,t)=>{const i=I(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ce=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=I(e);if(null===i)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return u.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),le=e=>{e&&"live"===e.readyState&&e.stop()},de=e=>{re(e)&&e.getTracks().forEach(le),e=null},ue=e=>i(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 oe(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),he=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=[];const s=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===q.AudioIn||e===q.AudioOut,video:!e||e===q.Video}))(e)).catch((e=>(console.error(e),null)));if(s){if(de(s),i=yield navigator.mediaDevices.enumerateDevices(),e&&(i=i.filter((t=>t.kind===e))),!0===t)return i;const n=[];i=i.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!n.includes(t)&&(n.push(t),!0)}))}return i})),pe=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ge=(e,t,s)=>i(void 0,void 0,void 0,(function*(){const i=yield he(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})),fe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},me=(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 ge(e,t,s).catch((e=>null));i&&(n.deviceId={exact:i})}return n})),ve=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]+=`${t}a=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},be=e=>/^m=audio/.test(e),ye=e=>/^m=video/.test(e),_e=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(be)<s.findIndex(ye))return e;const n=e.split(i),o=n.findIndex(be),r=n.findIndex(ye),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},we=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=Se(e);return i.includes(t)||s.includes(t)},Se=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Ie=(e,t=null,i=null)=>{if(!re(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}}))},Ce=e=>{Ie(e,"audio",!0)},Ee=e=>{Ie(e,"audio",!1)},ke=e=>{Ie(e,"audio",null)};function xe(){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:!!ue}}catch(e){return e.message}}var Re;function Ne(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 Ae(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 Te(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"}(Re||(Re={}));class Oe{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const De={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Le extends Oe{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in De)e&&i.hasOwnProperty(e)&&(i[De[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Pe extends Le{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 Me extends Le{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ue extends Le{toString(){return B.Invite}}class je extends Le{toString(){return B.Answer}}class Ve extends Le{toString(){return B.Attach}}class Be extends Le{toString(){return B.Bye}}class $e extends Le{toString(){return B.Modify}}class Fe extends Le{toString(){return B.Info}}class Ge extends Le{toString(){return B.Broadcast}}class He extends Le{toString(){return B.Subscribe}}class We extends Le{toString(){return B.Unsubscribe}}class qe{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===j.Offer}get isAnswer(){return this.type===j.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&&ae(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=>(M(v.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(re(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=I(e);t&&(t.muted=!0)})(e),ae(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=ve(e.sdp)),this.instance.localDescription&&(e.sdp=_e(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 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:j.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:j.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=ve(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(){S(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(re(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 ge(i,s,q.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 ge(o,r,q.Video).catch((e=>null)),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var t;return ue(e)}))}_isOffer(){return this.type===j.Offer}_isAnswer(){return this.type===j.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return u.info("RTC config",t),t}}const Ke=(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:$.conferenceUpdate,call:e.calls[n],canvasInfo:Je(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:W.LayerInfo},a);M(v.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:W.LayoutInfo},a);M(v.Notification,t,e.uuid);break}}},Je=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return w(t)};var ze="2.10.2";const Qe=ze;class Ye{constructor(e,t){this.session=e,this.id="",this.state=G[G.New],this.prevState="",this.channels=[],this.role=H.Participant,this.extension=null,this._state=G.New,this._prevState=G.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({},F,{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=Ne(this.options.ringtoneFile,"_ringtone"),this._ringback=Ne(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 qe(j.Offer,this.options),this._registerPeerEvents()}answer(e={}){var t;this.stopRingtone(),this.direction=V.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.peer=new qe(j.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ae(this._ringtone)}stopRingtone(){Te(this._ringtone)}playRingback(){Ae(this._ringback)}stopRingback(){Te(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(G.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(G.Destroy)};if(this.stopRingtone(),s){const e=new Be({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{u.error("telnyl_rtc.bye failed!",e),M(v.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 $e({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new $e({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new $e({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new $e({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new $e({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Fe({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 Fe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ee(this.options.localStream)}unmuteAudio(){Ce(this.options.localStream)}toggleAudioMute(){ke(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 oe({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,Ie(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ie(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ie(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 oe({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;ae(n,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ee(this.options.remoteStream)}undeaf(){Ce(this.options.remoteStream)}toggleDeaf(){ke(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(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:i}=this.peer,s=i.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===t));if(n){const i=n.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),u.info("Parameters: ",i),u.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield n.setParameters(i).then((()=>{u.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())})).catch((e=>console.error(e)))}else u.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=G[this._state].toLowerCase(),this.prevState=G[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:$.callUpdate,call:this}),e){case G.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case G.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ce(e,t)}),0);break;case G.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case B.Answer:if(this.gotAnswer=!0,this._state>=G.Active)return;this._state>=G.Early&&this.setState(G.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case B.Media:if(this._state>=G.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case B.Display:case B.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:$[t],call:this,displayName:e,displayNumber:s,displayDirection:o};M(v.Notification,r,this.id)||M(v.Notification,r,this.session.uuid);break}case B.Info:case B.Event:{const e=Object.assign(Object.assign({},i),{type:$.generic,call:this});M(v.Notification,e,this.id)||M(v.Notification,e,this.session.uuid);break}case B.Ringing:this.playRingback();break;case B.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 u.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:W.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i)),n&&a===H.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},_(s[e][1])));this._dispatchConferenceUpdate({action:W.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:W.Add,callId:n,index:o},_(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:W.Modify,callId:n,index:o},_(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:W.Delete,callId:n,index:o},_(s)));break;case"clear":this._dispatchConferenceUpdate({action:W.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:W.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)}));we(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;if("layout-info"===t.contentType)t.callID=this.id,Ke(this.session,t);else u.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfInfo subscription error:",e)}));we(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&&b(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:W.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:W.ModCmdResponse,command:t["conf-command"],response:t.response})}},n=yield this.session.vertoSubscribe(s).catch((e=>{u.error("ConfMod subscription error:",e)}));we(n,e)&&(this.role=H.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(G.Active):this.setState(G.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=_e(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=ve(t));const i={sdp:t,type:j.Answer};this.peer.instance.setRemoteDescription(i).then((()=>{this.gotEarly&&this.setState(G.Early),this.gotAnswer&&this.setState(G.Active)})).catch((e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){S(this.peer.onSdpReadyTwice)?M(v.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-${Qe}`};switch(i){case j.Offer:this.setState(G.Requesting),s=new Ue(n);break;case j.Answer:this.setState(G.Answering),s=!0===this.options.attach?new Ve(n):new je(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===j.Offer?this.setState(G.Trying):this.setState(G.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&&ae(t,i)}))}_onMediaError(e){this._dispatchNotification({type:$.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:$.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(M(v.Notification,e,this.id,!1)||M(v.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&&!b(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,D(v.MediaError,this._onMediaError,this.id),S(s)&&D(v.Notification,s.bind(this),this.id),this.setState(G.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;de(e),de(t),P(v.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")}}Ye.setStateTelnyx=e=>{if(e){switch(e._state){case G.Requesting:case G.Recovering:case G.Trying:case G.Early:e.state="connecting";break;case G.Active:e.state="active";break;case G.Held:e.state="held";break;case G.Hangup:case G.Destroy:e.state="done";break;case G.Answering:e.state="ringing";break;case G.New:e.state="new"}return e}};class Xe extends Ye{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof Xe&&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 Xe(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof Xe&&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)&&ce(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((()=>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`)})))})),u.info(t)}))),2e3)}}class Ze extends ne{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 te(p),e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield ue({audio:e,video:t});return de(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(G.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,i)=>{if(L(v.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 he().catch((e=>(M(v.MediaError,e,this.uuid),[])))}getVideoDevices(){return he(q.Video).catch((e=>(M(v.MediaError,e,this.uuid),[])))}getAudioInDevices(){return he(q.AudioIn).catch((e=>(M(v.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return he(q.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),M(v.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return ge(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 ue({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<pe.length;e++){const[i,n]=pe[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 de(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 fe(n),this._audioConstraints=yield me(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 fe(n),this._videoConstraints=yield me(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||[m,f]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=I(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=I(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 Ge({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 He({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=Se(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 We({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:n=[],notSubscribed:o=[]}=Se(s);return n.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),s}))}static telnyxStateCall(e){return Xe.setStateTelnyx(e)}}class et extends Le{constructor(){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,params:{}})}}class tt{constructor(e,t){this.code=t,this.message=e}}class it extends Le{constructor(){super(),this.method=B.Ping;this.buildRequest({method:this.method,params:{}})}}class st{constructor(e){this.session=e}_ack(e,t){const i=new Me(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*k(2,6)}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===B.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),n.dialogParams&&n.dialogParams.custom_headers&&n.dialogParams.custom_headers.length&&(e.customHeaders=n.dialogParams.custom_headers);const i=new Xe(t,e);return i.nodeId=this.nodeId,i},d=new et,h=new it;switch(s){case B.Ping:this.session.execute(h);break;case B.Punt:t.disconnect();break;case B.Invite:{const e=l();e.playRingtone(),e.setState(G.Ringing),this._ack(i,s);break}case B.Attach:{const t=l();this.session.autoRecoverCalls?t.answer():t.setState(G.Recovering),t.handleMessage(e);break}case B.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)?M(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?M(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):M(v.Notification,n,t.uuid);break;case B.Info:n.type=$.generic,M(v.Notification,n,t.uuid);break;case B.ClientReady:this.session.execute(d);break;default:{const i=R(e);if(i){switch(i){case K.REGISTER:case K.REGED:t.connection.previousGatewayState!==K.REGED&&t.connection.previousGatewayState!==K.REGISTER&&(st.retriedRegister=0,n.type=$.vertoClientReady,M(v.Ready,n,t.uuid));break;case K.UNREGED:case K.NOREG:if(st.retriedRegister+=1,5===st.retriedRegister){st.retriedRegister=0,M(v.Error,new tt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(d)}),this.reconnectDelay());break;case K.FAILED:case K.FAIL_WAIT:if(t.connection.previousGatewayState!==K.FAILED&&t.connection.previousGatewayState!==K.FAIL_WAIT){if(!this.session.hasAutoReconnect()){st.retriedConnect=0,M(v.Error,new tt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(st.retriedConnect+=1,5===st.retriedConnect){st.retriedConnect=0,M(v.Error,n,t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}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 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: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)}));we(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:$.conferenceUpdate,action:W.Leave,conferenceName:o,participantId:Number(l),role:d};M(v.Notification,i,s,!1)||M(v.Notification,i,t.uuid),null===e&&P(v.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":Ke(this.session,e);break;case"logo-info":{const t={type:$.conferenceUpdate,action:W.LogoInfo,logo:e.logoURL};M(v.Notification,t,this.session.uuid);break}}}}st.retriedConnect=0,st.retriedRegister=0;class nt extends Ze{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return x(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new Xe(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 Pe(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,ie(p,this.sessionid))}))}_onSocketMessage(e){new st(this).handleMessage(e)}}e.TelnyxRTC=class extends nt{constructor(e){super(e),console.log(`SDK version: ${ze}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return xe()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Re.not_supported},{browserName:"Firefox",supported:Re.not_supported},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",features:["audio"],supported:Re.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",features:["audio"],supported:Re.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 l="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=l,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(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 a(e,i,s){return function(){typeof console!==t&&(r.call(this,i,s),this[e].apply(this,arguments))}}function c(s,r,c){return function(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)}(s)||a.apply(this,arguments)}function l(e,i,n){var o,a=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(l)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=n||c,a.getLevel=function(){return o},a.setLevel=function(i,n){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=i),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},e.exports?e.exports=i():t.log=i()}));const u=d.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,i)=>{const s=h(e,t,i);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},u.setLevel(u.getLevel());const p="sessId",g="wss://rtc.telnyx.com",f={urls:"stun:stun.telnyx.com:3478"},m={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var v;!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"}(v||(v={}));const b=e=>0===Object.keys(e).length,y=e=>`@telnyx:${e}`,_=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}},w=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},S=e=>e instanceof Function||"function"==typeof e,I=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,C=/^(ws|wss):\/\//,E=(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?E(a,r):{result:n}},x=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),k=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),R=e=>{var t,i,s,n,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(n=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===n?void 0:n.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c},A="GLOBAL",N={},T=(e,t)=>`${e}|${t}`,O=(e,t=A)=>T(e,t)in N,D=(e,t,i=A)=>{const s=T(e,i);s in N||(N[s]=[]),N[s].push(t)},L=(e,t,i=A)=>{const s=function(n){P(e,s,i),t(n)};return s.prototype.targetRef=t,D(e,s,i)},P=(e,t,i=A)=>{if(!O(e,i))return!1;const s=T(e,i);if(S(t)){for(let e=N[s].length-1;e>=0;e--){const i=N[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&N[s].splice(e,1)}}else N[s]=[];return 0===N[s].length&&delete N[s],!0},M=(e,t,i=A,s=!0)=>{const n=s&&i!==A;if(!O(e,i))return n&&M(e,t),!1;const o=T(e,i),r=N[o].length;if(!r)return n&&M(e,t),!1;for(let e=r-1;e>=0;e--)N[o][e](t);return n&&M(e,t),!0},U=e=>{const t=T(e,"");Object.keys(N).filter((e=>0===e.indexOf(t))).forEach((e=>delete N[e]))};var j,V,B;!function(e){e.Offer="offer",e.Answer="answer"}(j||(j={})),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",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(B||(B={}));const $={generic:"event",[B.Display]:"participantData",[B.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,q,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"}(G||(G={})),function(e){e.Participant="participant",e.Moderator="moderator"}(H||(H={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(W||(W={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(q||(q={})),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 J="undefined"!=typeof WebSocket?WebSocket:null;const z=0,Q=1,Y=2,X=3;class Z{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=g,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${C.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":g)}get connected(){return this._wsClient&&this._wsClient.readyState===Q}get connecting(){return this._wsClient&&this._wsClient.readyState===z}get closing(){return this._wsClient&&this._wsClient.readyState===Y}get closed(){return this._wsClient&&this._wsClient.readyState===X}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new J(this._host),this._wsClient.onopen=e=>M(v.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>M(v.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>M(v.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=w(e.data);if("string"!=typeof s){if(this._unsetTimer(s.id),u.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}`]||!M(s.id,s)){const e=R(s);M(v.SocketMessage,s,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else 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();L(t.id,(t=>{const{result:s,error:n}=E(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&&(S(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((()=>{M(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)),M(v.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}const ee=()=>"undefined"==typeof window&&"undefined"!=typeof process,te=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){if(ee())return null;const i=window[e].getItem(y(t));return w(i)})))("sessionStorage",e),ie=(e,t)=>((e,t,s)=>i(void 0,void 0,void 0,(function*(){if(ee())return null;"object"==typeof s&&(s=JSON.stringify(s)),window[e].setItem(y(t),s)})))("sessionStorage",e,t),se=e=>((e,t)=>i(void 0,void 0,void 0,(function*(){return ee()?null:window[e].removeItem(y(t))})))("sessionStorage",e);class ne{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 Z(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*x(2,6)}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 k(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 se(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return D(e,t,this.uuid),this}off(e,t){return P(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(this.connection=new Z(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){M(v.Error,e,this.uuid)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){u.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&U(this.relayProtocol);for(const e in this.subscriptions)U(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],P(e,null,t)):(delete this.subscriptions[e],U(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},S(t)&&D(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(v.SocketOpen,this._onSocketOpen),this.on(v.SocketClose,this._onSocketCloseOrError),this.on(v.SocketError,this._onSocketCloseOrError),this.on(v.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(v.SocketOpen,this._onSocketOpen),this.off(v.SocketClose,this._onSocketCloseOrError),this.off(v.SocketError,this._onSocketCloseOrError),this.off(v.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){D(e,t)}static off(e){P(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const oe=e=>navigator.mediaDevices.getUserMedia(e),re=e=>e&&e instanceof MediaStream,ae=(e,t)=>{const i=I(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ce=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=I(e);if(null===i)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return u.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),le=e=>{e&&"live"===e.readyState&&e.stop()},de=e=>{re(e)&&e.getTracks().forEach(le),e=null},ue=e=>i(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 oe(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),he=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=[];const s=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===q.AudioIn||e===q.AudioOut,video:!e||e===q.Video}))(e)).catch((e=>(console.error(e),null)));if(s){if(de(s),i=yield navigator.mediaDevices.enumerateDevices(),e&&(i=i.filter((t=>t.kind===e))),!0===t)return i;const n=[];i=i.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!n.includes(t)&&(n.push(t),!0)}))}return i})),pe=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ge=(e,t,s)=>i(void 0,void 0,void 0,(function*(){const i=yield he(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})),fe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},me=(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 ge(e,t,s).catch((e=>null));i&&(n.deviceId={exact:i})}return n})),ve=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]+=`${t}a=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},be=e=>/^m=audio/.test(e),ye=e=>/^m=video/.test(e),_e=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(be)<s.findIndex(ye))return e;const n=e.split(i),o=n.findIndex(be),r=n.findIndex(ye),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},we=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=Se(e);return i.includes(t)||s.includes(t)},Se=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Ie=(e,t=null,i=null)=>{if(!re(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}}))},Ce=e=>{Ie(e,"audio",!0)},Ee=e=>{Ie(e,"audio",!1)},xe=e=>{Ie(e,"audio",null)};function ke(){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:!!ue}}catch(e){return e.message}}var Re;function Ae(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 Te(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"}(Re||(Re={}));class Oe{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const De={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Le extends Oe{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in De)e&&i.hasOwnProperty(e)&&(i[De[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Pe extends Le{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{},"User-Agent":window.navigator.userAgent};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class Me extends Le{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ue extends Le{toString(){return B.Invite}}class je extends Le{toString(){return B.Answer}}class Ve extends Le{toString(){return B.Attach}}class Be extends Le{toString(){return B.Bye}}class $e extends Le{toString(){return B.Modify}}class Fe extends Le{toString(){return B.Info}}class Ge extends Le{toString(){return B.Broadcast}}class He extends Le{toString(){return B.Subscribe}}class We extends Le{toString(){return B.Unsubscribe}}class qe{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===j.Offer}get isAnswer(){return this.type===j.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&&ae(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=>(M(v.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(re(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=I(e);t&&(t.muted=!0)})(e),ae(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=ve(e.sdp)),this.instance.localDescription&&(e.sdp=_e(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 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:j.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:j.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=ve(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(){S(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(re(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 ge(i,s,q.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 ge(o,r,q.Video).catch((e=>null)),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var t;return ue(e)}))}_isOffer(){return this.type===j.Offer}_isAnswer(){return this.type===j.Answer}_config(){const{iceServers:e=[]}=this.options,t={bundlePolicy:"max-compat",iceServers:e};return u.info("RTC config",t),t}}const Ke=(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:$.conferenceUpdate,call:e.calls[n],canvasInfo:Je(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:W.LayerInfo},a);M(v.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:W.LayoutInfo},a);M(v.Notification,t,e.uuid);break}}},Je=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return w(t)};var ze="2.11.0";const Qe=ze;class Ye{constructor(e,t){this.session=e,this.id="",this.state=G[G.New],this.prevState="",this.channels=[],this.role=H.Participant,this.extension=null,this._state=G.New,this._prevState=G.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({},F,{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=Ae(this.options.ringtoneFile,"_ringtone"),this._ringback=Ae(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 qe(j.Offer,this.options),this._registerPeerEvents()}answer(e={}){var t;this.stopRingtone(),this.direction=V.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.peer=new qe(j.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Te(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Te(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(G.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(G.Destroy)};if(this.stopRingtone(),s){const e=new Be({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{u.error("telnyl_rtc.bye failed!",e),M(v.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 $e({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new $e({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new $e({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new $e({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new $e({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Fe({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 Fe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ee(this.options.localStream)}unmuteAudio(){Ce(this.options.localStream)}toggleAudioMute(){xe(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 oe({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,Ie(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ie(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ie(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 oe({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;ae(n,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ee(this.options.remoteStream)}undeaf(){Ce(this.options.remoteStream)}toggleDeaf(){xe(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(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:i}=this.peer,s=i.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===t));if(n){const i=n.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),u.info("Parameters: ",i),u.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield n.setParameters(i).then((()=>{u.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())})).catch((e=>console.error(e)))}else u.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=G[this._state].toLowerCase(),this.prevState=G[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:$.callUpdate,call:this}),e){case G.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case G.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ce(e,t)}),0);break;case G.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case B.Answer:if(this.gotAnswer=!0,this._state>=G.Active)return;this._state>=G.Early&&this.setState(G.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case B.Media:if(this._state>=G.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case B.Display:case B.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:$[t],call:this,displayName:e,displayNumber:s,displayDirection:o};M(v.Notification,r,this.id)||M(v.Notification,r,this.session.uuid);break}case B.Info:case B.Event:{const e=Object.assign(Object.assign({},i),{type:$.generic,call:this});M(v.Notification,e,this.id)||M(v.Notification,e,this.session.uuid);break}case B.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case B.Bye: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 u.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:W.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i)),n&&a===H.Moderator&&(yield this._subscribeConferenceModerator(n));const c=[];for(const e in s)c.push(Object.assign({callId:s[e][0],index:Number(e)},_(s[e][1])));this._dispatchConferenceUpdate({action:W.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:W.Add,callId:n,index:o},_(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:W.Modify,callId:n,index:o},_(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:W.Delete,callId:n,index:o},_(s)));break;case"clear":this._dispatchConferenceUpdate({action:W.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:W.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)}));we(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;if("layout-info"===t.contentType)t.callID=this.id,Ke(this.session,t);else u.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfInfo subscription error:",e)}));we(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&&b(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:W.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:W.ModCmdResponse,command:t["conf-command"],response:t.response})}},n=yield this.session.vertoSubscribe(s).catch((e=>{u.error("ConfMod subscription error:",e)}));we(n,e)&&(this.role=H.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(G.Active):this.setState(G.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=_e(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=ve(t));const i={sdp:t,type:j.Answer};this.peer.instance.setRemoteDescription(i).then((()=>{this.gotEarly&&this.setState(G.Early),this.gotAnswer&&this.setState(G.Active)})).catch((e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){S(this.peer.onSdpReadyTwice)?M(v.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-${Qe}`};switch(i){case j.Offer:this.setState(G.Requesting),s=new Ue(n);break;case j.Answer:this.setState(G.Answering),s=!0===this.options.attach?new Ve(n):new je(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===j.Offer?this.setState(G.Trying):this.setState(G.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&&ae(t,i)}))}_onMediaError(e){this._dispatchNotification({type:$.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:$.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(M(v.Notification,e,this.id,!1)||M(v.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&&!b(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,D(v.MediaError,this._onMediaError,this.id),S(s)&&D(v.Notification,s.bind(this),this.id),this.setState(G.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;de(e),de(t),P(v.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")}}Ye.setStateTelnyx=e=>{if(e){switch(e._state){case G.Requesting:case G.Recovering:case G.Trying:case G.Early:e.state="connecting";break;case G.Active:e.state="active";break;case G.Held:e.state="held";break;case G.Hangup:case G.Destroy:e.state="done";break;case G.Answering:e.state="ringing";break;case G.New:e.state="new"}return e}};class Xe extends Ye{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof Xe&&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 Xe(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof Xe&&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)&&ce(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((()=>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`)})))})),u.info(t)}))),2e3)}}class Ze extends ne{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 te(p),e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield ue({audio:e,video:t});return de(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(G.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,i)=>{if(L(v.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 he().catch((e=>(M(v.MediaError,e,this.uuid),[])))}getVideoDevices(){return he(q.Video).catch((e=>(M(v.MediaError,e,this.uuid),[])))}getAudioInDevices(){return he(q.AudioIn).catch((e=>(M(v.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return he(q.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),M(v.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return ge(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 ue({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<pe.length;e++){const[i,n]=pe[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 de(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 fe(n),this._audioConstraints=yield me(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 fe(n),this._videoConstraints=yield me(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||[m,f]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=I(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=I(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 Ge({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 He({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=Se(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 We({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:n=[],notSubscribed:o=[]}=Se(s);return n.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),s}))}static telnyxStateCall(e){return Xe.setStateTelnyx(e)}}class et extends Le{constructor(){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,params:{}})}}class tt{constructor(e,t){this.code=t,this.message=e}}class it extends Le{constructor(){super(),this.method=B.Ping;this.buildRequest({method:this.method,params:{}})}}class st{constructor(e){this.session=e}_ack(e,t){const i=new Me(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*x(2,6)}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===B.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),n.dialogParams&&n.dialogParams.custom_headers&&n.dialogParams.custom_headers.length&&(e.customHeaders=n.dialogParams.custom_headers);const i=new Xe(t,e);return i.nodeId=this.nodeId,i},d=new et,h=new it;switch(s){case B.Ping:this.session.execute(h);break;case B.Punt:t.disconnect();break;case B.Invite:{const e=l();e.playRingtone(),e.setState(G.Ringing),e.direction=V.Inbound,this._ack(i,s);break}case B.Attach:{const t=l();this.session.autoRecoverCalls?t.answer():t.setState(G.Recovering),t.handleMessage(e);break}case B.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)?M(o,n,r):r===t.sessionid?this._handleSessionEvent(n.eventData):t._existsSubscription(o,a)?M(o,n,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):M(v.Notification,n,t.uuid);break;case B.Info:n.type=$.generic,M(v.Notification,n,t.uuid);break;case B.ClientReady:this.session.execute(d);break;default:{const i=R(e);if(i){switch(i){case K.REGISTER:case K.REGED:t.connection.previousGatewayState!==K.REGED&&t.connection.previousGatewayState!==K.REGISTER&&(st.retriedRegister=0,n.type=$.vertoClientReady,M(v.Ready,n,t.uuid));break;case K.UNREGED:case K.NOREG:if(st.retriedRegister+=1,5===st.retriedRegister){st.retriedRegister=0,M(v.Error,new tt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(d)}),this.reconnectDelay());break;case K.FAILED:case K.FAIL_WAIT:if(t.connection.previousGatewayState!==K.FAILED&&t.connection.previousGatewayState!==K.FAIL_WAIT){if(!this.session.hasAutoReconnect()){st.retriedConnect=0,M(v.Error,new tt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(st.retriedConnect+=1,5===st.retriedConnect){st.retriedConnect=0,M(v.Error,n,t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}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 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: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)}));we(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:$.conferenceUpdate,action:W.Leave,conferenceName:o,participantId:Number(l),role:d};M(v.Notification,i,s,!1)||M(v.Notification,i,t.uuid),null===e&&P(v.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":Ke(this.session,e);break;case"logo-info":{const t={type:$.conferenceUpdate,action:W.LogoInfo,logo:e.logoURL};M(v.Notification,t,this.session.uuid);break}}}}st.retriedConnect=0,st.retriedRegister=0;class nt extends Ze{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return k(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new Xe(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 Pe(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,ie(p,this.sessionid))}))}_onSocketMessage(e){new st(this).handleMessage(e)}}e.TelnyxRTC=class extends nt{constructor(e){super(e),console.log(`SDK version: ${ze}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return ke()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Re.not_supported},{browserName:"Firefox",supported:Re.not_supported},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",features:["audio"],supported:Re.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",features:["audio"],supported:Re.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(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 a(e,i,s){return function(){typeof console!==t&&(r.call(this,i,s),this[e].apply(this,arguments))}}function c(s,r,c){return function(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)}(s)||a.apply(this,arguments)}function l(e,i,n){var o,a=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(l)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=n||c,a.getLevel=function(){return o},a.setLevel=function(i,n){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=i),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},e.exports?e.exports=i():t.log=i()}));const d=l.getLogger("telnyx"),u=d.methodFactory;d.methodFactory=(e,t,i)=>{const s=u(e,t,i);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},d.setLevel(d.getLevel());const h="sessId",p="wss://rtc.telnyx.com",g={urls:"stun:stun.telnyx.com:3478"},f={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var m;!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"}(m||(m={}));const v=e=>0===Object.keys(e).length,b=e=>`@telnyx:${e}`,y=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){d.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,media:a,participantData:r}},_=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},w=e=>e instanceof Function||"function"==typeof e,S=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,I=/^(ws|wss):\/\//,C=(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?C(a,r):{result:n}},E=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),k=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),x=e=>{var t,i,s,n,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(n=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===n?void 0:n.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c},R="GLOBAL",N={},A=(e,t)=>`${e}|${t}`,T=(e,t=R)=>A(e,t)in N,O=(e,t,i=R)=>{const s=A(e,i);s in N||(N[s]=[]),N[s].push(t)},D=(e,t,i=R)=>{const s=function(n){L(e,s,i),t(n)};return s.prototype.targetRef=t,O(e,s,i)},L=(e,t,i=R)=>{if(!T(e,i))return!1;const s=A(e,i);if(w(t)){for(let e=N[s].length-1;e>=0;e--){const i=N[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&N[s].splice(e,1)}}else N[s]=[];return 0===N[s].length&&delete N[s],!0},P=(e,t,i=R,s=!0)=>{const n=s&&i!==R;if(!T(e,i))return n&&P(e,t),!1;const o=A(e,i),r=N[o].length;if(!r)return n&&P(e,t),!1;for(let e=r-1;e>=0;e--)N[o][e](t);return n&&P(e,t),!0},M=e=>{const t=A(e,"");Object.keys(N).filter((e=>0===e.indexOf(t))).forEach((e=>delete N[e]))};var U,j,V;!function(e){e.Offer="offer",e.Answer="answer"}(U||(U={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(j||(j={})),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",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(V||(V={}));const B={generic:"event",[V.Display]:"participantData",[V.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},$={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var F,G,H,W,q;!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"}(F||(F={})),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"}(q||(q={}));let K="undefined"!=typeof WebSocket?WebSocket:null;const J=0,z=1,Q=2,Y=3;class X{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=p,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${I.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":p)}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 K(this._host),this._wsClient.onopen=e=>P(m.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>P(m.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>P(m.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=_(e.data);if("string"!=typeof s){if(this._unsetTimer(s.id),d.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),q[`${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)){const e=x(s);P(m.SocketMessage,s,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else 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}=C(t);return n?i(n):e(s)})),this._setTimer(t.id)}));return d.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}close(){this._wsClient&&(w(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(m.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else d.warn("Unknown message from socket",e)}}const Z=()=>"undefined"==typeof window&&"undefined"!=typeof process,ee=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){if(Z())return null;const t=window[e].getItem(b(i));return _(t)})))("sessionStorage",e),te=(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(b(i),s)})))("sessionStorage",e,i),ie=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){return Z()?null:window[e].removeItem(b(i))})))("sessionStorage",e);class se{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 X(this)}get __logger(){return d}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*E(2,6)}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 k(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 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 t(this,void 0,void 0,(function*(){this.connection||(this.connection=new X(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){P(m.Error,e,this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){d.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]={},w(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(m.SocketOpen,this._onSocketOpen),this.on(m.SocketClose,this._onSocketCloseOrError),this.on(m.SocketError,this._onSocketCloseOrError),this.on(m.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(m.SocketOpen,this._onSocketOpen),this.off(m.SocketClose,this._onSocketCloseOrError),this.off(m.SocketError,this._onSocketCloseOrError),this.off(m.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 a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const ne=e=>navigator.mediaDevices.getUserMedia(e),oe=e=>e&&e instanceof MediaStream,re=(e,t)=>{const i=S(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ae=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=S(e);if(null===t)return d.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return d.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),ce=e=>{e&&"live"===e.readyState&&e.stop()},le=e=>{oe(e)&&e.getTracks().forEach(ce),e=null},de=e=>t(void 0,void 0,void 0,(function*(){d.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield ne(e)}catch(e){throw d.error("getUserMedia error: ",e),e}})),ue=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const s=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===W.AudioIn||e===W.AudioOut,video:!e||e===W.Video}))(e)).catch((e=>(console.error(e),null)));if(s){if(le(s),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const n=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!n.includes(t)&&(n.push(t),!0)}))}return t})),he=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],pe=(e,i,s)=>t(void 0,void 0,void 0,(function*(){const t=yield ue(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})),ge=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},fe=(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 pe(e,i,s).catch((e=>null));t&&(n.deviceId={exact:t})}return n})),me=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]+=`${t}a=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},ve=e=>/^m=audio/.test(e),be=e=>/^m=video/.test(e),ye=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(ve)<s.findIndex(be))return e;const n=e.split(i),o=n.findIndex(ve),r=n.findIndex(be),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},_e=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=we(e);return i.includes(t)||s.includes(t)},we=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Se=(e,t=null,i=null)=>{if(!oe(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}}))},Ie=e=>{Se(e,"audio",!0)},Ce=e=>{Se(e,"audio",!1)},Ee=e=>{Se(e,"audio",null)};function ke(){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:!!de}}catch(e){return e.message}}var xe;function Re(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 Ae(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"}(xe||(xe={}));class Te{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const Oe={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class De extends Te{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Oe)e&&i.hasOwnProperty(e)&&(i[Oe[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class Le extends De{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 Pe extends De{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Me extends De{toString(){return V.Invite}}class Ue extends De{toString(){return V.Answer}}class je extends De{toString(){return V.Attach}}class Ve extends De{toString(){return V.Bye}}class Be extends De{toString(){return V.Modify}}class $e extends De{toString(){return V.Info}}class Fe extends De{toString(){return V.Broadcast}}class Ge extends De{toString(){return V.Subscribe}}class He extends De{toString(){return V.Unsubscribe}}class We{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,d.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(){d.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{d.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),d.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(d.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(){d.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&&re(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=>(P(m.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(oe(t)){const s=t.getAudioTracks();d.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(d.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=S(e);t&&(t.muted=!0)})(e),re(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);d.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),d.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>d.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=me(e.sdp)),this.instance.localDescription&&(e.sdp=ye(e.sdp,this.instance.localDescription.sdp));const t=e;return d.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: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=me(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(){w(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(oe(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 pe(t,s,W.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 pe(o,r,W.Video).catch((e=>null)),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var i;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 d.info("RTC config",t),t}}const qe=(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:Ke(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:H.LayerInfo},a);P(m.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:H.LayoutInfo},a);P(m.Notification,t,e.uuid);break}}},Ke=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return _(t)};var Je="2.10.2";const ze=Je;class Qe{constructor(e,t){this.session=e,this.id="",this.state=F[F.New],this.prevState="",this.channels=[],this.role=G.Participant,this.extension=null,this._state=F.New,this._prevState=F.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({},$,{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=Re(this.options.ringtoneFile,"_ringtone"),this._ringback=Re(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=j.Outbound,this.peer=new We(U.Offer,this.options),this._registerPeerEvents()}answer(e={}){var t;this.stopRingtone(),this.direction=j.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.peer=new We(U.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Ae(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Ae(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(F.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(F.Destroy)};if(this.stopRingtone(),s){const e=new Ve({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{d.error("telnyl_rtc.bye failed!",e),P(m.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 Be({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Be({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Be({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 Be({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 Be({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 $e({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 $e({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ce(this.options.localStream)}unmuteAudio(){Ie(this.options.localStream)}toggleAudioMute(){Ee(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 ne({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,Se(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Se(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Se(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 ne({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;re(n,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ce(this.options.remoteStream)}undeaf(){Ie(this.options.remoteStream)}toggleDeaf(){Ee(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void d.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 d.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"}]),d.info("Parameters: ",t),d.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield n.setParameters(t).then((()=>{d.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())})).catch((e=>console.error(e)))}else d.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=F[this._state].toLowerCase(),this.prevState=F[this._prevState].toLowerCase(),d.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case F.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case F.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ae(e,t)}),0);break;case F.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case V.Answer:if(this.gotAnswer=!0,this._state>=F.Active)return;this._state>=F.Early&&this.setState(F.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case V.Media:if(this._state>=F.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case V.Display:case V.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===j.Inbound?j.Outbound:j.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:s,displayDirection:o};P(m.Notification,r,this.id)||P(m.Notification,r,this.session.uuid);break}case V.Info:case V.Event:{const e=Object.assign(Object.assign({},i),{type:B.generic,call:this});P(m.Notification,e,this.id)||P(m.Notification,e,this.session.uuid);break}case V.Ringing:this.playRingback();break;case V.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 d.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:H.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),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)},y(s[e][1])));this._dispatchConferenceUpdate({action:H.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:H.Add,callId:n,index:o},y(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:H.Modify,callId:n,index:o},y(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:H.Delete,callId:n,index:o},y(s)));break;case"clear":this._dispatchConferenceUpdate({action:H.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:H.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{d.error("ConfChat subscription error:",e)}));_e(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,qe(this.session,t);else d.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{d.error("ConfInfo subscription error:",e)}));_e(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&&v(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:H.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:H.ModCmdResponse,command:t["conf-command"],response:t.response})}},n=yield this.session.vertoSubscribe(s).catch((e=>{d.error("ConfMod subscription error:",e)}));_e(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(F.Active):this.setState(F.Held),!0}_handleChangeHoldStateError(e){return d.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=ye(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=me(t));const i={sdp:t,type:U.Answer};this.peer.instance.setRemoteDescription(i).then((()=>{this.gotEarly&&this.setState(F.Early),this.gotAnswer&&this.setState(F.Active)})).catch((e=>{d.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){w(this.peer.onSdpReadyTwice)?P(m.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 d.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-${ze}`};switch(i){case U.Offer:this.setState(F.Requesting),s=new Me(n);break;case U.Answer:this.setState(F.Answering),s=!0===this.options.attach?new je(n):new Ue(n);break;default:return d.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(F.Trying):this.setState(F.Active)})).catch((e=>{d.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?d.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&&re(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(m.Notification,e,this.id,!1)||P(m.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&&!v(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(m.MediaError,this._onMediaError,this.id),w(s)&&O(m.Notification,s.bind(this),this.id),this.setState(F.New),d.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;le(e),le(t),L(m.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),d.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),d.info("Stats stopped")}}Qe.setStateTelnyx=e=>{if(e){switch(e._state){case F.Requesting:case F.Recovering:case F.Trying:case F.Early:e.state="connecting";break;case F.Active:e.state="active";break;case F.Held:e.state="held";break;case F.Hangup:case F.Destroy:e.state="done";break;case F.Answering:e.state="ringing";break;case F.New:e.state="new"}return e}};class Ye extends Qe{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof Ye&&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 Ye(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof Ye&&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)&&ae(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);d.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`)})))})),d.info(t)}))),2e3)}}class Xe extends se{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 ee(h),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield de({audio:e,video:i});return le(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(F.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,i)=>{if(D(m.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 ue().catch((e=>(P(m.MediaError,e,this.uuid),[])))}getVideoDevices(){return ue(W.Video).catch((e=>(P(m.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ue(W.AudioIn).catch((e=>(P(m.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return ue(W.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),P(m.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return pe(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 de({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<he.length;e++){const[i,n]=he[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 le(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 ge(n),this._audioConstraints=yield fe(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 ge(n),this._videoConstraints=yield fe(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||[f,g]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=S(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=S(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const s=new Fe({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 Ge({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=we(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 He({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unsubscribed:n=[],notSubscribed:o=[]}=we(s);return n.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),s}))}static telnyxStateCall(e){return Ye.setStateTelnyx(e)}}class Ze extends De{constructor(){super(),this.method=V.GatewayState;this.buildRequest({method:this.method,params:{}})}}class et{constructor(e,t){this.code=t,this.message=e}}class tt extends De{constructor(){super(),this.method=V.Ping;this.buildRequest({method:this.method,params:{}})}}class it{constructor(e){this.session=e}_ack(e,t){const i=new Pe(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*E(2,6)}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===V.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),n.dialogParams&&n.dialogParams.custom_headers&&n.dialogParams.custom_headers.length&&(e.customHeaders=n.dialogParams.custom_headers);const i=new Ye(t,e);return i.nodeId=this.nodeId,i},u=new Ze,h=new tt;switch(s){case V.Ping:this.session.execute(h);break;case V.Punt:t.disconnect();break;case V.Invite:{const e=l();e.playRingtone(),e.setState(F.Ringing),this._ack(i,s);break}case V.Attach:{const t=l();this.session.autoRecoverCalls?t.answer():t.setState(F.Recovering),t.handleMessage(e);break}case V.Event:case"webrtc.event":if(!r)return void d.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(m.Notification,n,t.uuid);break;case V.Info:n.type=B.generic,P(m.Notification,n,t.uuid);break;case V.ClientReady:this.session.execute(u);break;default:{const i=x(e);if(i){switch(i){case q.REGISTER:case q.REGED:t.connection.previousGatewayState!==q.REGED&&t.connection.previousGatewayState!==q.REGISTER&&(it.retriedRegister=0,n.type=B.vertoClientReady,P(m.Ready,n,t.uuid));break;case q.UNREGED:case q.NOREG:if(it.retriedRegister+=1,5===it.retriedRegister){it.retriedRegister=0,P(m.Error,new et("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(u)}),this.reconnectDelay());break;case q.FAILED:case q.FAIL_WAIT:if(t.connection.previousGatewayState!==q.FAILED&&t.connection.previousGatewayState!==q.FAIL_WAIT){if(!this.session.hasAutoReconnect()){it.retriedConnect=0,P(m.Error,new et("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(it.retriedConnect+=1,5===it.retriedConnect){it.retriedConnect=0,P(m.Error,n,t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:d.warn("GatewayState message unknown method:",e)}break}d.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:u,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=>{d.error("liveArray subscription error:",e)}));_e(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(l),role:u};P(m.Notification,i,s,!1)||P(m.Notification,i,t.uuid),null===e&&L(m.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=>{d.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":qe(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:H.LogoInfo,logo:e.logoURL};P(m.Notification,t,this.session.uuid);break}}}}it.retriedConnect=0,it.retriedRegister=0;class st extends Xe{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return k(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new Ye(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 Le(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,te(h,this.sessionid))}))}_onSocketMessage(e){new it(this).handleMessage(e)}}class nt extends st{constructor(e){super(e),console.log(`SDK version: ${Je}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return ke()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:xe.full},{browserName:"Firefox",features:["audio"],supported:xe.partial},{browserName:"Safari",supported:xe.not_supported},{browserName:"Edge",supported:xe.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:xe.not_supported},{browserName:"Firefox",supported:xe.not_supported},{browserName:"Safari",features:["video","audio"],supported:xe.full},{browserName:"Edge",supported:xe.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:xe.full},{browserName:"Firefox",features:["audio"],supported:xe.partial},{browserName:"Safari",supported:xe.not_supported},{browserName:"Edge",supported:xe.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:xe.full},{browserName:"Firefox",features:["audio"],supported:xe.partial},{browserName:"Safari",features:["video","audio"],supported:xe.full},{browserName:"Edge",features:["audio"],supported:xe.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:xe.full},{browserName:"Firefox",features:["audio"],supported:xe.partial},{browserName:"Safari",supported:xe.not_supported},{browserName:"Edge",features:["audio"],supported:xe.partial}]}]}}export{nt 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 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(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 a(e,i,s){return function(){typeof console!==t&&(r.call(this,i,s),this[e].apply(this,arguments))}}function c(s,r,c){return function(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)}(s)||a.apply(this,arguments)}function l(e,i,n){var o,a=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=i.indexOf(encodeURIComponent(l)+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=n||c,a.getLevel=function(){return o},a.setLevel=function(i,n){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==n&&function(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=i),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},e.exports?e.exports=i():t.log=i()}));const d=l.getLogger("telnyx"),u=d.methodFactory;d.methodFactory=(e,t,i)=>{const s=u(e,t,i);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);s.apply(void 0,e)}},d.setLevel(d.getLevel());const h="sessId",p="wss://rtc.telnyx.com",g={urls:"stun:stun.telnyx.com:3478"},f={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var m;!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"}(m||(m={}));const v=e=>0===Object.keys(e).length,b=e=>`@telnyx:${e}`,y=e=>{const[t,i,s,n,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){d.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:s,codec:n,media:a,participantData:r}},_=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},w=e=>e instanceof Function||"function"==typeof e,S=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,I=/^(ws|wss):\/\//,C=(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?C(a,r):{result:n}},E=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),x=({login:e,passwd:t,password:i,login_token:s})=>Boolean(e&&(t||i)||s),k=e=>{var t,i,s,n,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(n=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===n?void 0:n.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c},R="GLOBAL",A={},N=(e,t)=>`${e}|${t}`,T=(e,t=R)=>N(e,t)in A,O=(e,t,i=R)=>{const s=N(e,i);s in A||(A[s]=[]),A[s].push(t)},D=(e,t,i=R)=>{const s=function(n){L(e,s,i),t(n)};return s.prototype.targetRef=t,O(e,s,i)},L=(e,t,i=R)=>{if(!T(e,i))return!1;const s=N(e,i);if(w(t)){for(let e=A[s].length-1;e>=0;e--){const i=A[s][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&A[s].splice(e,1)}}else A[s]=[];return 0===A[s].length&&delete A[s],!0},P=(e,t,i=R,s=!0)=>{const n=s&&i!==R;if(!T(e,i))return n&&P(e,t),!1;const o=N(e,i),r=A[o].length;if(!r)return n&&P(e,t),!1;for(let e=r-1;e>=0;e--)A[o][e](t);return n&&P(e,t),!0},M=e=>{const t=N(e,"");Object.keys(A).filter((e=>0===e.indexOf(t))).forEach((e=>delete A[e]))};var U,j,V;!function(e){e.Offer="offer",e.Answer="answer"}(U||(U={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(j||(j={})),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",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(V||(V={}));const B={generic:"event",[V.Display]:"participantData",[V.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},$={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var F,G,H,W,q;!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"}(F||(F={})),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"}(q||(q={}));let K="undefined"!=typeof WebSocket?WebSocket:null;const J=0,z=1,Q=2,Y=3;class X{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=p,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:i}=e.options;t&&(this._host=(e=>`${I.test(e)?"":"wss://"}${e}`)(t)),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":p)}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 K(this._host),this._wsClient.onopen=e=>P(m.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>P(m.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>P(m.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,i;const s=_(e.data);if("string"!=typeof s){if(this._unsetTimer(s.id),d.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),q[`${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)){const e=k(s);P(m.SocketMessage,s,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else 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}=C(t);return n?i(n):e(s)})),this._setTimer(t.id)}));return d.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),i}close(){this._wsClient&&(w(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(m.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else d.warn("Unknown message from socket",e)}}const Z=()=>"undefined"==typeof window&&"undefined"!=typeof process,ee=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){if(Z())return null;const t=window[e].getItem(b(i));return _(t)})))("sessionStorage",e),te=(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(b(i),s)})))("sessionStorage",e,i),ie=e=>((e,i)=>t(void 0,void 0,void 0,(function*(){return Z()?null:window[e].removeItem(b(i))})))("sessionStorage",e);class se{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 X(this)}get __logger(){return d}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*E(2,6)}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 t(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 t(this,void 0,void 0,(function*(){this.connection||(this.connection=new X(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){P(m.Error,e,this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){d.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]={},w(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(m.SocketOpen,this._onSocketOpen),this.on(m.SocketClose,this._onSocketCloseOrError),this.on(m.SocketError,this._onSocketCloseOrError),this.on(m.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(m.SocketOpen,this._onSocketOpen),this.off(m.SocketClose,this._onSocketCloseOrError),this.off(m.SocketError,this._onSocketCloseOrError),this.off(m.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 a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const ne=e=>navigator.mediaDevices.getUserMedia(e),oe=e=>e&&e instanceof MediaStream,re=(e,t)=>{const i=S(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ae=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=S(e);if(null===t)return d.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return d.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),ce=e=>{e&&"live"===e.readyState&&e.stop()},le=e=>{oe(e)&&e.getTracks().forEach(ce),e=null},de=e=>t(void 0,void 0,void 0,(function*(){d.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield ne(e)}catch(e){throw d.error("getUserMedia error: ",e),e}})),ue=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const s=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===W.AudioIn||e===W.AudioOut,video:!e||e===W.Video}))(e)).catch((e=>(console.error(e),null)));if(s){if(le(s),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const n=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!n.includes(t)&&(n.push(t),!0)}))}return t})),he=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],pe=(e,i,s)=>t(void 0,void 0,void 0,(function*(){const t=yield ue(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})),ge=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},fe=(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 pe(e,i,s).catch((e=>null));t&&(n.deviceId={exact:t})}return n})),me=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]+=`${t}a=fmtp:${n} stereo=1; sprop-stereo=1`,i.join(t)},ve=e=>/^m=audio/.test(e),be=e=>/^m=video/.test(e),ye=(e,t)=>{const i="\r\n",s=t.split(i);if(s.findIndex(ve)<s.findIndex(be))return e;const n=e.split(i),o=n.findIndex(ve),r=n.findIndex(be),a=n.slice(o,r),c=n.slice(r,n.length-1);return[...n.slice(0,o),...c,...a,""].join(i)},_e=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:s}=we(e);return i.includes(t)||s.includes(t)},we=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Se=(e,t=null,i=null)=>{if(!oe(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}}))},Ie=e=>{Se(e,"audio",!0)},Ce=e=>{Se(e,"audio",!1)},Ee=e=>{Se(e,"audio",null)};function xe(){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:!!de}}catch(e){return e.message}}var ke;function Re(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 Ae(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 Ne(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={}));class Te{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const Oe={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class De extends Te{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Oe)e&&i.hasOwnProperty(e)&&(i[Oe[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class Le extends De{constructor(e,t,i,s,n={}){super(),this.method="login";const o={login:e,passwd:t,login_token:i,userVariables:n,loginParams:{},"User-Agent":window.navigator.userAgent};s&&(o.sessid=s),this.buildRequest({method:this.method,params:o})}}class Pe extends De{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Me extends De{toString(){return V.Invite}}class Ue extends De{toString(){return V.Answer}}class je extends De{toString(){return V.Attach}}class Ve extends De{toString(){return V.Bye}}class Be extends De{toString(){return V.Modify}}class $e extends De{toString(){return V.Info}}class Fe extends De{toString(){return V.Broadcast}}class Ge extends De{toString(){return V.Subscribe}}class He extends De{toString(){return V.Unsubscribe}}class We{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,d.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(){d.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{d.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),d.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(d.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(){d.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&&re(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=>(P(m.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(oe(t)){const s=t.getAudioTracks();d.info("Local audio tracks: ",s);const n=t.getVideoTracks();if(d.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=S(e);t&&(t.muted=!0)})(e),re(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);d.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),d.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>d.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=me(e.sdp)),this.instance.localDescription&&(e.sdp=ye(e.sdp,this.instance.localDescription.sdp));const t=e;return d.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: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=me(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(){w(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(oe(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 pe(t,s,W.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 pe(o,r,W.Video).catch((e=>null)),o&&("boolean"==typeof n&&(n={}),n.deviceId={exact:o})),{audio:e,video:n}})));var i;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 d.info("RTC config",t),t}}const qe=(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:Ke(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:H.LayerInfo},a);P(m.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:H.LayoutInfo},a);P(m.Notification,t,e.uuid);break}}},Ke=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return _(t)};var Je="2.11.0";const ze=Je;class Qe{constructor(e,t){this.session=e,this.id="",this.state=F[F.New],this.prevState="",this.channels=[],this.role=G.Participant,this.extension=null,this._state=F.New,this._prevState=F.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({},$,{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=Re(this.options.ringtoneFile,"_ringtone"),this._ringback=Re(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=j.Outbound,this.peer=new We(U.Offer,this.options),this._registerPeerEvents()}answer(e={}){var t;this.stopRingtone(),this.direction=j.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.peer=new We(U.Answer,this.options),this._registerPeerEvents()}playRingtone(){Ae(this._ringtone)}stopRingtone(){Ne(this._ringtone)}playRingback(){Ae(this._ringback)}stopRingback(){Ne(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(F.Hangup);const n=()=>{this.peer&&this.peer.instance.close(),this.setState(F.Destroy)};if(this.stopRingtone(),s){const e=new Ve({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{d.error("telnyl_rtc.bye failed!",e),P(m.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 Be({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Be({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Be({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 Be({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 Be({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 $e({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 $e({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Ce(this.options.localStream)}unmuteAudio(){Ie(this.options.localStream)}toggleAudioMute(){Ee(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 ne({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,Se(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Se(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Se(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 ne({video:{deviceId:{exact:e}}}),s=t.getVideoTracks()[0];i.replaceTrack(s);const{localElement:n,localStream:o}=this.options;re(n,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ce(this.options.remoteStream)}undeaf(){Ie(this.options.remoteStream)}toggleDeaf(){Ee(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void d.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 d.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"}]),d.info("Parameters: ",t),d.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield n.setParameters(t).then((()=>{d.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",n.getParameters())})).catch((e=>console.error(e)))}else d.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=F[this._state].toLowerCase(),this.prevState=F[this._prevState].toLowerCase(),d.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case F.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case F.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ae(e,t)}),0);break;case F.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case V.Answer:if(this.gotAnswer=!0,this._state>=F.Active)return;this._state>=F.Early&&this.setState(F.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case V.Media:if(this._state>=F.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case V.Display:case V.Attach:{const{display_name:e,display_number:s,display_direction:n}=i;this.extension=s;const o=n===j.Inbound?j.Outbound:j.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:s,displayDirection:o};P(m.Notification,r,this.id)||P(m.Notification,r,this.session.uuid);break}case V.Info:case V.Event:{const e=Object.assign(Object.assign({},i),{type:B.generic,call:this});P(m.Notification,e,this.id)||P(m.Notification,e,this.session.uuid);break}case V.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case V.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 d.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:H.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),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)},y(s[e][1])));this._dispatchConferenceUpdate({action:H.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:H.Add,callId:n,index:o},y(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:H.Modify,callId:n,index:o},y(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:H.Delete,callId:n,index:o},y(s)));break;case"clear":this._dispatchConferenceUpdate({action:H.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:H.ChatMessage,direction:t,participantNumber:i,participantName:s,messageText:n,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{d.error("ConfChat subscription error:",e)}));_e(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,qe(this.session,t);else d.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{d.error("ConfInfo subscription error:",e)}));_e(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&&v(e))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:H.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:H.ModCmdResponse,command:t["conf-command"],response:t.response})}},n=yield this.session.vertoSubscribe(s).catch((e=>{d.error("ConfMod subscription error:",e)}));_e(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(F.Active):this.setState(F.Held),!0}_handleChangeHoldStateError(e){return d.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=ye(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=me(t));const i={sdp:t,type:U.Answer};this.peer.instance.setRemoteDescription(i).then((()=>{this.gotEarly&&this.setState(F.Early),this.gotAnswer&&this.setState(F.Active)})).catch((e=>{d.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){w(this.peer.onSdpReadyTwice)?P(m.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 d.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-${ze}`};switch(i){case U.Offer:this.setState(F.Requesting),s=new Me(n);break;case U.Answer:this.setState(F.Answering),s=!0===this.options.attach?new je(n):new Ue(n);break;default:return d.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(F.Trying):this.setState(F.Active)})).catch((e=>{d.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?d.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&&re(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(m.Notification,e,this.id,!1)||P(m.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&&!v(t)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(m.MediaError,this._onMediaError,this.id),w(s)&&O(m.Notification,s.bind(this),this.id),this.setState(F.New),d.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;le(e),le(t),L(m.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),d.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),d.info("Stats stopped")}}Qe.setStateTelnyx=e=>{if(e){switch(e._state){case F.Requesting:case F.Recovering:case F.Trying:case F.Early:e.state="connecting";break;case F.Active:e.state="active";break;case F.Held:e.state="held";break;case F.Hangup:case F.Destroy:e.state="done";break;case F.Answering:e.state="ringing";break;case F.New:e.state="new"}return e}};class Ye extends Qe{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof Ye&&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 Ye(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof Ye&&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)&&ae(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);d.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`)})))})),d.info(t)}))),2e3)}}class Xe extends se{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 ee(h),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield de({audio:e,video:i});return le(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(F.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,i)=>{if(D(m.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 ue().catch((e=>(P(m.MediaError,e,this.uuid),[])))}getVideoDevices(){return ue(W.Video).catch((e=>(P(m.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ue(W.AudioIn).catch((e=>(P(m.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return ue(W.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),P(m.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return pe(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 de({video:{deviceId:{exact:e}}}),s=i.getVideoTracks()[0];for(let e=0;e<he.length;e++){const[i,n]=he[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 le(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 ge(n),this._audioConstraints=yield fe(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 ge(n),this._videoConstraints=yield fe(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||[f,g]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=S(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=S(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const s=new Fe({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 Ge({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=we(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 He({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unsubscribed:n=[],notSubscribed:o=[]}=we(s);return n.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),s}))}static telnyxStateCall(e){return Ye.setStateTelnyx(e)}}class Ze extends De{constructor(){super(),this.method=V.GatewayState;this.buildRequest({method:this.method,params:{}})}}class et{constructor(e,t){this.code=t,this.message=e}}class tt extends De{constructor(){super(),this.method=V.Ping;this.buildRequest({method:this.method,params:{}})}}class it{constructor(e){this.session=e}_ack(e,t){const i=new Pe(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*E(2,6)}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===V.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),n.dialogParams&&n.dialogParams.custom_headers&&n.dialogParams.custom_headers.length&&(e.customHeaders=n.dialogParams.custom_headers);const i=new Ye(t,e);return i.nodeId=this.nodeId,i},u=new Ze,h=new tt;switch(s){case V.Ping:this.session.execute(h);break;case V.Punt:t.disconnect();break;case V.Invite:{const e=l();e.playRingtone(),e.setState(F.Ringing),e.direction=j.Inbound,this._ack(i,s);break}case V.Attach:{const t=l();this.session.autoRecoverCalls?t.answer():t.setState(F.Recovering),t.handleMessage(e);break}case V.Event:case"webrtc.event":if(!r)return void d.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(m.Notification,n,t.uuid);break;case V.Info:n.type=B.generic,P(m.Notification,n,t.uuid);break;case V.ClientReady:this.session.execute(u);break;default:{const i=k(e);if(i){switch(i){case q.REGISTER:case q.REGED:t.connection.previousGatewayState!==q.REGED&&t.connection.previousGatewayState!==q.REGISTER&&(it.retriedRegister=0,n.type=B.vertoClientReady,P(m.Ready,n,t.uuid));break;case q.UNREGED:case q.NOREG:if(it.retriedRegister+=1,5===it.retriedRegister){it.retriedRegister=0,P(m.Error,new et("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(u)}),this.reconnectDelay());break;case q.FAILED:case q.FAIL_WAIT:if(t.connection.previousGatewayState!==q.FAILED&&t.connection.previousGatewayState!==q.FAIL_WAIT){if(!this.session.hasAutoReconnect()){it.retriedConnect=0,P(m.Error,new et("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(it.retriedConnect+=1,5===it.retriedConnect){it.retriedConnect=0,P(m.Error,n,t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:d.warn("GatewayState message unknown method:",e)}break}d.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:u,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=>{d.error("liveArray subscription error:",e)}));_e(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(l),role:u};P(m.Notification,i,s,!1)||P(m.Notification,i,t.uuid),null===e&&L(m.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=>{d.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":qe(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:H.LogoInfo,logo:e.logoURL};P(m.Notification,t,this.session.uuid);break}}}}it.retriedConnect=0,it.retriedRegister=0;class st extends Xe{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return x(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");const t=new Ye(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 Le(e,t||i,s,this.sessionid,n),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,te(h,this.sessionid))}))}_onSocketMessage(e){new it(this).handleMessage(e)}}class nt extends st{constructor(e){super(e),console.log(`SDK version: ${Je}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return xe()}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}]}]}}export{nt as TelnyxRTC};
|