@telnyx/webrtc 2.11.0 → 2.13.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 CHANGED
@@ -1,3 +1,17 @@
1
+ ## [2.13.0](https://github.com/team-telnyx/webrtc/compare/webrtc/v2.12.0...webrtc/v2.13.0) (2024-04-22)
2
+
3
+
4
+ ### Features
5
+
6
+ * add probe to fetch webrtc statistics periodically ([#350](https://github.com/team-telnyx/webrtc/issues/350)) ([2a72b60](https://github.com/team-telnyx/webrtc/commit/2a72b60843599dd824ee40ef79bdce2d8ba1ce52))
7
+
8
+ ## [2.12.0](https://github.com/team-telnyx/webrtc/compare/webrtc/v2.11.0...webrtc/v2.12.0) (2024-04-05)
9
+
10
+
11
+ ### Features
12
+
13
+ * add a faster work-around for ice gathering never completing ([#349](https://github.com/team-telnyx/webrtc/issues/349)) ([47e1863](https://github.com/team-telnyx/webrtc/commit/47e18633b142263d49ca061f8b0c29fd5d5edf2a))
14
+
1
15
  ## [2.11.0](https://github.com/team-telnyx/webrtc/compare/webrtc/v2.10.2...webrtc/v2.11.0) (2024-02-26)
2
16
 
3
17
 
package/README.md CHANGED
@@ -154,6 +154,24 @@ call.muteAudio();
154
154
 
155
155
  > See [Call#methods](./docs/ts/classes/call.md#methods) for all methods.
156
156
 
157
+ ### Debugging
158
+
159
+ In order to have a better idea on what is going on under the hood you can gather webrtc metrics for a call:
160
+
161
+ ```js
162
+ const call = client.newCall({
163
+ // Destination is required and can be a phone number or SIP URI
164
+ destinationNumber: '18004377950',
165
+ callerNumber: '‬155531234567',
166
+ });
167
+
168
+ // Start the gathering of data
169
+ call.startDebugger();
170
+
171
+ // Stop the gathering of data
172
+ call.stopDebugger();
173
+ ```
174
+
157
175
  ---
158
176
 
159
177
  ## Examples
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}},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})}));
15
+ ***************************************************************************** */function t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function n(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}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 o(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||function(e,t){var n=t||0,i=r;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(s)}var d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function l(e,t){return e(t={exports:{}},t.exports),t.exports}var u=l((function(e){var t,n;t=d,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=n),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=n():t.log=n()}));const h=u.getLogger("telnyx"),p=h.methodFactory;h.methodFactory=(e,t,n)=>{const i=p(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},h.setLevel(h.getLevel());const g="sessId",f="Time to call invite",m="wss://rtc.telnyx.com",v={urls:"stun:stun.telnyx.com:3478"},b={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var y;!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"}(y||(y={}));const _=e=>0===Object.keys(e).length,w=e=>`@telnyx:${e}`,S=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){h.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},I=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},C=e=>e instanceof Function||"function"==typeof e,E=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,k=/^(ws|wss):\/\//,T=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?T(a,r):{result:s}},x=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),R=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),M=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};const A=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},D="GLOBAL",L={},N=(e,t)=>`${e}|${t}`,O=(e,t=D)=>N(e,t)in L,P=(e,t,n=D)=>{const i=N(e,n);i in L||(L[i]=[]),L[i].push(t)},U=(e,t,n=D)=>{const i=function(s){j(e,i,n),t(s)};return i.prototype.targetRef=t,P(e,i,n)},j=(e,t,n=D)=>{if(!O(e,n))return!1;const i=N(e,n);if(C(t)){for(let e=L[i].length-1;e>=0;e--){const n=L[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&L[i].splice(e,1)}}else L[i]=[];return 0===L[i].length&&delete L[i],!0},$=(e,t,n=D,i=!0)=>{const s=i&&n!==D;if(!O(e,n))return s&&$(e,t),!1;const o=N(e,n),r=L[o].length;if(!r)return s&&$(e,t),!1;for(let e=r-1;e>=0;e--)L[o][e](t);return s&&$(e,t),!0},V=e=>{const t=N(e,"");Object.keys(L).filter((e=>0===e.indexOf(t))).forEach((e=>delete L[e]))};var G,B,F;!function(e){e.Offer="offer",e.Answer="answer"}(G||(G={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(B||(B={})),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"}(F||(F={}));const W={generic:"event",[F.Display]:"participantData",[F.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},H={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var K,q,J,z,Y;!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"}(K||(K={})),function(e){e.Participant="participant",e.Moderator="moderator"}(q||(q={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(J||(J={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(z||(z={})),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"}(Y||(Y={}));let Q="undefined"!=typeof WebSocket?WebSocket:null;const X=0,Z=1,ee=2,te=3;class ne{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=m,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${k.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":m)}get connected(){return this._wsClient&&this._wsClient.readyState===Z}get connecting(){return this._wsClient&&this._wsClient.readyState===X}get closing(){return this._wsClient&&this._wsClient.readyState===ee}get closed(){return this._wsClient&&this._wsClient.readyState===te}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new Q(this._host),this._wsClient.onopen=e=>$(y.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>$(y.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>$(y.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=I(e.data);if("string"!=typeof i){if(this._unsetTimer(i.id),h.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),Y[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!$(i.id,i)){const e=M(i);$(y.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();U(t.id,(t=>{const{result:i,error:s}=T(t);return s?n(s):e(i)})),this._setTimer(t.id)}));return h.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(C(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((()=>{$(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)),$(y.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else h.warn("Unknown message from socket",e)}}const ie=()=>"undefined"==typeof window&&"undefined"!=typeof process,se=e=>((e,t)=>n(void 0,void 0,void 0,(function*(){if(ie())return null;const n=window[e].getItem(w(t));return I(n)})))("sessionStorage",e),oe=(e,t)=>((e,t,i)=>n(void 0,void 0,void 0,(function*(){if(ie())return null;"object"==typeof i&&(i=JSON.stringify(i)),window[e].setItem(w(t),i)})))("sessionStorage",e,t),re=e=>((e,t)=>n(void 0,void 0,void 0,(function*(){return ie()?null:window[e].removeItem(w(t))})))("sessionStorage",e);class ae{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 ne(this)}get __logger(){return h}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 R(this.options)}broadcast(e){}disconnect(){return n(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield re(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return P(e,t,this.uuid),this}off(e,t){return j(e,t,this.uuid),this}connect(){return n(this,void 0,void 0,(function*(){this.connection||(this.connection=new ne(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){$(y.Error,e,this.uuid)}_onSocketOpen(){return n(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){h.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&V(this.relayProtocol);for(const e in this.subscriptions)V(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],j(e,null,t)):(delete this.subscriptions[e],V(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},C(t)&&P(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(y.SocketOpen,this._onSocketOpen),this.on(y.SocketClose,this._onSocketCloseOrError),this.on(y.SocketError,this._onSocketCloseOrError),this.on(y.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(y.SocketOpen,this._onSocketOpen),this.off(y.SocketClose,this._onSocketCloseOrError),this.off(y.SocketError,this._onSocketCloseOrError),this.off(y.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){P(e,t)}static off(e){j(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const ce=e=>navigator.mediaDevices.getUserMedia(e),de=e=>e&&e instanceof MediaStream,le=(e,t)=>{const n=E(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},ue=(e,t)=>n(void 0,void 0,void 0,(function*(){const n=E(e);if(null===n)return h.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return h.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch(e){return!1}})),he=e=>{e&&"live"===e.readyState&&e.stop()},pe=e=>{de(e)&&e.getTracks().forEach(he),e=null},ge=e=>n(void 0,void 0,void 0,(function*(){h.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield ce(e)}catch(e){throw h.error("getUserMedia error: ",e),e}})),fe=(e=null,t=!1)=>n(void 0,void 0,void 0,(function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===z.AudioIn||e===z.AudioOut,video:!e||e===z.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(pe(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter((t=>t.kind===e))),!0===t)return n;const s=[];n=n.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return n})),me=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ve=(e,t,i)=>n(void 0,void 0,void 0,(function*(){const n=yield fe(i,!0);for(let i=0;i<n.length;i++){const{deviceId:s,label:o}=n[i];if(e===s||t===o)return s}return null})),be=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},ye=(e,t,i,s)=>n(void 0,void 0,void 0,(function*(){const{deviceId:n}=s;if(void 0===n&&(e||t)){const n=yield ve(e,t,i).catch((e=>null));n&&(s.deviceId={exact:n})}return s})),_e=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},we=e=>/^m=audio/.test(e),Se=e=>/^m=video/.test(e),Ie=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(we)<i.findIndex(Se))return e;const s=e.split(n),o=s.findIndex(we),r=s.findIndex(Se),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},Ce=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Ee(e);return n.includes(t)||i.includes(t)},Ee=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},ke=(e,t=null,n=null)=>{if(!de(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Te=e=>{ke(e,"audio",!0)},xe=e=>{ke(e,"audio",!1)},Re=e=>{ke(e,"audio",null)};function Me(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!ge}}catch(e){return e.message}}var Ae;function De(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Le(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"}(Ae||(Ae={}));class Oe{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const Pe={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 Ue extends Oe{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Pe)e&&n.hasOwnProperty(e)&&(n[Pe[e]]=n[e],delete n[e]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class je extends Ue{constructor(e,t,n,i,s={}){super(),this.method="login";const o={login:e,passwd:t,login_token:n,userVariables:s,loginParams:{},"User-Agent":window.navigator.userAgent};i&&(o.sessid=i),this.buildRequest({method:this.method,params:o})}}class $e extends Ue{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ve extends Ue{toString(){return F.Invite}}class Ge extends Ue{toString(){return F.Answer}}class Be extends Ue{toString(){return F.Attach}}class Fe extends Ue{toString(){return F.Bye}}class We extends Ue{toString(){return F.Modify}}class He extends Ue{toString(){return F.Info}}class Ke extends Ue{toString(){return F.Broadcast}}class qe extends Ue{toString(){return F.Subscribe}}class Je extends Ue{toString(){return F.Unsubscribe}}class ze{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleIceCandidate=e=>{e.candidate&&["relay","srflx"].includes(e.candidate.type)&&this.iceGatheringComplete.resolve(!0)},h.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this.iceGatheringComplete=function({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?A(i,e):i,n=s})),resolve:t,reject:n}}({debounceTime:100}),this._init()}get isOffer(){return this.type===G.Offer}get isAnswer(){return this.type===G.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){h.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{h.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),h.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(h.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){h.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&le(n,s)}createPeerConnection(){return n(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("icecandidate",this.handleIceCandidate),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>($(y.MediaError,e,this.options.id),null)))}))}_init(){return n(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:n=!1}=this.options;if(de(t)){const i=t.getAudioTracks();h.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(h.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){i.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),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=E(e);t&&(t.muted=!0)})(e),le(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),this._logTransceivers()}))}_getSenderByKind(e){return this.instance.getSenders().find((({track:t})=>t&&t.kind===e))}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);h.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),h.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>h.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=_e(e.sdp)),this.instance.localDescription&&(e.sdp=Ie(e.sdp,this.instance.localDescription.sdp));const t=e;return h.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return n(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:G.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:G.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=_e(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){C(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return n(this,void 0,void 0,(function*(){if(de(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,n(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:n}=t;const{micLabel:i=""}=t;n&&(n=yield ve(n,i,z.AudioIn).catch((e=>null)),n&&("boolean"==typeof e&&(e={}),e.deviceId={exact:n}));let{video:s=!1,camId:o}=t;const{camLabel:r=""}=t;return o&&(o=yield ve(o,r,z.Video).catch((e=>null)),o&&("boolean"==typeof s&&(s={}),s.deviceId={exact:o})),{audio:e,video:s}})));var t;return ge(e)}))}_isOffer(){return this.type===G.Offer}_isAnswer(){return this.type===G.Answer}_config(){const{iceServers:e=[]}=this.options,t={iceCandidatePoolSize:255,bundlePolicy:"max-compat",iceServers:e};return h.info("RTC config",t),t}}const Ye=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:W.conferenceUpdate,call:e.calls[s],canvasInfo:Qe(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:J.LayerInfo},a);$(y.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:J.LayoutInfo},a);$(y.Notification,t,e.uuid);break}}},Qe=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return I(t)};var Xe,Ze="2.13.0",et=Ze,tt=l((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(d)}}else c=a[t]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,n,i,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var l,u=new Uint8Array(16);function h(){if(!l&&!(l="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],f=0;256>f;++f)g.push((f+256).toString(16).substr(1));function m(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n}function v(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return m(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function w(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let S,I={},C=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:n}=e;let{connectionId:i,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=v()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),C.forEach((e=>{this.removeTrackEventListeners(e)})),C=[],this.shouldWrapGetUserMedia&&S&&(navigator.mediaDevices.getUserMedia=S)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=_(o),d={remote:s.options.remote},l=w(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,timeTaken:a-t,data:l};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),n.push(u),s.stats.parsed=l}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),S=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),S.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),C.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=n.bind(navigator.mediaDevices)}}}}));(Xe=tt)&&Xe.__esModule&&Object.prototype.hasOwnProperty.call(Xe,"default")&&Xe.default;var nt=tt.WebRTCStats;const it=et;class st{constructor(e,t){this.session=e,this.id="",this.state=K[K.New],this.prevState="",this.channels=[],this.role=q.Participant,this.extension=null,this._state=K.New,this._prevState=K.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 n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},H,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=De(this.options.ringtoneFile,"_ringtone"),this._ringback=De(this.options.ringbackFile,"_ringback"))}get isDebuggerRunning(){return null!=this._webRTCStats}startDebugger(){this.isDebuggerRunning||(this._webRTCStats=new nt({getStatsInterval:1e3,rawStats:!1,statsObject:!1,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"none"}),this._webRTCStats.addConnection({pc:this.peer.instance,peerId:this.options.id,connectionId:`${this.options.telnyxSessionId}/${this.options.telnyxLegId}`}))}stopDebugger(){if(null==this._webRTCStats)return;const e=this._webRTCStats.getTimeline("stats"),t=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=`call_${this.options.id}.json`,i.click(),URL.revokeObjectURL(n),this._webRTCStats.destroy(),this._webRTCStats=null}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(){return n(this,void 0,void 0,(function*(){this.direction=B.Outbound,this.peer=new ze(G.Offer,this.options),yield this.peer.iceGatheringComplete.promise,console.log("icegatheringcompleted"),this._onIceSdp(this.peer.instance.localDescription)}))}answer(e={}){var t;return n(this,void 0,void 0,(function*(){this.stopRingtone(),this.direction=B.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 ze(G.Answer,this.options),yield this.peer.iceGatheringComplete.promise,this._onIceSdp(this.peer.instance.localDescription)}))}playRingtone(){Le(this._ringtone)}stopRingtone(){Ne(this._ringtone)}playRingback(){Le(this._ringback)}stopRingback(){Ne(this._ringback)}hangup(e,t){let n=e||{},i=!1!==t;this.cause=n.cause||"NORMAL_CLEARING",this.causeCode=n.causeCode||16,this.sipCode=n.sipCode||null,this.sipReason=n.sipReason||null,this.sipCallId=n.sip_call_id||null,this.setState(K.Hangup);const s=()=>{this.peer&&this.peer.instance.close(),this.setState(K.Destroy)};if(this.stopRingtone(),this.stopDebugger(),i){const e=new Fe({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{h.error("telnyl_rtc.bye failed!",e),$(y.Error,e,this.session.uuid)})).then(s.bind(this))}else s()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new We({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new We({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new We({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 We({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 We({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 He({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new He({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){xe(this.options.localStream)}unmuteAudio(){Te(this.options.localStream)}toggleAudioMute(){Re(this.options.localStream)}setAudioInDevice(e){return n(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const t=yield ce({audio:{deviceId:{exact:e}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,ke(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,ke(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,ke(e,"video",null)}setVideoDevice(e){return n(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield ce({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);const{localElement:s,localStream:o}=this.options;le(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){xe(this.options.remoteStream)}undeaf(){Te(this.options.remoteStream)}toggleDeaf(){Re(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return n(this,void 0,void 0,(function*(){if(!this||!this.peer)return void h.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,i=n.getSenders();if(!i)return void h.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const s=i.find((({track:{kind:e}})=>e===t));if(s){const n=s.getParameters();n.encodings||(n.encodings=[{rid:"h"}]),h.info("Parameters: ",n),h.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),n.encodings[0].maxBitrate=e,yield s.setParameters(n).then((()=>{h.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else h.error("Could not set bandwidth (reason: no "+t+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=K[this._state].toLowerCase(),this.prevState=K[this._prevState].toLowerCase(),h.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:W.callUpdate,call:this}),e){case K.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case K.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ue(e,t)}),0);break;case K.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case F.Answer:if(this.gotAnswer=!0,this._state>=K.Active)return;this._state>=K.Early&&this.setState(K.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case F.Media:if(this._state>=K.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case F.Display:case F.Attach:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===B.Inbound?B.Outbound:B.Inbound,r={type:W[t],call:this,displayName:e,displayNumber:i,displayDirection:o};$(y.Notification,r,this.id)||$(y.Notification,r,this.session.uuid);break}case F.Info:case F.Event:{const e=Object.assign(Object.assign({},n),{type:W.generic,call:this});$(y.Notification,e,this.id)||$(y.Notification,e,this.session.uuid);break}case F.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case F.Bye:this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,t){return n(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return h.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:i,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:n,modChannel:s,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:J.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),n&&(yield this._subscribeConferenceInfo(n)),s&&a===q.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},S(i[e][1])));this._dispatchConferenceUpdate({action:J.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:J.Add,callId:s,index:o},S(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:J.Modify,callId:s,index:o},S(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:J.Delete,callId:s,index:o},S(i)));break;case"clear":this._dispatchConferenceUpdate({action:J.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:i,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return n(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:J.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfChat subscription error:",e)}));Ce(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_subscribeConferenceInfo(e){return n(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,Ye(this.session,t);else h.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfInfo subscription error:",e)}));Ce(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return n(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&_(e))throw`Conference ${this.id} has no video!`},i={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:J.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:J.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{h.error("ConfMod subscription error:",e)}));Ce(s,e)&&(this.role=q.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=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},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,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(K.Active):this.setState(K.Held),!0}_handleChangeHoldStateError(e){return h.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Ie(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=_e(t));const n={sdp:t,type:G.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(K.Early),this.gotAnswer&&this.setState(K.Active)})).catch((e=>{h.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){C(this.peer.onSdpReadyTwice)?$(y.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){var t,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return h.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${it}`};switch(s){case G.Offer:this.setState(K.Requesting),o=new Ve(r);break;case G.Answer:this.setState(K.Answering),o=!0===this.options.attach?new Be(r):new Ge(r);break;default:return h.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===G.Offer?this.setState(K.Trying):this.setState(K.Active)})).catch((e=>{h.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(f)}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?h.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onMediaError(e){this._dispatchNotification({type:W.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:W.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&($(y.Notification,e,this.id,!1)||$(y.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:n,onNotification:i}=this.options;e||(this.options.id=c()),this.id=this.options.id,t&&!_(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,P(y.MediaError,this._onMediaError,this.id),C(i)&&P(y.Notification,i.bind(this),this.id),this.setState(K.New),h.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;pe(e),pe(t),j(y.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),h.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),h.info("Stats stopped")}}st.setStateTelnyx=e=>{if(e){switch(e._state){case K.Requesting:case K.Recovering:case K.Trying:case K.Early:e.state="connecting";break;case K.Active:e.state="active";break;case K.Held:e.state="held";break;case K.Hangup:case K.Destroy:e.state="done";break;case K.Answering:e.state="ringing";break;case K.New:e.state="new"}return e}};class ot extends st{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof ot&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return n(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new ot(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof ot&&this.screenShare.hangup()}setAudioOutDevice(e){return n(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&ue(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);h.setLevel(2),this._statsInterval=window.setInterval((()=>n(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),h.info(t)}))),2e3)}}class rt extends ae{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 n(this,void 0,void 0,(function*(){this.sessionid=yield se(g),e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return n(this,void 0,void 0,(function*(){try{const n=yield ge({audio:e,video:t});return pe(n),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return n(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(K.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,n)=>{if(U(y.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return fe().catch((e=>($(y.MediaError,e,this.uuid),[])))}getVideoDevices(){return fe(z.Video).catch((e=>($(y.MediaError,e,this.uuid),[])))}getAudioInDevices(){return fe(z.AudioIn).catch((e=>($(y.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return fe(z.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),$(y.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return ve(e,t,n)}getDeviceResolutions(e){return n(this,void 0,void 0,(function*(){try{return yield(e=>n(void 0,void 0,void 0,(function*(){const t=[],n=yield ge({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<me.length;e++){const[n,s]=me[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return pe(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=t(e,["micId","micLabel"]);return be(s),this._audioConstraints=yield ye(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=e,s=t(e,["camId","camLabel"]);return be(s),this._videoConstraints=yield ye(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[b,v,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=E(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=E(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new Ke({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:t=[],handler:i}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new qe({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unauthorized:o=[],subscribed:r=[]}=Ee(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:t=[]}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new Je({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const i=yield this.execute(n),{unsubscribed:s=[],notSubscribed:o=[]}=Ee(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return ot.setStateTelnyx(e)}}class at extends Ue{constructor(){super(),this.method=F.GatewayState;this.buildRequest({method:this.method,params:{}})}}class ct{constructor(e,t){this.code=t,this.message=e}}class dt extends Ue{constructor(){super(),this.method=F.Ping;this.buildRequest({method:this.method,params:{}})}}class lt{constructor(e){this.session=e}_ack(e,t){const n=new $e(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*x(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:i,params:s={}}=e,o=null==s?void 0:s.callID,r=null==s?void 0:s.eventChannel,a=null==s?void 0:s.eventType,c=i===F.Attach;if("channelPvtData"===a)return this._handlePvtEvent(s.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(n,i);t.calls[o].hangup({},!1)}const d=()=>{const e={id:o,remoteSdp:s.sdp,destinationNumber:s.callee_id_number,remoteCallerName:s.caller_id_name,remoteCallerNumber:s.caller_id_number,callerName:s.callee_id_name,callerNumber:s.callee_id_number,attach:c,mediaSettings:s.mediaSettings};s.telnyx_call_control_id&&(e.telnyxCallControlId=s.telnyx_call_control_id),s.telnyx_session_id&&(e.telnyxSessionId=s.telnyx_session_id),s.telnyx_leg_id&&(e.telnyxLegId=s.telnyx_leg_id),s.client_state&&(e.clientState=s.client_state),s.dialogParams&&s.dialogParams.custom_headers&&s.dialogParams.custom_headers.length&&(e.customHeaders=s.dialogParams.custom_headers);const n=new ot(t,e);return n.nodeId=this.nodeId,n},l=new at,u=new dt;switch(i){case F.Ping:this.session.execute(u);break;case F.Punt:t.disconnect();break;case F.Invite:{const e=d();e.playRingtone(),e.setState(K.Ringing),e.direction=B.Inbound,this._ack(n,i);break}case F.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(K.Recovering),t.handleMessage(e);break}case F.Event:case"webrtc.event":if(!r)return void h.error("Verto received an unknown event:",s);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?$(o,s,r):r===t.sessionid?this._handleSessionEvent(s.eventData):t._existsSubscription(o,a)?$(o,s,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):$(y.Notification,s,t.uuid);break;case F.Info:s.type=W.generic,$(y.Notification,s,t.uuid);break;case F.ClientReady:this.session.execute(l);break;default:{const n=M(e);if(n){switch(n){case Y.REGISTER:case Y.REGED:t.connection.previousGatewayState!==Y.REGED&&t.connection.previousGatewayState!==Y.REGISTER&&(lt.retriedRegister=0,s.type=W.vertoClientReady,$(y.Ready,s,t.uuid));break;case Y.UNREGED:case Y.NOREG:if(lt.retriedRegister+=1,5===lt.retriedRegister){lt.retriedRegister=0,$(y.Error,new ct("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(l)}),this.reconnectDelay());break;case Y.FAILED:case Y.FAIL_WAIT:if(t.connection.previousGatewayState!==Y.FAILED&&t.connection.previousGatewayState!==Y.FAIL_WAIT){if(!this.session.hasAutoReconnect()){lt.retriedConnect=0,$(y.Error,new ct("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(lt.retriedConnect+=1,5===lt.retriedConnect){lt.retriedConnect=0,$(y.Error,s,t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:h.warn("GatewayState message unknown method:",e)}break}h.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return n(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=u||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{h.error("liveArray subscription error:",e)}));Ce(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:W.conferenceUpdate,action:J.Leave,conferenceName:o,participantId:Number(d),role:l};$(y.Notification,n,i,!1)||$(y.Notification,n,t.uuid),null===e&&j(y.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{h.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Ye(this.session,e);break;case"logo-info":{const t={type:W.conferenceUpdate,action:J.LogoInfo,logo:e.logoURL};$(y.Notification,t,this.session.uuid);break}}}}lt.retriedConnect=0,lt.retriedRegister=0;class ut extends rt{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 R(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(f);const t=new ot(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 n(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new je(e,t||n,i,this.sessionid,s),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,oe(g,this.sessionid))}))}_onSocketMessage(e){new lt(this).handleMessage(e)}}e.TelnyxRTC=class extends ut{constructor(e){super(e),console.log(`SDK version: ${Ze}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Me()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ae.not_supported},{browserName:"Firefox",supported:Ae.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",features:["audio"],supported:Ae.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",features:["audio"],supported:Ae.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),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};
15
+ function e(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),i=new Uint8Array(16);function s(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(i)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[i+a]=r[a];return t||function(e,t){var n=t||0,i=o;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(r)}var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function d(e,t){return e(t={exports:{}},t.exports),t.exports}var l=d((function(e){var t,n;t=c,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=n),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=n():t.log=n()}));const u=l.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,n)=>{const i=h(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},u.setLevel(u.getLevel());const p="sessId",g="Time to call invite",f="wss://rtc.telnyx.com",m={urls:"stun:stun.telnyx.com:3478"},v={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var b;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(b||(b={}));const y=e=>0===Object.keys(e).length,_=e=>`@telnyx:${e}`,w=e=>{const[t,n,i,s,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:n,participantName:i,codec:s,media:a,participantData:r}},S=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},I=e=>e instanceof Function||"function"==typeof e,C=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,E=/^(ws|wss):\/\//,k=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?k(a,r):{result:s}},T=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),x=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),R=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};const M=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},A="GLOBAL",D={},L=(e,t)=>`${e}|${t}`,N=(e,t=A)=>L(e,t)in D,O=(e,t,n=A)=>{const i=L(e,n);i in D||(D[i]=[]),D[i].push(t)},P=(e,t,n=A)=>{const i=function(s){U(e,i,n),t(s)};return i.prototype.targetRef=t,O(e,i,n)},U=(e,t,n=A)=>{if(!N(e,n))return!1;const i=L(e,n);if(I(t)){for(let e=D[i].length-1;e>=0;e--){const n=D[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&D[i].splice(e,1)}}else D[i]=[];return 0===D[i].length&&delete D[i],!0},j=(e,t,n=A,i=!0)=>{const s=i&&n!==A;if(!N(e,n))return s&&j(e,t),!1;const o=L(e,n),r=D[o].length;if(!r)return s&&j(e,t),!1;for(let e=r-1;e>=0;e--)D[o][e](t);return s&&j(e,t),!0},$=e=>{const t=L(e,"");Object.keys(D).filter((e=>0===e.indexOf(t))).forEach((e=>delete D[e]))};var V,G,B;!function(e){e.Offer="offer",e.Answer="answer"}(V||(V={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(G||(G={})),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 F={generic:"event",[B.Display]:"participantData",[B.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},H={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var W,K,q,J,z;!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"}(W||(W={})),function(e){e.Participant="participant",e.Moderator="moderator"}(K||(K={})),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"}(q||(q={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(J||(J={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(z||(z={}));let Y="undefined"!=typeof WebSocket?WebSocket:null;const Q=0,X=1,Z=2,ee=3;class te{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=f,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${E.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":f)}get connected(){return this._wsClient&&this._wsClient.readyState===X}get connecting(){return this._wsClient&&this._wsClient.readyState===Q}get closing(){return this._wsClient&&this._wsClient.readyState===Z}get closed(){return this._wsClient&&this._wsClient.readyState===ee}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){this._wsClient=new Y(this._host),this._wsClient.onopen=e=>j(b.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>j(b.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>j(b.SocketError,e,this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=S(e.data);if("string"!=typeof i){if(this._unsetTimer(i.id),u.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),z[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!j(i.id,i)){const e=R(i);j(b.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();P(t.id,(t=>{const{result:i,error:s}=k(t);return s?n(s):e(i)})),this._setTimer(t.id)}));return u.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(I(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_setTimer(e){this._timers[e]=setTimeout((()=>{j(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)),j(b.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}const ne=()=>"undefined"==typeof window&&"undefined"!=typeof process,ie=e=>((e,n)=>t(void 0,void 0,void 0,(function*(){if(ne())return null;const t=window[e].getItem(_(n));return S(t)})))("sessionStorage",e),se=(e,n)=>((e,n,i)=>t(void 0,void 0,void 0,(function*(){if(ne())return null;"object"==typeof i&&(i=JSON.stringify(i)),window[e].setItem(_(n),i)})))("sessionStorage",e,n),oe=e=>((e,n)=>t(void 0,void 0,void 0,(function*(){return ne()?null:window[e].removeItem(_(n))})))("sessionStorage",e);class re{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 te(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*T(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 oe(this.signature),this._executeQueue=[],this._detachListeners()}))}on(e,t){return O(e,t,this.uuid),this}off(e,t){return U(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new te(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){j(b.Error,e,this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}_onSocketCloseOrError(e){u.error(`Socket ${e.type} ${e.message}`),this.relayProtocol&&$(this.relayProtocol);for(const e in this.subscriptions)$(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],U(e,null,t)):(delete this.subscriptions[e],$(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},I(t)&&O(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(b.SocketOpen,this._onSocketOpen),this.on(b.SocketClose,this._onSocketCloseOrError),this.on(b.SocketError,this._onSocketCloseOrError),this.on(b.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(b.SocketOpen,this._onSocketOpen),this.off(b.SocketClose,this._onSocketCloseOrError),this.off(b.SocketError,this._onSocketCloseOrError),this.off(b.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){if(!0===this._doKeepAlive){if(!1===this._pong)return this._closeConnection();this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._keepAlive()),1e4)}}static on(e,t){O(e,t)}static off(e){U(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const ae=e=>navigator.mediaDevices.getUserMedia(e),ce=e=>e&&e instanceof MediaStream,de=(e,t)=>{const n=C(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},le=(e,n)=>t(void 0,void 0,void 0,(function*(){const t=C(e);if(null===t)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof n)return u.info(`Invalid speaker deviceId: '${n}'`),!1;try{return yield t.setSinkId(n),!0}catch(e){return!1}})),ue=e=>{e&&"live"===e.readyState&&e.stop()},he=e=>{ce(e)&&e.getTracks().forEach(ue),e=null},pe=e=>t(void 0,void 0,void 0,(function*(){u.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield ae(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),ge=(e=null,n=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===J.AudioIn||e===J.AudioOut,video:!e||e===J.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(he(i),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===n)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),fe=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],me=(e,n,i)=>t(void 0,void 0,void 0,(function*(){const t=yield ge(i,!0);for(let i=0;i<t.length;i++){const{deviceId:s,label:o}=t[i];if(e===s||n===o)return s}return null})),ve=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},be=(e,n,i,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||n)){const t=yield me(e,n,i).catch((e=>null));t&&(s.deviceId={exact:t})}return s})),ye=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},_e=e=>/^m=audio/.test(e),we=e=>/^m=video/.test(e),Se=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(_e)<i.findIndex(we))return e;const s=e.split(n),o=s.findIndex(_e),r=s.findIndex(we),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},Ie=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Ce(e);return n.includes(t)||i.includes(t)},Ce=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},Ee=(e,t=null,n=null)=>{if(!ce(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},ke=e=>{Ee(e,"audio",!0)},Te=e=>{Ee(e,"audio",!1)},xe=e=>{Ee(e,"audio",null)};function Re(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!pe}}catch(e){return e.message}}var Me;function Ae(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function De(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 Le(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"}(Me||(Me={}));class Ne{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 Pe extends Ne{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in Oe)e&&n.hasOwnProperty(e)&&(n[Oe[e]]=n[e],delete n[e]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class Ue extends Pe{constructor(e,t,n,i,s={}){super(),this.method="login";const o={login:e,passwd:t,login_token:n,userVariables:s,loginParams:{},"User-Agent":window.navigator.userAgent};i&&(o.sessid=i),this.buildRequest({method:this.method,params:o})}}class je extends Pe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class $e extends Pe{toString(){return B.Invite}}class Ve extends Pe{toString(){return B.Answer}}class Ge extends Pe{toString(){return B.Attach}}class Be extends Pe{toString(){return B.Bye}}class Fe extends Pe{toString(){return B.Modify}}class He extends Pe{toString(){return B.Info}}class We extends Pe{toString(){return B.Broadcast}}class Ke extends Pe{toString(){return B.Subscribe}}class qe extends Pe{toString(){return B.Unsubscribe}}class Je{constructor(e,t){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleIceCandidate=e=>{e.candidate&&["relay","srflx"].includes(e.candidate.type)&&this.iceGatheringComplete.resolve(!0)},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.iceGatheringComplete=function({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?M(i,e):i,n=s})),resolve:t,reject:n}}({debounceTime:100}),this._init()}get isOffer(){return this.type===V.Offer}get isAnswer(){return this.type===V.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:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&de(n,s)}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("icecandidate",this.handleIceCandidate),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>(j(b.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:n=!1}=this.options;if(ce(t)){const i=t.getAudioTracks();u.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(u.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){i.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),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=C(e);t&&(t.muted=!0)})(e),de(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=ye(e.sdp)),this.instance.localDescription&&(e.sdp=Se(e.sdp,this.instance.localDescription.sdp));const t=e;return u.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return t(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=ye(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){I(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(ce(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t}=n;const{micLabel:i=""}=n;t&&(t=yield me(t,i,J.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t}));let{video:s=!1,camId:o}=n;const{camLabel:r=""}=n;return o&&(o=yield me(o,r,J.Video).catch((e=>null)),o&&("boolean"==typeof s&&(s={}),s.deviceId={exact:o})),{audio:e,video:s}})));var n;return pe(e)}))}_isOffer(){return this.type===V.Offer}_isAnswer(){return this.type===V.Answer}_config(){const{iceServers:e=[]}=this.options,t={iceCandidatePoolSize:255,bundlePolicy:"max-compat",iceServers:e};return u.info("RTC config",t),t}}const ze=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:F.conferenceUpdate,call:e.calls[s],canvasInfo:Ye(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:q.LayerInfo},a);j(b.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:q.LayoutInfo},a);j(b.Notification,t,e.uuid);break}}},Ye=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return S(t)};var Qe,Xe="2.13.0",Ze=Xe,et=d((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(d)}}else c=a[t]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,n,i,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var l,u=new Uint8Array(16);function h(){if(!l&&!(l="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],f=0;256>f;++f)g.push((f+256).toString(16).substr(1));function m(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n}function v(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return m(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function w(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let S,I={},C=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:n}=e;let{connectionId:i,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=v()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),C.forEach((e=>{this.removeTrackEventListeners(e)})),C=[],this.shouldWrapGetUserMedia&&S&&(navigator.mediaDevices.getUserMedia=S)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=_(o),d={remote:s.options.remote},l=w(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,timeTaken:a-t,data:l};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),n.push(u),s.stats.parsed=l}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),S=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),S.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),C.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=n.bind(navigator.mediaDevices)}}}}));(Qe=et)&&Qe.__esModule&&Object.prototype.hasOwnProperty.call(Qe,"default")&&Qe.default;var tt=et.WebRTCStats;const nt=Ze;class it{constructor(e,t){this.session=e,this.id="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=K.Participant,this.extension=null,this._state=W.New,this._prevState=W.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 n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},H,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,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 isDebuggerRunning(){return null!=this._webRTCStats}startDebugger(){this.isDebuggerRunning||(this._webRTCStats=new tt({getStatsInterval:1e3,rawStats:!1,statsObject:!1,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"none"}),this._webRTCStats.addConnection({pc:this.peer.instance,peerId:this.options.id,connectionId:`${this.options.telnyxSessionId}/${this.options.telnyxLegId}`}))}stopDebugger(){if(null==this._webRTCStats)return;const e=this._webRTCStats.getTimeline("stats"),t=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=`call_${this.options.id}.json`,i.click(),URL.revokeObjectURL(n),this._webRTCStats.destroy(),this._webRTCStats=null}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(){return t(this,void 0,void 0,(function*(){this.direction=G.Outbound,this.peer=new Je(V.Offer,this.options),yield this.peer.iceGatheringComplete.promise,console.log("icegatheringcompleted"),this._onIceSdp(this.peer.instance.localDescription)}))}answer(e={}){var n;return t(this,void 0,void 0,(function*(){this.stopRingtone(),this.direction=G.Inbound,(null===(n=null==e?void 0:e.customHeaders)||void 0===n?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.peer=new Je(V.Answer,this.options),yield this.peer.iceGatheringComplete.promise,this._onIceSdp(this.peer.instance.localDescription)}))}playRingtone(){De(this._ringtone)}stopRingtone(){Le(this._ringtone)}playRingback(){De(this._ringback)}stopRingback(){Le(this._ringback)}hangup(e,t){let n=e||{},i=!1!==t;this.cause=n.cause||"NORMAL_CLEARING",this.causeCode=n.causeCode||16,this.sipCode=n.sipCode||null,this.sipReason=n.sipReason||null,this.sipCallId=n.sip_call_id||null,this.setState(W.Hangup);const s=()=>{this.peer&&this.peer.instance.close(),this.setState(W.Destroy)};if(this.stopRingtone(),this.stopDebugger(),i){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),j(b.Error,e,this.session.uuid)})).then(s.bind(this))}else s()}transfer(e){console.warn("The call.transfer method is not currently implemented.");const t=new Fe({sessid:this.session.sessionid,action:"transfer",destination:e,dialogParams:this.options});this._execute(t)}replace(e){const t=new Fe({sessid:this.session.sessionid,action:"replace",replaceCallID:e,dialogParams:this.options});this._execute(t)}hold(){const e=new Fe({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 Fe({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 Fe({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 He({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new He({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){Te(this.options.localStream)}unmuteAudio(){ke(this.options.localStream)}toggleAudioMute(){xe(this.options.localStream)}setAudioInDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const t=yield ae({audio:{deviceId:{exact:e}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Ee(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ee(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ee(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield ae({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);const{localElement:s,localStream:o}=this.options;de(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Te(this.options.remoteStream)}undeaf(){ke(this.options.remoteStream)}toggleDeaf(){xe(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void u.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:t}=this.peer,i=t.getSenders();if(!i)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 s=i.find((({track:{kind:e}})=>e===n));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),u.info("Parameters: ",t),u.info("Setting max ","audio"===n?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{u.info("audio"===n?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else u.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:F.callUpdate,call:this}),e){case W.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case W.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&le(e,t)}),0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case B.Answer:if(this.gotAnswer=!0,this._state>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case B.Media:if(this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case B.Display:case B.Attach:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===G.Inbound?G.Outbound:G.Inbound,r={type:F[t],call:this,displayName:e,displayNumber:i,displayDirection:o};j(b.Notification,r,this.id)||j(b.Notification,r,this.session.uuid);break}case B.Info:case B.Event:{const e=Object.assign(Object.assign({},n),{type:F.generic,call:this});j(b.Notification,e,this.id)||j(b.Notification,e,this.session.uuid);break}case B.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case B.Bye:this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,n){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return u.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:i,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=n;this._dispatchConferenceUpdate({action:q.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),s&&a===K.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},w(i[e][1])));this._dispatchConferenceUpdate({action:q.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:q.Add,callId:s,index:o},w(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:q.Modify,callId:s,index:o},w(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:q.Delete,callId:s,index:o},w(i)));break;case"clear":this._dispatchConferenceUpdate({action:q.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:i,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:q.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfChat subscription error:",e)}));Ie(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,ze(this.session,t);else u.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfInfo subscription error:",e)}));Ie(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return t(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&y(e))throw`Conference ${this.id} has no video!`},i={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:q.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:q.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{u.error("ConfMod subscription error:",e)}));Ie(s,e)&&(this.role=K.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=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},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,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Se(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=ye(t));const n={sdp:t,type:V.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this.setState(W.Active)})).catch((e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){I(this.peer.onSdpReadyTwice)?j(b.Error,new Error("SDP without candidates for the second time!"),this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return u.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${nt}`};switch(s){case V.Offer:this.setState(W.Requesting),o=new $e(r);break;case V.Answer:this.setState(W.Answering),o=!0===this.options.attach?new Ge(r):new Ve(r);break;default:return u.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===V.Offer?this.setState(W.Trying):this.setState(W.Active)})).catch((e=>{u.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(g)}_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)}_onMediaError(e){this._dispatchNotification({type:F.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:F.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(j(b.Notification,e,this.id,!1)||j(b.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:n,onNotification:i}=this.options;e||(this.options.id=a()),this.id=this.options.id,t&&!y(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(b.MediaError,this._onMediaError,this.id),I(i)&&O(b.Notification,i.bind(this),this.id),this.setState(W.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;he(e),he(t),U(b.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),u.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),u.info("Stats stopped")}}it.setStateTelnyx=e=>{if(e){switch(e._state){case W.Requesting:case W.Recovering:case W.Trying:case W.Early:e.state="connecting";break;case W.Active:e.state="active";break;case W.Held:e.state="held";break;case W.Hangup:case W.Destroy:e.state="done";break;case W.Answering:e.state="ringing";break;case W.New:e.state="new"}return e}};class st extends it{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof st&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new st(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof st&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&le(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);u.setLevel(2),this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),u.info(t)}))),2e3)}}class ot extends re{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 ie(p),e.connect.call(this)}))}checkPermissions(e=!0,n=!0){return t(this,void 0,void 0,(function*(){try{const t=yield pe({audio:e,video:n});return he(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(W.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,n)=>{if(P(b.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return ge().catch((e=>(j(b.MediaError,e,this.uuid),[])))}getVideoDevices(){return ge(J.Video).catch((e=>(j(b.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ge(J.AudioIn).catch((e=>(j(b.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return ge(J.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),j(b.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return me(e,t,n)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],n=yield pe({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<fe.length;e++){const[n,s]=fe[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return he(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{micId:t,micLabel:i}=n,s=e(n,["micId","micLabel"]);return ve(s),this._audioConstraints=yield be(t,i,"audioinput",s),this.micId=t,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{camId:t,camLabel:i}=n,s=e(n,["camId","camLabel"]);return ve(s),this._videoConstraints=yield be(t,i,"videoinput",s),this.camId=t,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[v,m,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=C(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=C(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new We({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ke({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=Ce(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:n=[]}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new qe({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const i=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=Ce(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return st.setStateTelnyx(e)}}class rt extends Pe{constructor(){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,params:{}})}}class at{constructor(e,t){this.code=t,this.message=e}}class ct extends Pe{constructor(){super(),this.method=B.Ping;this.buildRequest({method:this.method,params:{}})}}class dt{constructor(e){this.session=e}_ack(e,t){const n=new je(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*T(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:i,params:s={}}=e,o=null==s?void 0:s.callID,r=null==s?void 0:s.eventChannel,a=null==s?void 0:s.eventType,c=i===B.Attach;if("channelPvtData"===a)return this._handlePvtEvent(s.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(n,i);t.calls[o].hangup({},!1)}const d=()=>{const e={id:o,remoteSdp:s.sdp,destinationNumber:s.callee_id_number,remoteCallerName:s.caller_id_name,remoteCallerNumber:s.caller_id_number,callerName:s.callee_id_name,callerNumber:s.callee_id_number,attach:c,mediaSettings:s.mediaSettings};s.telnyx_call_control_id&&(e.telnyxCallControlId=s.telnyx_call_control_id),s.telnyx_session_id&&(e.telnyxSessionId=s.telnyx_session_id),s.telnyx_leg_id&&(e.telnyxLegId=s.telnyx_leg_id),s.client_state&&(e.clientState=s.client_state),s.dialogParams&&s.dialogParams.custom_headers&&s.dialogParams.custom_headers.length&&(e.customHeaders=s.dialogParams.custom_headers);const n=new st(t,e);return n.nodeId=this.nodeId,n},l=new rt,h=new ct;switch(i){case B.Ping:this.session.execute(h);break;case B.Punt:t.disconnect();break;case B.Invite:{const e=d();e.playRingtone(),e.setState(W.Ringing),e.direction=G.Inbound,this._ack(n,i);break}case B.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(W.Recovering),t.handleMessage(e);break}case B.Event:case"webrtc.event":if(!r)return void u.error("Verto received an unknown event:",s);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?j(o,s,r):r===t.sessionid?this._handleSessionEvent(s.eventData):t._existsSubscription(o,a)?j(o,s,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):j(b.Notification,s,t.uuid);break;case B.Info:s.type=F.generic,j(b.Notification,s,t.uuid);break;case B.ClientReady:this.session.execute(l);break;default:{const n=R(e);if(n){switch(n){case z.REGISTER:case z.REGED:t.connection.previousGatewayState!==z.REGED&&t.connection.previousGatewayState!==z.REGISTER&&(dt.retriedRegister=0,s.type=F.vertoClientReady,j(b.Ready,s,t.uuid));break;case z.UNREGED:case z.NOREG:if(dt.retriedRegister+=1,5===dt.retriedRegister){dt.retriedRegister=0,j(b.Error,new at("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t.uuid);break}setTimeout((()=>{this.session.execute(l)}),this.reconnectDelay());break;case z.FAILED:case z.FAIL_WAIT:if(t.connection.previousGatewayState!==z.FAILED&&t.connection.previousGatewayState!==z.FAIL_WAIT){if(!this.session.hasAutoReconnect()){dt.retriedConnect=0,j(b.Error,new at("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t.uuid);break}if(dt.retriedConnect+=1,5===dt.retriedConnect){dt.retriedConnect=0,j(b.Error,s,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 n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:h}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=h||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{u.error("liveArray subscription error:",e)}));Ie(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:F.conferenceUpdate,action:q.Leave,conferenceName:o,participantId:Number(d),role:l};j(b.Notification,n,i,!1)||j(b.Notification,n,t.uuid),null===e&&U(b.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{u.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ze(this.session,e);break;case"logo-info":{const t={type:F.conferenceUpdate,action:q.LogoInfo,logo:e.logoURL};j(b.Notification,t,this.session.uuid);break}}}}dt.retriedConnect=0,dt.retriedRegister=0;class lt extends ot{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.");console.time(g);const t=new st(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:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new Ue(e,t||n,i,this.sessionid,s),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid,se(p,this.sessionid))}))}_onSocketMessage(e){new dt(this).handleMessage(e)}}class ut extends lt{constructor(e){super(e),console.log(`SDK version: ${Xe}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Re()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Me.full},{browserName:"Firefox",features:["audio"],supported:Me.partial},{browserName:"Safari",supported:Me.not_supported},{browserName:"Edge",supported:Me.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Me.not_supported},{browserName:"Firefox",supported:Me.not_supported},{browserName:"Safari",features:["video","audio"],supported:Me.full},{browserName:"Edge",supported:Me.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Me.full},{browserName:"Firefox",features:["audio"],supported:Me.partial},{browserName:"Safari",supported:Me.not_supported},{browserName:"Edge",supported:Me.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Me.full},{browserName:"Firefox",features:["audio"],supported:Me.partial},{browserName:"Safari",features:["video","audio"],supported:Me.full},{browserName:"Edge",features:["audio"],supported:Me.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Me.full},{browserName:"Firefox",features:["audio"],supported:Me.partial},{browserName:"Safari",supported:Me.not_supported},{browserName:"Edge",features:["audio"],supported:Me.partial}]}]}}export{ut as TelnyxRTC};
@@ -2,6 +2,7 @@ export declare const STORAGE_PREFIX = "@telnyx:";
2
2
  export declare const ADD = "add";
3
3
  export declare const REMOVE = "remove";
4
4
  export declare const SESSION_ID = "sessId";
5
+ export declare const TIME_CALL_INVITE = "Time to call invite";
5
6
  export declare const PROD_HOST = "wss://rtc.telnyx.com";
6
7
  export declare const DEV_HOST = "wss://rtcdev.telnyx.com";
7
8
  export declare const STUN_SERVER: {
@@ -22,3 +22,14 @@ export declare const destructResponse: (response: any, nodeId?: string) => {
22
22
  export declare const randomInt: (min: number, max: number) => number;
23
23
  export declare const isValidOptions: ({ login, passwd, password, login_token, }: IVertoOptions) => boolean;
24
24
  export declare const getGatewayState: (msg: IMessageRPC) => GatewayStateType | '';
25
+ export declare type DeferredPromise<T> = {
26
+ promise: Promise<T>;
27
+ resolve: (value: T | PromiseLike<T>) => void;
28
+ reject: (reason?: any) => void;
29
+ };
30
+ declare type DeferredPromiseOptions = {
31
+ debounceTime?: number;
32
+ };
33
+ export declare function deferredPromise<T>({ debounceTime, }: DeferredPromiseOptions): DeferredPromise<T>;
34
+ export declare const debounce: (func: Function, wait: number) => (...args: any) => void;
35
+ export {};
@@ -5,6 +5,7 @@ import { IVertoCallOptions, IWebRTCCall, AnswerParams } from './interfaces';
5
5
  import Call from './Call';
6
6
  export default abstract class BaseCall implements IWebRTCCall {
7
7
  protected session: BrowserSession;
8
+ private _webRTCStats;
8
9
  id: string;
9
10
  state: string;
10
11
  prevState: string;
@@ -32,6 +33,9 @@ export default abstract class BaseCall implements IWebRTCCall {
32
33
  private _statsBindings;
33
34
  private _statsIntervalId;
34
35
  constructor(session: BrowserSession, opts?: IVertoCallOptions);
36
+ get isDebuggerRunning(): boolean;
37
+ startDebugger(): void;
38
+ stopDebugger(): void;
35
39
  get nodeId(): string;
36
40
  set nodeId(what: string);
37
41
  get telnyxIDs(): {
@@ -42,8 +46,8 @@ export default abstract class BaseCall implements IWebRTCCall {
42
46
  get localStream(): MediaStream;
43
47
  get remoteStream(): MediaStream;
44
48
  get memberChannel(): string;
45
- invite(): void;
46
- answer(params?: AnswerParams): void;
49
+ invite(): Promise<void>;
50
+ answer(params?: AnswerParams): Promise<void>;
47
51
  playRingtone(): void;
48
52
  stopRingtone(): void;
49
53
  playRingback(): void;
@@ -86,7 +90,6 @@ export default abstract class BaseCall implements IWebRTCCall {
86
90
  private _requestAnotherLocalDescription;
87
91
  private _onIceSdp;
88
92
  private _onIce;
89
- private _registerPeerEvents;
90
93
  private _checkConferenceSerno;
91
94
  private _onMediaError;
92
95
  private _dispatchConferenceUpdate;
@@ -1,9 +1,11 @@
1
1
  import { PeerType } from './constants';
2
+ import { DeferredPromise } from '../util/helpers';
2
3
  import { IVertoCallOptions } from './interfaces';
3
4
  export default class Peer {
4
5
  type: PeerType;
5
6
  private options;
6
7
  instance: RTCPeerConnection;
8
+ iceGatheringComplete: DeferredPromise<boolean>;
7
9
  onSdpReadyTwice: Function;
8
10
  private _constraints;
9
11
  private _negotiating;
@@ -15,6 +17,7 @@ export default class Peer {
15
17
  private handleSignalingStateChangeEvent;
16
18
  private handleNegotiationNeededEvent;
17
19
  private handleTrackEvent;
20
+ private handleIceCandidate;
18
21
  private createPeerConnection;
19
22
  private _init;
20
23
  private _getSenderByKind;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telnyx/webrtc",
3
- "version": "2.11.0",
3
+ "version": "2.13.0",
4
4
  "description": "Telnyx WebRTC Client",
5
5
  "keywords": [
6
6
  "telnyx",
@@ -42,6 +42,7 @@
42
42
  "bugs:": "https://github.com/team-telnyx/webrtc/issues",
43
43
  "license": "MIT",
44
44
  "dependencies": {
45
+ "@peermetrics/webrtc-stats": "^5.7.1",
45
46
  "loglevel": "^1.6.8",
46
47
  "uuid": "^7.0.3"
47
48
  },