@telnyx/ai-agent-widget 0.2.0 → 0.3.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/dist/bundle.min.js +4 -4
- package/package.json +1 -1
package/dist/bundle.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){"use strict";var ye,F,St,ue,Ct,kt,xt,It,Qe,Xe,et,we={},Et=[],jn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Se=Array.isArray;function se(t,e){for(var n in e)t[n]=e[n];return t}function tt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function le(t,e,n){var i,o,r,s={};for(r in e)r=="key"?i=e[r]:r=="ref"?o=e[r]:s[r]=e[r];if(arguments.length>2&&(s.children=arguments.length>3?ye.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)s[r]===void 0&&(s[r]=t.defaultProps[r]);return Ce(t,s,i,o,null)}function Ce(t,e,n,i,o){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++St,__i:-1,__u:0};return o==null&&F.vnode!=null&&F.vnode(r),r}function ke(t){return t.children}function De(t,e){this.props=t,this.context=e}function pe(t,e){if(e==null)return t.__?pe(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?pe(t):null}function Tt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Tt(t)}}function At(t){(!t.__d&&(t.__d=!0)&&ue.push(t)&&!Oe.__r++||Ct!=F.debounceRendering)&&((Ct=F.debounceRendering)||kt)(Oe)}function Oe(){for(var t,e,n,i,o,r,s,c=1;ue.length;)ue.length>c&&ue.sort(xt),t=ue.shift(),c=ue.length,t.__d&&(n=void 0,o=(i=(e=t).__v).__e,r=[],s=[],e.__P&&((n=se({},i)).__v=i.__v+1,F.vnode&&F.vnode(n),nt(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[o]:null,r,o??pe(i),!!(32&i.__u),s),n.__v=i.__v,n.__.__k[n.__i]=n,Ot(r,n,s),n.__e!=o&&Tt(n)));Oe.__r=0}function Rt(t,e,n,i,o,r,s,c,d,h,g){var p,b,m,C,A,y,S=i&&i.__k||Et,k=e.length;for(d=Un(n,e,S,d,k),p=0;p<k;p++)(m=n.__k[p])!=null&&(b=m.__i==-1?we:S[m.__i]||we,m.__i=p,y=nt(t,m,b,o,r,s,c,d,h,g),C=m.__e,m.ref&&b.ref!=m.ref&&(b.ref&&it(b.ref,null,m),g.push(m.ref,m.__c||C,m)),A==null&&C!=null&&(A=C),4&m.__u||b.__k===m.__k?d=Mt(m,d,t):typeof m.type=="function"&&y!==void 0?d=y:C&&(d=C.nextSibling),m.__u&=-7);return n.__e=A,d}function Un(t,e,n,i,o){var r,s,c,d,h,g=n.length,p=g,b=0;for(t.__k=new Array(o),r=0;r<o;r++)(s=e[r])!=null&&typeof s!="boolean"&&typeof s!="function"?(d=r+b,(s=t.__k[r]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?Ce(null,s,null,null,null):Se(s)?Ce(ke,{children:s},null,null,null):s.constructor==null&&s.__b>0?Ce(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,c=null,(h=s.__i=Bn(s,n,d,p))!=-1&&(p--,(c=n[h])&&(c.__u|=2)),c==null||c.__v==null?(h==-1&&(o>g?b--:o<g&&b++),typeof s.type!="function"&&(s.__u|=4)):h!=d&&(h==d-1?b--:h==d+1?b++:(h>d?b--:b++,s.__u|=4))):t.__k[r]=null;if(p)for(r=0;r<g;r++)(c=n[r])!=null&&(2&c.__u)==0&&(c.__e==i&&(i=pe(c)),$t(c,c));return i}function Mt(t,e,n){var i,o;if(typeof t.type=="function"){for(i=t.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=t,e=Mt(i[o],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=pe(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Nt(t,e){return e=e||[],t==null||typeof t=="boolean"||(Se(t)?t.some(function(n){Nt(n,e)}):e.push(t)),e}function Bn(t,e,n,i){var o,r,s=t.key,c=t.type,d=e[n];if(d===null&&t.key==null||d&&s==d.key&&c==d.type&&(2&d.__u)==0)return n;if(i>(d!=null&&(2&d.__u)==0?1:0))for(o=n-1,r=n+1;o>=0||r<e.length;){if(o>=0){if((d=e[o])&&(2&d.__u)==0&&s==d.key&&c==d.type)return o;o--}if(r<e.length){if((d=e[r])&&(2&d.__u)==0&&s==d.key&&c==d.type)return r;r++}}return-1}function Lt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||jn.test(e)?n:n+"px"}function Pe(t,e,n,i,o){var r,s;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Lt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Lt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(It,"$1")),s=e.toLowerCase(),e=s in t||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?i?n.u=i.u:(n.u=Qe,t.addEventListener(e,r?et:Xe,r)):t.removeEventListener(e,r?et:Xe,r);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Dt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Qe++;else if(e.t<n.u)return;return n(F.event?F.event(e):e)}}}function nt(t,e,n,i,o,r,s,c,d,h){var g,p,b,m,C,A,y,S,k,L,P,H,Q,V,D,a,l,u=e.type;if(e.constructor!=null)return null;128&n.__u&&(d=!!(32&n.__u),r=[c=e.__e=n.__e]),(g=F.__b)&&g(e);e:if(typeof u=="function")try{if(S=e.props,k="prototype"in u&&u.prototype.render,L=(g=u.contextType)&&i[g.__c],P=g?L?L.props.value:g.__:i,n.__c?y=(p=e.__c=n.__c).__=p.__E:(k?e.__c=p=new u(S,P):(e.__c=p=new De(S,P),p.constructor=u,p.render=Vn),L&&L.sub(p),p.props=S,p.state||(p.state={}),p.context=P,p.__n=i,b=p.__d=!0,p.__h=[],p._sb=[]),k&&p.__s==null&&(p.__s=p.state),k&&u.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=se({},p.__s)),se(p.__s,u.getDerivedStateFromProps(S,p.__s))),m=p.props,C=p.state,p.__v=e,b)k&&u.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),k&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(k&&u.getDerivedStateFromProps==null&&S!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(S,P),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(S,p.__s,P)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(p.props=S,p.state=p.__s,p.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(f){f&&(f.__=e)}),H=0;H<p._sb.length;H++)p.__h.push(p._sb[H]);p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(S,p.__s,P),k&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,C,A)})}if(p.context=P,p.props=S,p.__P=t,p.__e=!1,Q=F.__r,V=0,k){for(p.state=p.__s,p.__d=!1,Q&&Q(e),g=p.render(p.props,p.state,p.context),D=0;D<p._sb.length;D++)p.__h.push(p._sb[D]);p._sb=[]}else do p.__d=!1,Q&&Q(e),g=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++V<25);p.state=p.__s,p.getChildContext!=null&&(i=se(se({},i),p.getChildContext())),k&&!b&&p.getSnapshotBeforeUpdate!=null&&(A=p.getSnapshotBeforeUpdate(m,C)),a=g,g!=null&&g.type===ke&&g.key==null&&(a=Pt(g.props.children)),c=Rt(t,Se(a)?a:[a],e,n,i,o,r,s,c,d,h),p.base=e.__e,e.__u&=-161,p.__h.length&&s.push(p),y&&(p.__E=p.__=null)}catch(f){if(e.__v=null,d||r!=null)if(f.then){for(e.__u|=d?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;r[r.indexOf(c)]=null,e.__e=c}else for(l=r.length;l--;)tt(r[l]);else e.__e=n.__e,e.__k=n.__k;F.__e(f,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):c=e.__e=Hn(n.__e,e,n,i,o,r,s,d,h);return(g=F.diffed)&&g(e),128&e.__u?void 0:c}function Ot(t,e,n){for(var i=0;i<n.length;i++)it(n[i],n[++i],n[++i]);F.__c&&F.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(r){r.call(o)})}catch(r){F.__e(r,o.__v)}})}function Pt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Se(t)?t.map(Pt):se({},t)}function Hn(t,e,n,i,o,r,s,c,d){var h,g,p,b,m,C,A,y=n.props,S=e.props,k=e.type;if(k=="svg"?o="http://www.w3.org/2000/svg":k=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),r!=null){for(h=0;h<r.length;h++)if((m=r[h])&&"setAttribute"in m==!!k&&(k?m.localName==k:m.nodeType==3)){t=m,r[h]=null;break}}if(t==null){if(k==null)return document.createTextNode(S);t=document.createElementNS(o,k,S.is&&S),c&&(F.__m&&F.__m(e,r),c=!1),r=null}if(k==null)y===S||c&&t.data==S||(t.data=S);else{if(r=r&&ye.call(t.childNodes),y=n.props||we,!c&&r!=null)for(y={},h=0;h<t.attributes.length;h++)y[(m=t.attributes[h]).name]=m.value;for(h in y)if(m=y[h],h!="children"){if(h=="dangerouslySetInnerHTML")p=m;else if(!(h in S)){if(h=="value"&&"defaultValue"in S||h=="checked"&&"defaultChecked"in S)continue;Pe(t,h,null,m,o)}}for(h in S)m=S[h],h=="children"?b=m:h=="dangerouslySetInnerHTML"?g=m:h=="value"?C=m:h=="checked"?A=m:c&&typeof m!="function"||y[h]===m||Pe(t,h,m,y[h],o);if(g)c||p&&(g.__html==p.__html||g.__html==t.innerHTML)||(t.innerHTML=g.__html),e.__k=[];else if(p&&(t.innerHTML=""),Rt(e.type=="template"?t.content:t,Se(b)?b:[b],e,n,i,k=="foreignObject"?"http://www.w3.org/1999/xhtml":o,r,s,r?r[0]:n.__k&&pe(n,0),c,d),r!=null)for(h=r.length;h--;)tt(r[h]);c||(h="value",k=="progress"&&C==null?t.removeAttribute("value"):C!=null&&(C!==t[h]||k=="progress"&&!C||k=="option"&&C!=y[h])&&Pe(t,h,C,y[h],o),h="checked",A!=null&&A!=t[h]&&Pe(t,h,A,y[h],o))}return t}function it(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(o){F.__e(o,n)}}function $t(t,e,n){var i,o;if(F.unmount&&F.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||it(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){F.__e(r,e)}i.base=i.__P=null}if(i=t.__k)for(o=0;o<i.length;o++)i[o]&&$t(i[o],e,n||typeof t.type!="function");n||tt(t.__e),t.__c=t.__=t.__e=void 0}function Vn(t,e,n){return this.constructor(t,n)}function $e(t,e,n){var i,o,r,s;e==document&&(e=document.documentElement),F.__&&F.__(t,e),o=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],s=[],nt(e,t=(!i&&n||e).__k=le(ke,null,[t]),o||we,we,e.namespaceURI,!i&&n?[n]:o?null:e.firstChild?ye.call(e.childNodes):null,r,!i&&n?n:o?o.__e:e.firstChild,i,s),Ot(r,t,s)}function Ft(t,e){$e(t,e,Ft)}function jt(t,e,n){var i,o,r,s,c=se({},t.props);for(r in t.type&&t.type.defaultProps&&(s=t.type.defaultProps),e)r=="key"?i=e[r]:r=="ref"?o=e[r]:c[r]=e[r]===void 0&&s!=null?s[r]:e[r];return arguments.length>2&&(c.children=arguments.length>3?ye.call(arguments,2):n),Ce(t.type,c,i||t.key,o||t.ref,null)}ye=Et.slice,F={__e:function(t,e,n,i){for(var o,r,s;e=e.__;)if((o=e.__c)&&!o.__)try{if((r=o.constructor)&&r.getDerivedStateFromError!=null&&(o.setState(r.getDerivedStateFromError(t)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,i||{}),s=o.__d),s)return o.__E=o}catch(c){t=c}throw t}},St=0,De.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=se({},this.state),typeof t=="function"&&(t=t(se({},n),this.props)),t&&se(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),At(this))},De.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),At(this))},De.prototype.render=ke,ue=[],kt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,xt=function(t,e){return t.__v.__b-e.__v.__b},Oe.__r=0,It=/(PointerCapture)$|Capture$/i,Qe=0,Xe=Dt(!1),et=Dt(!0);var Gn=0;function T(t,e,n,i,o,r){e||(e={});var s,c,d=e;if("ref"in d)for(c in d={},e)c=="ref"?s=e[c]:d[c]=e[c];var h={type:t,props:d,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Gn,__i:-1,__u:0,__source:o,__self:r};if(typeof t=="function"&&(s=t.defaultProps))for(c in s)d[c]===void 0&&(d[c]=s[c]);return F.vnode&&F.vnode(h),h}function ot(){return(ot=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var zn=["context","children"];function qn(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,o){if(i==null)return{};var r,s,c={},d=Object.keys(i);for(s=0;s<d.length;s++)o.indexOf(r=d[s])>=0||(c[r]=i[r]);return c}(t,zn);return jt(e,n)}function Wn(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=le(qn,ot({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var o=[],r={},s=0,c=n.attributes,d=n.childNodes;for(s=c.length;s--;)c[s].name!=="slot"&&(r[c[s].name]=c[s].value,r[Ut(c[s].name)]=c[s].value);for(s=d.length;s--;){var h=e(d[s],null),g=d[s].slot;g?r[g]=le(Bt,{name:g},h):o[s]=h}var p=i?le(Bt,null,o):o;return le(i||n.nodeName.toLowerCase(),r,p)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ft:$e)(this._vdom,this._root)}function Ut(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Kn(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ut(t)]=n,this._vdom=jt(this._vdom,i),$e(this._vdom,this._root)}}function Jn(){$e(this._vdom=null,this._root)}function Bt(t,e){var n=this;return le("slot",ot({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(o){o.stopPropagation(),o.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Yn(t,e,n,i){function o(){var r=Reflect.construct(HTMLElement,[],o);return r._vdomComponent=t,r._root=i&&i.shadow?r.attachShadow({mode:i.mode||"open"}):r,r}return(o.prototype=Object.create(HTMLElement.prototype)).constructor=o,o.prototype.connectedCallback=Wn,o.prototype.attributeChangedCallback=Kn,o.prototype.disconnectedCallback=Jn,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),o.observedAttributes=n,n.forEach(function(r){Object.defineProperty(o.prototype,r,{get:function(){return this._vdom.props[r]},set:function(s){this._vdom?this.attributeChangedCallback(r,null,s):(this._props||(this._props={}),this._props[r]=s,this.connectedCallback());var c=typeof s;s!=null&&c!=="string"&&c!=="boolean"&&c!=="number"||this.setAttribute(r,s)}})}),customElements.define(e,o)}var xe,B,rt,Ht,Fe=0,Vt=[],G=F,Gt=G.__b,zt=G.__r,qt=G.diffed,Wt=G.__c,Kt=G.unmount,Jt=G.__;function st(t,e){G.__h&&G.__h(B,t,Fe||e),Fe=0;var n=B.__H||(B.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ie(t){return Fe=1,Zn(Xt,t)}function Zn(t,e,n){var i=st(xe++,2);if(i.t=t,!i.__c&&(i.__=[Xt(void 0,e),function(c){var d=i.__N?i.__N[0]:i.__[0],h=i.t(d,c);d!==h&&(i.__N=[h,i.__[1]],i.__c.setState({}))}],i.__c=B,!B.__f)){var o=function(c,d,h){if(!i.__c.__H)return!0;var g=i.__c.__H.__.filter(function(b){return!!b.__c});if(g.every(function(b){return!b.__N}))return!r||r.call(this,c,d,h);var p=i.__c.props!==c;return g.forEach(function(b){if(b.__N){var m=b.__[0];b.__=b.__N,b.__N=void 0,m!==b.__[0]&&(p=!0)}}),r&&r.call(this,c,d,h)||p};B.__f=!0;var r=B.shouldComponentUpdate,s=B.componentWillUpdate;B.componentWillUpdate=function(c,d,h){if(this.__e){var g=r;r=void 0,o(c,d,h),r=g}s&&s.call(this,c,d,h)},B.shouldComponentUpdate=o}return i.__N||i.__}function fe(t,e){var n=st(xe++,3);!G.__s&&Qt(n.__H,e)&&(n.__=t,n.u=e,B.__H.__h.push(n))}function je(t){return Fe=5,Yt(function(){return{current:t}},[])}function Yt(t,e){var n=st(xe++,7);return Qt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Qn(){for(var t;t=Vt.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Ue),t.__H.__h.forEach(at),t.__H.__h=[]}catch(e){t.__H.__h=[],G.__e(e,t.__v)}}G.__b=function(t){B=null,Gt&&Gt(t)},G.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Jt&&Jt(t,e)},G.__r=function(t){zt&&zt(t),xe=0;var e=(B=t.__c).__H;e&&(rt===B?(e.__h=[],B.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Ue),e.__h.forEach(at),e.__h=[],xe=0)),rt=B},G.diffed=function(t){qt&&qt(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Vt.push(e)!==1&&Ht===G.requestAnimationFrame||((Ht=G.requestAnimationFrame)||Xn)(Qn)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),rt=B=null},G.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Ue),n.__h=n.__h.filter(function(i){return!i.__||at(i)})}catch(i){e.some(function(o){o.__h&&(o.__h=[])}),e=[],G.__e(i,n.__v)}}),Wt&&Wt(t,e)},G.unmount=function(t){Kt&&Kt(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{Ue(i)}catch(o){e=o}}),n.__H=void 0,e&&G.__e(e,n.__v))};var Zt=typeof requestAnimationFrame=="function";function Xn(t){var e,n=function(){clearTimeout(i),Zt&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Zt&&(e=requestAnimationFrame(n))}function Ue(t){var e=B,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),B=e}function at(t){var e=B;t.__c=t.__(),B=e}function Qt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Xt(t,e){return typeof e=="function"?e(t):e}/**
|
|
1
|
+
(function(){"use strict";var ye,F,St,ue,Ct,kt,xt,It,Qe,Xe,et,we={},Et=[],Un=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Se=Array.isArray;function se(t,e){for(var n in e)t[n]=e[n];return t}function tt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function le(t,e,n){var i,o,r,s={};for(r in e)r=="key"?i=e[r]:r=="ref"?o=e[r]:s[r]=e[r];if(arguments.length>2&&(s.children=arguments.length>3?ye.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)s[r]===void 0&&(s[r]=t.defaultProps[r]);return Ce(t,s,i,o,null)}function Ce(t,e,n,i,o){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++St,__i:-1,__u:0};return o==null&&F.vnode!=null&&F.vnode(r),r}function ke(t){return t.children}function De(t,e){this.props=t,this.context=e}function pe(t,e){if(e==null)return t.__?pe(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?pe(t):null}function Tt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Tt(t)}}function At(t){(!t.__d&&(t.__d=!0)&&ue.push(t)&&!Oe.__r++||Ct!=F.debounceRendering)&&((Ct=F.debounceRendering)||kt)(Oe)}function Oe(){for(var t,e,n,i,o,r,s,c=1;ue.length;)ue.length>c&&ue.sort(xt),t=ue.shift(),c=ue.length,t.__d&&(n=void 0,o=(i=(e=t).__v).__e,r=[],s=[],e.__P&&((n=se({},i)).__v=i.__v+1,F.vnode&&F.vnode(n),nt(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[o]:null,r,o??pe(i),!!(32&i.__u),s),n.__v=i.__v,n.__.__k[n.__i]=n,Ot(r,n,s),n.__e!=o&&Tt(n)));Oe.__r=0}function Rt(t,e,n,i,o,r,s,c,d,h,g){var p,b,m,C,A,y,S=i&&i.__k||Et,k=e.length;for(d=jn(n,e,S,d,k),p=0;p<k;p++)(m=n.__k[p])!=null&&(b=m.__i==-1?we:S[m.__i]||we,m.__i=p,y=nt(t,m,b,o,r,s,c,d,h,g),C=m.__e,m.ref&&b.ref!=m.ref&&(b.ref&&it(b.ref,null,m),g.push(m.ref,m.__c||C,m)),A==null&&C!=null&&(A=C),4&m.__u||b.__k===m.__k?d=Mt(m,d,t):typeof m.type=="function"&&y!==void 0?d=y:C&&(d=C.nextSibling),m.__u&=-7);return n.__e=A,d}function jn(t,e,n,i,o){var r,s,c,d,h,g=n.length,p=g,b=0;for(t.__k=new Array(o),r=0;r<o;r++)(s=e[r])!=null&&typeof s!="boolean"&&typeof s!="function"?(d=r+b,(s=t.__k[r]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?Ce(null,s,null,null,null):Se(s)?Ce(ke,{children:s},null,null,null):s.constructor==null&&s.__b>0?Ce(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,c=null,(h=s.__i=Bn(s,n,d,p))!=-1&&(p--,(c=n[h])&&(c.__u|=2)),c==null||c.__v==null?(h==-1&&(o>g?b--:o<g&&b++),typeof s.type!="function"&&(s.__u|=4)):h!=d&&(h==d-1?b--:h==d+1?b++:(h>d?b--:b++,s.__u|=4))):t.__k[r]=null;if(p)for(r=0;r<g;r++)(c=n[r])!=null&&(2&c.__u)==0&&(c.__e==i&&(i=pe(c)),$t(c,c));return i}function Mt(t,e,n){var i,o;if(typeof t.type=="function"){for(i=t.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=t,e=Mt(i[o],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=pe(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Nt(t,e){return e=e||[],t==null||typeof t=="boolean"||(Se(t)?t.some(function(n){Nt(n,e)}):e.push(t)),e}function Bn(t,e,n,i){var o,r,s=t.key,c=t.type,d=e[n];if(d===null&&t.key==null||d&&s==d.key&&c==d.type&&(2&d.__u)==0)return n;if(i>(d!=null&&(2&d.__u)==0?1:0))for(o=n-1,r=n+1;o>=0||r<e.length;){if(o>=0){if((d=e[o])&&(2&d.__u)==0&&s==d.key&&c==d.type)return o;o--}if(r<e.length){if((d=e[r])&&(2&d.__u)==0&&s==d.key&&c==d.type)return r;r++}}return-1}function Lt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Un.test(e)?n:n+"px"}function Pe(t,e,n,i,o){var r,s;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Lt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Lt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(It,"$1")),s=e.toLowerCase(),e=s in t||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?i?n.u=i.u:(n.u=Qe,t.addEventListener(e,r?et:Xe,r)):t.removeEventListener(e,r?et:Xe,r);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Dt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Qe++;else if(e.t<n.u)return;return n(F.event?F.event(e):e)}}}function nt(t,e,n,i,o,r,s,c,d,h){var g,p,b,m,C,A,y,S,k,L,P,H,Q,V,D,a,l,u=e.type;if(e.constructor!=null)return null;128&n.__u&&(d=!!(32&n.__u),r=[c=e.__e=n.__e]),(g=F.__b)&&g(e);e:if(typeof u=="function")try{if(S=e.props,k="prototype"in u&&u.prototype.render,L=(g=u.contextType)&&i[g.__c],P=g?L?L.props.value:g.__:i,n.__c?y=(p=e.__c=n.__c).__=p.__E:(k?e.__c=p=new u(S,P):(e.__c=p=new De(S,P),p.constructor=u,p.render=Vn),L&&L.sub(p),p.props=S,p.state||(p.state={}),p.context=P,p.__n=i,b=p.__d=!0,p.__h=[],p._sb=[]),k&&p.__s==null&&(p.__s=p.state),k&&u.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=se({},p.__s)),se(p.__s,u.getDerivedStateFromProps(S,p.__s))),m=p.props,C=p.state,p.__v=e,b)k&&u.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),k&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(k&&u.getDerivedStateFromProps==null&&S!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(S,P),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(S,p.__s,P)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(p.props=S,p.state=p.__s,p.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(f){f&&(f.__=e)}),H=0;H<p._sb.length;H++)p.__h.push(p._sb[H]);p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(S,p.__s,P),k&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,C,A)})}if(p.context=P,p.props=S,p.__P=t,p.__e=!1,Q=F.__r,V=0,k){for(p.state=p.__s,p.__d=!1,Q&&Q(e),g=p.render(p.props,p.state,p.context),D=0;D<p._sb.length;D++)p.__h.push(p._sb[D]);p._sb=[]}else do p.__d=!1,Q&&Q(e),g=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++V<25);p.state=p.__s,p.getChildContext!=null&&(i=se(se({},i),p.getChildContext())),k&&!b&&p.getSnapshotBeforeUpdate!=null&&(A=p.getSnapshotBeforeUpdate(m,C)),a=g,g!=null&&g.type===ke&&g.key==null&&(a=Pt(g.props.children)),c=Rt(t,Se(a)?a:[a],e,n,i,o,r,s,c,d,h),p.base=e.__e,e.__u&=-161,p.__h.length&&s.push(p),y&&(p.__E=p.__=null)}catch(f){if(e.__v=null,d||r!=null)if(f.then){for(e.__u|=d?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;r[r.indexOf(c)]=null,e.__e=c}else for(l=r.length;l--;)tt(r[l]);else e.__e=n.__e,e.__k=n.__k;F.__e(f,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):c=e.__e=Hn(n.__e,e,n,i,o,r,s,d,h);return(g=F.diffed)&&g(e),128&e.__u?void 0:c}function Ot(t,e,n){for(var i=0;i<n.length;i++)it(n[i],n[++i],n[++i]);F.__c&&F.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(r){r.call(o)})}catch(r){F.__e(r,o.__v)}})}function Pt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Se(t)?t.map(Pt):se({},t)}function Hn(t,e,n,i,o,r,s,c,d){var h,g,p,b,m,C,A,y=n.props,S=e.props,k=e.type;if(k=="svg"?o="http://www.w3.org/2000/svg":k=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),r!=null){for(h=0;h<r.length;h++)if((m=r[h])&&"setAttribute"in m==!!k&&(k?m.localName==k:m.nodeType==3)){t=m,r[h]=null;break}}if(t==null){if(k==null)return document.createTextNode(S);t=document.createElementNS(o,k,S.is&&S),c&&(F.__m&&F.__m(e,r),c=!1),r=null}if(k==null)y===S||c&&t.data==S||(t.data=S);else{if(r=r&&ye.call(t.childNodes),y=n.props||we,!c&&r!=null)for(y={},h=0;h<t.attributes.length;h++)y[(m=t.attributes[h]).name]=m.value;for(h in y)if(m=y[h],h!="children"){if(h=="dangerouslySetInnerHTML")p=m;else if(!(h in S)){if(h=="value"&&"defaultValue"in S||h=="checked"&&"defaultChecked"in S)continue;Pe(t,h,null,m,o)}}for(h in S)m=S[h],h=="children"?b=m:h=="dangerouslySetInnerHTML"?g=m:h=="value"?C=m:h=="checked"?A=m:c&&typeof m!="function"||y[h]===m||Pe(t,h,m,y[h],o);if(g)c||p&&(g.__html==p.__html||g.__html==t.innerHTML)||(t.innerHTML=g.__html),e.__k=[];else if(p&&(t.innerHTML=""),Rt(e.type=="template"?t.content:t,Se(b)?b:[b],e,n,i,k=="foreignObject"?"http://www.w3.org/1999/xhtml":o,r,s,r?r[0]:n.__k&&pe(n,0),c,d),r!=null)for(h=r.length;h--;)tt(r[h]);c||(h="value",k=="progress"&&C==null?t.removeAttribute("value"):C!=null&&(C!==t[h]||k=="progress"&&!C||k=="option"&&C!=y[h])&&Pe(t,h,C,y[h],o),h="checked",A!=null&&A!=t[h]&&Pe(t,h,A,y[h],o))}return t}function it(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(o){F.__e(o,n)}}function $t(t,e,n){var i,o;if(F.unmount&&F.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||it(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){F.__e(r,e)}i.base=i.__P=null}if(i=t.__k)for(o=0;o<i.length;o++)i[o]&&$t(i[o],e,n||typeof t.type!="function");n||tt(t.__e),t.__c=t.__=t.__e=void 0}function Vn(t,e,n){return this.constructor(t,n)}function $e(t,e,n){var i,o,r,s;e==document&&(e=document.documentElement),F.__&&F.__(t,e),o=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],s=[],nt(e,t=(!i&&n||e).__k=le(ke,null,[t]),o||we,we,e.namespaceURI,!i&&n?[n]:o?null:e.firstChild?ye.call(e.childNodes):null,r,!i&&n?n:o?o.__e:e.firstChild,i,s),Ot(r,t,s)}function Ft(t,e){$e(t,e,Ft)}function Ut(t,e,n){var i,o,r,s,c=se({},t.props);for(r in t.type&&t.type.defaultProps&&(s=t.type.defaultProps),e)r=="key"?i=e[r]:r=="ref"?o=e[r]:c[r]=e[r]===void 0&&s!=null?s[r]:e[r];return arguments.length>2&&(c.children=arguments.length>3?ye.call(arguments,2):n),Ce(t.type,c,i||t.key,o||t.ref,null)}ye=Et.slice,F={__e:function(t,e,n,i){for(var o,r,s;e=e.__;)if((o=e.__c)&&!o.__)try{if((r=o.constructor)&&r.getDerivedStateFromError!=null&&(o.setState(r.getDerivedStateFromError(t)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,i||{}),s=o.__d),s)return o.__E=o}catch(c){t=c}throw t}},St=0,De.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=se({},this.state),typeof t=="function"&&(t=t(se({},n),this.props)),t&&se(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),At(this))},De.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),At(this))},De.prototype.render=ke,ue=[],kt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,xt=function(t,e){return t.__v.__b-e.__v.__b},Oe.__r=0,It=/(PointerCapture)$|Capture$/i,Qe=0,Xe=Dt(!1),et=Dt(!0);var Gn=0;function T(t,e,n,i,o,r){e||(e={});var s,c,d=e;if("ref"in d)for(c in d={},e)c=="ref"?s=e[c]:d[c]=e[c];var h={type:t,props:d,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Gn,__i:-1,__u:0,__source:o,__self:r};if(typeof t=="function"&&(s=t.defaultProps))for(c in s)d[c]===void 0&&(d[c]=s[c]);return F.vnode&&F.vnode(h),h}function ot(){return(ot=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var zn=["context","children"];function qn(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,o){if(i==null)return{};var r,s,c={},d=Object.keys(i);for(s=0;s<d.length;s++)o.indexOf(r=d[s])>=0||(c[r]=i[r]);return c}(t,zn);return Ut(e,n)}function Wn(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=le(qn,ot({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var o=[],r={},s=0,c=n.attributes,d=n.childNodes;for(s=c.length;s--;)c[s].name!=="slot"&&(r[c[s].name]=c[s].value,r[jt(c[s].name)]=c[s].value);for(s=d.length;s--;){var h=e(d[s],null),g=d[s].slot;g?r[g]=le(Bt,{name:g},h):o[s]=h}var p=i?le(Bt,null,o):o;return le(i||n.nodeName.toLowerCase(),r,p)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ft:$e)(this._vdom,this._root)}function jt(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Kn(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[jt(t)]=n,this._vdom=Ut(this._vdom,i),$e(this._vdom,this._root)}}function Jn(){$e(this._vdom=null,this._root)}function Bt(t,e){var n=this;return le("slot",ot({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(o){o.stopPropagation(),o.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Yn(t,e,n,i){function o(){var r=Reflect.construct(HTMLElement,[],o);return r._vdomComponent=t,r._root=i&&i.shadow?r.attachShadow({mode:i.mode||"open"}):r,r}return(o.prototype=Object.create(HTMLElement.prototype)).constructor=o,o.prototype.connectedCallback=Wn,o.prototype.attributeChangedCallback=Kn,o.prototype.disconnectedCallback=Jn,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),o.observedAttributes=n,n.forEach(function(r){Object.defineProperty(o.prototype,r,{get:function(){return this._vdom.props[r]},set:function(s){this._vdom?this.attributeChangedCallback(r,null,s):(this._props||(this._props={}),this._props[r]=s,this.connectedCallback());var c=typeof s;s!=null&&c!=="string"&&c!=="boolean"&&c!=="number"||this.setAttribute(r,s)}})}),customElements.define(e,o)}var xe,B,rt,Ht,Fe=0,Vt=[],G=F,Gt=G.__b,zt=G.__r,qt=G.diffed,Wt=G.__c,Kt=G.unmount,Jt=G.__;function st(t,e){G.__h&&G.__h(B,t,Fe||e),Fe=0;var n=B.__H||(B.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ie(t){return Fe=1,Zn(Xt,t)}function Zn(t,e,n){var i=st(xe++,2);if(i.t=t,!i.__c&&(i.__=[Xt(void 0,e),function(c){var d=i.__N?i.__N[0]:i.__[0],h=i.t(d,c);d!==h&&(i.__N=[h,i.__[1]],i.__c.setState({}))}],i.__c=B,!B.__f)){var o=function(c,d,h){if(!i.__c.__H)return!0;var g=i.__c.__H.__.filter(function(b){return!!b.__c});if(g.every(function(b){return!b.__N}))return!r||r.call(this,c,d,h);var p=i.__c.props!==c;return g.forEach(function(b){if(b.__N){var m=b.__[0];b.__=b.__N,b.__N=void 0,m!==b.__[0]&&(p=!0)}}),r&&r.call(this,c,d,h)||p};B.__f=!0;var r=B.shouldComponentUpdate,s=B.componentWillUpdate;B.componentWillUpdate=function(c,d,h){if(this.__e){var g=r;r=void 0,o(c,d,h),r=g}s&&s.call(this,c,d,h)},B.shouldComponentUpdate=o}return i.__N||i.__}function fe(t,e){var n=st(xe++,3);!G.__s&&Qt(n.__H,e)&&(n.__=t,n.u=e,B.__H.__h.push(n))}function Ue(t){return Fe=5,Yt(function(){return{current:t}},[])}function Yt(t,e){var n=st(xe++,7);return Qt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Qn(){for(var t;t=Vt.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(je),t.__H.__h.forEach(at),t.__H.__h=[]}catch(e){t.__H.__h=[],G.__e(e,t.__v)}}G.__b=function(t){B=null,Gt&&Gt(t)},G.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Jt&&Jt(t,e)},G.__r=function(t){zt&&zt(t),xe=0;var e=(B=t.__c).__H;e&&(rt===B?(e.__h=[],B.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(je),e.__h.forEach(at),e.__h=[],xe=0)),rt=B},G.diffed=function(t){qt&&qt(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Vt.push(e)!==1&&Ht===G.requestAnimationFrame||((Ht=G.requestAnimationFrame)||Xn)(Qn)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),rt=B=null},G.__c=function(t,e){e.some(function(n){try{n.__h.forEach(je),n.__h=n.__h.filter(function(i){return!i.__||at(i)})}catch(i){e.some(function(o){o.__h&&(o.__h=[])}),e=[],G.__e(i,n.__v)}}),Wt&&Wt(t,e)},G.unmount=function(t){Kt&&Kt(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{je(i)}catch(o){e=o}}),n.__H=void 0,e&&G.__e(e,n.__v))};var Zt=typeof requestAnimationFrame=="function";function Xn(t){var e,n=function(){clearTimeout(i),Zt&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Zt&&(e=requestAnimationFrame(n))}function je(t){var e=B,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),B=e}function at(t){var e=B;t.__c=t.__(),B=e}function Qt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Xt(t,e){return typeof e=="function"?e(t):e}/**
|
|
2
2
|
* @license lucide-preact v0.515.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -38,13 +38,13 @@
|
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
40
40
|
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const ai=Be("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]),ci=({stream:t})=>{const e=je(null);return fe(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),T("audio",{ref:e,autoPlay:!0})};function nn(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var o=t.length;for(e=0;e<o;e++)t[e]&&(n=nn(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function ct(){for(var t,e,n=0,i="",o=arguments.length;n<o;n++)(t=arguments[n])&&(e=nn(t))&&(i&&(i+=" "),i+=e);return i}const li={green:"bg-[linear-gradient(180deg,_#004B1E_0%,_#5FEFA9_47.12%,_#004B1E_100%)]",purple:"bg-[linear-gradient(180deg,_#1F023A_0%,_#CA76FF_47.12%,_#1F023A_100%)]",pink:"bg-[linear-gradient(180deg,_#FD05F9_0%,_#FFD4FE_47.12%,_#B400B1_100%)]",darkBlue:"bg-[linear-gradient(180deg,_#371A5E_0%,_#81B9FF_47.12%,_#371A5E_100%)]",orange:"bg-[linear-gradient(180deg,_#FC5F00_0%,_#FFFFFF_47.12%,_#FC5F00_100%)]",blue:"bg-[linear-gradient(180deg,_#005A98_0%,_#4CE5F2_47.12%,_#005A98_100%)]"};function di({stream:t,color:e="purple"}){const n=je([]),i=je(null);fe(()=>{if(!t||n.current.every(m=>m===null))return;const r=new window.AudioContext,s=r.createMediaStreamSource(t),c=r.createAnalyser();c.fftSize=512;const d=c.frequencyBinCount,h=new Uint8Array(d);s.connect(c);const g=6,p=12;function b(){i.current=requestAnimationFrame(b),c.getByteFrequencyData(h);for(let m=0;m<g;m++){const C=n.current[m],A=m*Math.floor(d/g);let y=h[A];const S=1+m*.6;y*=S;const k=Math.min(y/255,1),L=Math.max(k*100,p);C.style.height=`${L}%`}}return b(),()=>{i.current&&cancelAnimationFrame(i.current),r.close()}},[t]);const o=Yt(()=>Array.from({length:6},(r,s)=>T("div",{ref:c=>n.current[s]=c,className:ct("min-h-[20px] min-w-[20px] rounded-full transition-all duration-100 ease-out border border-white/10 border-solid",li[e])},s)),[e]);return T("div",{className:"flex items-center justify-center h-24 w-full bg-black gap-0.5 px-2 overflow-hidden",children:o})}function lt(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}function R(t,e,n,i){return new(n||(n=Promise))(function(o,r){function s(h){try{d(i.next(h))}catch(g){r(g)}}function c(h){try{d(i.throw(h))}catch(g){r(g)}}function d(h){var g;h.done?o(h.value):(g=h.value,g instanceof n?g:new n(function(p){p(g)})).then(s,c)}d((i=i.apply(t,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var on=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),ui=new Uint8Array(16);function hi(){if(!on)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return on(ui)}for(var rn=[],He=0;He<256;++He)rn[He]=(He+256).toString(16).substr(1);function Ee(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var o=(t=t||{}).random||(t.rng||hi)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e)for(var r=0;r<16;++r)e[i+r]=o[r];return e||function(s,c){var d=0,h=rn;return[h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]]].join("")}(o)}var pi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sn(t,e){return t(e={exports:{}},e.exports),e.exports}var fi=sn(function(t){var e,n;e=pi,n=function(){var i=function(){},o="undefined",r=typeof window!==o&&typeof window.navigator!==o&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function c(y,S){var k=y[S];if(typeof k.bind=="function")return k.bind(y);try{return Function.prototype.bind.call(k,y)}catch{return function(){return Function.prototype.apply.apply(k,[y,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(y,S){for(var k=0;k<s.length;k++){var L=s[k];this[L]=k<y?i:this.methodFactory(L,y,S)}this.log=this.debug}function g(y,S,k){return function(){typeof console!==o&&(h.call(this,S,k),this[y].apply(this,arguments))}}function p(y,S,k){return function(L){return L==="debug"&&(L="log"),typeof console!==o&&(L==="trace"&&r?d:console[L]!==void 0?c(console,L):console.log!==void 0?c(console,"log"):i)}(y)||g.apply(this,arguments)}function b(y,S,k){var L,P=this;S=S??"WARN";var H="loglevel";function Q(){var D;if(typeof window!==o&&H){try{D=window.localStorage[H]}catch{}if(typeof D===o)try{var a=window.document.cookie,l=a.indexOf(encodeURIComponent(H)+"=");l!==-1&&(D=/^([^;]+)/.exec(a.slice(l))[1])}catch{}return P.levels[D]===void 0&&(D=void 0),D}}typeof y=="string"?H+=":"+y:typeof y=="symbol"&&(H=void 0),P.name=y,P.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},P.methodFactory=k||p,P.getLevel=function(){return L},P.setLevel=function(D,a){if(typeof D=="string"&&P.levels[D.toUpperCase()]!==void 0&&(D=P.levels[D.toUpperCase()]),!(typeof D=="number"&&D>=0&&D<=P.levels.SILENT))throw"log.setLevel() called with invalid level: "+D;if(L=D,a!==!1&&function(l){var u=(s[l]||"silent").toUpperCase();if(typeof window!==o&&H){try{return void(window.localStorage[H]=u)}catch{}try{window.document.cookie=encodeURIComponent(H)+"="+u+";"}catch{}}}(D),h.call(P,D,y),typeof console===o&&D<P.levels.SILENT)return"No console available for logging"},P.setDefaultLevel=function(D){S=D,Q()||P.setLevel(D,!1)},P.resetLevel=function(){P.setLevel(S,!1),function(){if(typeof window!==o&&H){try{return void window.localStorage.removeItem(H)}catch{}try{window.document.cookie=encodeURIComponent(H)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},P.enableAll=function(D){P.setLevel(P.levels.TRACE,D)},P.disableAll=function(D){P.setLevel(P.levels.SILENT,D)};var V=Q();V==null&&(V=S),P.setLevel(V,!1)}var m=new b,C={};m.getLogger=function(y){if(typeof y!="symbol"&&typeof y!="string"||y==="")throw new TypeError("You must supply a name when creating a logger.");var S=C[y];return S||(S=C[y]=new b(y,m.getLevel(),m.methodFactory)),S};var A=typeof window!==o?window.log:void 0;return m.noConflict=function(){return typeof window!==o&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m},t.exports?t.exports=n():e.log=n()});const I=fi.getLogger("telnyx"),gi=I.methodFactory;I.methodFactory=(t,e,n)=>{const i=gi(t,e,n);return function(){const o=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let r=0;r<arguments.length;r++)o.push(arguments[r]);i.apply(void 0,o)}},I.setLevel(I.getLevel());const an="Time to call invite",cn="wss://rtc.telnyx.com",_i={urls:"stun:stun.telnyx.com:3478"},mi={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var E;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError"})(E||(E={}));const ln=t=>Object.keys(t).length===0,Ve=t=>{const[e,n,i,o,r,s]=t;let c={};try{c=JSON.parse(r.replace(/ID"/g,'Id"'))}catch{I.warn("Verto LA invalid media JSON string:",r)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:o,media:c,participantData:s}},dn=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},ge=t=>t instanceof Function||typeof t=="function",Te=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,vi=/^(ws|wss):\/\//,un=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:o=null}=n;if(o===null)return e!==null&&(n.node_id=e),{result:n};const{code:r=null,node_id:s=null,result:c=null}=o;return r&&r!=="200"?{error:o}:c?un(c,s):{result:o}},hn=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),dt=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Ge=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,ut=t=>{var e,n,i,o,r,s;let c="",d="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(c=(o=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||o===void 0?void 0:o.state),!((r=t==null?void 0:t.params)===null||r===void 0)&&r.state&&(d=(s=t==null?void 0:t.params)===null||s===void 0?void 0:s.state),c||d};function pn({debounceTime:t}){let e,n;return{promise:new Promise((i,o)=>{e=t?bi(i,t):i,n=o}),resolve:e,reject:n}}const bi=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},_e="GLOBAL",J={},Ae=(t,e)=>`${t}|${e}`,fn=(t,e=_e)=>Ae(t,e)in J,me=(t,e,n=_e)=>{const i=Ae(t,n);i in J||(J[i]=[]),J[i].push(e)},gn=(t,e,n=_e)=>{const i=function(o){ve(t,i,n),e(o)};return i.prototype.targetRef=e,me(t,i,n)},ve=(t,e,n=_e)=>{if(!fn(t,n))return!1;const i=Ae(t,n);if(ge(e))for(let o=J[i].length-1;o>=0;o--){const r=J[i][o];(e===r||r.prototype&&e===r.prototype.targetRef)&&J[i].splice(o,1)}else J[i]=[];return J[i].length===0&&delete J[i],!0},N=(t,e,n=_e,i=!0)=>{const o=i&&n!==_e;if(!fn(t,n))return o&&N(t,e),!1;const r=Ae(t,n),s=J[r].length;if(!s)return o&&N(t,e),!1;for(let c=s-1;c>=0;c--)J[r][c](e);return o&&N(t,e),!0},ht=t=>{const e=Ae(t,"");Object.keys(J).filter(n=>n.indexOf(e)===0).forEach(n=>delete J[n])};var Y,de,$;(function(t){t.Offer="offer",t.Answer="answer"})(Y||(Y={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(de||(de={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}($||($={}));const ae={generic:"event",[$.Display]:"participantData",[$.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},yi={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var M,Re,W,ce,K;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(M||(M={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Re||(Re={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(W||(W={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(ce||(ce={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(K||(K={}));const pt="telnyx-voice-sdk-id";function ft(){return sessionStorage.getItem(pt)}typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(pt)});let wi=typeof WebSocket<"u"?WebSocket:null;const Si=0,Ci=1,ki=2,xi=3;class _n{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=cn,this._timers={},this.upDur=null,this.downDur=null;const{host:n,env:i,region:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":cn),n&&(this._host=(r=>`${vi.test(r)?"":"wss://"}${r}`)(n)),o&&(this._host=this._host.replace(/rtc(dev)?/,`${o}.rtc$1`))}get connected(){return this._wsClient&&this._wsClient.readyState===Ci}get connecting(){return this._wsClient&&this._wsClient.readyState===Si}get closing(){return this._wsClient&&this._wsClient.readyState===ki}get closed(){return this._wsClient&&this._wsClient.readyState===xi}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),n=ft();n&&e.searchParams.set("voice_sdk_id",n),this._wsClient=new wi(e.toString()),this._wsClient.onopen=i=>N(E.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>N(E.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>N(E.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var o,r;const s=dn(i.data);var c;if(typeof s!="string"){if(s.voice_sdk_id&&(c=s.voice_sdk_id,sessionStorage.setItem(pt,c)),this._unsetTimer(s.id),I.debug(`RECV:
|
|
41
|
+
*/const ai=Be("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]),ci=({stream:t})=>{const e=Ue(null);return fe(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),T("audio",{ref:e,autoPlay:!0})};function nn(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var o=t.length;for(e=0;e<o;e++)t[e]&&(n=nn(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function ct(){for(var t,e,n=0,i="",o=arguments.length;n<o;n++)(t=arguments[n])&&(e=nn(t))&&(i&&(i+=" "),i+=e);return i}const li={green:"bg-[linear-gradient(180deg,_#004B1E_0%,_#5FEFA9_47.12%,_#004B1E_100%)]",purple:"bg-[linear-gradient(180deg,_#1F023A_0%,_#CA76FF_47.12%,_#1F023A_100%)]",pink:"bg-[linear-gradient(180deg,_#FD05F9_0%,_#FFD4FE_47.12%,_#B400B1_100%)]",darkBlue:"bg-[linear-gradient(180deg,_#371A5E_0%,_#81B9FF_47.12%,_#371A5E_100%)]",orange:"bg-[linear-gradient(180deg,_#FC5F00_0%,_#FFFFFF_47.12%,_#FC5F00_100%)]",blue:"bg-[linear-gradient(180deg,_#005A98_0%,_#4CE5F2_47.12%,_#005A98_100%)]"};function di({stream:t,color:e="purple"}){const n=Ue([]),i=Ue(null);fe(()=>{if(!t||n.current.every(m=>m===null))return;const r=new window.AudioContext,s=r.createMediaStreamSource(t),c=r.createAnalyser();c.fftSize=512;const d=c.frequencyBinCount,h=new Uint8Array(d);s.connect(c);const g=6,p=12;function b(){i.current=requestAnimationFrame(b),c.getByteFrequencyData(h);for(let m=0;m<g;m++){const C=n.current[m],A=m*Math.floor(d/g);let y=h[A];const S=1+m*.6;y*=S;const k=Math.min(y/255,1),L=Math.max(k*100,p);C.style.height=`${L}%`}}return b(),()=>{i.current&&cancelAnimationFrame(i.current),r.close()}},[t]);const o=Yt(()=>Array.from({length:6},(r,s)=>T("div",{ref:c=>n.current[s]=c,className:ct("min-h-[20px] min-w-[20px] rounded-full transition-all duration-100 ease-out border border-white/10 border-solid",li[e])},s)),[e]);return T("div",{className:"flex items-center justify-center h-24 w-full bg-black gap-0.5 px-2 overflow-hidden",children:o})}function lt(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}function R(t,e,n,i){return new(n||(n=Promise))(function(o,r){function s(h){try{d(i.next(h))}catch(g){r(g)}}function c(h){try{d(i.throw(h))}catch(g){r(g)}}function d(h){var g;h.done?o(h.value):(g=h.value,g instanceof n?g:new n(function(p){p(g)})).then(s,c)}d((i=i.apply(t,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var on=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),ui=new Uint8Array(16);function hi(){if(!on)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return on(ui)}for(var rn=[],He=0;He<256;++He)rn[He]=(He+256).toString(16).substr(1);function Ee(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var o=(t=t||{}).random||(t.rng||hi)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e)for(var r=0;r<16;++r)e[i+r]=o[r];return e||function(s,c){var d=0,h=rn;return[h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],"-",h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]],h[s[d++]]].join("")}(o)}var pi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sn(t,e){return t(e={exports:{}},e.exports),e.exports}var fi=sn(function(t){var e,n;e=pi,n=function(){var i=function(){},o="undefined",r=typeof window!==o&&typeof window.navigator!==o&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"];function c(y,S){var k=y[S];if(typeof k.bind=="function")return k.bind(y);try{return Function.prototype.bind.call(k,y)}catch{return function(){return Function.prototype.apply.apply(k,[y,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(y,S){for(var k=0;k<s.length;k++){var L=s[k];this[L]=k<y?i:this.methodFactory(L,y,S)}this.log=this.debug}function g(y,S,k){return function(){typeof console!==o&&(h.call(this,S,k),this[y].apply(this,arguments))}}function p(y,S,k){return function(L){return L==="debug"&&(L="log"),typeof console!==o&&(L==="trace"&&r?d:console[L]!==void 0?c(console,L):console.log!==void 0?c(console,"log"):i)}(y)||g.apply(this,arguments)}function b(y,S,k){var L,P=this;S=S??"WARN";var H="loglevel";function Q(){var D;if(typeof window!==o&&H){try{D=window.localStorage[H]}catch{}if(typeof D===o)try{var a=window.document.cookie,l=a.indexOf(encodeURIComponent(H)+"=");l!==-1&&(D=/^([^;]+)/.exec(a.slice(l))[1])}catch{}return P.levels[D]===void 0&&(D=void 0),D}}typeof y=="string"?H+=":"+y:typeof y=="symbol"&&(H=void 0),P.name=y,P.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},P.methodFactory=k||p,P.getLevel=function(){return L},P.setLevel=function(D,a){if(typeof D=="string"&&P.levels[D.toUpperCase()]!==void 0&&(D=P.levels[D.toUpperCase()]),!(typeof D=="number"&&D>=0&&D<=P.levels.SILENT))throw"log.setLevel() called with invalid level: "+D;if(L=D,a!==!1&&function(l){var u=(s[l]||"silent").toUpperCase();if(typeof window!==o&&H){try{return void(window.localStorage[H]=u)}catch{}try{window.document.cookie=encodeURIComponent(H)+"="+u+";"}catch{}}}(D),h.call(P,D,y),typeof console===o&&D<P.levels.SILENT)return"No console available for logging"},P.setDefaultLevel=function(D){S=D,Q()||P.setLevel(D,!1)},P.resetLevel=function(){P.setLevel(S,!1),function(){if(typeof window!==o&&H){try{return void window.localStorage.removeItem(H)}catch{}try{window.document.cookie=encodeURIComponent(H)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},P.enableAll=function(D){P.setLevel(P.levels.TRACE,D)},P.disableAll=function(D){P.setLevel(P.levels.SILENT,D)};var V=Q();V==null&&(V=S),P.setLevel(V,!1)}var m=new b,C={};m.getLogger=function(y){if(typeof y!="symbol"&&typeof y!="string"||y==="")throw new TypeError("You must supply a name when creating a logger.");var S=C[y];return S||(S=C[y]=new b(y,m.getLevel(),m.methodFactory)),S};var A=typeof window!==o?window.log:void 0;return m.noConflict=function(){return typeof window!==o&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m},t.exports?t.exports=n():e.log=n()});const I=fi.getLogger("telnyx"),gi=I.methodFactory;I.methodFactory=(t,e,n)=>{const i=gi(t,e,n);return function(){const o=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let r=0;r<arguments.length;r++)o.push(arguments[r]);i.apply(void 0,o)}},I.setLevel(I.getLevel());const an="Time to call invite",cn="wss://rtc.telnyx.com",_i={urls:"stun:stun.telnyx.com:3478"},mi={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var E;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError"})(E||(E={}));const ln=t=>Object.keys(t).length===0,Ve=t=>{const[e,n,i,o,r,s]=t;let c={};try{c=JSON.parse(r.replace(/ID"/g,'Id"'))}catch{I.warn("Verto LA invalid media JSON string:",r)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:o,media:c,participantData:s}},dn=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},ge=t=>t instanceof Function||typeof t=="function",Te=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,vi=/^(ws|wss):\/\//,un=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:o=null}=n;if(o===null)return e!==null&&(n.node_id=e),{result:n};const{code:r=null,node_id:s=null,result:c=null}=o;return r&&r!=="200"?{error:o}:c?un(c,s):{result:o}},hn=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),dt=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Ge=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,ut=t=>{var e,n,i,o,r,s;let c="",d="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(c=(o=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||o===void 0?void 0:o.state),!((r=t==null?void 0:t.params)===null||r===void 0)&&r.state&&(d=(s=t==null?void 0:t.params)===null||s===void 0?void 0:s.state),c||d};function pn({debounceTime:t}){let e,n;return{promise:new Promise((i,o)=>{e=t?bi(i,t):i,n=o}),resolve:e,reject:n}}const bi=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},_e="GLOBAL",J={},Ae=(t,e)=>`${t}|${e}`,fn=(t,e=_e)=>Ae(t,e)in J,me=(t,e,n=_e)=>{const i=Ae(t,n);i in J||(J[i]=[]),J[i].push(e)},gn=(t,e,n=_e)=>{const i=function(o){ve(t,i,n),e(o)};return i.prototype.targetRef=e,me(t,i,n)},ve=(t,e,n=_e)=>{if(!fn(t,n))return!1;const i=Ae(t,n);if(ge(e))for(let o=J[i].length-1;o>=0;o--){const r=J[i][o];(e===r||r.prototype&&e===r.prototype.targetRef)&&J[i].splice(o,1)}else J[i]=[];return J[i].length===0&&delete J[i],!0},N=(t,e,n=_e,i=!0)=>{const o=i&&n!==_e;if(!fn(t,n))return o&&N(t,e),!1;const r=Ae(t,n),s=J[r].length;if(!s)return o&&N(t,e),!1;for(let c=s-1;c>=0;c--)J[r][c](e);return o&&N(t,e),!0},ht=t=>{const e=Ae(t,"");Object.keys(J).filter(n=>n.indexOf(e)===0).forEach(n=>delete J[n])};var Y,de,$;(function(t){t.Offer="offer",t.Answer="answer"})(Y||(Y={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(de||(de={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}($||($={}));const ae={generic:"event",[$.Display]:"participantData",[$.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},yi={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var M,Re,W,ce,K;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(M||(M={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Re||(Re={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(W||(W={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(ce||(ce={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(K||(K={}));const pt="telnyx-voice-sdk-id";function ft(){return sessionStorage.getItem(pt)}typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(pt)});let wi=typeof WebSocket<"u"?WebSocket:null;const Si=0,Ci=1,ki=2,xi=3;class _n{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=cn,this._timers={},this.upDur=null,this.downDur=null;const{host:n,env:i,region:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":cn),n&&(this._host=(r=>`${vi.test(r)?"":"wss://"}${r}`)(n)),o&&(this._host=this._host.replace(/rtc(dev)?/,`${o}.rtc$1`))}get connected(){return this._wsClient&&this._wsClient.readyState===Ci}get connecting(){return this._wsClient&&this._wsClient.readyState===Si}get closing(){return this._wsClient&&this._wsClient.readyState===ki}get closed(){return this._wsClient&&this._wsClient.readyState===xi}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),n=ft();n&&e.searchParams.set("voice_sdk_id",n),this._wsClient=new wi(e.toString()),this._wsClient.onopen=i=>N(E.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>N(E.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>N(E.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var o,r;const s=dn(i.data);var c;if(typeof s!="string"){if(s.voice_sdk_id&&(c=s.voice_sdk_id,sessionStorage.setItem(pt,c)),this._unsetTimer(s.id),I.debug(`RECV:
|
|
42
42
|
`,JSON.stringify(s,null,2),`
|
|
43
43
|
`),K[`${(r=(o=s==null?void 0:s.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.state}`]||!N(s.id,s)){const d=ut(s);N(E.SocketMessage,s,this.session.uuid),d&&(this.previousGatewayState=d)}}else this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((o,r)=>{if(n.hasOwnProperty("result"))return o();gn(n.id,s=>{const{result:c,error:d}=un(s);return d?r(d):o(c)})});return I.debug(`SEND:
|
|
44
44
|
`,JSON.stringify(n,null,2),`
|
|
45
45
|
`),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(ge(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),N(E.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else I.warn("Unknown message from socket",e)}}class ze{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Ee()},e)}}const mn={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 Z extends ze{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=lt(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in mn)i&&n.hasOwnProperty(i)&&(n[mn[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class vn extends Z{constructor(){super(),this.method=$.GatewayState,this.buildRequest({method:this.method,params:{}})}}class Ii{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>R(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(ut(n))}),this.getIsRegistered=()=>R(this,void 0,void 0,function*(){const n=new vn;this.pendingRequestId=n.request.id,this.gatewayStateTask=pn({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[K.REGISTER,K.REGED].includes(i)}),this.session=e,this.gatewayStateTask=pn({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Ei{constructor(e){if(this.options=e,this.uuid=Ee(),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.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new _n(this),this.registerAgent=new Ii(this)}get __logger(){return I}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*hn(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return dt(this.options)||Ge(this.options)}broadcast(e){}disconnect(){return R(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners()})}on(e,n){return me(e,n,this.uuid),this}off(e,n){return ve(e,n,this.uuid),this}connect(){return R(this,void 0,void 0,function*(){this.connection||(this.connection=new _n(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){N(E.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return R(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&ht(this.relayProtocol);for(const e in this.subscriptions)ht(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],ve(e,null,n)):(delete this.subscriptions[e],ht(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},ge(n)&&me(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(E.SocketOpen,this._onSocketOpen),this.on(E.SocketClose,this.onNetworkClose),this.on(E.SocketError,this.onNetworkClose),this.on(E.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(E.SocketOpen,this._onSocketOpen),this.off(E.SocketClose,this.onNetworkClose),this.off(E.SocketError,this.onNetworkClose),this.off(E.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){this._doKeepAlive===!0&&(this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),3e4))}static on(e,n){me(e,n)}static off(e){ve(e)}static uuid(){return Ee()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const gt=t=>navigator.mediaDevices.getUserMedia(t),qe=t=>t&&t instanceof MediaStream,We=(t,e)=>{const n=Te(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},bn=(t,e)=>R(void 0,void 0,void 0,function*(){const n=Te(t);if(n===null)return I.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return I.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Ti=t=>{t&&t.readyState==="live"&&t.stop()},Me=t=>{qe(t)&&t.getTracks().forEach(Ti),t=null},Ke=t=>R(void 0,void 0,void 0,function*(){I.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield gt(t)}catch(i){throw I.error("getUserMedia error: ",i),i}}),Ne=(t=null,e=!1)=>R(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((o=null)=>({audio:!o||o===ce.AudioIn||o===ce.AudioOut,video:!o||o===ce.Video}))(t)).catch(o=>(console.error(o),null));if(i){if(Me(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(r=>r.kind===t)),e===!0)return n;const o=[];n=n.filter(r=>{if(!r.groupId)return!0;const s=`${r.kind}-${r.groupId}`;return!o.includes(s)&&(o.push(s),!0)})}return n}),yn=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Je=(t,e,n)=>R(void 0,void 0,void 0,function*(){const i=yield Ne(n,!0);for(let o=0;o<i.length;o++){const{deviceId:r,label:s}=i[o];if(t===r||e===s)return r}return null}),wn=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Sn=(t,e,n,i)=>R(void 0,void 0,void 0,function*(){const{deviceId:o}=i;if(o===void 0&&(t||e)){const r=yield Je(t,e,n).catch(s=>null);r&&(i.deviceId={exact:r})}return i}),_t=t=>{const e=`\r
|
|
46
46
|
`,n=t.split(e),i=n.findIndex(c=>/^a=rtpmap/.test(c)&&/opus\/48000/.test(c));if(i<0)return t;const o=(c=>{const d=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),h=c.match(d);return h&&h.length==2?h[1]:null})(n[i]),r=new RegExp(`a=fmtp:${o}`),s=n.findIndex(c=>r.test(c));return s>=0?/stereo=1;/.test(n[s])||(n[s]+="; stereo=1; sprop-stereo=1"):n[i]+=`${e}a=fmtp:${o} stereo=1; sprop-stereo=1`,n.join(e)},Cn=t=>/^m=audio/.test(t),kn=t=>/^m=video/.test(t),xn=(t,e)=>{const n=`\r
|
|
47
|
-
`,i=e.split(n);if(i.findIndex(Cn)<i.findIndex(kn))return t;const o=t.split(n),r=o.findIndex(Cn),s=o.findIndex(kn),c=o.slice(r,s),d=o.slice(s,o.length-1);return[...o.slice(0,r),...d,...c,""].join(n)},Ye=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=mt(t);return n.includes(e)||i.includes(e)},mt=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},be=(t,e=null,n=null)=>{if(!qe(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(o=>{switch(n){case"on":case!0:o.enabled=!0;break;case"off":case!1:o.enabled=!1;break;default:o.enabled=!o.enabled}})},In=t=>{be(t,"audio",!0)},En=t=>{be(t,"audio",!1)},Tn=t=>{be(t,"audio",null)};function Ai(){try{const{browserInfo:t,name:e,version:n,supportAudio:i,supportVideo:o}=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 g=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const g=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const g=navigator.userAgent.match(/safari/gim)[0],p=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),b=parseInt(p[1],10);return{browserInfo:navigator.userAgent,name:g,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const g=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),r=window.RTCPeerConnection,s=window.RTCSessionDescription,c=window.RTCIceCandidate,d=window.navigator&&window.navigator.mediaDevices,h=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(r&&s&&c&&d&&h),supportWebRTCAudio:i,supportWebRTCVideo:o,supportRTCPeerConnection:!!r,supportSessionDescription:!!s,supportIceCandidate:!!c,supportMediaDevices:!!d,supportGetUserMedia:!!Ke}}catch(t){return t.message}}var U;function An(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Rn(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),t._playFulfilled=!0}))}function Mn(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(U||(U={}));var Nn="2.22.12",vt=Nn;class Ri extends Z{constructor(e,n,i,o,r={},s){super(),this.method="login";const c={login:e,passwd:n,login_token:i,userVariables:r,reconnection:s,loginParams:{},"User-Agent":{sdkVersion:vt,data:navigator.userAgent}};o&&(c.sessid=o),this.buildRequest({method:this.method,params:c})}}class Mi extends Z{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Ni extends Z{toString(){return $.Invite}}class Li extends Z{toString(){return $.Answer}}class Di extends Z{toString(){return $.Attach}}class Oi extends Z{toString(){return $.Bye}}class bt extends Z{toString(){return $.Modify}}class Ln extends Z{toString(){return $.Info}}class Pi extends Z{toString(){return $.Broadcast}}class $i extends Z{toString(){return $.Subscribe}}class Fi extends Z{toString(){return $.Unsubscribe}}const Dn=(t,e)=>{const{contentType:n,canvasType:i,callID:o,canvasInfo:r=null,currentLayerIdx:s=-1}=e;r&&i!=="mcu-personal-canvas"&&delete r.memberID;const c={type:ae.conferenceUpdate,call:t.calls[o],canvasInfo:ji(r),currentLayerIdx:s};switch(n){case"layer-info":{const d=Object.assign({action:W.LayerInfo},c);N(E.Notification,d,t.uuid);break}case"layout-info":{const d=Object.assign({action:W.LayoutInfo},c);N(E.Notification,d,t.uuid);break}}},ji=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return dn(e)};var Ze,On=sn(function(t,e){var n;function i(){}function o(){o.init.call(this)}function r(a){return a._maxListeners===void 0?o.defaultMaxListeners:a._maxListeners}function s(a,l,u,f){var _,w,v;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if((w=a._events)?(w.newListener&&(a.emit("newListener",l,u.listener?u.listener:u),w=a._events),v=w[l]):(w=a._events=new i,a._eventsCount=0),v){if(typeof v=="function"?v=w[l]=f?[u,v]:[v,u]:f?v.unshift(u):v.push(u),!v.warned&&(_=r(a))&&0<_&&v.length>_){v.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+v.length+" "+l+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=a,x.type=l,x.count=v.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(x)}}else v=w[l]=u,++a._eventsCount;return a}function c(a,l,u){function f(){a.removeListener(l,f),_||(_=!0,u.apply(a,arguments))}var _=!1;return f.listener=u,f}function d(a){var l=this._events;if(l){var u=l[a];if(typeof u=="function")return 1;if(u)return u.length}return 0}function h(a,l){for(var u=Array(l);l--;)u[l]=a[l];return u}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.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},o.prototype.setMaxListeners=function(a){if(typeof a!="number"||0>a||isNaN(a))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=a,this},o.prototype.getMaxListeners=function(){return r(this)},o.prototype.emit=function(a){var l,u,f,_,w,v,x,O=a==="error";if(v=this._events)O=O&&v.error==null;else if(!O)return!1;if(x=this.domain,O){if(l=arguments[1],!x){if(l instanceof Error)throw l;var ne=new Error('Uncaught, unspecified "error" event. ('+l+")");throw ne.context=l,ne}return l||(l=new Error('Uncaught, unspecified "error" event')),l.domainEmitter=this,l.domain=x,l.domainThrown=!1,x.emit("error",l),!1}if(!(u=v[a]))return!1;var oe=typeof u=="function";switch(f=arguments.length){case 1:(function(j,re,q){if(re)j.call(q);else for(var z=j.length,X=h(j,z),ee=0;ee<z;++ee)X[ee].call(q)})(u,oe,this);break;case 2:(function(j,re,q,z){if(re)j.call(q,z);else for(var X=j.length,ee=h(j,X),ie=0;ie<X;++ie)ee[ie].call(q,z)})(u,oe,this,arguments[1]);break;case 3:(function(j,re,q,z,X){if(re)j.call(q,z,X);else for(var ee=j.length,ie=h(j,ee),Le=0;Le<ee;++Le)ie[Le].call(q,z,X)})(u,oe,this,arguments[1],arguments[2]);break;case 4:(function(j,re,q,z,X,ee){if(re)j.call(q,z,X,ee);else for(var ie=j.length,Le=h(j,ie),wt=0;wt<ie;++wt)Le[wt].call(q,z,X,ee)})(u,oe,this,arguments[1],arguments[2],arguments[3]);break;default:for(_=Array(f-1),w=1;w<f;w++)_[w-1]=arguments[w];(function(j,re,q,z){if(re)j.apply(q,z);else for(var X=j.length,ee=h(j,X),ie=0;ie<X;++ie)ee[ie].apply(q,z)})(u,oe,this,_)}return!0},o.prototype.addListener=function(a,l){return s(this,a,l,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(a,l){return s(this,a,l,!0)},o.prototype.once=function(a,l){if(typeof l!="function")throw new TypeError('"listener" argument must be a function');return this.on(a,c(this,a,l)),this},o.prototype.prependOnceListener=function(a,l){if(typeof l!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(a,c(this,a,l)),this},o.prototype.removeListener=function(a,l){var u,f,_,w,v;if(typeof l!="function")throw new TypeError('"listener" argument must be a function');if(!(f=this._events))return this;if(!(u=f[a]))return this;if(u===l||u.listener&&u.listener===l)--this._eventsCount==0?this._events=new i:(delete f[a],f.removeListener&&this.emit("removeListener",a,u.listener||l));else if(typeof u!="function"){for(_=-1,w=u.length;0<w--;)if(u[w]===l||u[w].listener&&u[w].listener===l){v=u[w].listener,_=w;break}if(0>_)return this;if(u.length===1){if(u[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete f[a]}else(function(x,O){for(var ne=O,oe=ne+1,j=x.length;oe<j;ne+=1,oe+=1)x[ne]=x[oe];x.pop()})(u,_);f.removeListener&&this.emit("removeListener",a,v||l)}return this},o.prototype.removeAllListeners=function(a){var l,u;if(!(u=this._events))return this;if(!u.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):u[a]&&(--this._eventsCount==0?this._events=new i:delete u[a]),this;if(arguments.length===0){for(var f,_=Object.keys(u),w=0;w<_.length;++w)(f=_[w])!=="removeListener"&&this.removeAllListeners(f);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(l=u[a])=="function")this.removeListener(a,l);else if(l)do this.removeListener(a,l[l.length-1]);while(l[0]);return this},o.prototype.listeners=function(a){var l,u,f=this._events;return f?u=(l=f[a])?typeof l=="function"?[l.listener||l]:function(_){for(var w=Array(_.length),v=0;v<w.length;++v)w[v]=_[v].listener||_[v];return w}(l):[]:u=[],u},o.listenerCount=function(a,l){return typeof a.listenerCount=="function"?a.listenerCount(l):d.call(a,l)},o.prototype.listenerCount=d,o.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var g,p=new Uint8Array(16);function b(){if(!g&&!(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(p)}for(var m=/^(?:[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,C=[],A=0;256>A;++A)C.push((A+256).toString(16).substr(1));function y(a){var l=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,u=(C[a[l+0]]+C[a[l+1]]+C[a[l+2]]+C[a[l+3]]+"-"+C[a[l+4]]+C[a[l+5]]+"-"+C[a[l+6]]+C[a[l+7]]+"-"+C[a[l+8]]+C[a[l+9]]+"-"+C[a[l+10]]+C[a[l+11]]+C[a[l+12]]+C[a[l+13]]+C[a[l+14]]+C[a[l+15]]).toLowerCase();if(!function(f){return typeof f=="string"&&m.test(f)}(u))throw TypeError("Stringified UUID is invalid");return u}function S(a,l,u){var f=(a=a||{}).random||(a.rng||b)();return f[6]=64|15&f[6],f[8]=128|63&f[8],y(f)}function k(a,l){if(!a||!l)return{};const u={...a};if(u.localCandidateId){const f=l.get(u.localCandidateId);u.local={...f}}if(u.remoteCandidateId){const f=l.get(u.remoteCandidateId);u.remote={...f}}return u}function L(a,l,u){return 8*function(f,_,w){const v=f[w],x=_?_[w]:null;return v===null||x===null?null:(v-x)/(f.timestamp-_.timestamp)*1e3}(a,l,u)}function P(a){if(!a.entries)return a;const l={};return a.forEach(function(u,f){l[f]=u}),l}function H(a,l,u={}){if(!a)return null;let f={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};u.remote&&(f.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const _ of a.values())switch(_.type){case"outbound-rtp":{const w=_.mediaType||_.kind,v={};let x={};if(!["audio","video"].includes(w))continue;if(_.codecId){const O=a.get(_.codecId);O&&(v.clockRate=O.clockRate,v.mimeType=O.mimeType,v.payloadType=O.payloadType)}x=a.get(_.mediaSourceId)||a.get(_.trackId)||{},f[w].outbound.push({..._,...v,track:{...x}});break}case"inbound-rtp":{let w=_.mediaType||_.kind,v={};const x={};if(!["audio","video"].includes(w))if(_.id.includes("Video"))w="video";else{if(!_.id.includes("Audio"))continue;w="audio"}if(_.codecId){const O=a.get(_.codecId);O&&(x.clockRate=O.clockRate,x.mimeType=O.mimeType,x.payloadType=O.payloadType)}if(!f.connection.id&&_.transportId){const O=a.get(_.transportId);if(O&&O.selectedCandidatePairId){const ne=a.get(O.selectedCandidatePairId);f.connection=k(ne,a)}}v=a.get(_.mediaSourceId)||a.get(_.trackId)||{},f[w].inbound.push({..._,...x,track:{...v}});break}case"peer-connection":f.connection.dataChannelsClosed=_.dataChannelsClosed,f.connection.dataChannelsOpened=_.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!u.remote)break;let w=_.mediaType||_.kind;const v={};if(!["audio","video"].includes(w))if(_.id.includes("Video"))w="video";else{if(!_.id.includes("Audio"))continue;w="audio"}if(_.codecId){const x=a.get(_.codecId);x&&(v.clockRate=x.clockRate,v.mimeType=x.mimeType,v.payloadType=x.payloadType)}if(!f.connection.id&&_.transportId){const x=a.get(_.transportId);if(x&&x.selectedCandidatePairId){const O=a.get(x.selectedCandidatePairId);f.connection=k(O,a)}}f.remote[w].inbound.push({..._,...v});break}case"remote-outbound-rtp":{if(!u.remote)break;const w=_.mediaType||_.kind,v={};if(!["audio","video"].includes(w))continue;if(_.codecId){const x=a.get(_.codecId);x&&(v.clockRate=x.clockRate,v.mimeType=x.mimeType,v.payloadType=x.payloadType)}f.remote[w].outbound.push({..._,...v});break}}if(!f.connection.id)for(const _ of a.values())_.type==="candidate-pair"&&_.nominated&&_.state==="succeeded"&&(f.connection=k(_,a));return f=function(_,w){return w&&(_.audio.inbound.map(v=>{let x=w.audio.inbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesReceived"),v.packetRate=L(v,x,"packetsReceived")}),_.audio.outbound.map(v=>{let x=w.audio.outbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesSent"),v.packetRate=L(v,x,"packetsSent")}),_.video.inbound.map(v=>{let x=w.video.inbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesReceived"),v.packetRate=L(v,x,"packetsReceived")}),_.video.outbound.map(v=>{let x=w.video.outbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesSent"),v.packetRate=L(v,x,"packetsSent")})),_}(f,l),f}let Q,V={},D=[];e.WebRTCStats=class extends o{constructor(a){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"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const l={...a};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=l.getStatsInterval||1e3,this.rawStats=!!l.rawStats,this.statsObject=!!l.statsObject,this.filteredStats=!!l.filteredStats,this.shouldWrapGetUserMedia=!!l.wrapGetUserMedia,typeof l.remote=="boolean"&&(this.remote=l.remote),this.debug=!!l.debug,this.logLevel=l.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(a,l){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:a,pc:l})}async addConnection(a){const{pc:l,peerId:u}=a;let{connectionId:f,remote:_}=a;if(_=typeof _=="boolean"?_:this.remote,!(l&&l instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!u)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[u]){if(f&&f in this.peersToMonitor[u])throw new Error(`We are already monitoring connection with id ${f}.`);for(let v in this.peersToMonitor[u]){const x=this.peersToMonitor[u][v];if(x.pc===l)throw new Error(`We are already monitoring peer with id ${u}.`);x.pc.connectionState==="closed"&&this.removeConnection({pc:x.pc})}}const w=l.getConfiguration();return w.iceServers&&w.iceServers.forEach(function(v){delete v.credential}),f||(f=S()),this.emitEvent({event:"addConnection",tag:"peer",peerId:u,connectionId:f,data:{options:a,peerConfiguration:w}}),this.monitorPeer({peerId:u,connectionId:f,pc:l,remote:_}),{connectionId:f}}getTimeline(a){return this.timeline=this.timeline.sort((l,u)=>l.timestamp.getTime()-u.timestamp.getTime()),a?this.timeline.filter(l=>l.tag===a):this.timeline}get logger(){const a=l=>{const u=["none","error","warn","info","debug"];return u.slice(0,u.indexOf(this.logLevel)+1).indexOf(l)>-1};return{error(...l){this.debug&&a("error")&&console.error("[webrtc-stats][error] ",...l)},warn(...l){this.debug&&a("warn")&&console.warn("[webrtc-stats][warn] ",...l)},info(...l){this.debug&&a("info")&&console.log("[webrtc-stats][info] ",...l)},debug(...l){this.debug&&a("debug")&&console.debug("[webrtc-stats][debug] ",...l)}}}removeConnection(a){let l,{connectionId:u,pc:f}=a;if(!f&&!u)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(u){if(typeof u!="string")throw new Error("connectionId must be a string.");for(let _ in this.peersToMonitor)u in this.peersToMonitor[_]&&(f=this.peersToMonitor[_][u].pc,l=_)}else if(f){if(!(f instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let _ in this.peersToMonitor)for(let w in this.peersToMonitor[_])this.peersToMonitor[_][w].pc===f&&(u=w,l=_)}if(!f||!u)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(u,f),delete this.peersToMonitor[l][u],Object.values(this.peersToMonitor[l]).length===0&&delete this.peersToMonitor[l],{connectionId:u}}removeAllPeers(){for(let a in this.peersToMonitor)this.removePeer(a)}removePeer(a){if(this.logger.info(`Removing PeerConnection with id ${a}.`),this.peersToMonitor[a]){for(let l in this.peersToMonitor[a]){let u=this.peersToMonitor[a][l].pc;this.removePeerConnectionEventListeners(l,u)}delete this.peersToMonitor[a]}}destroy(){this.removeAllPeers(),D.forEach(a=>{this.removeTrackEventListeners(a)}),D=[],this.shouldWrapGetUserMedia&&Q&&(navigator.mediaDevices.getUserMedia=Q)}monitorPeer(a){let{peerId:l,connectionId:u,pc:f,remote:_}=a;if(!f)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const w={pc:f,connectionId:u,stream:null,stats:{parsed:null,raw:null},options:{remote:_}};if(this.peersToMonitor[l]){if(u in this.peersToMonitor[l])return void this.logger.warn(`Already watching connection with ID ${u}`);this.peersToMonitor[l][u]=w}else this.peersToMonitor[l]={[u]:w};this.addPeerConnectionEventListeners(l,u,f),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(a=>{a.forEach(l=>{this.emitEvent(l)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(a=null){this.logger.info(a?`Getting stats from peer ${a}`:"Getting stats from all peers");let l={};if(a){if(!this.peersToMonitor[a])throw new Error(`Cannot get stats. Peer with id ${a} does not exist`);l[a]=this.peersToMonitor[a]}else l=this.peersToMonitor;let u=[];for(const f in l)for(const _ in l[f]){const w=l[f][_],v=w.pc;if(v&&!this.checkIfConnectionIsClosed(f,_,v))try{const x=this.getTimestamp(),O=v.getStats(null);if(O){const ne=await O,oe=this.getTimestamp(),j=P(ne),re={remote:w.options.remote},q=H(ne,w.stats.parsed,re),z={event:"stats",tag:"stats",peerId:f,connectionId:_,timeTaken:oe-x,data:q};this.rawStats===!0&&(z.rawStats=ne),this.statsObject===!0&&(z.statsObject=j),this.filteredStats===!0&&(z.filteredStats=this.filteroutStats(j)),u.push(z),w.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${f} did not return any stats data`)}catch(x){this.logger.error(x)}}return u}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const a in this.peersToMonitor)for(const l in this.peersToMonitor[a]){const u=this.peersToMonitor[a][l].pc;this.checkIfConnectionIsClosed(a,l,u)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(a,l,u){const f=this.isConnectionClosed(u);if(f){this.removeConnection({pc:u});let _=u.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:_,peerId:a,connectionId:l,tag:"connection",data:"closed"})}return f}isConnectionClosed(a){return a.connectionState==="closed"||a.iceConnectionState==="closed"}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."),Q=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const a=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return a({constraints:arguments[0]}),Q.apply(navigator.mediaDevices,arguments).then(l=>(a({stream:l}),l),l=>(a({error:l}),Promise.reject(l)))}).bind(navigator.mediaDevices)}filteroutStats(a={}){const l={...a};for(const f in l){var u=l[f];this.statsToMonitor.includes(u.type)||delete l[f]}return l}get peerConnectionListeners(){return{icecandidate:(a,l,u,f)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",f),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:a,connectionId:l,data:f.candidate})},track:(a,l,u,f)=>{this.logger.debug(`[pc-event] track | peerId: ${a}`,f);const _=f.track,w=f.streams[0];a in this.peersToMonitor&&l in this.peersToMonitor[a]&&(this.peersToMonitor[a][l].stream=w),this.addTrackEventListeners(_,l),this.emitEvent({event:"ontrack",tag:"track",peerId:a,connectionId:l,data:{stream:w?this.getStreamDetails(w):null,track:_?this.getMediaTrackDetails(_):null,title:f.track.kind+":"+f.track.id+" "+f.streams.map(function(v){return"stream:"+v.id})}})},signalingstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${a}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:a,connectionId:l,data:{signalingState:u.signalingState,localDescription:u.localDescription,remoteDescription:u.remoteDescription}})},iceconnectionstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${a}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:a,connectionId:l,data:u.iceConnectionState})},icegatheringstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${a}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:a,connectionId:l,data:u.iceGatheringState})},icecandidateerror:(a,l,u,f)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${a}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:a,connectionId:l,error:{errorCode:f.errorCode}})},connectionstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${a}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:a,connectionId:l,data:u.connectionState})},negotiationneeded:(a,l,u)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${a}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:a,connectionId:l})},datachannel:(a,l,u,f)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${a}`,f),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:a,connectionId:l,data:f.channel})}}}addPeerConnectionEventListeners(a,l,u){this.logger.debug(`Adding event listeners for peer ${a} and connection ${l}.`),V[l]={},Object.keys(this.peerConnectionListeners).forEach(f=>{V[l][f]=this.peerConnectionListeners[f].bind(this,a,l,u),u.addEventListener(f,V[l][f],!1)})}parseGetUserMedia(a){try{const l={event:"getUserMedia",tag:"getUserMedia",data:{...a}};a.stream&&(l.data.details=this.parseStream(a.stream),a.stream.getTracks().map(u=>{this.addTrackEventListeners(u),D.push(u)})),this.emitEvent(l)}catch{}}parseStream(a){const l={audio:[],video:[]};return a.getTracks().forEach(u=>{l[u.kind].push(this.getMediaTrackDetails(u))}),l}getMediaTrackDetails(a){return{enabled:a.enabled,id:a.id,contentHint:a.contentHint,kind:a.kind,label:a.label,muted:a.muted,readyState:a.readyState,constructorName:a.constructor.name,capabilities:a.getCapabilities?a.getCapabilities():{},constraints:a.getConstraints?a.getConstraints():{},settings:a.getSettings?a.getSettings():{},_track:a}}getStreamDetails(a){return{active:a.active,id:a.id,_stream:a}}getTrackEventObject(a){return{mute:l=>{this.emitEvent({event:"mute",tag:"track",connectionId:a,data:{event:l}})},unmute:l=>{this.emitEvent({event:"unmute",tag:"track",connectionId:a,data:{event:l}})},overconstrained:l=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:a,data:{event:l}})},ended:l=>{this.emitEvent({event:"ended",tag:"track",connectionId:a,data:{event:l}}),this.removeTrackEventListeners(l.target)}}}addTrackEventListeners(a,l){V[a.id]={};const u=this.getTrackEventObject(l);Object.keys(u).forEach(f=>{V[a.id][f]=u[f].bind(this),a.addEventListener(f,V[a.id][f])}),V[a.id].readyState=setInterval(()=>{if(a.readyState==="ended"){let f=new CustomEvent("ended",{detail:{check:"readyState"}});a.dispatchEvent(f)}},1e3)}removeTrackEventListeners(a){if(a.id in V){const l=this.getTrackEventObject();Object.keys(l).forEach(u=>{a.removeEventListener(u,V[a.id][u])}),clearInterval(V[a.id].readyState),delete V[a.id]}}addToTimeline(a){this.timeline.push(a),this.emit("timeline",a)}emitEvent(a){const l={...a,timestamp:new Date};this.addToTimeline(l),l.tag&&this.emit(l.tag,l)}set getStatsInterval(a){if(!Number.isInteger(a))throw new Error(`getStatsInterval should be an integer, got: ${a}`);this._getStatsInterval=a,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(a,l){a in V&&(Object.keys(this.peerConnectionListeners).forEach(u=>{l.removeEventListener(u,V[a][u],!1)}),delete V[a]),l.getSenders().forEach(u=>{u.track&&this.removeTrackEventListeners(u.track)}),l.getReceivers().forEach(u=>{u.track&&this.removeTrackEventListeners(u.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const a=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const l=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),u=function(){return a.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),l.apply(navigator.mediaDevices,arguments).then(function(f){return f},function(f){return a.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,f.name),Promise.reject(f)})};navigator.mediaDevices.getDisplayMedia=u.bind(navigator.mediaDevices)}}}});(Ze=On)&&Ze.__esModule&&Object.prototype.hasOwnProperty.call(Ze,"default")&&Ze.default;var Ui=On.WebRTCStats;function Bi(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:o}=t,r=function(h){const{jitter:g,rtt:p}=h,b=g+p/2;return .024*b+.11*(b-177.3)*(b>177.3?1:0)}({rtt:o,jitter:i}),s=function(h){const{packetsLost:g,packetsReceived:p}=h,b=g/(p+g)*100;return 20*Math.log(1+b)}({packetsLost:e,packetsReceived:n}),c=93.2-r-s+0,d=1+.035*c+7e-6*c*(c-60)*(100-c);return Math.min(Math.max(d,1),5)}function Hi(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class Vi extends ze{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class Gi extends ze{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class zi extends ze{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function qi(t){const e=Ee(),n=new Ui({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=o=>R(this,void 0,void 0,function*(){o.event==="stats"&&N(E.StatsFrame,function({data:r}){var s,c,d,h,g,p,b,m;const{audio:C,remote:A}=r,{audio:y}=A,S=(c=(s=y.inbound[0])===null||s===void 0?void 0:s.jitter)!==null&&c!==void 0?c:1/0,k=(h=(d=y.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&h!==void 0?h:1/0,L=(p=(g=C.inbound[0])===null||g===void 0?void 0:g.packetsReceived)!==null&&p!==void 0?p:-1,P=(m=(b=C.inbound[0])===null||b===void 0?void 0:b.packetsLost)!==null&&m!==void 0?m:-1,H=Bi({jitter:1e3*S,rtt:1e3*k,packetsLost:P,packetsReceived:L});return{jitter:S,rtt:k,mos:H,quality:Hi(H),inboundAudio:C.inbound[0],outboundAudio:C.outbound[0],remoteInboundAudio:y.inbound[0],remoteOutboundAudio:y.outbound[0]}}(o),t.uuid),yield t.execute(new zi(e,o))});return{start:(o,r,s)=>R(this,void 0,void 0,function*(){yield t.execute(new Vi(e)),n.on("timeline",i),yield new Promise(c=>setTimeout(c,500)),n.addConnection({pc:o,peerId:r,connectionId:s})}),stop:o=>R(this,void 0,void 0,function*(){const r=n.getTimeline();N(E.StatsReport,r,t.uuid),o==="file"&&function(s,c){const d=new Blob([JSON.stringify(s)],{type:"application/json"}),h=URL.createObjectURL(d),g=document.createElement("a");g.href=h,g.download=`${c}.json`,g.click(),URL.revokeObjectURL(h)}(r,`webrtc-stats-${e}-${Date.now()}`),yield t.execute(new Gi(e)),n.removeAllPeers(),n.destroy()})}}class Pn{constructor(e,n,i){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=o=>R(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State`,r),r==="failed"||r==="disconnected"){const s=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",s)};if(navigator.onLine)return s();window.addEventListener("online",s)}}),this._handleIceConnectionStateChange=o=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=o=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=o=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return o.setCodecPreferences?o.setCodecPreferences(this.options.preferred_codecs):void 0},I.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._session=i,this._init(),this.isDebugEnabled&&(this.statsReporter=qi(i))}get isOffer(){return this.type===Y.Offer}get isAnswer(){return this.type===Y.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){I.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{I.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),I.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(I.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(){I.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:o}=this.options;let{remoteStream:r}=this.options;r=n,o===!1&&We(i,r)}createPeerConnection(){return R(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(N(E.MediaError,n,this.options.id),null))})}_init(){var e;return R(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:o=!1}=this.options;if(qe(i)){const r=i.getAudioTracks();I.info("Local audio tracks: ",r);const s=i.getVideoTracks();if(I.info("Local video tracks: ",s),this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(d=>{this.options.userVariables.microphoneLabel=d.label;const h=this.instance.addTransceiver(d,c);this._setAudioCodec(h)}),console.debug("Applying video transceiverParams",c),s.forEach(d=>{this.options.userVariables.cameraLabel=d.label,this.instance.addTransceiver(d,c)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{this.options.userVariables.microphoneLabel=c.label,this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>this._setAudioCodec(c)),s.forEach(c=>{this.options.userVariables.cameraLabel=c.label,this.instance.addTrack(c,i)})):this.instance.addStream(i);o===!1&&((c=>{const d=Te(c);d&&(d.muted=!0)})(n),We(n,i))}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:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);I.info("Add transceiver",e,n)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,I.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>I.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=_t(e.sdp)),this.instance.localDescription&&(e.sdp=xn(e.sdp,this.instance.localDescription.sdp));const n=e;return I.info(`REMOTE SDP
|
|
47
|
+
`,i=e.split(n);if(i.findIndex(Cn)<i.findIndex(kn))return t;const o=t.split(n),r=o.findIndex(Cn),s=o.findIndex(kn),c=o.slice(r,s),d=o.slice(s,o.length-1);return[...o.slice(0,r),...d,...c,""].join(n)},Ye=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=mt(t);return n.includes(e)||i.includes(e)},mt=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},be=(t,e=null,n=null)=>{if(!qe(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(o=>{switch(n){case"on":case!0:o.enabled=!0;break;case"off":case!1:o.enabled=!1;break;default:o.enabled=!o.enabled}})},In=t=>{be(t,"audio",!0)},En=t=>{be(t,"audio",!1)},Tn=t=>{be(t,"audio",null)};function Ai(){try{const{browserInfo:t,name:e,version:n,supportAudio:i,supportVideo:o}=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 g=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const g=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const g=navigator.userAgent.match(/safari/gim)[0],p=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),b=parseInt(p[1],10);return{browserInfo:navigator.userAgent,name:g,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const g=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),p=g[0],b=parseInt(g[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),r=window.RTCPeerConnection,s=window.RTCSessionDescription,c=window.RTCIceCandidate,d=window.navigator&&window.navigator.mediaDevices,h=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(r&&s&&c&&d&&h),supportWebRTCAudio:i,supportWebRTCVideo:o,supportRTCPeerConnection:!!r,supportSessionDescription:!!s,supportIceCandidate:!!c,supportMediaDevices:!!d,supportGetUserMedia:!!Ke}}catch(t){return t.message}}var j;function An(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Rn(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),t._playFulfilled=!0}))}function Mn(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(j||(j={}));var Nn="2.22.12",vt=Nn;class Ri extends Z{constructor(e,n,i,o,r={},s){super(),this.method="login";const c={login:e,passwd:n,login_token:i,userVariables:r,reconnection:s,loginParams:{},"User-Agent":{sdkVersion:vt,data:navigator.userAgent}};o&&(c.sessid=o),this.buildRequest({method:this.method,params:c})}}class Mi extends Z{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Ni extends Z{toString(){return $.Invite}}class Li extends Z{toString(){return $.Answer}}class Di extends Z{toString(){return $.Attach}}class Oi extends Z{toString(){return $.Bye}}class bt extends Z{toString(){return $.Modify}}class Ln extends Z{toString(){return $.Info}}class Pi extends Z{toString(){return $.Broadcast}}class $i extends Z{toString(){return $.Subscribe}}class Fi extends Z{toString(){return $.Unsubscribe}}const Dn=(t,e)=>{const{contentType:n,canvasType:i,callID:o,canvasInfo:r=null,currentLayerIdx:s=-1}=e;r&&i!=="mcu-personal-canvas"&&delete r.memberID;const c={type:ae.conferenceUpdate,call:t.calls[o],canvasInfo:Ui(r),currentLayerIdx:s};switch(n){case"layer-info":{const d=Object.assign({action:W.LayerInfo},c);N(E.Notification,d,t.uuid);break}case"layout-info":{const d=Object.assign({action:W.LayoutInfo},c);N(E.Notification,d,t.uuid);break}}},Ui=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return dn(e)};var Ze,On=sn(function(t,e){var n;function i(){}function o(){o.init.call(this)}function r(a){return a._maxListeners===void 0?o.defaultMaxListeners:a._maxListeners}function s(a,l,u,f){var _,w,v;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if((w=a._events)?(w.newListener&&(a.emit("newListener",l,u.listener?u.listener:u),w=a._events),v=w[l]):(w=a._events=new i,a._eventsCount=0),v){if(typeof v=="function"?v=w[l]=f?[u,v]:[v,u]:f?v.unshift(u):v.push(u),!v.warned&&(_=r(a))&&0<_&&v.length>_){v.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+v.length+" "+l+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=a,x.type=l,x.count=v.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(x)}}else v=w[l]=u,++a._eventsCount;return a}function c(a,l,u){function f(){a.removeListener(l,f),_||(_=!0,u.apply(a,arguments))}var _=!1;return f.listener=u,f}function d(a){var l=this._events;if(l){var u=l[a];if(typeof u=="function")return 1;if(u)return u.length}return 0}function h(a,l){for(var u=Array(l);l--;)u[l]=a[l];return u}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.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},o.prototype.setMaxListeners=function(a){if(typeof a!="number"||0>a||isNaN(a))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=a,this},o.prototype.getMaxListeners=function(){return r(this)},o.prototype.emit=function(a){var l,u,f,_,w,v,x,O=a==="error";if(v=this._events)O=O&&v.error==null;else if(!O)return!1;if(x=this.domain,O){if(l=arguments[1],!x){if(l instanceof Error)throw l;var ne=new Error('Uncaught, unspecified "error" event. ('+l+")");throw ne.context=l,ne}return l||(l=new Error('Uncaught, unspecified "error" event')),l.domainEmitter=this,l.domain=x,l.domainThrown=!1,x.emit("error",l),!1}if(!(u=v[a]))return!1;var oe=typeof u=="function";switch(f=arguments.length){case 1:(function(U,re,q){if(re)U.call(q);else for(var z=U.length,X=h(U,z),ee=0;ee<z;++ee)X[ee].call(q)})(u,oe,this);break;case 2:(function(U,re,q,z){if(re)U.call(q,z);else for(var X=U.length,ee=h(U,X),ie=0;ie<X;++ie)ee[ie].call(q,z)})(u,oe,this,arguments[1]);break;case 3:(function(U,re,q,z,X){if(re)U.call(q,z,X);else for(var ee=U.length,ie=h(U,ee),Le=0;Le<ee;++Le)ie[Le].call(q,z,X)})(u,oe,this,arguments[1],arguments[2]);break;case 4:(function(U,re,q,z,X,ee){if(re)U.call(q,z,X,ee);else for(var ie=U.length,Le=h(U,ie),wt=0;wt<ie;++wt)Le[wt].call(q,z,X,ee)})(u,oe,this,arguments[1],arguments[2],arguments[3]);break;default:for(_=Array(f-1),w=1;w<f;w++)_[w-1]=arguments[w];(function(U,re,q,z){if(re)U.apply(q,z);else for(var X=U.length,ee=h(U,X),ie=0;ie<X;++ie)ee[ie].apply(q,z)})(u,oe,this,_)}return!0},o.prototype.addListener=function(a,l){return s(this,a,l,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(a,l){return s(this,a,l,!0)},o.prototype.once=function(a,l){if(typeof l!="function")throw new TypeError('"listener" argument must be a function');return this.on(a,c(this,a,l)),this},o.prototype.prependOnceListener=function(a,l){if(typeof l!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(a,c(this,a,l)),this},o.prototype.removeListener=function(a,l){var u,f,_,w,v;if(typeof l!="function")throw new TypeError('"listener" argument must be a function');if(!(f=this._events))return this;if(!(u=f[a]))return this;if(u===l||u.listener&&u.listener===l)--this._eventsCount==0?this._events=new i:(delete f[a],f.removeListener&&this.emit("removeListener",a,u.listener||l));else if(typeof u!="function"){for(_=-1,w=u.length;0<w--;)if(u[w]===l||u[w].listener&&u[w].listener===l){v=u[w].listener,_=w;break}if(0>_)return this;if(u.length===1){if(u[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete f[a]}else(function(x,O){for(var ne=O,oe=ne+1,U=x.length;oe<U;ne+=1,oe+=1)x[ne]=x[oe];x.pop()})(u,_);f.removeListener&&this.emit("removeListener",a,v||l)}return this},o.prototype.removeAllListeners=function(a){var l,u;if(!(u=this._events))return this;if(!u.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):u[a]&&(--this._eventsCount==0?this._events=new i:delete u[a]),this;if(arguments.length===0){for(var f,_=Object.keys(u),w=0;w<_.length;++w)(f=_[w])!=="removeListener"&&this.removeAllListeners(f);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(l=u[a])=="function")this.removeListener(a,l);else if(l)do this.removeListener(a,l[l.length-1]);while(l[0]);return this},o.prototype.listeners=function(a){var l,u,f=this._events;return f?u=(l=f[a])?typeof l=="function"?[l.listener||l]:function(_){for(var w=Array(_.length),v=0;v<w.length;++v)w[v]=_[v].listener||_[v];return w}(l):[]:u=[],u},o.listenerCount=function(a,l){return typeof a.listenerCount=="function"?a.listenerCount(l):d.call(a,l)},o.prototype.listenerCount=d,o.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var g,p=new Uint8Array(16);function b(){if(!g&&!(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(p)}for(var m=/^(?:[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,C=[],A=0;256>A;++A)C.push((A+256).toString(16).substr(1));function y(a){var l=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,u=(C[a[l+0]]+C[a[l+1]]+C[a[l+2]]+C[a[l+3]]+"-"+C[a[l+4]]+C[a[l+5]]+"-"+C[a[l+6]]+C[a[l+7]]+"-"+C[a[l+8]]+C[a[l+9]]+"-"+C[a[l+10]]+C[a[l+11]]+C[a[l+12]]+C[a[l+13]]+C[a[l+14]]+C[a[l+15]]).toLowerCase();if(!function(f){return typeof f=="string"&&m.test(f)}(u))throw TypeError("Stringified UUID is invalid");return u}function S(a,l,u){var f=(a=a||{}).random||(a.rng||b)();return f[6]=64|15&f[6],f[8]=128|63&f[8],y(f)}function k(a,l){if(!a||!l)return{};const u={...a};if(u.localCandidateId){const f=l.get(u.localCandidateId);u.local={...f}}if(u.remoteCandidateId){const f=l.get(u.remoteCandidateId);u.remote={...f}}return u}function L(a,l,u){return 8*function(f,_,w){const v=f[w],x=_?_[w]:null;return v===null||x===null?null:(v-x)/(f.timestamp-_.timestamp)*1e3}(a,l,u)}function P(a){if(!a.entries)return a;const l={};return a.forEach(function(u,f){l[f]=u}),l}function H(a,l,u={}){if(!a)return null;let f={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};u.remote&&(f.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const _ of a.values())switch(_.type){case"outbound-rtp":{const w=_.mediaType||_.kind,v={};let x={};if(!["audio","video"].includes(w))continue;if(_.codecId){const O=a.get(_.codecId);O&&(v.clockRate=O.clockRate,v.mimeType=O.mimeType,v.payloadType=O.payloadType)}x=a.get(_.mediaSourceId)||a.get(_.trackId)||{},f[w].outbound.push({..._,...v,track:{...x}});break}case"inbound-rtp":{let w=_.mediaType||_.kind,v={};const x={};if(!["audio","video"].includes(w))if(_.id.includes("Video"))w="video";else{if(!_.id.includes("Audio"))continue;w="audio"}if(_.codecId){const O=a.get(_.codecId);O&&(x.clockRate=O.clockRate,x.mimeType=O.mimeType,x.payloadType=O.payloadType)}if(!f.connection.id&&_.transportId){const O=a.get(_.transportId);if(O&&O.selectedCandidatePairId){const ne=a.get(O.selectedCandidatePairId);f.connection=k(ne,a)}}v=a.get(_.mediaSourceId)||a.get(_.trackId)||{},f[w].inbound.push({..._,...x,track:{...v}});break}case"peer-connection":f.connection.dataChannelsClosed=_.dataChannelsClosed,f.connection.dataChannelsOpened=_.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!u.remote)break;let w=_.mediaType||_.kind;const v={};if(!["audio","video"].includes(w))if(_.id.includes("Video"))w="video";else{if(!_.id.includes("Audio"))continue;w="audio"}if(_.codecId){const x=a.get(_.codecId);x&&(v.clockRate=x.clockRate,v.mimeType=x.mimeType,v.payloadType=x.payloadType)}if(!f.connection.id&&_.transportId){const x=a.get(_.transportId);if(x&&x.selectedCandidatePairId){const O=a.get(x.selectedCandidatePairId);f.connection=k(O,a)}}f.remote[w].inbound.push({..._,...v});break}case"remote-outbound-rtp":{if(!u.remote)break;const w=_.mediaType||_.kind,v={};if(!["audio","video"].includes(w))continue;if(_.codecId){const x=a.get(_.codecId);x&&(v.clockRate=x.clockRate,v.mimeType=x.mimeType,v.payloadType=x.payloadType)}f.remote[w].outbound.push({..._,...v});break}}if(!f.connection.id)for(const _ of a.values())_.type==="candidate-pair"&&_.nominated&&_.state==="succeeded"&&(f.connection=k(_,a));return f=function(_,w){return w&&(_.audio.inbound.map(v=>{let x=w.audio.inbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesReceived"),v.packetRate=L(v,x,"packetsReceived")}),_.audio.outbound.map(v=>{let x=w.audio.outbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesSent"),v.packetRate=L(v,x,"packetsSent")}),_.video.inbound.map(v=>{let x=w.video.inbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesReceived"),v.packetRate=L(v,x,"packetsReceived")}),_.video.outbound.map(v=>{let x=w.video.outbound.find(O=>O.id===v.id);v.bitrate=L(v,x,"bytesSent"),v.packetRate=L(v,x,"packetsSent")})),_}(f,l),f}let Q,V={},D=[];e.WebRTCStats=class extends o{constructor(a){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"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const l={...a};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=l.getStatsInterval||1e3,this.rawStats=!!l.rawStats,this.statsObject=!!l.statsObject,this.filteredStats=!!l.filteredStats,this.shouldWrapGetUserMedia=!!l.wrapGetUserMedia,typeof l.remote=="boolean"&&(this.remote=l.remote),this.debug=!!l.debug,this.logLevel=l.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(a,l){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:a,pc:l})}async addConnection(a){const{pc:l,peerId:u}=a;let{connectionId:f,remote:_}=a;if(_=typeof _=="boolean"?_:this.remote,!(l&&l instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!u)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[u]){if(f&&f in this.peersToMonitor[u])throw new Error(`We are already monitoring connection with id ${f}.`);for(let v in this.peersToMonitor[u]){const x=this.peersToMonitor[u][v];if(x.pc===l)throw new Error(`We are already monitoring peer with id ${u}.`);x.pc.connectionState==="closed"&&this.removeConnection({pc:x.pc})}}const w=l.getConfiguration();return w.iceServers&&w.iceServers.forEach(function(v){delete v.credential}),f||(f=S()),this.emitEvent({event:"addConnection",tag:"peer",peerId:u,connectionId:f,data:{options:a,peerConfiguration:w}}),this.monitorPeer({peerId:u,connectionId:f,pc:l,remote:_}),{connectionId:f}}getTimeline(a){return this.timeline=this.timeline.sort((l,u)=>l.timestamp.getTime()-u.timestamp.getTime()),a?this.timeline.filter(l=>l.tag===a):this.timeline}get logger(){const a=l=>{const u=["none","error","warn","info","debug"];return u.slice(0,u.indexOf(this.logLevel)+1).indexOf(l)>-1};return{error(...l){this.debug&&a("error")&&console.error("[webrtc-stats][error] ",...l)},warn(...l){this.debug&&a("warn")&&console.warn("[webrtc-stats][warn] ",...l)},info(...l){this.debug&&a("info")&&console.log("[webrtc-stats][info] ",...l)},debug(...l){this.debug&&a("debug")&&console.debug("[webrtc-stats][debug] ",...l)}}}removeConnection(a){let l,{connectionId:u,pc:f}=a;if(!f&&!u)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(u){if(typeof u!="string")throw new Error("connectionId must be a string.");for(let _ in this.peersToMonitor)u in this.peersToMonitor[_]&&(f=this.peersToMonitor[_][u].pc,l=_)}else if(f){if(!(f instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let _ in this.peersToMonitor)for(let w in this.peersToMonitor[_])this.peersToMonitor[_][w].pc===f&&(u=w,l=_)}if(!f||!u)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(u,f),delete this.peersToMonitor[l][u],Object.values(this.peersToMonitor[l]).length===0&&delete this.peersToMonitor[l],{connectionId:u}}removeAllPeers(){for(let a in this.peersToMonitor)this.removePeer(a)}removePeer(a){if(this.logger.info(`Removing PeerConnection with id ${a}.`),this.peersToMonitor[a]){for(let l in this.peersToMonitor[a]){let u=this.peersToMonitor[a][l].pc;this.removePeerConnectionEventListeners(l,u)}delete this.peersToMonitor[a]}}destroy(){this.removeAllPeers(),D.forEach(a=>{this.removeTrackEventListeners(a)}),D=[],this.shouldWrapGetUserMedia&&Q&&(navigator.mediaDevices.getUserMedia=Q)}monitorPeer(a){let{peerId:l,connectionId:u,pc:f,remote:_}=a;if(!f)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const w={pc:f,connectionId:u,stream:null,stats:{parsed:null,raw:null},options:{remote:_}};if(this.peersToMonitor[l]){if(u in this.peersToMonitor[l])return void this.logger.warn(`Already watching connection with ID ${u}`);this.peersToMonitor[l][u]=w}else this.peersToMonitor[l]={[u]:w};this.addPeerConnectionEventListeners(l,u,f),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(a=>{a.forEach(l=>{this.emitEvent(l)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(a=null){this.logger.info(a?`Getting stats from peer ${a}`:"Getting stats from all peers");let l={};if(a){if(!this.peersToMonitor[a])throw new Error(`Cannot get stats. Peer with id ${a} does not exist`);l[a]=this.peersToMonitor[a]}else l=this.peersToMonitor;let u=[];for(const f in l)for(const _ in l[f]){const w=l[f][_],v=w.pc;if(v&&!this.checkIfConnectionIsClosed(f,_,v))try{const x=this.getTimestamp(),O=v.getStats(null);if(O){const ne=await O,oe=this.getTimestamp(),U=P(ne),re={remote:w.options.remote},q=H(ne,w.stats.parsed,re),z={event:"stats",tag:"stats",peerId:f,connectionId:_,timeTaken:oe-x,data:q};this.rawStats===!0&&(z.rawStats=ne),this.statsObject===!0&&(z.statsObject=U),this.filteredStats===!0&&(z.filteredStats=this.filteroutStats(U)),u.push(z),w.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${f} did not return any stats data`)}catch(x){this.logger.error(x)}}return u}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const a in this.peersToMonitor)for(const l in this.peersToMonitor[a]){const u=this.peersToMonitor[a][l].pc;this.checkIfConnectionIsClosed(a,l,u)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(a,l,u){const f=this.isConnectionClosed(u);if(f){this.removeConnection({pc:u});let _=u.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:_,peerId:a,connectionId:l,tag:"connection",data:"closed"})}return f}isConnectionClosed(a){return a.connectionState==="closed"||a.iceConnectionState==="closed"}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."),Q=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const a=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return a({constraints:arguments[0]}),Q.apply(navigator.mediaDevices,arguments).then(l=>(a({stream:l}),l),l=>(a({error:l}),Promise.reject(l)))}).bind(navigator.mediaDevices)}filteroutStats(a={}){const l={...a};for(const f in l){var u=l[f];this.statsToMonitor.includes(u.type)||delete l[f]}return l}get peerConnectionListeners(){return{icecandidate:(a,l,u,f)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",f),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:a,connectionId:l,data:f.candidate})},track:(a,l,u,f)=>{this.logger.debug(`[pc-event] track | peerId: ${a}`,f);const _=f.track,w=f.streams[0];a in this.peersToMonitor&&l in this.peersToMonitor[a]&&(this.peersToMonitor[a][l].stream=w),this.addTrackEventListeners(_,l),this.emitEvent({event:"ontrack",tag:"track",peerId:a,connectionId:l,data:{stream:w?this.getStreamDetails(w):null,track:_?this.getMediaTrackDetails(_):null,title:f.track.kind+":"+f.track.id+" "+f.streams.map(function(v){return"stream:"+v.id})}})},signalingstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${a}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:a,connectionId:l,data:{signalingState:u.signalingState,localDescription:u.localDescription,remoteDescription:u.remoteDescription}})},iceconnectionstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${a}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:a,connectionId:l,data:u.iceConnectionState})},icegatheringstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${a}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:a,connectionId:l,data:u.iceGatheringState})},icecandidateerror:(a,l,u,f)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${a}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:a,connectionId:l,error:{errorCode:f.errorCode}})},connectionstatechange:(a,l,u)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${a}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:a,connectionId:l,data:u.connectionState})},negotiationneeded:(a,l,u)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${a}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:a,connectionId:l})},datachannel:(a,l,u,f)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${a}`,f),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:a,connectionId:l,data:f.channel})}}}addPeerConnectionEventListeners(a,l,u){this.logger.debug(`Adding event listeners for peer ${a} and connection ${l}.`),V[l]={},Object.keys(this.peerConnectionListeners).forEach(f=>{V[l][f]=this.peerConnectionListeners[f].bind(this,a,l,u),u.addEventListener(f,V[l][f],!1)})}parseGetUserMedia(a){try{const l={event:"getUserMedia",tag:"getUserMedia",data:{...a}};a.stream&&(l.data.details=this.parseStream(a.stream),a.stream.getTracks().map(u=>{this.addTrackEventListeners(u),D.push(u)})),this.emitEvent(l)}catch{}}parseStream(a){const l={audio:[],video:[]};return a.getTracks().forEach(u=>{l[u.kind].push(this.getMediaTrackDetails(u))}),l}getMediaTrackDetails(a){return{enabled:a.enabled,id:a.id,contentHint:a.contentHint,kind:a.kind,label:a.label,muted:a.muted,readyState:a.readyState,constructorName:a.constructor.name,capabilities:a.getCapabilities?a.getCapabilities():{},constraints:a.getConstraints?a.getConstraints():{},settings:a.getSettings?a.getSettings():{},_track:a}}getStreamDetails(a){return{active:a.active,id:a.id,_stream:a}}getTrackEventObject(a){return{mute:l=>{this.emitEvent({event:"mute",tag:"track",connectionId:a,data:{event:l}})},unmute:l=>{this.emitEvent({event:"unmute",tag:"track",connectionId:a,data:{event:l}})},overconstrained:l=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:a,data:{event:l}})},ended:l=>{this.emitEvent({event:"ended",tag:"track",connectionId:a,data:{event:l}}),this.removeTrackEventListeners(l.target)}}}addTrackEventListeners(a,l){V[a.id]={};const u=this.getTrackEventObject(l);Object.keys(u).forEach(f=>{V[a.id][f]=u[f].bind(this),a.addEventListener(f,V[a.id][f])}),V[a.id].readyState=setInterval(()=>{if(a.readyState==="ended"){let f=new CustomEvent("ended",{detail:{check:"readyState"}});a.dispatchEvent(f)}},1e3)}removeTrackEventListeners(a){if(a.id in V){const l=this.getTrackEventObject();Object.keys(l).forEach(u=>{a.removeEventListener(u,V[a.id][u])}),clearInterval(V[a.id].readyState),delete V[a.id]}}addToTimeline(a){this.timeline.push(a),this.emit("timeline",a)}emitEvent(a){const l={...a,timestamp:new Date};this.addToTimeline(l),l.tag&&this.emit(l.tag,l)}set getStatsInterval(a){if(!Number.isInteger(a))throw new Error(`getStatsInterval should be an integer, got: ${a}`);this._getStatsInterval=a,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(a,l){a in V&&(Object.keys(this.peerConnectionListeners).forEach(u=>{l.removeEventListener(u,V[a][u],!1)}),delete V[a]),l.getSenders().forEach(u=>{u.track&&this.removeTrackEventListeners(u.track)}),l.getReceivers().forEach(u=>{u.track&&this.removeTrackEventListeners(u.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const a=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const l=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),u=function(){return a.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),l.apply(navigator.mediaDevices,arguments).then(function(f){return f},function(f){return a.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,f.name),Promise.reject(f)})};navigator.mediaDevices.getDisplayMedia=u.bind(navigator.mediaDevices)}}}});(Ze=On)&&Ze.__esModule&&Object.prototype.hasOwnProperty.call(Ze,"default")&&Ze.default;var ji=On.WebRTCStats;function Bi(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:o}=t,r=function(h){const{jitter:g,rtt:p}=h,b=g+p/2;return .024*b+.11*(b-177.3)*(b>177.3?1:0)}({rtt:o,jitter:i}),s=function(h){const{packetsLost:g,packetsReceived:p}=h,b=g/(p+g)*100;return 20*Math.log(1+b)}({packetsLost:e,packetsReceived:n}),c=93.2-r-s+0,d=1+.035*c+7e-6*c*(c-60)*(100-c);return Math.min(Math.max(d,1),5)}function Hi(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class Vi extends ze{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class Gi extends ze{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class zi extends ze{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function qi(t){const e=Ee(),n=new ji({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=o=>R(this,void 0,void 0,function*(){o.event==="stats"&&N(E.StatsFrame,function({data:r}){var s,c,d,h,g,p,b,m;const{audio:C,remote:A}=r,{audio:y}=A,S=(c=(s=y.inbound[0])===null||s===void 0?void 0:s.jitter)!==null&&c!==void 0?c:1/0,k=(h=(d=y.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&h!==void 0?h:1/0,L=(p=(g=C.inbound[0])===null||g===void 0?void 0:g.packetsReceived)!==null&&p!==void 0?p:-1,P=(m=(b=C.inbound[0])===null||b===void 0?void 0:b.packetsLost)!==null&&m!==void 0?m:-1,H=Bi({jitter:1e3*S,rtt:1e3*k,packetsLost:P,packetsReceived:L});return{jitter:S,rtt:k,mos:H,quality:Hi(H),inboundAudio:C.inbound[0],outboundAudio:C.outbound[0],remoteInboundAudio:y.inbound[0],remoteOutboundAudio:y.outbound[0]}}(o),t.uuid),yield t.execute(new zi(e,o))});return{start:(o,r,s)=>R(this,void 0,void 0,function*(){yield t.execute(new Vi(e)),n.on("timeline",i),yield new Promise(c=>setTimeout(c,500)),n.addConnection({pc:o,peerId:r,connectionId:s})}),stop:o=>R(this,void 0,void 0,function*(){const r=n.getTimeline();N(E.StatsReport,r,t.uuid),o==="file"&&function(s,c){const d=new Blob([JSON.stringify(s)],{type:"application/json"}),h=URL.createObjectURL(d),g=document.createElement("a");g.href=h,g.download=`${c}.json`,g.click(),URL.revokeObjectURL(h)}(r,`webrtc-stats-${e}-${Date.now()}`),yield t.execute(new Gi(e)),n.removeAllPeers(),n.destroy()})}}class Pn{constructor(e,n,i){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=o=>R(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State`,r),r==="failed"||r==="disconnected"){const s=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",s)};if(navigator.onLine)return s();window.addEventListener("online",s)}}),this._handleIceConnectionStateChange=o=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=o=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=o=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return o.setCodecPreferences?o.setCodecPreferences(this.options.preferred_codecs):void 0},I.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._session=i,this._init(),this.isDebugEnabled&&(this.statsReporter=qi(i))}get isOffer(){return this.type===Y.Offer}get isAnswer(){return this.type===Y.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){I.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{I.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),I.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(I.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(){I.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:o}=this.options;let{remoteStream:r}=this.options;r=n,o===!1&&We(i,r)}createPeerConnection(){return R(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(N(E.MediaError,n,this.options.id),null))})}_init(){var e;return R(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:o=!1}=this.options;if(qe(i)){const r=i.getAudioTracks();I.info("Local audio tracks: ",r);const s=i.getVideoTracks();if(I.info("Local video tracks: ",s),this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(d=>{this.options.userVariables.microphoneLabel=d.label;const h=this.instance.addTransceiver(d,c);this._setAudioCodec(h)}),console.debug("Applying video transceiverParams",c),s.forEach(d=>{this.options.userVariables.cameraLabel=d.label,this.instance.addTransceiver(d,c)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{this.options.userVariables.microphoneLabel=c.label,this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>this._setAudioCodec(c)),s.forEach(c=>{this.options.userVariables.cameraLabel=c.label,this.instance.addTrack(c,i)})):this.instance.addStream(i);o===!1&&((c=>{const d=Te(c);d&&(d.muted=!0)})(n),We(n,i))}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:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);I.info("Add transceiver",e,n)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,I.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>I.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=_t(e.sdp)),this.instance.localDescription&&(e.sdp=xn(e.sdp,this.instance.localDescription.sdp));const n=e;return I.info(`REMOTE SDP
|
|
48
48
|
`,`Type: ${e.type}`,`
|
|
49
49
|
|
|
50
50
|
`,e.sdp),this.instance.setRemoteDescription(n)}_createAnswer(){return R(this,void 0,void 0,function*(){if(!this._isAnswer())return;if(this.instance.signalingState!=="stable")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:Y.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Y.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)})}_setLocalDescription(e){const{useStereo:n,googleMaxBitrate:i,googleMinBitrate:o,googleStartBitrate:r,mediaSettings:s}=this.options;return n&&(e.sdp=_t(e.sdp)),i&&o&&r&&(e.sdp=((c,d,h,g)=>{const p=c.split(`\r
|
|
@@ -58,4 +58,4 @@ b=`+h+":"+g+`\r
|
|
|
58
58
|
`),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce);let s=null;const c={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Wi}`};switch(r){case Y.Offer:this.setState(M.Requesting),s=new Ni(c);break;case Y.Answer:this.setState(M.Answering),s=this.options.attach===!0?new Di(c):new Li(c);break;default:return I.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(s).then(d=>{const{node_id:h=null}=d;this._targetNodeId=h,r===Y.Offer?this.setState(M.Trying):this.setState(M.Active)}).catch(d=>{I.error(`${this.id} - Sending ${r} error:`,d),this.hangup()}),console.timeEnd(an)}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?I.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:o,screenShare:r}=this.options;r===!1&&We(i,o)})}_onMediaError(e){this._dispatchNotification({type:ae.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:ae.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(N(E.Notification,e,this.id,!1)||N(E.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:n,remoteCallerNumber:i,onNotification:o}=this.options;e||(this.options.id=Ee()),this.id=this.options.id,n&&!ln(n)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,me(E.MediaError,this._onMediaError,this.id),ge(o)&&me(E.Notification,o.bind(this),this.id),this.setState(M.New),I.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:n}=this.options;Me(e),Me(n),ve(E.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),I.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),I.info("Stats stopped")}}$n.setStateTelnyx=t=>{if(t){switch(t._state){case M.Requesting:case M.Recovering:case M.Trying:case M.Early:t.state="connecting";break;case M.Active:t.state="active";break;case M.Held:t.state="held";break;case M.Hangup:case M.Destroy:t.state="done";break;case M.Answering:t.state="ringing";break;case M.New:t.state="new"}return t}};class he extends $n{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},n=!0){this.screenShare instanceof he&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return R(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(h=>{h.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:o,remoteCallerNumber:r,callerName:s,callerNumber:c}=this.options,d=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:o,remoteCallerNumber:`${r}-screen`,callerName:`${s} (Screen)`,callerNumber:`${c} (Screen)`},e);return this.screenShare=new he(this.session,d),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof he&&this.screenShare.hangup()}setAudioOutDevice(e){return R(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&bn(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);I.setLevel(2),this._statsInterval=window.setInterval(()=>R(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const o=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],r=["id","type","timestamp"];n.forEach(s=>{o.includes(s.type)||(i+=`
|
|
59
59
|
${s.type}
|
|
60
60
|
`,Object.keys(s).forEach(c=>{r.includes(c)||(i+=` ${c}: ${s[c]}
|
|
61
|
-
`)}))}),I.info(i)}),2e3)}}class Ki extends Ei{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 R(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return R(this,void 0,void 0,function*(){try{const i=yield Ke({audio:e,video:n});return Me(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return R(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(M.Purge)),this.calls={},yield e.disconnect.call(this)})}speedTest(e){return new Promise((n,i)=>{if(gn(E.SpeedTest,s=>{const{upDur:c,downDur:d}=s,h=d?8*e/(d/1e3)/1024:0;n({upDur:c,downDur:d,upKps:(c?8*e/(c/1e3)/1024:0).toFixed(0),downKps:h.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let o=e/1024;e%1024&&o++;const r=".".repeat(1024);for(let s=0;s<o;s++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return Ne().catch(e=>(N(E.MediaError,e,this.uuid),[]))}getVideoDevices(){return Ne(ce.Video).catch(e=>(N(E.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Ne(ce.AudioIn).catch(e=>(N(E.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Ne(ce.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),N(E.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Je(e,n,i)}getDeviceResolutions(e){return R(this,void 0,void 0,function*(){try{return yield(n=>R(void 0,void 0,void 0,function*(){const i=[],o=yield Ke({video:{deviceId:{exact:n}}}),r=o.getVideoTracks()[0];for(let s=0;s<yn.length;s++){const[c,d]=yn[s];(yield r.applyConstraints({width:{exact:c},height:{exact:d}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${c}x${d}`,width:c,height:d})}return Me(o),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return R(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,o=lt(e,["micId","micLabel"]);return wn(o),this._audioConstraints=yield Sn(n,i,"audioinput",o),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return R(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=e,o=lt(e,["camId","camLabel"]);return wn(o),this._videoConstraints=yield Sn(n,i,"videoinput",o),this.camId=n,this.camLabel=i,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[n]:[]:e||[mi,_i,n]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Te(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Te(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const o=new Pi({sessid:this.sessionid,eventChannel:n,data:i});e&&(o.targetNodeId=e),this.execute(o).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return R(this,void 0,void 0,function*(){if(!(n=n.filter(d=>d&&!this._existsSubscription(this.relayProtocol,d))).length)return{};const o=new $i({sessid:this.sessionid,eventChannel:n});e&&(o.targetNodeId=e);const r=yield this.execute(o),{unauthorized:s=[],subscribed:c=[]}=mt(r);return s.length&&s.forEach(d=>this._removeSubscription(this.relayProtocol,d)),c.forEach(d=>this._addSubscription(this.relayProtocol,i,d)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return R(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&this._existsSubscription(this.relayProtocol,c))).length)return{};const i=new Fi({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const o=yield this.execute(i),{unsubscribed:r=[],notSubscribed:s=[]}=mt(o);return r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),s.forEach(c=>this._removeSubscription(this.relayProtocol,c)),o})}static telnyxStateCall(e){return he.setStateTelnyx(e)}}class Fn{constructor(e,n){this.code=n,this.message=e}}class Ji extends Z{constructor(){super(),this.method=$.Ping,this.buildRequest({method:this.method,params:{}})}}class te{constructor(e){this.session=e}_ack(e,n){const i=new Mi(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*hn(2,6)}handleMessage(e){const{session:n}=this,{id:i,method:o,params:r={}}=e,s=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,h=o===$.Attach;if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(s&&n.calls.hasOwnProperty(s)){if(!h)return n.calls[s].handleMessage(e),void this._ack(i,o);n.calls[s].hangup({},!1)}const g=()=>{var m,C,A,y;const S={id:s,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:h,mediaSettings:r.mediaSettings,debug:(m=n.options.debug)!==null&&m!==void 0&&m,debugOutput:(C=n.options.debugOutput)!==null&&C!==void 0?C:"socket",prefetchIceCandidates:(A=n.options.prefetchIceCandidates)!==null&&A!==void 0&&A,forceRelayCandidate:(y=n.options.forceRelayCandidate)!==null&&y!==void 0&&y};r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const k=new he(n,S);return k.nodeId=this.nodeId,k},p=new vn,b=new Ji;switch(o){case $.Ping:this.session.execute(b);break;case $.Punt:n.disconnect();break;case $.Invite:{const A=g();A.playRingtone(),A.setState(M.Ringing),A.direction=de.Inbound,this._ack(i,o);break}case $.Attach:{const A=g();this.session.autoRecoverCalls?A.answer():A.setState(M.Recovering),A.handleMessage(e);break}case $.Event:case"webrtc.event":if(!c)return void I.error("Verto received an unknown event:",r);const m=n.relayProtocol,C=c.split(".")[0];n._existsSubscription(m,c)?N(m,r,c):c===n.sessionid?this._handleSessionEvent(r.eventData):n._existsSubscription(m,C)?N(m,r,C):n.calls.hasOwnProperty(c)?n.calls[c].handleMessage(e):N(E.Notification,r,n.uuid);break;case $.Info:r.type=ae.generic,N(E.Notification,r,n.uuid);break;case $.ClientReady:this.session.execute(p);break;default:{const A=ut(e);if(A){switch(A){case K.REGISTER:case K.REGED:n.connection.previousGatewayState!==K.REGED&&n.connection.previousGatewayState!==K.REGISTER&&(te.retriedRegister=0,r.type=ae.vertoClientReady,N(E.Ready,r,n.uuid));break;case K.UNREGED:case K.NOREG:if(te.retriedRegister+=1,te.retriedRegister===5){te.retriedRegister=0,N(E.Error,{error:new Fn("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:n.sessionid},n.uuid);break}setTimeout(()=>{this.session.execute(p)},this.reconnectDelay());break;case K.FAILED:case K.FAIL_WAIT:if(n.connection.previousGatewayState!==K.FAILED&&n.connection.previousGatewayState!==K.FAIL_WAIT){if(!this.session.hasAutoReconnect()){te.retriedConnect=0,N(E.Error,{error:new Fn("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(te.retriedConnect+=1,te.retriedConnect===5){te.retriedConnect=0,N(E.Error,{error:new Error("Connection Retry Failed"),sessionId:n.sessionid},n.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:I.warn("GatewayState message unknown method:",e)}break}I.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(o=>this.session.calls[o].channels.includes(n));{const o=e.data.find(r=>i.includes(r[0]));if(o instanceof Array)return o[0]}}_handlePvtEvent(e){return R(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:o,laChannel:r,laName:s,chatChannel:c,infoChannel:d,modChannel:h,conferenceMemberID:g,role:p,callID:b}=e;switch(o){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:s}}})},C={nodeId:this.nodeId,channels:[r],handler:({data:y})=>{const S=b||this._retrieveCallId(y,r);if(S&&n.calls.hasOwnProperty(S)){const k=n.calls[S];k._addChannel(r),k.extension=s,k.handleConferenceUpdate(y,e).then(L=>{L==="INVALID_PACKET"&&m()})}}},A=yield n.vertoSubscribe(C).catch(y=>{I.error("liveArray subscription error:",y)});Ye(A,r)&&m();break}case"conference-liveArray-part":{let m=null;if(r&&n._existsSubscription(i,r)){const{callId:A=null}=n.subscriptions[i][r];if(m=n.calls[A]||null,A!==null){const y={type:ae.conferenceUpdate,action:W.Leave,conferenceName:s,participantId:Number(g),role:p};N(E.Notification,y,A,!1)||N(E.Notification,y,n.uuid),m===null&&ve(E.Notification,null,A)}}const C=[r,c,d,h];n.vertoUnsubscribe({nodeId:this.nodeId,channels:C}).then(({unsubscribedChannels:A=[]})=>{m&&(m.channels=m.channels.filter(y=>!A.includes(y)))}).catch(A=>{I.error("liveArray unsubscribe error:",A)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Dn(this.session,e);break;case"logo-info":{const n={type:ae.conferenceUpdate,action:W.LogoInfo,logo:e.logoURL};N(E.Notification,n,this.session.uuid);break}}}}te.retriedConnect=0,te.retriedRegister=0;class Yi extends Z{constructor(e,n,i,o={},r){super(),this.method="anonymous_login";const s={target_type:e,target_id:n,userVariables:o,reconnection:r,"User-Agent":{sdkVersion:vt,data:navigator.userAgent}};i&&(s.sessid=i),this.buildRequest({method:this.method,params:s})}}class Zi extends Ki{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>R(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:o,login_token:r,userVariables:s,autoReconnect:c=!0}=this.options,d=new Ri(n,i||o,r,this.sessionid,s,!!ft()),h=yield this.execute(d).catch(this._handleLoginError);h&&(this._autoReconnect=c,this.sessionid=h.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>R(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,{target_type:i,target_id:o}=n,r=new Yi(i,o,this.sessionid,this.options.userVariables,!!ft()),s=yield this.execute(r).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&this.calls[i].hangup({},!0)})})}validateOptions(){return dt(this.options)||Ge(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(an);const n=new he(this,e);return n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Ge(this.options)||!!e.destinationNumber}_onSocketOpen(){return R(this,void 0,void 0,function*(){return dt(this.options)?this.handleLoginOnSocketOpen():Ge(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new te(this).handleMessage(e)}}class Qi extends Zi{constructor(e){super(e),console.log(`SDK version: ${Nn}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ai()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:U.full},{browserName:"Firefox",features:["audio"],supported:U.partial},{browserName:"Safari",supported:U.not_supported},{browserName:"Edge",supported:U.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:U.not_supported},{browserName:"Firefox",supported:U.not_supported},{browserName:"Safari",features:["video","audio"],supported:U.full},{browserName:"Edge",supported:U.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:U.full},{browserName:"Firefox",features:["audio"],supported:U.partial},{browserName:"Safari",supported:U.not_supported},{browserName:"Edge",supported:U.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:U.full},{browserName:"Firefox",features:["audio"],supported:U.partial},{browserName:"Safari",features:["video","audio"],supported:U.full},{browserName:"Edge",features:["audio"],supported:U.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:U.full},{browserName:"Firefox",features:["audio"],supported:U.partial},{browserName:"Safari",supported:U.not_supported},{browserName:"Edge",features:["audio"],supported:U.partial}]}]}}function Xi(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function eo(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function to(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function no(t){return eo(t)?{id:t.params.item_id,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function io(t){return!to(t)||t.params.item.role!=="user"||t.params.item.status!=="completed"?null:{id:t.params.item.id,role:t.params.item.role,content:t.params.item.content.map(e=>e.transcript).join(" "),timestamp:new Date}}function oo(t){const[e,n]=Ie([]);return fe(()=>{if(!t)return;const i=o=>{if(Xi(o))switch(o.params.type){case"response.text.delta":{n(r=>{const s=no(o);return s?[...r,s]:r});return}case"conversation.item.created":{const r=io(o);r&&n(s=>[...s,r]);return}}};return t.on(E.SocketMessage,i),()=>{t.off(E.SocketMessage,i)}},[t]),e}function ro({item:t}){const e=je(null);return fe(()=>{e.current&&e.current.scrollIntoView({behavior:"smooth"})},[]),T("div",{ref:e,className:ct("flex gap-2 text-left",{"flex-row-reverse":t.role==="user"}),children:T("p",{className:ct("text-sm rounded-2xl font-mono py-2 px-4",{"bg-[#FEFDF5] text-black":t.role==="assistant"," border border-[#FEFDF5] text-white":t.role==="user"}),children:t.content})})}const so=({transcript:t})=>T("div",{id:"transcript-log",className:"flex h-[400px] overflow-y-auto max-h-full flex-col gap-4 w-[360px] max-w-full p-4",children:t.map((e,n)=>T(ro,{item:e},e.id+n))}),ao=({call:t,client:e})=>{const n=oo(e);return T("div",{className:"bg-black gap-3 text-white border w-[360px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col border-solid",children:[T(di,{color:"green",stream:t.remoteStream}),T("h1",{className:"text-2xl font-medium",children:"Call in progress..."}),T("p",{className:"text-sm text-neutral-400 ",children:"Ask our AI assistant your questions to discover what it can do, or end the call to try a different role and personality."}),T(ci,{stream:(t==null?void 0:t.remoteStream)||null}),T(so,{transcript:n}),T("button",{onClick:()=>t.hangup(),className:"cursor-pointer bg-red-400 p-4 rounded-full",children:T(si,{})})]})},yt=()=>T("div",{className:"bg-black gap-3 text-white border w-[360px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col border-solid",children:T("div",{className:"animate-spin rounded-full border-t-2 border-b-2 border-gray-900",children:T(ri,{})})}),co=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return T(yt,{});case"done":case"purged":case"destroy":return null;case"active":return T(ao,{client:e,call:t});default:return T(yt,{})}},lo=(t,e)=>{const[n,i]=Ie(null);return fe(()=>{if(!t)return;const o=new Qi({env:e||"production",anonymous_login:{target_id:t,target_type:"ai_assistant"}});i(o)},[t,e]),n},uo=(t,{onReady:e,onNotification:n,onError:i})=>(fe(()=>{if(t)return t.connect().then().catch(console.error),t.on(E.Ready,e),t.on(E.Notification,n),t.on(E.Error,i),()=>{t.off(E.Ready,e),t.off(E.Notification,n),t.off(E.Error,i),t.disconnect()}},[t]),null),ho=["agent-id","environment"],po=({className:t})=>T("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[T("g",{clipPath:"url(#:R5lfm:)",children:[T("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),T("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),T("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),T("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),T("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),T("defs",{children:T("clipPath",{id:":R5lfm:",children:T("rect",{width:"236",height:"211",fill:"currentColor"})})})]}),fo=({onStartCall:t})=>T("button",{onClick:t,className:"bg-black cursor-pointer text-white px-4 py-2 rounded-full flex items-center text-xl font-medium",children:[T(po,{className:"w-8 h-8 mr-2"}),"Let's Talk"]}),go='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-green-400:oklch(79.2% .209 151.711);--color-gray-900:oklch(21% .034 264.665);--color-neutral-400:oklch(70.8% 0 0);--color-black:#000;--color-white:#fff;--spacing:.25rem;--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--radius-2xl:1rem;--radius-4xl:2rem;--ease-out:cubic-bezier(0,0,.2,1);--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-4{margin-left:calc(var(--spacing)*4)}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-8{height:calc(var(--spacing)*8)}.h-24{height:calc(var(--spacing)*24)}.h-\\[400px\\]{height:400px}.h-full{height:100%}.max-h-full{max-height:100%}.min-h-\\[20px\\]{min-height:20px}.w-4{width:calc(var(--spacing)*4)}.w-8{width:calc(var(--spacing)*8)}.w-\\[344px\\]{width:344px}.w-\\[360px\\]{width:360px}.w-full{width:100%}.max-w-full{max-width:100%}.min-w-\\[20px\\]{min-width:20px}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-row-reverse{flex-direction:row-reverse}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\\.5{gap:calc(var(--spacing)*.5)}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.border{border-style:var(--tw-border-style);border-width:1px}.border-t-2{border-top-style:var(--tw-border-style);border-top-width:2px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#FEFDF5\\]{border-color:#fefdf5}.border-gray-900{border-color:var(--color-gray-900)}.border-white\\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.border-white\\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-black{background-color:var(--color-black)}.bg-red-400{background-color:var(--color-red-400)}.bg-\\[linear-gradient\\(180deg\\,_\\#1F023A_0\\%\\,_\\#CA76FF_47\\.12\\%\\,_\\#1F023A_100\\%\\)\\]{background-image:linear-gradient(#1f023a,#ca76ff 47.12%,#1f023a)}.bg-\\[linear-gradient\\(180deg\\,_\\#004B1E_0\\%\\,_\\#5FEFA9_47\\.12\\%\\,_\\#004B1E_100\\%\\)\\]{background-image:linear-gradient(#004b1e,#5fefa9 47.12%,#004b1e)}.bg-\\[linear-gradient\\(180deg\\,_\\#005A98_0\\%\\,_\\#4CE5F2_47\\.12\\%\\,_\\#005A98_100\\%\\)\\]{background-image:linear-gradient(#005a98,#4ce5f2 47.12%,#005a98)}.bg-\\[linear-gradient\\(180deg\\,_\\#371A5E_0\\%\\,_\\#81B9FF_47\\.12\\%\\,_\\#371A5E_100\\%\\)\\]{background-image:linear-gradient(#371a5e,#81b9ff 47.12%,#371a5e)}.bg-\\[linear-gradient\\(180deg\\,_\\#FC5F00_0\\%\\,_\\#FFFFFF_47\\.12\\%\\,_\\#FC5F00_100\\%\\)\\]{background-image:linear-gradient(#fc5f00,#fff 47.12%,#fc5f00)}.bg-\\[linear-gradient\\(180deg\\,_\\#FD05F9_0\\%\\,_\\#FFD4FE_47\\.12\\%\\,_\\#B400B1_100\\%\\)\\]{background-image:linear-gradient(#fd05f9,#ffd4fe 47.12%,#b400b1)}.p-4{padding:calc(var(--spacing)*4)}.p-10{padding:calc(var(--spacing)*10)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-2{padding-block:calc(var(--spacing)*2)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-neutral-400{color:var(--color-neutral-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-100{--tw-duration:.1s;transition-duration:.1s}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',_o=({children:t})=>T("main",{className:"pointer-events-auto inset-0 z-[9999] fixed",children:T("div",{className:"relative w-full h-full flex items-end justify-end p-10",children:t})}),mo=({children:t})=>T(ke,{children:[T("style",{children:go}),T(_o,{children:t})]}),vo=t=>T("div",{className:"bg-black rounded-2xl p-4 flex flex-col items-center justify-center text-white w-[344px] max-w-full",children:[T(oi,{className:"w-8 h-8 text-red-400"}),T("h1",{className:"text-2xl font-medium mt-2 mb-4",children:"An error occurred"}),T("ul",{className:"list-disc ml-4 text-sm gap-4",children:[T("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),T("li",{children:["Make sure that the"," ",T("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"font-medium text-green-400 underline inline-flex items-center gap-1",children:["Support Unauthenticated Web Calls"," ",T(ai,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function bo({"agent-id":t,environment:e}){const n=lo(t,e),[i,o]=Ie(null),[r,s]=Ie(!0),[c,d]=Ie(!1);uo(n,{onReady:()=>s(!1),onNotification:C=>{var A;if(((A=C.call)==null?void 0:A.state)==="destroy")return o(null);o(C)},onError:()=>{s(!1),d(!0)}});const b=()=>{if(!n){console.error("Client is not initialized.");return}n.newCall({})};return T(mo,{children:t?c?T(vo,{agentId:t}):r?T(yt,{}):i!=null&&i.call?T(co,{call:i.call,client:n}):T(fo,{onStartCall:b}):T("div",{children:"Please provide an assistant ID."})})}Yn(bo,"telnyx-ai-agent",ho,{shadow:!0})})();
|
|
61
|
+
`)}))}),I.info(i)}),2e3)}}class Ki extends Ei{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 R(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return R(this,void 0,void 0,function*(){try{const i=yield Ke({audio:e,video:n});return Me(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return R(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(M.Purge)),this.calls={},yield e.disconnect.call(this)})}speedTest(e){return new Promise((n,i)=>{if(gn(E.SpeedTest,s=>{const{upDur:c,downDur:d}=s,h=d?8*e/(d/1e3)/1024:0;n({upDur:c,downDur:d,upKps:(c?8*e/(c/1e3)/1024:0).toFixed(0),downKps:h.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let o=e/1024;e%1024&&o++;const r=".".repeat(1024);for(let s=0;s<o;s++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return Ne().catch(e=>(N(E.MediaError,e,this.uuid),[]))}getVideoDevices(){return Ne(ce.Video).catch(e=>(N(E.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Ne(ce.AudioIn).catch(e=>(N(E.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Ne(ce.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),N(E.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Je(e,n,i)}getDeviceResolutions(e){return R(this,void 0,void 0,function*(){try{return yield(n=>R(void 0,void 0,void 0,function*(){const i=[],o=yield Ke({video:{deviceId:{exact:n}}}),r=o.getVideoTracks()[0];for(let s=0;s<yn.length;s++){const[c,d]=yn[s];(yield r.applyConstraints({width:{exact:c},height:{exact:d}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${c}x${d}`,width:c,height:d})}return Me(o),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return R(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,o=lt(e,["micId","micLabel"]);return wn(o),this._audioConstraints=yield Sn(n,i,"audioinput",o),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return R(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=e,o=lt(e,["camId","camLabel"]);return wn(o),this._videoConstraints=yield Sn(n,i,"videoinput",o),this.camId=n,this.camLabel=i,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[n]:[]:e||[mi,_i,n]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Te(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Te(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const o=new Pi({sessid:this.sessionid,eventChannel:n,data:i});e&&(o.targetNodeId=e),this.execute(o).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return R(this,void 0,void 0,function*(){if(!(n=n.filter(d=>d&&!this._existsSubscription(this.relayProtocol,d))).length)return{};const o=new $i({sessid:this.sessionid,eventChannel:n});e&&(o.targetNodeId=e);const r=yield this.execute(o),{unauthorized:s=[],subscribed:c=[]}=mt(r);return s.length&&s.forEach(d=>this._removeSubscription(this.relayProtocol,d)),c.forEach(d=>this._addSubscription(this.relayProtocol,i,d)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return R(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&this._existsSubscription(this.relayProtocol,c))).length)return{};const i=new Fi({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const o=yield this.execute(i),{unsubscribed:r=[],notSubscribed:s=[]}=mt(o);return r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),s.forEach(c=>this._removeSubscription(this.relayProtocol,c)),o})}static telnyxStateCall(e){return he.setStateTelnyx(e)}}class Fn{constructor(e,n){this.code=n,this.message=e}}class Ji extends Z{constructor(){super(),this.method=$.Ping,this.buildRequest({method:this.method,params:{}})}}class te{constructor(e){this.session=e}_ack(e,n){const i=new Mi(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*hn(2,6)}handleMessage(e){const{session:n}=this,{id:i,method:o,params:r={}}=e,s=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,h=o===$.Attach;if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(s&&n.calls.hasOwnProperty(s)){if(!h)return n.calls[s].handleMessage(e),void this._ack(i,o);n.calls[s].hangup({},!1)}const g=()=>{var m,C,A,y;const S={id:s,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:h,mediaSettings:r.mediaSettings,debug:(m=n.options.debug)!==null&&m!==void 0&&m,debugOutput:(C=n.options.debugOutput)!==null&&C!==void 0?C:"socket",prefetchIceCandidates:(A=n.options.prefetchIceCandidates)!==null&&A!==void 0&&A,forceRelayCandidate:(y=n.options.forceRelayCandidate)!==null&&y!==void 0&&y};r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const k=new he(n,S);return k.nodeId=this.nodeId,k},p=new vn,b=new Ji;switch(o){case $.Ping:this.session.execute(b);break;case $.Punt:n.disconnect();break;case $.Invite:{const A=g();A.playRingtone(),A.setState(M.Ringing),A.direction=de.Inbound,this._ack(i,o);break}case $.Attach:{const A=g();this.session.autoRecoverCalls?A.answer():A.setState(M.Recovering),A.handleMessage(e);break}case $.Event:case"webrtc.event":if(!c)return void I.error("Verto received an unknown event:",r);const m=n.relayProtocol,C=c.split(".")[0];n._existsSubscription(m,c)?N(m,r,c):c===n.sessionid?this._handleSessionEvent(r.eventData):n._existsSubscription(m,C)?N(m,r,C):n.calls.hasOwnProperty(c)?n.calls[c].handleMessage(e):N(E.Notification,r,n.uuid);break;case $.Info:r.type=ae.generic,N(E.Notification,r,n.uuid);break;case $.ClientReady:this.session.execute(p);break;default:{const A=ut(e);if(A){switch(A){case K.REGISTER:case K.REGED:n.connection.previousGatewayState!==K.REGED&&n.connection.previousGatewayState!==K.REGISTER&&(te.retriedRegister=0,r.type=ae.vertoClientReady,N(E.Ready,r,n.uuid));break;case K.UNREGED:case K.NOREG:if(te.retriedRegister+=1,te.retriedRegister===5){te.retriedRegister=0,N(E.Error,{error:new Fn("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:n.sessionid},n.uuid);break}setTimeout(()=>{this.session.execute(p)},this.reconnectDelay());break;case K.FAILED:case K.FAIL_WAIT:if(n.connection.previousGatewayState!==K.FAILED&&n.connection.previousGatewayState!==K.FAIL_WAIT){if(!this.session.hasAutoReconnect()){te.retriedConnect=0,N(E.Error,{error:new Fn("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(te.retriedConnect+=1,te.retriedConnect===5){te.retriedConnect=0,N(E.Error,{error:new Error("Connection Retry Failed"),sessionId:n.sessionid},n.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:I.warn("GatewayState message unknown method:",e)}break}I.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(o=>this.session.calls[o].channels.includes(n));{const o=e.data.find(r=>i.includes(r[0]));if(o instanceof Array)return o[0]}}_handlePvtEvent(e){return R(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:o,laChannel:r,laName:s,chatChannel:c,infoChannel:d,modChannel:h,conferenceMemberID:g,role:p,callID:b}=e;switch(o){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:s}}})},C={nodeId:this.nodeId,channels:[r],handler:({data:y})=>{const S=b||this._retrieveCallId(y,r);if(S&&n.calls.hasOwnProperty(S)){const k=n.calls[S];k._addChannel(r),k.extension=s,k.handleConferenceUpdate(y,e).then(L=>{L==="INVALID_PACKET"&&m()})}}},A=yield n.vertoSubscribe(C).catch(y=>{I.error("liveArray subscription error:",y)});Ye(A,r)&&m();break}case"conference-liveArray-part":{let m=null;if(r&&n._existsSubscription(i,r)){const{callId:A=null}=n.subscriptions[i][r];if(m=n.calls[A]||null,A!==null){const y={type:ae.conferenceUpdate,action:W.Leave,conferenceName:s,participantId:Number(g),role:p};N(E.Notification,y,A,!1)||N(E.Notification,y,n.uuid),m===null&&ve(E.Notification,null,A)}}const C=[r,c,d,h];n.vertoUnsubscribe({nodeId:this.nodeId,channels:C}).then(({unsubscribedChannels:A=[]})=>{m&&(m.channels=m.channels.filter(y=>!A.includes(y)))}).catch(A=>{I.error("liveArray unsubscribe error:",A)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Dn(this.session,e);break;case"logo-info":{const n={type:ae.conferenceUpdate,action:W.LogoInfo,logo:e.logoURL};N(E.Notification,n,this.session.uuid);break}}}}te.retriedConnect=0,te.retriedRegister=0;class Yi extends Z{constructor(e,n,i,o={},r){super(),this.method="anonymous_login";const s={target_type:e,target_id:n,userVariables:o,reconnection:r,"User-Agent":{sdkVersion:vt,data:navigator.userAgent}};i&&(s.sessid=i),this.buildRequest({method:this.method,params:s})}}class Zi extends Ki{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>R(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:o,login_token:r,userVariables:s,autoReconnect:c=!0}=this.options,d=new Ri(n,i||o,r,this.sessionid,s,!!ft()),h=yield this.execute(d).catch(this._handleLoginError);h&&(this._autoReconnect=c,this.sessionid=h.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>R(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,{target_type:i,target_id:o}=n,r=new Yi(i,o,this.sessionid,this.options.userVariables,!!ft()),s=yield this.execute(r).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&this.calls[i].hangup({},!0)})})}validateOptions(){return dt(this.options)||Ge(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(an);const n=new he(this,e);return n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Ge(this.options)||!!e.destinationNumber}_onSocketOpen(){return R(this,void 0,void 0,function*(){return dt(this.options)?this.handleLoginOnSocketOpen():Ge(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new te(this).handleMessage(e)}}class Qi extends Zi{constructor(e){super(e),console.log(`SDK version: ${Nn}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ai()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:j.full},{browserName:"Firefox",features:["audio"],supported:j.partial},{browserName:"Safari",supported:j.not_supported},{browserName:"Edge",supported:j.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:j.not_supported},{browserName:"Firefox",supported:j.not_supported},{browserName:"Safari",features:["video","audio"],supported:j.full},{browserName:"Edge",supported:j.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:j.full},{browserName:"Firefox",features:["audio"],supported:j.partial},{browserName:"Safari",supported:j.not_supported},{browserName:"Edge",supported:j.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:j.full},{browserName:"Firefox",features:["audio"],supported:j.partial},{browserName:"Safari",features:["video","audio"],supported:j.full},{browserName:"Edge",features:["audio"],supported:j.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:j.full},{browserName:"Firefox",features:["audio"],supported:j.partial},{browserName:"Safari",supported:j.not_supported},{browserName:"Edge",features:["audio"],supported:j.partial}]}]}}function Xi(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function eo(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function to(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function no(t){return eo(t)?{id:t.params.item_id,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function io(t){return!to(t)||t.params.item.role!=="user"||t.params.item.status!=="completed"?null:{id:t.params.item.id,role:t.params.item.role,content:t.params.item.content.map(e=>e.transcript).join(" "),timestamp:new Date}}function oo(t){const[e,n]=Ie([]);return fe(()=>{if(!t)return;const i=o=>{if(Xi(o))switch(o.params.type){case"response.text.delta":{n(r=>{const s=no(o);return s?[...r,s]:r});return}case"conversation.item.created":{const r=io(o);r&&n(s=>[...s,r]);return}}};return t.on(E.SocketMessage,i),()=>{t.off(E.SocketMessage,i)}},[t]),e}function ro({item:t}){const e=Ue(null);return fe(()=>{e.current&&e.current.scrollIntoView({behavior:"smooth"})},[]),T("div",{ref:e,className:ct("flex gap-2 text-left",{"flex-row-reverse":t.role==="user"}),children:T("p",{className:ct("text-sm rounded-2xl font-mono py-2 px-4",{"bg-[#FEFDF5] text-black":t.role==="assistant"," border border-[#FEFDF5] text-white":t.role==="user"}),children:t.content})})}const so=({transcript:t})=>T("div",{id:"transcript-log",className:"flex h-[400px] overflow-y-auto max-h-full flex-col gap-4 w-[360px] max-w-full p-4",children:t.map((e,n)=>T(ro,{item:e},e.id+n))}),ao=({call:t,client:e})=>{const n=oo(e);return T("div",{className:"bg-black gap-3 text-white border w-[360px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col border-solid",children:[T(di,{color:"green",stream:t.remoteStream}),T("h1",{className:"text-2xl font-medium",children:"Call in progress..."}),T("p",{className:"text-sm text-neutral-400 ",children:"Ask our AI assistant your questions to discover what it can do, or end the call to try a different role and personality."}),T(ci,{stream:(t==null?void 0:t.remoteStream)||null}),T(so,{transcript:n}),T("button",{onClick:()=>t.hangup(),className:"cursor-pointer bg-red-400 p-4 rounded-full",children:T(si,{})})]})},yt=()=>T("div",{className:"bg-black gap-3 text-white border w-[360px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col border-solid",children:T("div",{className:"animate-spin rounded-full border-t-2 border-b-2 border-gray-900",children:T(ri,{})})}),co=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return T(yt,{});case"done":case"purged":case"destroy":return null;case"active":return T(ao,{client:e,call:t});default:return T(yt,{})}},lo=(t,e)=>{const[n,i]=Ie(null);return fe(()=>{if(!t)return;const o=new Qi({env:e||"production",anonymous_login:{target_id:t,target_type:"ai_assistant"}});i(o)},[t,e]),n},uo=(t,{onReady:e,onNotification:n,onError:i})=>(fe(()=>{if(t)return t.connect().then().catch(console.error),t.on(E.Ready,e),t.on(E.Notification,n),t.on(E.Error,i),()=>{t.off(E.Ready,e),t.off(E.Notification,n),t.off(E.Error,i),t.disconnect()}},[t]),null),ho=["agent-id","environment"],po=({className:t})=>T("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[T("g",{clipPath:"url(#:R5lfm:)",children:[T("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),T("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),T("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),T("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),T("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),T("defs",{children:T("clipPath",{id:":R5lfm:",children:T("rect",{width:"236",height:"211",fill:"currentColor"})})})]}),fo=({onStartCall:t})=>T("button",{onClick:t,className:"bg-black cursor-pointer text-white px-4 py-2 rounded-full flex items-center text-xl font-medium",children:[T(po,{className:"w-8 h-8 mr-2"}),"Let's Talk"]}),go='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-green-400:oklch(79.2% .209 151.711);--color-gray-900:oklch(21% .034 264.665);--color-neutral-400:oklch(70.8% 0 0);--color-black:#000;--color-white:#fff;--spacing:.25rem;--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--radius-2xl:1rem;--radius-4xl:2rem;--ease-out:cubic-bezier(0,0,.2,1);--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.inset-0{inset:calc(var(--spacing)*0)}.right-10{right:calc(var(--spacing)*10)}.bottom-10{bottom:calc(var(--spacing)*10)}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-4{margin-left:calc(var(--spacing)*4)}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-8{height:calc(var(--spacing)*8)}.h-24{height:calc(var(--spacing)*24)}.h-\\[400px\\]{height:400px}.max-h-full{max-height:100%}.min-h-\\[20px\\]{min-height:20px}.w-4{width:calc(var(--spacing)*4)}.w-8{width:calc(var(--spacing)*8)}.w-\\[344px\\]{width:344px}.w-\\[360px\\]{width:360px}.w-full{width:100%}.max-w-full{max-width:100%}.min-w-\\[20px\\]{min-width:20px}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-row-reverse{flex-direction:row-reverse}.items-center{align-items:center}.justify-center{justify-content:center}.gap-0\\.5{gap:calc(var(--spacing)*.5)}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.border{border-style:var(--tw-border-style);border-width:1px}.border-t-2{border-top-style:var(--tw-border-style);border-top-width:2px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#FEFDF5\\]{border-color:#fefdf5}.border-gray-900{border-color:var(--color-gray-900)}.border-white\\/10{border-color:#ffffff1a}@supports (color:color-mix(in lab,red,red)){.border-white\\/10{border-color:color-mix(in oklab,var(--color-white)10%,transparent)}}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-black{background-color:var(--color-black)}.bg-red-400{background-color:var(--color-red-400)}.bg-\\[linear-gradient\\(180deg\\,_\\#1F023A_0\\%\\,_\\#CA76FF_47\\.12\\%\\,_\\#1F023A_100\\%\\)\\]{background-image:linear-gradient(#1f023a,#ca76ff 47.12%,#1f023a)}.bg-\\[linear-gradient\\(180deg\\,_\\#004B1E_0\\%\\,_\\#5FEFA9_47\\.12\\%\\,_\\#004B1E_100\\%\\)\\]{background-image:linear-gradient(#004b1e,#5fefa9 47.12%,#004b1e)}.bg-\\[linear-gradient\\(180deg\\,_\\#005A98_0\\%\\,_\\#4CE5F2_47\\.12\\%\\,_\\#005A98_100\\%\\)\\]{background-image:linear-gradient(#005a98,#4ce5f2 47.12%,#005a98)}.bg-\\[linear-gradient\\(180deg\\,_\\#371A5E_0\\%\\,_\\#81B9FF_47\\.12\\%\\,_\\#371A5E_100\\%\\)\\]{background-image:linear-gradient(#371a5e,#81b9ff 47.12%,#371a5e)}.bg-\\[linear-gradient\\(180deg\\,_\\#FC5F00_0\\%\\,_\\#FFFFFF_47\\.12\\%\\,_\\#FC5F00_100\\%\\)\\]{background-image:linear-gradient(#fc5f00,#fff 47.12%,#fc5f00)}.bg-\\[linear-gradient\\(180deg\\,_\\#FD05F9_0\\%\\,_\\#FFD4FE_47\\.12\\%\\,_\\#B400B1_100\\%\\)\\]{background-image:linear-gradient(#fd05f9,#ffd4fe 47.12%,#b400b1)}.p-4{padding:calc(var(--spacing)*4)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-2{padding-block:calc(var(--spacing)*2)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-neutral-400{color:var(--color-neutral-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-100{--tw-duration:.1s;transition-duration:.1s}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',_o=({children:t})=>T("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:T("div",{className:"absolute bottom-10 right-10 pointer-events-auto",children:t})}),mo=({children:t})=>T(ke,{children:[T("style",{children:go}),T(_o,{children:t})]}),vo=t=>T("div",{className:"bg-black rounded-2xl p-4 flex flex-col items-center justify-center text-white w-[344px] max-w-full",children:[T(oi,{className:"w-8 h-8 text-red-400"}),T("h1",{className:"text-2xl font-medium mt-2 mb-4",children:"An error occurred"}),T("ul",{className:"list-disc ml-4 text-sm gap-4",children:[T("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),T("li",{children:["Make sure that the"," ",T("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"font-medium text-green-400 underline inline-flex items-center gap-1",children:["Support Unauthenticated Web Calls"," ",T(ai,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function bo({"agent-id":t,environment:e}){const n=lo(t,e),[i,o]=Ie(null),[r,s]=Ie(!0),[c,d]=Ie(!1);uo(n,{onReady:()=>s(!1),onNotification:C=>{var A;if(((A=C.call)==null?void 0:A.state)==="destroy")return o(null);o(C)},onError:()=>{s(!1),d(!0)}});const b=()=>{if(!n){console.error("Client is not initialized.");return}n.newCall({})};return T(mo,{children:t?c?T(vo,{agentId:t}):r?T(yt,{}):i!=null&&i.call?T(co,{call:i.call,client:n}):T(fo,{onStartCall:b}):T("div",{children:"Please provide an assistant ID."})})}Yn(bo,"telnyx-ai-agent",ho,{shadow:!0})})();
|