@telnyx/ai-agent-widget 0.2.0 → 0.4.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 +41 -29
- package/package.json +2 -1
package/dist/bundle.min.js
CHANGED
|
@@ -1,61 +1,73 @@
|
|
|
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 ft,ne,Ui,Xe,Gi,ji,zi,qi,ni,si,oi,_t={},Vi=[],Ls=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,gt=Array.isArray;function Ne(i,e){for(var t in e)i[t]=e[t];return i}function ri(i){i&&i.parentNode&&i.parentNode.removeChild(i)}function He(i,e,t){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?ft.call(arguments,2):t),typeof i=="function"&&i.defaultProps!=null)for(o in i.defaultProps)r[o]===void 0&&(r[o]=i.defaultProps[o]);return mt(i,r,n,s,null)}function mt(i,e,t,n,s){var o={type:i,props:e,key:t,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Ui,__i:-1,__u:0};return s==null&&ne.vnode!=null&&ne.vnode(o),o}function vt(i){return i.children}function Ot(i,e){this.props=i,this.context=e}function it(i,e){if(e==null)return i.__?it(i.__,i.__i+1):null;for(var t;e<i.__k.length;e++)if((t=i.__k[e])!=null&&t.__e!=null)return t.__e;return typeof i.type=="function"?it(i):null}function Wi(i){var e,t;if((i=i.__)!=null&&i.__c!=null){for(i.__e=i.__c.base=null,e=0;e<i.__k.length;e++)if((t=i.__k[e])!=null&&t.__e!=null){i.__e=i.__c.base=t.__e;break}return Wi(i)}}function Xi(i){(!i.__d&&(i.__d=!0)&&Xe.push(i)&&!Dt.__r++||Gi!=ne.debounceRendering)&&((Gi=ne.debounceRendering)||ji)(Dt)}function Dt(){for(var i,e,t,n,s,o,r,l=1;Xe.length;)Xe.length>l&&Xe.sort(zi),i=Xe.shift(),l=Xe.length,i.__d&&(t=void 0,s=(n=(e=i).__v).__e,o=[],r=[],e.__P&&((t=Ne({},n)).__v=n.__v+1,ne.vnode&&ne.vnode(t),ai(e.__P,t,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??it(n),!!(32&n.__u),r),t.__v=n.__v,t.__.__k[t.__i]=t,en(o,t,r),t.__e!=s&&Wi(t)));Dt.__r=0}function Yi(i,e,t,n,s,o,r,l,h,u,_){var p,b,g,x,E,y,w=n&&n.__k||Vi,k=e.length;for(h=As(t,e,w,h,k),p=0;p<k;p++)(g=t.__k[p])!=null&&(b=g.__i==-1?_t:w[g.__i]||_t,g.__i=p,y=ai(i,g,b,s,o,r,l,h,u,_),x=g.__e,g.ref&&b.ref!=g.ref&&(b.ref&&li(b.ref,null,g),_.push(g.ref,g.__c||x,g)),E==null&&x!=null&&(E=x),4&g.__u||b.__k===g.__k?h=Ki(g,h,i):typeof g.type=="function"&&y!==void 0?h=y:x&&(h=x.nextSibling),g.__u&=-7);return t.__e=E,h}function As(i,e,t,n,s){var o,r,l,h,u,_=t.length,p=_,b=0;for(i.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(h=o+b,(r=i.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?mt(null,r,null,null,null):gt(r)?mt(vt,{children:r},null,null,null):r.constructor==null&&r.__b>0?mt(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=i,r.__b=i.__b+1,l=null,(u=r.__i=Ns(r,t,h,p))!=-1&&(p--,(l=t[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(s>_?b--:s<_&&b++),typeof r.type!="function"&&(r.__u|=4)):u!=h&&(u==h-1?b--:u==h+1?b++:(u>h?b--:b++,r.__u|=4))):i.__k[o]=null;if(p)for(o=0;o<_;o++)(l=t[o])!=null&&(2&l.__u)==0&&(l.__e==n&&(n=it(l)),nn(l,l));return n}function Ki(i,e,t){var n,s;if(typeof i.type=="function"){for(n=i.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=i,e=Ki(n[s],e,t));return e}i.__e!=e&&(e&&i.type&&!t.contains(e)&&(e=it(i)),t.insertBefore(i.__e,e||null),e=i.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ji(i,e){return e=e||[],i==null||typeof i=="boolean"||(gt(i)?i.some(function(t){Ji(t,e)}):e.push(i)),e}function Ns(i,e,t,n){var s,o,r=i.key,l=i.type,h=e[t];if(h===null&&i.key==null||h&&r==h.key&&l==h.type&&(2&h.__u)==0)return t;if(n>(h!=null&&(2&h.__u)==0?1:0))for(s=t-1,o=t+1;s>=0||o<e.length;){if(s>=0){if((h=e[s])&&(2&h.__u)==0&&r==h.key&&l==h.type)return s;s--}if(o<e.length){if((h=e[o])&&(2&h.__u)==0&&r==h.key&&l==h.type)return o;o++}}return-1}function Qi(i,e,t){e[0]=="-"?i.setProperty(e,t??""):i[e]=t==null?"":typeof t!="number"||Ls.test(e)?t:t+"px"}function Pt(i,e,t,n,s){var o,r;e:if(e=="style")if(typeof t=="string")i.style.cssText=t;else{if(typeof n=="string"&&(i.style.cssText=n=""),n)for(e in n)t&&e in t||Qi(i.style,e,"");if(t)for(e in t)n&&t[e]==n[e]||Qi(i.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(qi,"$1")),r=e.toLowerCase(),e=r in i||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),i.l||(i.l={}),i.l[e+o]=t,t?n?t.u=n.u:(t.u=ni,i.addEventListener(e,o?oi:si,o)):i.removeEventListener(e,o?oi:si,o);else{if(s=="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 i)try{i[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?i.removeAttribute(e):i.setAttribute(e,e=="popover"&&t==1?"":t))}}function Zi(i){return function(e){if(this.l){var t=this.l[e.type+i];if(e.t==null)e.t=ni++;else if(e.t<t.u)return;return t(ne.event?ne.event(e):e)}}}function ai(i,e,t,n,s,o,r,l,h,u){var _,p,b,g,x,E,y,w,k,T,L,K,ee,D,O,c,d,a=e.type;if(e.constructor!=null)return null;128&t.__u&&(h=!!(32&t.__u),o=[l=e.__e=t.__e]),(_=ne.__b)&&_(e);e:if(typeof a=="function")try{if(w=e.props,k="prototype"in a&&a.prototype.render,T=(_=a.contextType)&&n[_.__c],L=_?T?T.props.value:_.__:n,t.__c?y=(p=e.__c=t.__c).__=p.__E:(k?e.__c=p=new a(w,L):(e.__c=p=new Ot(w,L),p.constructor=a,p.render=Os),T&&T.sub(p),p.props=w,p.state||(p.state={}),p.context=L,p.__n=n,b=p.__d=!0,p.__h=[],p._sb=[]),k&&p.__s==null&&(p.__s=p.state),k&&a.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ne({},p.__s)),Ne(p.__s,a.getDerivedStateFromProps(w,p.__s))),g=p.props,x=p.state,p.__v=e,b)k&&a.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),k&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(k&&a.getDerivedStateFromProps==null&&w!==g&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(w,L),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(w,p.__s,L)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(p.props=w,p.state=p.__s,p.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(f){f&&(f.__=e)}),K=0;K<p._sb.length;K++)p.__h.push(p._sb[K]);p._sb=[],p.__h.length&&r.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(w,p.__s,L),k&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(g,x,E)})}if(p.context=L,p.props=w,p.__P=i,p.__e=!1,ee=ne.__r,D=0,k){for(p.state=p.__s,p.__d=!1,ee&&ee(e),_=p.render(p.props,p.state,p.context),O=0;O<p._sb.length;O++)p.__h.push(p._sb[O]);p._sb=[]}else do p.__d=!1,ee&&ee(e),_=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++D<25);p.state=p.__s,p.getChildContext!=null&&(n=Ne(Ne({},n),p.getChildContext())),k&&!b&&p.getSnapshotBeforeUpdate!=null&&(E=p.getSnapshotBeforeUpdate(g,x)),c=_,_!=null&&_.type===vt&&_.key==null&&(c=tn(_.props.children)),l=Yi(i,gt(c)?c:[c],e,t,n,s,o,r,l,h,u),p.base=e.__e,e.__u&=-161,p.__h.length&&r.push(p),y&&(p.__E=p.__=null)}catch(f){if(e.__v=null,h||o!=null)if(f.then){for(e.__u|=h?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;o[o.indexOf(l)]=null,e.__e=l}else for(d=o.length;d--;)ri(o[d]);else e.__e=t.__e,e.__k=t.__k;ne.__e(f,e,t)}else o==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):l=e.__e=Ms(t.__e,e,t,n,s,o,r,h,u);return(_=ne.diffed)&&_(e),128&e.__u?void 0:l}function en(i,e,t){for(var n=0;n<t.length;n++)li(t[n],t[++n],t[++n]);ne.__c&&ne.__c(e,i),i.some(function(s){try{i=s.__h,s.__h=[],i.some(function(o){o.call(s)})}catch(o){ne.__e(o,s.__v)}})}function tn(i){return typeof i!="object"||i==null||i.__b&&i.__b>0?i:gt(i)?i.map(tn):Ne({},i)}function Ms(i,e,t,n,s,o,r,l,h){var u,_,p,b,g,x,E,y=t.props,w=e.props,k=e.type;if(k=="svg"?s="http://www.w3.org/2000/svg":k=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(u=0;u<o.length;u++)if((g=o[u])&&"setAttribute"in g==!!k&&(k?g.localName==k:g.nodeType==3)){i=g,o[u]=null;break}}if(i==null){if(k==null)return document.createTextNode(w);i=document.createElementNS(s,k,w.is&&w),l&&(ne.__m&&ne.__m(e,o),l=!1),o=null}if(k==null)y===w||l&&i.data==w||(i.data=w);else{if(o=o&&ft.call(i.childNodes),y=t.props||_t,!l&&o!=null)for(y={},u=0;u<i.attributes.length;u++)y[(g=i.attributes[u]).name]=g.value;for(u in y)if(g=y[u],u!="children"){if(u=="dangerouslySetInnerHTML")p=g;else if(!(u in w)){if(u=="value"&&"defaultValue"in w||u=="checked"&&"defaultChecked"in w)continue;Pt(i,u,null,g,s)}}for(u in w)g=w[u],u=="children"?b=g:u=="dangerouslySetInnerHTML"?_=g:u=="value"?x=g:u=="checked"?E=g:l&&typeof g!="function"||y[u]===g||Pt(i,u,g,y[u],s);if(_)l||p&&(_.__html==p.__html||_.__html==i.innerHTML)||(i.innerHTML=_.__html),e.__k=[];else if(p&&(i.innerHTML=""),Yi(e.type=="template"?i.content:i,gt(b)?b:[b],e,t,n,k=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:t.__k&&it(t,0),l,h),o!=null)for(u=o.length;u--;)ri(o[u]);l||(u="value",k=="progress"&&x==null?i.removeAttribute("value"):x!=null&&(x!==i[u]||k=="progress"&&!x||k=="option"&&x!=y[u])&&Pt(i,u,x,y[u],s),u="checked",E!=null&&E!=i[u]&&Pt(i,u,E,y[u],s))}return i}function li(i,e,t){try{if(typeof i=="function"){var n=typeof i.__u=="function";n&&i.__u(),n&&e==null||(i.__u=i(e))}else i.current=e}catch(s){ne.__e(s,t)}}function nn(i,e,t){var n,s;if(ne.unmount&&ne.unmount(i),(n=i.ref)&&(n.current&&n.current!=i.__e||li(n,null,e)),(n=i.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){ne.__e(o,e)}n.base=n.__P=null}if(n=i.__k)for(s=0;s<n.length;s++)n[s]&&nn(n[s],e,t||typeof i.type!="function");t||ri(i.__e),i.__c=i.__=i.__e=void 0}function Os(i,e,t){return this.constructor(i,t)}function Bt(i,e,t){var n,s,o,r;e==document&&(e=document.documentElement),ne.__&&ne.__(i,e),s=(n=typeof t=="function")?null:t&&t.__k||e.__k,o=[],r=[],ai(e,i=(!n&&t||e).__k=He(vt,null,[i]),s||_t,_t,e.namespaceURI,!n&&t?[t]:s?null:e.firstChild?ft.call(e.childNodes):null,o,!n&&t?t:s?s.__e:e.firstChild,n,r),en(o,i,r)}function sn(i,e){Bt(i,e,sn)}function on(i,e,t){var n,s,o,r,l=Ne({},i.props);for(o in i.type&&i.type.defaultProps&&(r=i.type.defaultProps),e)o=="key"?n=e[o]:o=="ref"?s=e[o]:l[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(l.children=arguments.length>3?ft.call(arguments,2):t),mt(i.type,l,n||i.key,s||i.ref,null)}ft=Vi.slice,ne={__e:function(i,e,t,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(i)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(i,n||{}),r=s.__d),r)return s.__E=s}catch(l){i=l}throw i}},Ui=0,Ot.prototype.setState=function(i,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ne({},this.state),typeof i=="function"&&(i=i(Ne({},t),this.props)),i&&Ne(t,i),i!=null&&this.__v&&(e&&this._sb.push(e),Xi(this))},Ot.prototype.forceUpdate=function(i){this.__v&&(this.__e=!0,i&&this.__h.push(i),Xi(this))},Ot.prototype.render=vt,Xe=[],ji=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,zi=function(i,e){return i.__v.__b-e.__v.__b},Dt.__r=0,qi=/(PointerCapture)$|Capture$/i,ni=0,si=Zi(!1),oi=Zi(!0);var Ds=0;function A(i,e,t,n,s,o){e||(e={});var r,l,h=e;if("ref"in h)for(l in h={},e)l=="ref"?r=e[l]:h[l]=e[l];var u={type:i,props:h,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ds,__i:-1,__u:0,__source:s,__self:o};if(typeof i=="function"&&(r=i.defaultProps))for(l in r)h[l]===void 0&&(h[l]=r[l]);return ne.vnode&&ne.vnode(u),u}function ci(){return(ci=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=t[n])}return i}).apply(this,arguments)}var Ps=["context","children"];function Bs(i){this.getChildContext=function(){return i.context};var e=i.children,t=function(n,s){if(n==null)return{};var o,r,l={},h=Object.keys(n);for(r=0;r<h.length;r++)s.indexOf(o=h[r])>=0||(l[o]=n[o]);return l}(i,Ps);return on(e,t)}function $s(){var i=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(i),this._vdom=He(Bs,ci({},this._props,{context:i.detail.context}),function e(t,n){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var s=[],o={},r=0,l=t.attributes,h=t.childNodes;for(r=l.length;r--;)l[r].name!=="slot"&&(o[l[r].name]=l[r].value,o[rn(l[r].name)]=l[r].value);for(r=h.length;r--;){var u=e(h[r],null),_=h[r].slot;_?o[_]=He(an,{name:_},u):s[r]=u}var p=n?He(an,null,s):s;return He(n||t.nodeName.toLowerCase(),o,p)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?sn:Bt)(this._vdom,this._root)}function rn(i){return i.replace(/-(\w)/g,function(e,t){return t?t.toUpperCase():""})}function Fs(i,e,t){if(this._vdom){var n={};n[i]=t=t??void 0,n[rn(i)]=t,this._vdom=on(this._vdom,n),Bt(this._vdom,this._root)}}function Hs(){Bt(this._vdom=null,this._root)}function an(i,e){var t=this;return He("slot",ci({},i,{ref:function(n){n?(t.ref=n,t._listener||(t._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",t._listener))):t.ref.removeEventListener("_preact",t._listener)}}))}function Us(i,e,t,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=i,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=$s,s.prototype.attributeChangedCallback=Fs,s.prototype.disconnectedCallback=Hs,t=t||i.observedAttributes||Object.keys(i.propTypes||{}),s.observedAttributes=t,t.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var l=typeof r;r!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var bt,ue,di,ln,$t=0,cn=[],pe=ne,dn=pe.__b,hn=pe.__r,un=pe.diffed,pn=pe.__c,fn=pe.unmount,_n=pe.__;function hi(i,e){pe.__h&&pe.__h(ue,i,$t||e),$t=0;var t=ue.__H||(ue.__H={__:[],__h:[]});return i>=t.__.length&&t.__.push({}),t.__[i]}function yt(i){return $t=1,Gs(vn,i)}function Gs(i,e,t){var n=hi(bt++,2);if(n.t=i,!n.__c&&(n.__=[vn(void 0,e),function(l){var h=n.__N?n.__N[0]:n.__[0],u=n.t(h,l);h!==u&&(n.__N=[u,n.__[1]],n.__c.setState({}))}],n.__c=ue,!ue.__f)){var s=function(l,h,u){if(!n.__c.__H)return!0;var _=n.__c.__H.__.filter(function(b){return!!b.__c});if(_.every(function(b){return!b.__N}))return!o||o.call(this,l,h,u);var p=n.__c.props!==l;return _.forEach(function(b){if(b.__N){var g=b.__[0];b.__=b.__N,b.__N=void 0,g!==b.__[0]&&(p=!0)}}),o&&o.call(this,l,h,u)||p};ue.__f=!0;var o=ue.shouldComponentUpdate,r=ue.componentWillUpdate;ue.componentWillUpdate=function(l,h,u){if(this.__e){var _=o;o=void 0,s(l,h,u),o=_}r&&r.call(this,l,h,u)},ue.shouldComponentUpdate=s}return n.__N||n.__}function nt(i,e){var t=hi(bt++,3);!pe.__s&&mn(t.__H,e)&&(t.__=i,t.u=e,ue.__H.__h.push(t))}function ui(i){return $t=5,js(function(){return{current:i}},[])}function js(i,e){var t=hi(bt++,7);return mn(t.__H,e)&&(t.__=i(),t.__H=e,t.__h=i),t.__}function zs(){for(var i;i=cn.shift();)if(i.__P&&i.__H)try{i.__H.__h.forEach(Ft),i.__H.__h.forEach(pi),i.__H.__h=[]}catch(e){i.__H.__h=[],pe.__e(e,i.__v)}}pe.__b=function(i){ue=null,dn&&dn(i)},pe.__=function(i,e){i&&e.__k&&e.__k.__m&&(i.__m=e.__k.__m),_n&&_n(i,e)},pe.__r=function(i){hn&&hn(i),bt=0;var e=(ue=i.__c).__H;e&&(di===ue?(e.__h=[],ue.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(Ft),e.__h.forEach(pi),e.__h=[],bt=0)),di=ue},pe.diffed=function(i){un&&un(i);var e=i.__c;e&&e.__H&&(e.__H.__h.length&&(cn.push(e)!==1&&ln===pe.requestAnimationFrame||((ln=pe.requestAnimationFrame)||qs)(zs)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),di=ue=null},pe.__c=function(i,e){e.some(function(t){try{t.__h.forEach(Ft),t.__h=t.__h.filter(function(n){return!n.__||pi(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],pe.__e(n,t.__v)}}),pn&&pn(i,e)},pe.unmount=function(i){fn&&fn(i);var e,t=i.__c;t&&t.__H&&(t.__H.__.forEach(function(n){try{Ft(n)}catch(s){e=s}}),t.__H=void 0,e&&pe.__e(e,t.__v))};var gn=typeof requestAnimationFrame=="function";function qs(i){var e,t=function(){clearTimeout(n),gn&&cancelAnimationFrame(e),setTimeout(i)},n=setTimeout(t,35);gn&&(e=requestAnimationFrame(t))}function Ft(i){var e=ue,t=i.__c;typeof t=="function"&&(i.__c=void 0,t()),ue=e}function pi(i){var e=ue;i.__c=i.__(),ue=e}function mn(i,e){return!i||i.length!==e.length||e.some(function(t,n){return t!==i[n]})}function vn(i,e){return typeof e=="function"?e(i):e}const Vs=({stream:i})=>{const e=ui(null);return nt(()=>{!e.current||!i||(e.current.srcObject=i)},[i]),A("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
|
|
2
|
+
* audioMotion-analyzer
|
|
3
|
+
* High-resolution real-time graphic audio spectrum analyzer JS module
|
|
4
|
+
*
|
|
5
|
+
* @version 4.5.1
|
|
6
|
+
* @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
|
|
7
|
+
* @license AGPL-3.0-or-later
|
|
8
|
+
*/const Ws="4.5.1",fi=Math.PI,st=2*fi,_i=fi/2,bn=8.17579892,yn="dual-combined",Ht="dual-horizontal",Ue="single",Me="dual-vertical",wn="bar-index",Sn="bar-level",Ut="gradient",Cn=60,xn="click",Xs="fullscreenchange",kn="resize",Ys="#111",In="",En="A",Tn="B",Rn="C",Ln="D",An="468",Gt="sans-serif",Ks="#0f0",Js="#7f7f7f22",ot=10,Nn="create",Mn="fschange",Qs="lores",Zs=kn,gi="user",eo="#000c",On="#fff",to="#4f4",Dn="#888",io="#555",mi="bark",wt="linear",rt="log",vi="mel",Pn=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Bn=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Pn}],["rainbow",{dir:"h",colorStops:["#817",...Pn,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],St={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Ue,colorMode:Ut,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:rt,gradient:Bn[0][0],gravity:3.8,height:void 0,ledBars:!1,linearAmplitude:!1,linearBoost:1,lineWidth:0,loRes:!1,lumiBars:!1,maxDecibels:-25,maxFPS:0,maxFreq:22e3,minDecibels:-85,minFreq:20,mirror:0,mode:0,noteLabels:!1,outlineBars:!1,overlay:!1,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.3,reflexAlpha:.15,reflexBright:1,reflexFit:!0,reflexRatio:0,roundBars:!1,showBgColor:!0,showFPS:!1,showPeaks:!0,showScaleX:!0,showScaleY:!1,smoothing:.5,spinSpeed:0,splitGradient:!1,start:!0,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:In,width:void 0},no=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],so=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],oo=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],bi=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],ro=["ERR_INVALID_MODE","Invalid mode"],ao=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],lo=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],co=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],ho=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],uo=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ee extends Error{constructor(e,t){const[n,s]=e;super(s+(t!==void 0?`: ${t}`:"")),this.name="AudioMotionError",this.code=n}}const $n=(i,e)=>console.warn(`${i} is deprecated. Use ${e} instead.`),Fn=i=>{for(const e in i)return!1;return!0},jt=(i,e,t="toLowerCase")=>e[Math.max(0,e.indexOf((""+i)[t]()))],po=(i,e,t,n,s)=>e+(n-e)*(s-i)/(t-i);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(i){let e=this.length;for(;e-- >0;)if(i(this[e]))return e;return-1});class fo{constructor(e,t={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(Fn(t)&&!Fn(e)&&(t=e),e=null),this._ownCanvas=!(t.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):t.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[p,b]of Bn)this.registerGradient(p,b);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(t.source&&(s=t.source.context))){if(!(s=t.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Ee(no)}}if(!s.createGain)throw new Ee(so);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),l=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),t.source&&this.connectInput(t.source);for(const p of[0,1])r.connect(o[p],p);l.connect(this._output),t.connectSpeakers!==!1&&this.connectOutput();for(const p of["_scaleX","_scaleR"])this[p]=document.createElement("canvas").getContext("2d");this._fsEl=t.fsElement||n;const h=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Zs),this._fsTimeout=0)},Cn))};window.ResizeObserver&&(this._observer=new ResizeObserver(h),this._observer.observe(this._container)),this._controller=new AbortController;const u=this._controller.signal;window.addEventListener(kn,h,{signal:u}),n.addEventListener(Xs,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Mn),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Cn)},{signal:u});const _=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(xn,_))};window.addEventListener(xn,_),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:u}),this._setProps(t,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(Nn)}get alphaBars(){return this._alphaBars}set alphaBars(e){this._alphaBars=!!e,this._calcBars()}get ansiBands(){return this._ansiBands}set ansiBands(e){this._ansiBands=!!e,this._calcBars()}get barSpace(){return this._barSpace}set barSpace(e){this._barSpace=+e||0,this._calcBars()}get channelLayout(){return this._chLayout}set channelLayout(e){this._chLayout=jt(e,[Ue,Ht,Me,yn]),this._input.disconnect(),this._input.connect(this._chLayout!=Ue?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Ue?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=jt(e,[Ut,wn,Sn])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const t=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(t),new Float32Array(t)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=jt(e,[rt,mi,vi,wt]),this._calcBars()}get gradient(){return this._selectedGrads[0]}set gradient(e){this._setGradient(e)}get gradientLeft(){return this._selectedGrads[0]}set gradientLeft(e){this._setGradient(e,0)}get gradientRight(){return this._selectedGrads[1]}set gradientRight(e){this._setGradient(e,1)}get gravity(){return this._gravity}set gravity(e){this._gravity=e>0?+e:this._gravity||St.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(gi)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(Qs)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const t of[0,1])this._analyzer[t].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new Ee(bi);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const t of[0,1])this._analyzer[t].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new Ee(bi);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const t=e|0;if(t>=0&&t<=10&&t!=9)this._mode=t,this._calcBars(),this._makeGrad();else throw new Ee(ro,e)}get noteLabels(){return this._noteLabels}set noteLabels(e){this._noteLabels=!!e,this._createScales()}get outlineBars(){return this._outlineBars}set outlineBars(e){this._outlineBars=!!e,this._calcBars()}get peakFadeTime(){return this._peakFadeTime}set peakFadeTime(e){this._peakFadeTime=e>=0?+e:this._peakFadeTime||St.peakFadeTime}get peakHoldTime(){return this._peakHoldTime}set peakHoldTime(e){this._peakHoldTime=+e||0}get peakLine(){return this._peakLine}set peakLine(e){this._peakLine=!!e}get radial(){return this._radial}set radial(e){this._radial=!!e,this._calcBars(),this._makeGrad()}get radialInvert(){return this._radialInvert}set radialInvert(e){this._radialInvert=!!e,this._calcBars(),this._makeGrad()}get radius(){return this._radius}set radius(e){this._radius=+e||0,this._calcBars(),this._makeGrad()}get reflexRatio(){return this._reflexRatio}set reflexRatio(e){if(e=+e||0,e<0||e>=1)throw new Ee(ao);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const t of[0,1])this._analyzer[t].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-_i),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return $n("stereo","channelLayout"),this._chLayout!=Ue}set stereo(e){$n("stereo","channelLayout"),this.channelLayout=e?Me:Ue}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=jt(e,[In,En,Tn,Rn,Ln,An],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(gi)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return Ws}connectInput(e){const t=e instanceof HTMLMediaElement;if(!(t||e.connect))throw new Ee(lo);const n=t?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const t of[0,1])this._analyzer[t].connect(this._chLayout==Ue&&!t?this._output:this._merger,0,t)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:t,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:l,_ownContext:h,_splitter:u}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),u.disconnect(),o.disconnect(),h&&e.close(),l&&t.remove(),this._calcBars()}disconnectInput(e,t){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(t&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(t=>t!==e):[],this._outNodes.length==0))for(const t of[0,1])this._analyzer[t].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:t,freqLo:n,freqHi:s,hold:o,peak:r,value:l})=>({posX:e,freq:t,freqLo:n,freqHi:s,hold:o,peak:r,value:l}))}getEnergy(e,t){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const l={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!l[e])return null;[e,t]=l[e]}const n=this._freqToBin(e),s=t?this._freqToBin(t):n,o=this._chLayout==Ue?1:2;let r=0;for(let l=0;l<o;l++)for(let h=n;h<=s;h++)r+=this._normalizedB(this._fftData[l][h]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let t={};for(const n of Object.keys(St))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(t.gradientLeft=this.gradientLeft,t.gradientRight=this.gradientRight):n!="start"&&(t[n]=this[n]));return t}registerGradient(e,t){if(typeof e!="string"||e.trim().length==0)throw new Ee(co);if(typeof t!="object")throw new Ee(ho);const{colorStops:n}=t;if(!Array.isArray(n)||!n.length)throw new Ee(uo);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,l)=>{const h=l/Math.max(1,s-1);typeof r!="object"?n[l]={pos:h,color:r}:o(r.pos)&&(r.pos=h),o(r.level)&&(n[l].level=1-l/s)}),n.sort((r,l)=>r.level<l.level?1:r.level>l.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:t.bgColor||Ys,dir:t.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,t){this._width=e,this._height=t,this._setCanvas(gi)}setFreqRange(e,t){if(e<1||t<1)throw new Ee(bi);this._minFreq=Math.min(e,t),this.maxFreq=Math.max(e,t)}setLedParams(e){let t,n,s;e&&(t=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=t>0&&n>0&&s>=0?[t,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,t){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,t),this._analyzer[n].maxDecibels=Math.max(e,t)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const t=this.isOn;return e===void 0&&(e=!t),t&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!t&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:t,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:l,_mirror:h,_mode:u,_radial:_,_radialInvert:p,_reflexRatio:b}=this,g=s.width>>1,x=s.height>>1,E=o==Me&&!_,y=o==Ht,w=u%10!=0,k=w&&this._frequencyScale==rt,T=this._showLeds&&w&&!_,L=this._lumiBars&&w&&!_,K=this._alphaBars&&!L&&u!=ot,ee=this._outlineBars&&w&&!L&&!T,D=this._roundBars&&w&&!L&&!T,O=o!=Me||b>0&&!L,c=s.height-(E&&!T?.5:0)>>E,d=c*(L||_?1:1-b)|0,a=s.width-g*(y||h!=0),f=E?s.height-c*2:0,m=g*(h==-1&&!y&&!_);let C=Math.min(s.width,s.height)*.375*(o==Me?1:this._radius)|0,v=Math.min(g,x);p&&o!=Me&&([C,v]=[v,C]);const S=G=>e.push({...G,peak:[0,0],hold:[0],alpha:[0],value:[0]}),R=G=>{const q=this._freqToBin(G,"floor"),V=this._binToFreq(q),Y=this._binToFreq(q+1),le=Math.log2(G/V)/Math.log2(Y/V);return[q,le]};let P,J,B;if(k){const G=(ie,de,te)=>+ie.toPrecision(te?Math.max(de,1+Math.log10(ie)|0):de),q=ie=>{const de=[1,1.12,1.25,1.4,1.6,1.8,2,2.24,2.5,2.8,3.15,3.55,4,4.5,5,5.6,6.3,7.1,8,9,10],te=Math.log10(ie)|0,Pe=ie/10**te;let Le=1;for(;Le<de.length&&Pe>de[Le];)Le++;return Pe-de[Le-1]<de[Le]-Pe&&Le--,(de[Le]*10**(te+5)|0)/1e5},V=[0,24,12,8,6,4,3,2,1][u],Y=t?10**(3/(V*10)):2**(1/V),le=Y**.5;let ye=t?7.94328235/(V%2?1:le):bn;do{let ie=ye;const de=G(ie/le,4,!0),te=G(ie*le,4,!0),[Pe,Le]=R(de),[Lt,Be]=R(te);t?ie=V<4?q(ie):G(ie,ie.toString()[0]<5?3:2):ie=G(ie,4,!0),ie>=l&&S({posX:0,freq:ie,freqLo:de,freqHi:te,binLo:Pe,binHi:Lt,ratioLo:Le,ratioHi:Be}),ye*=Y}while(ye<=r);P=a/e.length,e.forEach((ie,de)=>ie.posX=m+de*P);const ce=e[0],me=e[e.length-1];J=this._freqScaling(ce.freqLo),B=a/(this._freqScaling(me.freqHi)-J),ce.freqLo<l&&(ce.freqLo=l,[ce.binLo,ce.ratioLo]=R(l)),me.freqHi>r&&(me.freqHi=r,[me.binHi,me.ratioHi]=R(r))}else if(w){const G=[0,24,12,8,6,4,3,2,1][u]*10,q=V=>{switch(this._frequencyScale){case mi:return 1960/(26.81/(V+.53)-1);case vi:return 700*(2**V-1);case wt:return V}};P=a/G,J=this._freqScaling(l),B=a/(this._freqScaling(r)-J);for(let V=0,Y=0;V<G;V++,Y+=P){const le=q(J+Y/B),ye=q(J+(Y+P/2)/B),ce=q(J+(Y+P)/B),[me,ie]=R(le),[de,te]=R(ce);S({posX:m+Y,freq:ye,freqLo:le,freqHi:ce,binLo:me,binHi:de,ratioLo:ie,ratioHi:te})}}else{P=1,J=this._freqScaling(l),B=a/(this._freqScaling(r)-J);const G=this._freqToBin(l,"floor"),q=this._freqToBin(r);let V=-999;for(let Y=G;Y<=q;Y++){const le=this._binToFreq(Y),ye=m+Math.round(B*(this._freqScaling(le)-J));if(ye>V)S({posX:ye,freq:le,freqLo:le,freqHi:le,binLo:Y,binHi:Y,ratioLo:0,ratioHi:0}),V=ye;else if(e.length){const ce=e[e.length-1];ce.binHi=Y,ce.freqHi=le,ce.freq=(ce.freqLo*le)**.5}}}let se=0,X=0;if(T){const G=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),q=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],V=this._ledParams,[Y,le,ye]=V||q[u];let ce,me=d;if(V){const ie=2*G;let de;ce=Y+1;do ce--,de=me/ce/(1+le),X=de*le;while((de<ie||X<ie)&&ce>1)}else{const ie=540/le;X=Math.min(le*G,Math.max(2,me/ie+.1|0))}O&&(me+=X),V||(ce=Math.min(Y,me/(X*2)|0)),se=ye>=1?ye:P*ye,this._leds=[ce,se,X,me/ce-X]}const $=Math.min(P-1,n*(n>0&&n<1?P:1));w&&(P-=Math.max(T?se:0,$)),e.forEach((G,q)=>{let V=G.posX,Y=P;w&&(n==0&&!T?(V|=0,Y|=0,q>0&&V>e[q-1].posX+e[q-1].width&&(V--,Y++)):V+=Math.max(T?se:0,$)/2,G.posX=V),G.barCenter=V+(P==1?0:Y/2),G.width=Y});const re=[];for(const G of[0,1]){const q=o==Me?(c+f)*G:0,V=q+c,Y=q+d-(!T||O?0:X);re.push({channelTop:q,channelBottom:V,analyzerBottom:Y})}this._aux={analyzerHeight:d,analyzerWidth:a,centerX:g,centerY:x,channelCoords:re,channelHeight:c,channelGap:f,initialX:m,innerRadius:C,outerRadius:v,scaleMin:J,unitWidth:B},this._flg={isAlpha:K,isBands:w,isLeds:T,isLumi:L,isOctaves:k,isOutline:ee,isRound:D,noLedGap:O},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:t,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:l,_mirror:h,_noteLabels:u,_radial:_,_scaleX:p,_scaleR:b}=this,g=p.canvas,x=b.canvas,E=[],y=this._chLayout==Ht,w=this._chLayout==Me,k=Math.min(r.width,r.height),T=["C",,"D",,"E","F",,"G",,"A",,"B"],L=k/34|0,K=g.height>>1,ee=L>>1,D=K*(u?.7:1.5),O=ee*(u?1:2),c=2**(1/12);if(!u&&(this._ansiBands||l!=rt))E.push(16,31.5,63,125,250,500,1e3,2e3,4e3),l==wt?E.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):E.push(8e3,16e3);else{let v=bn;for(let S=-1;S<11;S++)for(let R=0;R<12;R++){if(v>=this._minFreq&&v<=this._maxFreq){const P=T[R],J=P=="C";(P&&u&&!h&&!y||J)&&E.push(u?[v,P+(J?S:"")]:v)}v*=c}}x.width=x.height=Math.max(k*.15,(n<<1)+w*L);const d=x.width>>1,a=d-L*.7,f=(v,S)=>{const R=st*(v/r.width),P=R-_i,J=a*Math.cos(P),B=a*Math.sin(P);b.save(),b.translate(d+J,d+B),b.rotate(R),b.fillText(S,0,0),b.restore()};g.width|=0,p.fillStyle=b.strokeStyle=eo,p.fillRect(0,0,g.width,g.height),b.arc(d,d,d-L/2,0,st),b.lineWidth=L,b.stroke(),p.fillStyle=b.fillStyle=On,p.font=`${K}px ${Gt}`,b.font=`${ee}px ${Gt}`,p.textAlign=b.textAlign="center";let m=-D/4,C=-O;for(const v of E){const[S,R]=Array.isArray(v)?v:[v,v<1e3?v|0:`${(v/100|0)/10}k`],P=o*(this._freqScaling(S)-s),J=g.height*.75,B=R[0]=="C",se=K*(u&&!h&&!y?B?1.2:.6:3);if(p.fillStyle=b.fillStyle=B&&!h&&!y?to:On,u){const X=l==rt,$=l==wt;let re=["C"];if((X||S>2e3||!$&&S>250||(!_||w)&&(!$&&S>125||S>1e3))&&re.push("G"),(X||S>4e3||!$&&S>500||(!_||w)&&(!$&&S>250||S>2e3))&&re.push("E"),($&&S>4e3||(!_||w)&&(X||S>2e3||!$&&S>500))&&re.push("D","F","A","B"),!re.includes(R[0]))continue}P>=m+D/2&&P<=e&&(p.fillText(R,y&&h==-1?e-P:t+P,J,se),(y||h&&(P>D||h==1))&&p.fillText(R,y&&h!=1?e+P:(t||r.width)-P,J,se),m=P+Math.min(se,p.measureText(R).width)/2),P>=C+O&&P<e-O&&(f(y&&h==1?e-P:P,R),(y||h&&(P>O||h==1))&&f(y&&h!=-1?e+P:-P,R),C=P)}}_draw(e){this._runId=requestAnimationFrame(I=>this._draw(I));const t=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,t>=1e3&&(this._fps=this._frames/t*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:l,isLumi:h,isOctaves:u,isOutline:_,isRound:p,noLedGap:b}=this._flg,{analyzerHeight:g,centerX:x,centerY:E,channelCoords:y,channelHeight:w,channelGap:k,initialX:T,innerRadius:L,outerRadius:K}=this._aux,{_bars:ee,canvas:D,_canvasGradients:O,_chLayout:c,_colorMode:d,_ctx:a,_energy:f,_fadePeaks:m,fillAlpha:C,_fps:v,_linearAmplitude:S,_lineWidth:R,maxDecibels:P,minDecibels:J,_mirror:B,_mode:se,overlay:X,_radial:$,showBgColor:re,showPeaks:G,useCanvas:q,_weightingFilter:V}=this,Y=this._scaleX.canvas,le=this._scaleR.canvas,ye=v*this._peakFadeTime/1e3,ce=v**2,me=this._gravity*1e3,ie=v*this._peakHoldTime/1e3,de=c==yn,te=c==Ht,Pe=c==Me,Le=c==Ue,Lt=l&&this._trueLeds&&d==Ut,Be=$?D.width:this._aux.analyzerWidth,Mi=T+Be,At=G&&this._peakLine&&se==ot,ze=$?K-L:g,Mr=ze/this._pixelRatio,[Or,Fr,Nt,Oi]=this._leds||[];f.val>0&&v>0&&(this._spinAngle+=this._spinSpeed*st/60/v);const Dr=I=>{if(this._reflexRatio>0&&!h&&!$){let Q,$e;this.reflexFit||Pe?(Q=Pe&&I==0?w+k:0,$e=w-g):(Q=D.height-g*2,$e=g),a.save(),a.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(a.filter=`brightness(${this.reflexBright})`),a.setTransform(1,0,0,-1,0,D.height),a.drawImage(D,0,y[I].channelTop,D.width,g,0,Q,D.width,$e),a.restore()}},Pr=()=>{this.showScaleX&&($?(a.save(),a.translate(x,E),this._spinSpeed&&a.rotate(this._spinAngle+_i),a.drawImage(le,-le.width>>1,-le.width>>1),a.restore()):a.drawImage(Y,0,D.height-Y.height))},Br=I=>{const Q=I**2,$e=424.36,ge=11599.29,ei=25122.25,qe=544496.41,Ge=148693636,Je=Qe=>20*Math.log10(Qe);switch(V){case En:const Qe=Ge*Q**2/((Q+$e)*Math.sqrt((Q+ge)*(Q+qe))*(Q+Ge));return 2+Je(Qe);case Tn:const Ze=Ge*Q*I/((Q+$e)*Math.sqrt(Q+ei)*(Q+Ge));return .17+Je(Ze);case Rn:const Bi=Ge*Q/((Q+$e)*(Q+Ge));return .06+Je(Bi);case Ln:const ti=((103791848e-2-Q)**2+108076816e-2*Q)/((9837328-Q)**2+11723776*Q),$i=I/68966888496476e-18*Math.sqrt(ti/((Q+79919.29)*(Q+1345600)));return Je($i);case An:const ii=-4737338981378384e-39*I**6+2043828333606125e-30*I**4-1363894795463638e-22*Q+1,et=1306612257412824e-34*I**5-2118150887518656e-26*I**3+.0005559488023498642*I,Ie=.0001246332637532143*I/Math.hypot(ii,et);return 18.2+Je(Ie)}return 0},Di=(I,Q,$e)=>{a.beginPath(),a.moveTo(I,Q),a.lineTo(I,$e),a.stroke()},Pi=I=>{if(I&&R){const Q=a.globalAlpha;a.globalAlpha=1,a.stroke(),a.globalAlpha=Q}},Ke=I=>Math.max(0,(I*Or|0)*(Oi+Nt)-Nt),$r=I=>{f.val=I,f.peak>0&&(f.hold--,f.hold<0&&(f.peak+=f.hold*me/ce/D.height*this._pixelRatio)),I>=f.peak&&(f.peak=I,f.hold=ie)};X&&a.clearRect(0,0,D.width,D.height);let ks=0;const Is=ee.length,Es=Le?1:2;for(let I=0;I<Es;I++){const{channelTop:Q,channelBottom:$e,analyzerBottom:ge}=y[I],ei=this._gradients[this._selectedGrads[I]],qe=ei.colorStops,Ge=qe.length,Je=!re||l&&!X?"#000":ei.bgColor,Qe=Pe&&$&&I?-1:1,Ze=!I&&B==-1||I&&B==1,Bi=!te||I&&B!=1?0:Be>>(I||!Ze),ti=te&&Ze?-1:1,$i=()=>{const F=Y.height,H=F>>1,j=S?100:P,ae=S?0:J,fe=S?20:5,ke=g/(j-ae),Fe=B!=-1&&(!te||I==0||B==1),Ve=B!=1&&(!te||I!=B);a.save(),a.fillStyle=Dn,a.font=`${H}px ${Gt}`,a.textAlign="right",a.lineWidth=1;for(let We=j;We>ae;We-=fe){const ut=Q+(j-We)*ke,_e=We%2==0|0;if(_e){const we=ut+H*(ut==Q?.8:.35);Fe&&a.fillText(We,F*.85,we),Ve&&a.fillText(We,(te?Be:D.width)-F*.1,we),a.strokeStyle=Dn,a.setLineDash([2,4]),a.lineDashOffset=0}else a.strokeStyle=io,a.setLineDash([2,8]),a.lineDashOffset=1;a.beginPath(),a.moveTo(T+F*_e*Fe,~~ut+.5),a.lineTo(Mi-F*_e*Ve,~~ut+.5),a.stroke()}a.restore()},ii=(F,H)=>{const j=Ae[F]+(F<Ae.length-1?(Ae[F+1]-Ae[F])*H:0);return isNaN(j)?-1/0:j},et=(F,H=ti)=>H*st*((F+Bi)/D.width)+this._spinAngle,Ie=(F,H,j)=>{const ae=L+H*Qe,fe=et(F,j);return[x+ae*Math.cos(fe),E+ae*Math.sin(fe)]},Fi=(F,H,j,ae,fe)=>{a.beginPath();for(const ke of B&&!te?[1,-1]:[ti]){const[Fe,Ve]=p?[et(F,ke),et(F+j,ke)]:[];a.moveTo(...Ie(F,H,ke)),a.lineTo(...Ie(F,H+ae,ke)),p?a.arc(x,E,L+(H+ae)*Qe,Fe,Ve,ke!=1):a.lineTo(...Ie(F+j,H+ae,ke)),a.lineTo(...Ie(F+j,H,ke)),p&&!fe&&a.arc(x,E,L+H*Qe,Ve,Fe,ke==1)}Pi(fe),a.fill()},Hi=(F=0,H=0)=>{let j;if(d==Ut&&!Lt||se==ot)j=O[I];else{const ae=d==wn?H%Ge:qe.findLastIndex(fe=>l?Ke(F)<=Ke(fe.level):F<=fe.level);j=qe[ae].color}a.fillStyle=a.strokeStyle=j};if(q){if(te&&!$){const F=Be*(I+Ze),H=Ze?-1:1;a.setTransform(H,0,0,1,F,0)}if((!X||re)&&(X&&(a.globalAlpha=this.bgAlpha),a.fillStyle=Je,(I==0||!$&&!de)&&a.fillRect(T,Q-k,Be,(X&&this.reflexAlpha==1?g:w)+k),a.globalAlpha=1),this.showScaleY&&!h&&!$&&(I==0||!de)&&$i(),l?(a.setLineDash([Oi,Nt]),a.lineWidth=ee[0].width):a.lineWidth=_?Math.min(R,ee[0].width/2):R,a.save(),!$){const F=new Path2D;F.rect(0,Q,D.width,g),a.clip(F)}}let Ae=this._fftData[I];this._analyzer[I].getFloatFrequencyData(Ae),V&&(Ae=Ae.map((F,H)=>F+Br(this._binToFreq(H)))),a.beginPath();let Mt=[];for(let F=0;F<Is;F++){const H=ee[F],{posX:j,barCenter:ae,width:fe,freq:ke,binLo:Fe,binHi:Ve,ratioLo:We,ratioHi:ut}=H;let _e=Math.max(ii(Fe,We),ii(Ve,ut));for(let oe=Fe+1;oe<Ve;oe++)Ae[oe]>_e&&(_e=Ae[oe]);if(_e=this._normalizedB(_e),H.value[I]=_e,ks+=_e,H.peak[I]>0&&H.alpha[I]>0&&(H.hold[I]--,H.hold[I]<0)){if(m&&!At){const oe=!o||_&&R>0?1:o?H.peak[I]:C;H.alpha[I]=oe*(1+H.hold[I]/ye)}else H.peak[I]+=H.hold[I]*me/ce/Mr;H.alpha[I]<=0&&(H.peak[I]=0)}if(_e>=H.peak[I]&&(H.peak[I]=_e,H.hold[I]=ie,H.alpha[I]=!o||_&&R>0?1:o?_e:C),!q)continue;a.globalAlpha=h||o?_e:_?C:1,Hi(_e,F);const we=h?ze:l?Ke(_e):_e*ze|0;if(se==ot){const oe=F?0:(this._normalizedB(Ae[ee[1].binLo])*ze+we)/2;if($){if(F==0&&(te&&a.moveTo(...Ie(0,0)),a.lineTo(...Ie(0,j<0?oe:we))),j>=0){const Re=[j,we];a.lineTo(...Ie(...Re)),Mt.push(Re)}}else{if(F==0)if(B==-1&&!te)a.moveTo(T,ge-(j<T?oe:we));else{const Re=Fe?this._normalizedB(Ae[Fe-1])*ze:we;a.moveTo(T-R,ge-Re)}(te||B!=-1||j>=T)&&a.lineTo(j,ge-we)}}else if(l){if(re&&!X&&(I==0||!de)){const oe=a.globalAlpha;a.strokeStyle=Js,a.globalAlpha=1,Di(ae,Q,ge),a.strokeStyle=a.fillStyle,a.globalAlpha=oe}if(Lt){const oe=h?0:qe.findLastIndex(tt=>Ke(_e)<=Ke(tt.level));let Re=ge;for(let tt=Ge-1;tt>=oe;tt--){a.strokeStyle=qe[tt].color;let Rs=ge-(tt==oe?we:Ke(qe[tt].level));Di(ae,Re,Rs),Re=Rs-Nt}}else Di(ae,ge,ge-we)}else if(j>=T)if($)Fi(j,0,fe,we,_);else if(p){const oe=fe/2,Re=ge+oe;a.beginPath(),a.moveTo(j,Re),a.lineTo(j,Re-we),a.arc(ae,Re-we,oe,fi,st),a.lineTo(j+fe,Re),Pi(_),a.fill()}else{const oe=_?a.lineWidth:0;a.beginPath(),a.rect(j,ge+oe,fe,-we-oe),Pi(_),a.fill()}const pt=H.peak[I],Ts=H.alpha[I];if(pt>0&&Ts>0&&G&&!At&&!h&&j>=T&&j<Mi){if(m?a.globalAlpha=Ts:_&&R>0?a.globalAlpha=1:o&&(a.globalAlpha=pt),(d==Sn||Lt)&&Hi(pt),l){const oe=Ke(pt);oe>=Nt&&a.fillRect(j,ge-oe,fe,Oi)}else if(!$)a.fillRect(j,ge-pt*ze,fe,2);else if(se!=ot){const oe=pt*ze;Fi(j,oe,fe,!this._radialInvert||Pe||oe+L>=2?-2:2)}}}if(q){if(a.globalAlpha=1,se==ot){if(Hi(),$&&!te){if(B){let F;for(;F=Mt.pop();)a.lineTo(...Ie(...F,-1))}a.closePath()}if(R>0&&a.stroke(),C>0){if($){const F=te?et(Be>>1):0,H=te?et(Be):st;a.moveTo(...Ie(te?Be>>1:0,0)),a.arc(x,E,L,F,H,te?!Ze:!0)}else a.lineTo(Mi,ge),a.lineTo(T,ge);a.globalAlpha=C,a.fill(),a.globalAlpha=1}if((At||$&&G)&&(Mt=[],a.beginPath(),ee.forEach((F,H)=>{let j=F.posX,ae=F.peak[I],fe=H?"lineTo":"moveTo";if($&&j<0){const ke=ee[H+1];ae=po(j,ae,ke.posX,ke.peak[I],0),j=0}ae*=ze,At?(a[fe](...$?Ie(j,ae):[j,ge-ae]),$&&B&&!te&&Mt.push([j,ae])):ae>0&&Fi(j,ae,1,-2)}),At)){let F;for(;F=Mt.pop();)a.lineTo(...Ie(...F,-1));a.lineWidth=1,a.stroke()}}a.restore(),te&&!$&&a.setTransform(1,0,0,1,0,0),(!te&&!de||I)&&Dr(I)}}if($r(ks/(Is<<Es-1)),q&&(B&&!$&&!te&&(a.setTransform(-1,0,0,1,D.width-T,0),a.drawImage(D,T,0,x,D.height,0,0,x,D.height),a.setTransform(1,0,0,1,0,0)),a.setLineDash([]),Pr()),this.showFPS){const I=Y.height;a.font=`bold ${I}px ${Gt}`,a.fillStyle=Ks,a.textAlign="right",a.fillText(Math.round(v),D.width-I,I*2)}this.onCanvasDraw&&(a.save(),a.fillStyle=a.strokeStyle=O[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:O}),a.restore())}_freqScaling(e){switch(this._frequencyScale){case rt:return Math.log2(e);case mi:return 26.81*e/(1960+e)-.53;case vi:return Math.log2(1+e/700);case wt:return e}}_freqToBin(e,t="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[t](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:t,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:l,initialX:h,innerRadius:u,outerRadius:_}=this._aux,{isLumi:p}=this._flg,b=this._chLayout==Me,g=1-s,x=p?e.height:e.height*(1-s*!b)|0;for(const E of[0,1]){const y=this._gradients[this._selectedGrads[E]],w=y.colorStops,k=y.dir=="h";let T;if(n?T=t.createRadialGradient(r,l,_,r,l,u-(_-u)*b):T=t.createLinearGradient(...k?[h,0,h+o,0]:[0,0,0,x]),w){const L=b&&!this._splitGradient&&(!k||n);for(let K=0;K<1+L;K++){const ee=w.length-1;w.forEach((D,O)=>{let c=D.pos;if(L&&(c/=2),b&&!p&&!n&&!k&&(c*=g,!L&&c>.5*g&&(c+=.5*s)),K==1)if(n||p){const d=ee-O;D=w[d],c=1-D.pos/2}else O==0&&c>0&&T.addColorStop(.5,D.color),c+=.5;T.addColorStop(c,D.color),b&&O==ee&&c<.5&&T.addColorStop(.5,D.color)})}}this._canvasGradients[E]=T}}_normalizedB(e){const t=this._linearAmplitude,n=t?1/this._linearBoost:1,s=(h,u,_)=>h<=u?u:h>=_?_:h,o=h=>10**(h/20);let r=this.maxDecibels,l=this.minDecibels;return t&&(r=o(r),l=o(l),e=o(e)**n),s((e-l)/(r-l)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:t,_ctx:n}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,l=window.screen.height*o;Math.abs(window.orientation)==90&&r<l&&([r,l]=[l,r]);const h=this.isFullscreen,u=h&&this._fsEl==t,_=u?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,p=u?l:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=l,!(e!=Nn&&t.width==_&&t.height==p)&&(t.width=_,t.height=p,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,_,p)),n.lineJoin="bevel",s.width=_,s.height=Math.max(20*o,Math.min(_,p)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==h&&(e=Mn),this._fsStatus=h,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,t){if(!this._gradients.hasOwnProperty(e))throw new Ee(oo,e);[0,1].includes(t)||(this._selectedGrads[1]=e,t=0),this._selectedGrads[t]=e,this._makeGrad()}_setProps(e,t){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(St).filter(r=>r!="start").concat(n,s);(t||e===void 0)&&(e={...St,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const _o=({stream:i})=>{const e=ui(null);return nt(()=>{if(!e.current||!i)return;const t=new AudioContext,n=t.createMediaStreamSource(i),s=new fo(e.current,{source:n,audioCtx:t,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:.7,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:1024,fillAlpha:.25,frequencyScale:"log",gradient:"prism",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!1,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!0,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return s.registerGradient("gradient",{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]}),s.gradient="gradient",()=>{s.disconnectInput()}},[i]),A("div",{className:"px-4 w-full h-[150px]",ref:e})};function yi(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]])}return t}function U(i,e,t,n){return new(t||(t=Promise))(function(s,o){function r(u){try{h(n.next(u))}catch(_){o(_)}}function l(u){try{h(n.throw(u))}catch(_){o(_)}}function h(u){var _;u.done?s(u.value):(_=u.value,_ instanceof t?_:new t(function(p){p(_)})).then(r,l)}h((n=n.apply(i,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var Hn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),go=new Uint8Array(16);function mo(){if(!Hn)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Hn(go)}for(var Un=[],zt=0;zt<256;++zt)Un[zt]=(zt+256).toString(16).substr(1);function Ct(i,e,t){var n=e&&t||0;typeof i=="string"&&(e=i==="binary"?new Array(16):null,i=null);var s=(i=i||{}).random||(i.rng||mo)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,l){var h=0,u=Un;return[u[r[h++]],u[r[h++]],u[r[h++]],u[r[h++]],"-",u[r[h++]],u[r[h++]],"-",u[r[h++]],u[r[h++]],"-",u[r[h++]],u[r[h++]],"-",u[r[h++]],u[r[h++]],u[r[h++]],u[r[h++]],u[r[h++]],u[r[h++]]].join("")}(s)}var vo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gn(i,e){return i(e={exports:{}},e.exports),e.exports}var bo=Gn(function(i){var e,t;e=vo,t=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function l(y,w){var k=y[w];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 h(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function u(y,w){for(var k=0;k<r.length;k++){var T=r[k];this[T]=k<y?n:this.methodFactory(T,y,w)}this.log=this.debug}function _(y,w,k){return function(){typeof console!==s&&(u.call(this,w,k),this[y].apply(this,arguments))}}function p(y,w,k){return function(T){return T==="debug"&&(T="log"),typeof console!==s&&(T==="trace"&&o?h:console[T]!==void 0?l(console,T):console.log!==void 0?l(console,"log"):n)}(y)||_.apply(this,arguments)}function b(y,w,k){var T,L=this;w=w??"WARN";var K="loglevel";function ee(){var O;if(typeof window!==s&&K){try{O=window.localStorage[K]}catch{}if(typeof O===s)try{var c=window.document.cookie,d=c.indexOf(encodeURIComponent(K)+"=");d!==-1&&(O=/^([^;]+)/.exec(c.slice(d))[1])}catch{}return L.levels[O]===void 0&&(O=void 0),O}}typeof y=="string"?K+=":"+y:typeof y=="symbol"&&(K=void 0),L.name=y,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=k||p,L.getLevel=function(){return T},L.setLevel=function(O,c){if(typeof O=="string"&&L.levels[O.toUpperCase()]!==void 0&&(O=L.levels[O.toUpperCase()]),!(typeof O=="number"&&O>=0&&O<=L.levels.SILENT))throw"log.setLevel() called with invalid level: "+O;if(T=O,c!==!1&&function(d){var a=(r[d]||"silent").toUpperCase();if(typeof window!==s&&K){try{return void(window.localStorage[K]=a)}catch{}try{window.document.cookie=encodeURIComponent(K)+"="+a+";"}catch{}}}(O),u.call(L,O,y),typeof console===s&&O<L.levels.SILENT)return"No console available for logging"},L.setDefaultLevel=function(O){w=O,ee()||L.setLevel(O,!1)},L.resetLevel=function(){L.setLevel(w,!1),function(){if(typeof window!==s&&K){try{return void window.localStorage.removeItem(K)}catch{}try{window.document.cookie=encodeURIComponent(K)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},L.enableAll=function(O){L.setLevel(L.levels.TRACE,O)},L.disableAll=function(O){L.setLevel(L.levels.SILENT,O)};var D=ee();D==null&&(D=w),L.setLevel(D,!1)}var g=new b,x={};g.getLogger=function(y){if(typeof y!="symbol"&&typeof y!="string"||y==="")throw new TypeError("You must supply a name when creating a logger.");var w=x[y];return w||(w=x[y]=new b(y,g.getLevel(),g.methodFactory)),w};var E=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=E),g},g.getLoggers=function(){return x},g.default=g,g},i.exports?i.exports=t():e.log=t()});const N=bo.getLogger("telnyx"),yo=N.methodFactory;N.methodFactory=(i,e,t)=>{const n=yo(i,e,t);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);n.apply(void 0,s)}},N.setLevel(N.getLevel());const jn="Time to call invite",zn="wss://rtc.telnyx.com",wo={urls:"stun:stun.telnyx.com:3478"},So={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var M;(function(i){i.SocketOpen="telnyx.socket.open",i.SocketClose="telnyx.socket.close",i.SocketError="telnyx.socket.error",i.SocketMessage="telnyx.socket.message",i.SpeedTest="telnyx.internal.speedtest",i.Ready="telnyx.ready",i.Error="telnyx.error",i.Notification="telnyx.notification",i.StatsFrame="telnyx.stats.frame",i.StatsReport="telnyx.stats.report",i.Messages="telnyx.messages",i.Calls="telnyx.calls",i.MediaError="telnyx.rtc.mediaError"})(M||(M={}));const qn=i=>Object.keys(i).length===0,qt=i=>{const[e,t,n,s,o,r]=i;let l={};try{l=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{N.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:t,participantName:n,codec:s,media:l,participantData:r}},Vn=i=>{if(typeof i!="string")return i;try{return JSON.parse(i)}catch{return i}},at=i=>i instanceof Function||typeof i=="function",xt=i=>typeof document=="object"&&"getElementById"in document?typeof i=="string"?document.getElementById(i)||null:typeof i=="function"?i():i instanceof HTMLMediaElement?i:null:null,Co=/^(ws|wss):\/\//,Wn=(i,e=null)=>{const{result:t={},error:n}=i;if(n)return{error:n};const{result:s=null}=t;if(s===null)return e!==null&&(t.node_id=e),{result:t};const{code:o=null,node_id:r=null,result:l=null}=s;return o&&o!=="200"?{error:s}:l?Wn(l,r):{result:s}},Xn=(i,e)=>Math.floor(Math.random()*(e-i+1)+i),wi=({login:i,passwd:e,password:t,login_token:n})=>!!(i&&(e||t)||n),Vt=({anonymous_login:i})=>!!i&&!!i.target_id&&!!i.target_type,Si=i=>{var e,t,n,s,o,r;let l="",h="";return!((t=(e=i==null?void 0:i.result)===null||e===void 0?void 0:e.params)===null||t===void 0)&&t.state&&(l=(s=(n=i==null?void 0:i.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state),!((o=i==null?void 0:i.params)===null||o===void 0)&&o.state&&(h=(r=i==null?void 0:i.params)===null||r===void 0?void 0:r.state),l||h};function Yn({debounceTime:i}){let e,t;return{promise:new Promise((n,s)=>{e=i?xo(n,i):n,t=s}),resolve:e,reject:t}}const xo=(i,e)=>{let t;return(...n)=>{clearTimeout(t),t=window.setTimeout(()=>{i(...n)},e)}},lt="GLOBAL",Se={},kt=(i,e)=>`${i}|${e}`,Kn=(i,e=lt)=>kt(i,e)in Se,ct=(i,e,t=lt)=>{const n=kt(i,t);n in Se||(Se[n]=[]),Se[n].push(e)},Jn=(i,e,t=lt)=>{const n=function(s){dt(i,n,t),e(s)};return n.prototype.targetRef=e,ct(i,n,t)},dt=(i,e,t=lt)=>{if(!Kn(i,t))return!1;const n=kt(i,t);if(at(e))for(let s=Se[n].length-1;s>=0;s--){const o=Se[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Se[n].splice(s,1)}else Se[n]=[];return Se[n].length===0&&delete Se[n],!0},W=(i,e,t=lt,n=!0)=>{const s=n&&t!==lt;if(!Kn(i,t))return s&&W(i,e),!1;const o=kt(i,t),r=Se[o].length;if(!r)return s&&W(i,e),!1;for(let l=r-1;l>=0;l--)Se[o][l](e);return s&&W(i,e),!0},Ci=i=>{const e=kt(i,"");Object.keys(Se).filter(t=>t.indexOf(e)===0).forEach(t=>delete Se[t])};var Ce,je,Z;(function(i){i.Offer="offer",i.Answer="answer"})(Ce||(Ce={})),function(i){i.Inbound="inbound",i.Outbound="outbound"}(je||(je={})),function(i){i.Invite="telnyx_rtc.invite",i.Attach="telnyx_rtc.attach",i.Answer="telnyx_rtc.answer",i.Info="telnyx_rtc.info",i.Display="telnyx_rtc.display",i.Media="telnyx_rtc.media",i.Event="telnyx_rtc.event",i.Bye="telnyx_rtc.bye",i.Punt="telnyx_rtc.punt",i.Broadcast="telnyx_rtc.broadcast",i.Subscribe="telnyx_rtc.subscribe",i.Unsubscribe="telnyx_rtc.unsubscribe",i.ClientReady="telnyx_rtc.clientReady",i.Modify="telnyx_rtc.modify",i.Ringing="telnyx_rtc.ringing",i.GatewayState="telnyx_rtc.gatewayState",i.Ping="telnyx_rtc.ping",i.Pong="telnyx_rtc.pong"}(Z||(Z={}));const Oe={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},ko={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 z,It,ve,De,be;(function(i){i[i.New=0]="New",i[i.Requesting=1]="Requesting",i[i.Trying=2]="Trying",i[i.Recovering=3]="Recovering",i[i.Ringing=4]="Ringing",i[i.Answering=5]="Answering",i[i.Early=6]="Early",i[i.Active=7]="Active",i[i.Held=8]="Held",i[i.Hangup=9]="Hangup",i[i.Destroy=10]="Destroy",i[i.Purge=11]="Purge"})(z||(z={})),function(i){i.Participant="participant",i.Moderator="moderator"}(It||(It={})),function(i){i.Join="join",i.Leave="leave",i.Bootstrap="bootstrap",i.Add="add",i.Modify="modify",i.Delete="delete",i.Clear="clear",i.ChatMessage="chatMessage",i.LayerInfo="layerInfo",i.LogoInfo="logoInfo",i.LayoutInfo="layoutInfo",i.LayoutList="layoutList",i.ModCmdResponse="modCommandResponse"}(ve||(ve={})),function(i){i.Video="videoinput",i.AudioIn="audioinput",i.AudioOut="audiooutput"}(De||(De={})),function(i){i.REGED="REGED",i.UNREGED="UNREGED",i.NOREG="NOREG",i.FAILED="FAILED",i.FAIL_WAIT="FAIL_WAIT",i.REGISTER="REGISTER",i.TRYING="TRYING",i.EXPIRED="EXPIRED",i.UNREGISTER="UNREGISTER"}(be||(be={}));const xi="telnyx-voice-sdk-id";function ki(){return sessionStorage.getItem(xi)}typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(xi)});let Io=typeof WebSocket<"u"?WebSocket:null;const Eo=0,To=1,Ro=2,Lo=3;class Qn{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=zn,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n,region:s}=e.options;n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":zn),t&&(this._host=(o=>`${Co.test(o)?"":"wss://"}${o}`)(t)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`))}get connected(){return this._wsClient&&this._wsClient.readyState===To}get connecting(){return this._wsClient&&this._wsClient.readyState===Eo}get closing(){return this._wsClient&&this._wsClient.readyState===Ro}get closed(){return this._wsClient&&this._wsClient.readyState===Lo}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),t=ki();t&&e.searchParams.set("voice_sdk_id",t),this._wsClient=new Io(e.toString()),this._wsClient.onopen=n=>W(M.SocketOpen,n,this.session.uuid),this._wsClient.onclose=n=>W(M.SocketClose,n,this.session.uuid),this._wsClient.onerror=n=>W(M.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=n=>{var s,o;const r=Vn(n.data);var l;if(typeof r!="string"){if(r.voice_sdk_id&&(l=r.voice_sdk_id,sessionStorage.setItem(xi,l)),this._unsetTimer(r.id),N.debug(`RECV:
|
|
9
|
+
`,JSON.stringify(r,null,2),`
|
|
10
|
+
`),be[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!W(r.id,r)){const h=Si(r);W(M.SocketMessage,r,this.session.uuid),h&&(this.previousGatewayState=h)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise((s,o)=>{if(t.hasOwnProperty("result"))return s();Jn(t.id,r=>{const{result:l,error:h}=Wn(r);return h?o(h):s(l)})});return N.debug(`SEND:
|
|
11
|
+
`,JSON.stringify(t,null,2),`
|
|
12
|
+
`),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(at(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)),W(M.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else N.warn("Unknown message from socket",e)}}class Wt{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Ct()},e)}}const Zn={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 xe extends Wt{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const t=yi(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const n in Zn)n&&t.hasOwnProperty(n)&&(t[Zn[n]]=t[n],delete t[n]);e.dialogParams=t}this.buildRequest({method:this.toString(),params:e})}}class es extends xe{constructor(){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,params:{}})}}class Ao{constructor(e){this.pendingRequestId=null,this.onSocketMessage=t=>U(this,void 0,void 0,function*(){t.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Si(t))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const t=new es;this.pendingRequestId=t.request.id,this.gatewayStateTask=Yn({}),this.session.execute(t);const n=yield this.gatewayStateTask.promise;return!!n&&[be.REGISTER,be.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Yn({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class No{constructor(e){if(this.options=e,this.uuid=Ct(),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 Qn(this),this.registerAgent=new Ao(this)}get __logger(){return N}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*Xn(2,6)}execute(e){return this._idle?new Promise(t=>this._executeQueue.push({resolve:t,msg:e})):this.connected?this.connection.send(e):new Promise(t=>{this._executeQueue.push({resolve:t,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return wi(this.options)||Vt(this.options)}broadcast(e){}disconnect(){return U(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,t){return ct(e,t,this.uuid),this}off(e,t){return dt(e,t,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(this.connection=new Qn(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){W(M.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return U(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Ci(this.relayProtocol);for(const e in this.subscriptions)Ci(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],dt(e,null,t)):(delete this.subscriptions[e],Ci(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},at(t)&&ct(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(M.SocketOpen,this._onSocketOpen),this.on(M.SocketClose,this.onNetworkClose),this.on(M.SocketError,this.onNetworkClose),this.on(M.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(M.SocketOpen,this._onSocketOpen),this.off(M.SocketClose,this.onNetworkClose),this.off(M.SocketError,this.onNetworkClose),this.off(M.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:t})=>{typeof t=="string"?this.executeRaw(t):e(this.execute(t))})}_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,t){ct(e,t)}static off(e){dt(e)}static uuid(){return Ct()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const Ii=i=>navigator.mediaDevices.getUserMedia(i),Xt=i=>i&&i instanceof MediaStream,Yt=(i,e)=>{const t=xt(i);t!==null&&(t.getAttribute("autoplay")||t.setAttribute("autoplay","autoplay"),t.getAttribute("playsinline")||t.setAttribute("playsinline","playsinline"),t.srcObject=e)},ts=(i,e)=>U(void 0,void 0,void 0,function*(){const t=xt(i);if(t===null)return N.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return N.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield t.setSinkId(e),!0}catch{return!1}}),Mo=i=>{i&&i.readyState==="live"&&i.stop()},Et=i=>{Xt(i)&&i.getTracks().forEach(Mo),i=null},Kt=i=>U(void 0,void 0,void 0,function*(){N.info("RTCService.getUserMedia",i);const{audio:e,video:t}=i;if(!e&&!t)return null;try{return yield Ii(i)}catch(n){throw N.error("getUserMedia error: ",n),n}}),Tt=(i=null,e=!1)=>U(void 0,void 0,void 0,function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===De.AudioIn||s===De.AudioOut,video:!s||s===De.Video}))(i)).catch(s=>(console.error(s),null));if(n){if(Et(n),t=yield navigator.mediaDevices.enumerateDevices(),i&&(t=t.filter(o=>o.kind===i)),e===!0)return t;const s=[];t=t.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return t}),is=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Jt=(i,e,t)=>U(void 0,void 0,void 0,function*(){const n=yield Tt(t,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(i===o||e===r)return o}return null}),ns=i=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(i).map(t=>{e.hasOwnProperty(t)&&i[t]!==null&&i[t]!==void 0||delete i[t]})},ss=(i,e,t,n)=>U(void 0,void 0,void 0,function*(){const{deviceId:s}=n;if(s===void 0&&(i||e)){const o=yield Jt(i,e,t).catch(r=>null);o&&(n.deviceId={exact:o})}return n}),Ei=i=>{const e=`\r
|
|
13
|
+
`,t=i.split(e),n=t.findIndex(l=>/^a=rtpmap/.test(l)&&/opus\/48000/.test(l));if(n<0)return i;const s=(l=>{const h=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),u=l.match(h);return u&&u.length==2?u[1]:null})(t[n]),o=new RegExp(`a=fmtp:${s}`),r=t.findIndex(l=>o.test(l));return r>=0?/stereo=1;/.test(t[r])||(t[r]+="; stereo=1; sprop-stereo=1"):t[n]+=`${e}a=fmtp:${s} stereo=1; sprop-stereo=1`,t.join(e)},os=i=>/^m=audio/.test(i),rs=i=>/^m=video/.test(i),as=(i,e)=>{const t=`\r
|
|
14
|
+
`,n=e.split(t);if(n.findIndex(os)<n.findIndex(rs))return i;const s=i.split(t),o=s.findIndex(os),r=s.findIndex(rs),l=s.slice(o,r),h=s.slice(r,s.length-1);return[...s.slice(0,o),...h,...l,""].join(t)},Qt=(i,e)=>{if(!i)return!1;const{subscribed:t,alreadySubscribed:n}=Ti(i);return t.includes(e)||n.includes(e)},Ti=i=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(t=>{e[t]=i[`${t}Channels`]||[]}),e},ht=(i,e=null,t=null)=>{if(!Xt(i))return null;let n=[];switch(e){case"audio":n=i.getAudioTracks();break;case"video":n=i.getVideoTracks();break;default:n=i.getTracks()}n.forEach(s=>{switch(t){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},ls=i=>{ht(i,"audio",!0)},cs=i=>{ht(i,"audio",!1)},ds=i=>{ht(i,"audio",null)};function Oo(){try{const{browserInfo:i,name:e,version:t,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const _=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),p=_[0],b=parseInt(_[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 _=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),p=_[0],b=parseInt(_[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 _=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:_,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const _=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),p=_[0],b=parseInt(_[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()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,l=window.RTCIceCandidate,h=window.navigator&&window.navigator.mediaDevices,u=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:i,browserName:e,browserVersion:t,supportWebRTC:!!(o&&r&&l&&h&&u),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!l,supportMediaDevices:!!h,supportGetUserMedia:!!Kt}}catch(i){return i.message}}var he;function hs(i,e){const t=document.getElementById(e);if(t)return t;if(i&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=i,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function us(i){i&&(i._playFulfilled=!1,i._promise=i.play(),i._promise.then(()=>{i._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),i._playFulfilled=!0}))}function ps(i){i&&(i._playFulfilled?(i.pause(),i.currentTime=0):i._promise&&i._promise.then?i._promise.then(()=>{i.pause(),i.currentTime=0}):setTimeout(()=>{i.pause(),i.currentTime=0},1e3))}(function(i){i.not_supported="not supported",i.full="full",i.partial="partial"})(he||(he={}));var fs="2.22.12",Ri=fs;class Do extends xe{constructor(e,t,n,s,o={},r){super(),this.method="login";const l={login:e,passwd:t,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Ri,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Po extends xe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Bo extends xe{toString(){return Z.Invite}}class $o extends xe{toString(){return Z.Answer}}class Fo extends xe{toString(){return Z.Attach}}class Ho extends xe{toString(){return Z.Bye}}class Li extends xe{toString(){return Z.Modify}}class _s extends xe{toString(){return Z.Info}}class Uo extends xe{toString(){return Z.Broadcast}}class Go extends xe{toString(){return Z.Subscribe}}class jo extends xe{toString(){return Z.Unsubscribe}}const gs=(i,e)=>{const{contentType:t,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const l={type:Oe.conferenceUpdate,call:i.calls[s],canvasInfo:zo(o),currentLayerIdx:r};switch(t){case"layer-info":{const h=Object.assign({action:ve.LayerInfo},l);W(M.Notification,h,i.uuid);break}case"layout-info":{const h=Object.assign({action:ve.LayoutInfo},l);W(M.Notification,h,i.uuid);break}}},zo=i=>{const e=JSON.stringify(i).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Vn(e)};var Zt,ms=Gn(function(i,e){var t;function n(){}function s(){s.init.call(this)}function o(c){return c._maxListeners===void 0?s.defaultMaxListeners:c._maxListeners}function r(c,d,a,f){var m,C,v;if(typeof a!="function")throw new TypeError('"listener" argument must be a function');if((C=c._events)?(C.newListener&&(c.emit("newListener",d,a.listener?a.listener:a),C=c._events),v=C[d]):(C=c._events=new n,c._eventsCount=0),v){if(typeof v=="function"?v=C[d]=f?[a,v]:[v,a]:f?v.unshift(a):v.push(a),!v.warned&&(m=o(c))&&0<m&&v.length>m){v.warned=!0;var S=new Error("Possible EventEmitter memory leak detected. "+v.length+" "+d+" listeners added. Use emitter.setMaxListeners() to increase limit");S.name="MaxListenersExceededWarning",S.emitter=c,S.type=d,S.count=v.length,function(R){typeof console.warn=="function"?console.warn(R):console.log(R)}(S)}}else v=C[d]=a,++c._eventsCount;return c}function l(c,d,a){function f(){c.removeListener(d,f),m||(m=!0,a.apply(c,arguments))}var m=!1;return f.listener=a,f}function h(c){var d=this._events;if(d){var a=d[c];if(typeof a=="function")return 1;if(a)return a.length}return 0}function u(c,d){for(var a=Array(d);d--;)a[d]=c[d];return a}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&t.active&&!(this instanceof t.Domain)&&(this.domain=t.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(c){if(typeof c!="number"||0>c||isNaN(c))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=c,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(c){var d,a,f,m,C,v,S,R=c==="error";if(v=this._events)R=R&&v.error==null;else if(!R)return!1;if(S=this.domain,R){if(d=arguments[1],!S){if(d instanceof Error)throw d;var P=new Error('Uncaught, unspecified "error" event. ('+d+")");throw P.context=d,P}return d||(d=new Error('Uncaught, unspecified "error" event')),d.domainEmitter=this,d.domain=S,d.domainThrown=!1,S.emit("error",d),!1}if(!(a=v[c]))return!1;var J=typeof a=="function";switch(f=arguments.length){case 1:(function(B,se,X){if(se)B.call(X);else for(var $=B.length,re=u(B,$),G=0;G<$;++G)re[G].call(X)})(a,J,this);break;case 2:(function(B,se,X,$){if(se)B.call(X,$);else for(var re=B.length,G=u(B,re),q=0;q<re;++q)G[q].call(X,$)})(a,J,this,arguments[1]);break;case 3:(function(B,se,X,$,re){if(se)B.call(X,$,re);else for(var G=B.length,q=u(B,G),V=0;V<G;++V)q[V].call(X,$,re)})(a,J,this,arguments[1],arguments[2]);break;case 4:(function(B,se,X,$,re,G){if(se)B.call(X,$,re,G);else for(var q=B.length,V=u(B,q),Y=0;Y<q;++Y)V[Y].call(X,$,re,G)})(a,J,this,arguments[1],arguments[2],arguments[3]);break;default:for(m=Array(f-1),C=1;C<f;C++)m[C-1]=arguments[C];(function(B,se,X,$){if(se)B.apply(X,$);else for(var re=B.length,G=u(B,re),q=0;q<re;++q)G[q].apply(X,$)})(a,J,this,m)}return!0},s.prototype.addListener=function(c,d){return r(this,c,d,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(c,d){return r(this,c,d,!0)},s.prototype.once=function(c,d){if(typeof d!="function")throw new TypeError('"listener" argument must be a function');return this.on(c,l(this,c,d)),this},s.prototype.prependOnceListener=function(c,d){if(typeof d!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(c,l(this,c,d)),this},s.prototype.removeListener=function(c,d){var a,f,m,C,v;if(typeof d!="function")throw new TypeError('"listener" argument must be a function');if(!(f=this._events))return this;if(!(a=f[c]))return this;if(a===d||a.listener&&a.listener===d)--this._eventsCount==0?this._events=new n:(delete f[c],f.removeListener&&this.emit("removeListener",c,a.listener||d));else if(typeof a!="function"){for(m=-1,C=a.length;0<C--;)if(a[C]===d||a[C].listener&&a[C].listener===d){v=a[C].listener,m=C;break}if(0>m)return this;if(a.length===1){if(a[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete f[c]}else(function(S,R){for(var P=R,J=P+1,B=S.length;J<B;P+=1,J+=1)S[P]=S[J];S.pop()})(a,m);f.removeListener&&this.emit("removeListener",c,v||d)}return this},s.prototype.removeAllListeners=function(c){var d,a;if(!(a=this._events))return this;if(!a.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):a[c]&&(--this._eventsCount==0?this._events=new n:delete a[c]),this;if(arguments.length===0){for(var f,m=Object.keys(a),C=0;C<m.length;++C)(f=m[C])!=="removeListener"&&this.removeAllListeners(f);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(d=a[c])=="function")this.removeListener(c,d);else if(d)do this.removeListener(c,d[d.length-1]);while(d[0]);return this},s.prototype.listeners=function(c){var d,a,f=this._events;return f?a=(d=f[c])?typeof d=="function"?[d.listener||d]:function(m){for(var C=Array(m.length),v=0;v<C.length;++v)C[v]=m[v].listener||m[v];return C}(d):[]:a=[],a},s.listenerCount=function(c,d){return typeof c.listenerCount=="function"?c.listenerCount(d):h.call(c,d)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var _,p=new Uint8Array(16);function b(){if(!_&&!(_=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 _(p)}for(var g=/^(?:[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,x=[],E=0;256>E;++E)x.push((E+256).toString(16).substr(1));function y(c){var d=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,a=(x[c[d+0]]+x[c[d+1]]+x[c[d+2]]+x[c[d+3]]+"-"+x[c[d+4]]+x[c[d+5]]+"-"+x[c[d+6]]+x[c[d+7]]+"-"+x[c[d+8]]+x[c[d+9]]+"-"+x[c[d+10]]+x[c[d+11]]+x[c[d+12]]+x[c[d+13]]+x[c[d+14]]+x[c[d+15]]).toLowerCase();if(!function(f){return typeof f=="string"&&g.test(f)}(a))throw TypeError("Stringified UUID is invalid");return a}function w(c,d,a){var f=(c=c||{}).random||(c.rng||b)();return f[6]=64|15&f[6],f[8]=128|63&f[8],y(f)}function k(c,d){if(!c||!d)return{};const a={...c};if(a.localCandidateId){const f=d.get(a.localCandidateId);a.local={...f}}if(a.remoteCandidateId){const f=d.get(a.remoteCandidateId);a.remote={...f}}return a}function T(c,d,a){return 8*function(f,m,C){const v=f[C],S=m?m[C]:null;return v===null||S===null?null:(v-S)/(f.timestamp-m.timestamp)*1e3}(c,d,a)}function L(c){if(!c.entries)return c;const d={};return c.forEach(function(a,f){d[f]=a}),d}function K(c,d,a={}){if(!c)return null;let f={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};a.remote&&(f.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const m of c.values())switch(m.type){case"outbound-rtp":{const C=m.mediaType||m.kind,v={};let S={};if(!["audio","video"].includes(C))continue;if(m.codecId){const R=c.get(m.codecId);R&&(v.clockRate=R.clockRate,v.mimeType=R.mimeType,v.payloadType=R.payloadType)}S=c.get(m.mediaSourceId)||c.get(m.trackId)||{},f[C].outbound.push({...m,...v,track:{...S}});break}case"inbound-rtp":{let C=m.mediaType||m.kind,v={};const S={};if(!["audio","video"].includes(C))if(m.id.includes("Video"))C="video";else{if(!m.id.includes("Audio"))continue;C="audio"}if(m.codecId){const R=c.get(m.codecId);R&&(S.clockRate=R.clockRate,S.mimeType=R.mimeType,S.payloadType=R.payloadType)}if(!f.connection.id&&m.transportId){const R=c.get(m.transportId);if(R&&R.selectedCandidatePairId){const P=c.get(R.selectedCandidatePairId);f.connection=k(P,c)}}v=c.get(m.mediaSourceId)||c.get(m.trackId)||{},f[C].inbound.push({...m,...S,track:{...v}});break}case"peer-connection":f.connection.dataChannelsClosed=m.dataChannelsClosed,f.connection.dataChannelsOpened=m.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!a.remote)break;let C=m.mediaType||m.kind;const v={};if(!["audio","video"].includes(C))if(m.id.includes("Video"))C="video";else{if(!m.id.includes("Audio"))continue;C="audio"}if(m.codecId){const S=c.get(m.codecId);S&&(v.clockRate=S.clockRate,v.mimeType=S.mimeType,v.payloadType=S.payloadType)}if(!f.connection.id&&m.transportId){const S=c.get(m.transportId);if(S&&S.selectedCandidatePairId){const R=c.get(S.selectedCandidatePairId);f.connection=k(R,c)}}f.remote[C].inbound.push({...m,...v});break}case"remote-outbound-rtp":{if(!a.remote)break;const C=m.mediaType||m.kind,v={};if(!["audio","video"].includes(C))continue;if(m.codecId){const S=c.get(m.codecId);S&&(v.clockRate=S.clockRate,v.mimeType=S.mimeType,v.payloadType=S.payloadType)}f.remote[C].outbound.push({...m,...v});break}}if(!f.connection.id)for(const m of c.values())m.type==="candidate-pair"&&m.nominated&&m.state==="succeeded"&&(f.connection=k(m,c));return f=function(m,C){return C&&(m.audio.inbound.map(v=>{let S=C.audio.inbound.find(R=>R.id===v.id);v.bitrate=T(v,S,"bytesReceived"),v.packetRate=T(v,S,"packetsReceived")}),m.audio.outbound.map(v=>{let S=C.audio.outbound.find(R=>R.id===v.id);v.bitrate=T(v,S,"bytesSent"),v.packetRate=T(v,S,"packetsSent")}),m.video.inbound.map(v=>{let S=C.video.inbound.find(R=>R.id===v.id);v.bitrate=T(v,S,"bytesReceived"),v.packetRate=T(v,S,"packetsReceived")}),m.video.outbound.map(v=>{let S=C.video.outbound.find(R=>R.id===v.id);v.bitrate=T(v,S,"bytesSent"),v.packetRate=T(v,S,"packetsSent")})),m}(f,d),f}let ee,D={},O=[];e.WebRTCStats=class extends s{constructor(c){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 d={...c};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=d.getStatsInterval||1e3,this.rawStats=!!d.rawStats,this.statsObject=!!d.statsObject,this.filteredStats=!!d.filteredStats,this.shouldWrapGetUserMedia=!!d.wrapGetUserMedia,typeof d.remote=="boolean"&&(this.remote=d.remote),this.debug=!!d.debug,this.logLevel=d.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(c,d){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:c,pc:d})}async addConnection(c){const{pc:d,peerId:a}=c;let{connectionId:f,remote:m}=c;if(m=typeof m=="boolean"?m:this.remote,!(d&&d instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!a)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[a]){if(f&&f in this.peersToMonitor[a])throw new Error(`We are already monitoring connection with id ${f}.`);for(let v in this.peersToMonitor[a]){const S=this.peersToMonitor[a][v];if(S.pc===d)throw new Error(`We are already monitoring peer with id ${a}.`);S.pc.connectionState==="closed"&&this.removeConnection({pc:S.pc})}}const C=d.getConfiguration();return C.iceServers&&C.iceServers.forEach(function(v){delete v.credential}),f||(f=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:a,connectionId:f,data:{options:c,peerConfiguration:C}}),this.monitorPeer({peerId:a,connectionId:f,pc:d,remote:m}),{connectionId:f}}getTimeline(c){return this.timeline=this.timeline.sort((d,a)=>d.timestamp.getTime()-a.timestamp.getTime()),c?this.timeline.filter(d=>d.tag===c):this.timeline}get logger(){const c=d=>{const a=["none","error","warn","info","debug"];return a.slice(0,a.indexOf(this.logLevel)+1).indexOf(d)>-1};return{error(...d){this.debug&&c("error")&&console.error("[webrtc-stats][error] ",...d)},warn(...d){this.debug&&c("warn")&&console.warn("[webrtc-stats][warn] ",...d)},info(...d){this.debug&&c("info")&&console.log("[webrtc-stats][info] ",...d)},debug(...d){this.debug&&c("debug")&&console.debug("[webrtc-stats][debug] ",...d)}}}removeConnection(c){let d,{connectionId:a,pc:f}=c;if(!f&&!a)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(a){if(typeof a!="string")throw new Error("connectionId must be a string.");for(let m in this.peersToMonitor)a in this.peersToMonitor[m]&&(f=this.peersToMonitor[m][a].pc,d=m)}else if(f){if(!(f instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let m in this.peersToMonitor)for(let C in this.peersToMonitor[m])this.peersToMonitor[m][C].pc===f&&(a=C,d=m)}if(!f||!a)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(a,f),delete this.peersToMonitor[d][a],Object.values(this.peersToMonitor[d]).length===0&&delete this.peersToMonitor[d],{connectionId:a}}removeAllPeers(){for(let c in this.peersToMonitor)this.removePeer(c)}removePeer(c){if(this.logger.info(`Removing PeerConnection with id ${c}.`),this.peersToMonitor[c]){for(let d in this.peersToMonitor[c]){let a=this.peersToMonitor[c][d].pc;this.removePeerConnectionEventListeners(d,a)}delete this.peersToMonitor[c]}}destroy(){this.removeAllPeers(),O.forEach(c=>{this.removeTrackEventListeners(c)}),O=[],this.shouldWrapGetUserMedia&&ee&&(navigator.mediaDevices.getUserMedia=ee)}monitorPeer(c){let{peerId:d,connectionId:a,pc:f,remote:m}=c;if(!f)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const C={pc:f,connectionId:a,stream:null,stats:{parsed:null,raw:null},options:{remote:m}};if(this.peersToMonitor[d]){if(a in this.peersToMonitor[d])return void this.logger.warn(`Already watching connection with ID ${a}`);this.peersToMonitor[d][a]=C}else this.peersToMonitor[d]={[a]:C};this.addPeerConnectionEventListeners(d,a,f),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(c=>{c.forEach(d=>{this.emitEvent(d)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(c=null){this.logger.info(c?`Getting stats from peer ${c}`:"Getting stats from all peers");let d={};if(c){if(!this.peersToMonitor[c])throw new Error(`Cannot get stats. Peer with id ${c} does not exist`);d[c]=this.peersToMonitor[c]}else d=this.peersToMonitor;let a=[];for(const f in d)for(const m in d[f]){const C=d[f][m],v=C.pc;if(v&&!this.checkIfConnectionIsClosed(f,m,v))try{const S=this.getTimestamp(),R=v.getStats(null);if(R){const P=await R,J=this.getTimestamp(),B=L(P),se={remote:C.options.remote},X=K(P,C.stats.parsed,se),$={event:"stats",tag:"stats",peerId:f,connectionId:m,timeTaken:J-S,data:X};this.rawStats===!0&&($.rawStats=P),this.statsObject===!0&&($.statsObject=B),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(B)),a.push($),C.stats.parsed=X}else this.logger.error(`PeerConnection from peer ${f} did not return any stats data`)}catch(S){this.logger.error(S)}}return a}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const c in this.peersToMonitor)for(const d in this.peersToMonitor[c]){const a=this.peersToMonitor[c][d].pc;this.checkIfConnectionIsClosed(c,d,a)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(c,d,a){const f=this.isConnectionClosed(a);if(f){this.removeConnection({pc:a});let m=a.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:m,peerId:c,connectionId:d,tag:"connection",data:"closed"})}return f}isConnectionClosed(c){return c.connectionState==="closed"||c.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."),ee=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const c=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return c({constraints:arguments[0]}),ee.apply(navigator.mediaDevices,arguments).then(d=>(c({stream:d}),d),d=>(c({error:d}),Promise.reject(d)))}).bind(navigator.mediaDevices)}filteroutStats(c={}){const d={...c};for(const f in d){var a=d[f];this.statsToMonitor.includes(a.type)||delete d[f]}return d}get peerConnectionListeners(){return{icecandidate:(c,d,a,f)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",f),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:c,connectionId:d,data:f.candidate})},track:(c,d,a,f)=>{this.logger.debug(`[pc-event] track | peerId: ${c}`,f);const m=f.track,C=f.streams[0];c in this.peersToMonitor&&d in this.peersToMonitor[c]&&(this.peersToMonitor[c][d].stream=C),this.addTrackEventListeners(m,d),this.emitEvent({event:"ontrack",tag:"track",peerId:c,connectionId:d,data:{stream:C?this.getStreamDetails(C):null,track:m?this.getMediaTrackDetails(m):null,title:f.track.kind+":"+f.track.id+" "+f.streams.map(function(v){return"stream:"+v.id})}})},signalingstatechange:(c,d,a)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${c}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:c,connectionId:d,data:{signalingState:a.signalingState,localDescription:a.localDescription,remoteDescription:a.remoteDescription}})},iceconnectionstatechange:(c,d,a)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${c}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:c,connectionId:d,data:a.iceConnectionState})},icegatheringstatechange:(c,d,a)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${c}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:c,connectionId:d,data:a.iceGatheringState})},icecandidateerror:(c,d,a,f)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${c}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:c,connectionId:d,error:{errorCode:f.errorCode}})},connectionstatechange:(c,d,a)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${c}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:c,connectionId:d,data:a.connectionState})},negotiationneeded:(c,d,a)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${c}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:c,connectionId:d})},datachannel:(c,d,a,f)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${c}`,f),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:c,connectionId:d,data:f.channel})}}}addPeerConnectionEventListeners(c,d,a){this.logger.debug(`Adding event listeners for peer ${c} and connection ${d}.`),D[d]={},Object.keys(this.peerConnectionListeners).forEach(f=>{D[d][f]=this.peerConnectionListeners[f].bind(this,c,d,a),a.addEventListener(f,D[d][f],!1)})}parseGetUserMedia(c){try{const d={event:"getUserMedia",tag:"getUserMedia",data:{...c}};c.stream&&(d.data.details=this.parseStream(c.stream),c.stream.getTracks().map(a=>{this.addTrackEventListeners(a),O.push(a)})),this.emitEvent(d)}catch{}}parseStream(c){const d={audio:[],video:[]};return c.getTracks().forEach(a=>{d[a.kind].push(this.getMediaTrackDetails(a))}),d}getMediaTrackDetails(c){return{enabled:c.enabled,id:c.id,contentHint:c.contentHint,kind:c.kind,label:c.label,muted:c.muted,readyState:c.readyState,constructorName:c.constructor.name,capabilities:c.getCapabilities?c.getCapabilities():{},constraints:c.getConstraints?c.getConstraints():{},settings:c.getSettings?c.getSettings():{},_track:c}}getStreamDetails(c){return{active:c.active,id:c.id,_stream:c}}getTrackEventObject(c){return{mute:d=>{this.emitEvent({event:"mute",tag:"track",connectionId:c,data:{event:d}})},unmute:d=>{this.emitEvent({event:"unmute",tag:"track",connectionId:c,data:{event:d}})},overconstrained:d=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:c,data:{event:d}})},ended:d=>{this.emitEvent({event:"ended",tag:"track",connectionId:c,data:{event:d}}),this.removeTrackEventListeners(d.target)}}}addTrackEventListeners(c,d){D[c.id]={};const a=this.getTrackEventObject(d);Object.keys(a).forEach(f=>{D[c.id][f]=a[f].bind(this),c.addEventListener(f,D[c.id][f])}),D[c.id].readyState=setInterval(()=>{if(c.readyState==="ended"){let f=new CustomEvent("ended",{detail:{check:"readyState"}});c.dispatchEvent(f)}},1e3)}removeTrackEventListeners(c){if(c.id in D){const d=this.getTrackEventObject();Object.keys(d).forEach(a=>{c.removeEventListener(a,D[c.id][a])}),clearInterval(D[c.id].readyState),delete D[c.id]}}addToTimeline(c){this.timeline.push(c),this.emit("timeline",c)}emitEvent(c){const d={...c,timestamp:new Date};this.addToTimeline(d),d.tag&&this.emit(d.tag,d)}set getStatsInterval(c){if(!Number.isInteger(c))throw new Error(`getStatsInterval should be an integer, got: ${c}`);this._getStatsInterval=c,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(c,d){c in D&&(Object.keys(this.peerConnectionListeners).forEach(a=>{d.removeEventListener(a,D[c][a],!1)}),delete D[c]),d.getSenders().forEach(a=>{a.track&&this.removeTrackEventListeners(a.track)}),d.getReceivers().forEach(a=>{a.track&&this.removeTrackEventListeners(a.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const c=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const d=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),a=function(){return c.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),d.apply(navigator.mediaDevices,arguments).then(function(f){return f},function(f){return c.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,f.name),Promise.reject(f)})};navigator.mediaDevices.getDisplayMedia=a.bind(navigator.mediaDevices)}}}});(Zt=ms)&&Zt.__esModule&&Object.prototype.hasOwnProperty.call(Zt,"default")&&Zt.default;var qo=ms.WebRTCStats;function Vo(i){const{packetsLost:e,packetsReceived:t,jitter:n,rtt:s}=i,o=function(u){const{jitter:_,rtt:p}=u,b=_+p/2;return .024*b+.11*(b-177.3)*(b>177.3?1:0)}({rtt:s,jitter:n}),r=function(u){const{packetsLost:_,packetsReceived:p}=u,b=_/(p+_)*100;return 20*Math.log(1+b)}({packetsLost:e,packetsReceived:t}),l=93.2-o-r+0,h=1+.035*l+7e-6*l*(l-60)*(100-l);return Math.min(Math.max(h,1),5)}function Wo(i){return isNaN(i)?null:i>4.2?"excellent":i>=4.1&&i<=4.2?"good":i>=3.7&&i<=4?"fair":i>=3.1&&i<=3.6?"poor":"bad"}class Xo extends Wt{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class Yo extends Wt{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class Ko extends Wt{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function Jo(i){const e=Ct(),t=new qo({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),n=s=>U(this,void 0,void 0,function*(){s.event==="stats"&&W(M.StatsFrame,function({data:o}){var r,l,h,u,_,p,b,g;const{audio:x,remote:E}=o,{audio:y}=E,w=(l=(r=y.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&l!==void 0?l:1/0,k=(u=(h=y.inbound[0])===null||h===void 0?void 0:h.roundTripTime)!==null&&u!==void 0?u:1/0,T=(p=(_=x.inbound[0])===null||_===void 0?void 0:_.packetsReceived)!==null&&p!==void 0?p:-1,L=(g=(b=x.inbound[0])===null||b===void 0?void 0:b.packetsLost)!==null&&g!==void 0?g:-1,K=Vo({jitter:1e3*w,rtt:1e3*k,packetsLost:L,packetsReceived:T});return{jitter:w,rtt:k,mos:K,quality:Wo(K),inboundAudio:x.inbound[0],outboundAudio:x.outbound[0],remoteInboundAudio:y.inbound[0],remoteOutboundAudio:y.outbound[0]}}(s),i.uuid),yield i.execute(new Ko(e,s))});return{start:(s,o,r)=>U(this,void 0,void 0,function*(){yield i.execute(new Xo(e)),t.on("timeline",n),yield new Promise(l=>setTimeout(l,500)),t.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>U(this,void 0,void 0,function*(){const o=t.getTimeline();W(M.StatsReport,o,i.uuid),s==="file"&&function(r,l){const h=new Blob([JSON.stringify(r)],{type:"application/json"}),u=URL.createObjectURL(h),_=document.createElement("a");_.href=u,_.download=`${l}.json`,_.click(),URL.revokeObjectURL(u)}(o,`webrtc-stats-${e}-${Date.now()}`),yield i.execute(new Yo(e)),t.removeAllPeers(),t.destroy()})}}class vs{constructor(e,t,n){this.type=e,this.options=t,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=s=>U(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State`,o),o==="failed"||o==="disconnected"){const r=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",r)};if(navigator.onLine)return r();window.addEventListener("online",r)}}),this._handleIceConnectionStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=s=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return s.setCodecPreferences?s.setCodecPreferences(this.options.preferred_codecs):void 0},N.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=n,this._init(),this.isDebugEnabled&&(this.statsReporter=Jo(n))}get isOffer(){return this.type===Ce.Offer}get isAnswer(){return this.type===Ce.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(){N.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,t)=>{N.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),N.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(e){switch(N.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(){N.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=t,s===!1&&Yt(n,o)}createPeerConnection(){return U(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",t=>{this.options.remoteStream=t.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(t=>(W(M.MediaError,t,this.options.id),null))})}_init(){var e;return U(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:t,localStream:n=null,screenShare:s=!1}=this.options;if(Xt(n)){const o=n.getAudioTracks();N.info("Local audio tracks: ",o);const r=n.getVideoTracks();if(N.info("Local video tracks: ",r),this.isOffer&&typeof this.instance.addTransceiver=="function"){const l={direction:"sendrecv",streams:[n]};o.forEach(h=>{this.options.userVariables.microphoneLabel=h.label;const u=this.instance.addTransceiver(h,l);this._setAudioCodec(u)}),console.debug("Applying video transceiverParams",l),r.forEach(h=>{this.options.userVariables.cameraLabel=h.label,this.instance.addTransceiver(h,l)})}else typeof this.instance.addTrack=="function"?(o.forEach(l=>{this.options.userVariables.microphoneLabel=l.label,this.instance.addTrack(l,n)}),this.instance.getTransceivers().forEach(l=>this._setAudioCodec(l)),r.forEach(l=>{this.options.userVariables.cameraLabel=l.label,this.instance.addTrack(l,n)})):this.instance.addStream(n);s===!1&&((l=>{const h=xt(l);h&&(h.muted=!0)})(t),Yt(t,n))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:t})=>t&&t.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);N.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,N.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(e=>N.error("Peer _createOffer error:",e)))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=Ei(e.sdp)),this.instance.localDescription&&(e.sdp=as(e.sdp,this.instance.localDescription.sdp));const t=e;return N.info(`REMOTE SDP
|
|
15
|
+
`,`Type: ${e.type}`,`
|
|
16
|
+
|
|
17
|
+
`,e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return U(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:Ce.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ce.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)})}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:s,googleStartBitrate:o,mediaSettings:r}=this.options;return t&&(e.sdp=Ei(e.sdp)),n&&s&&o&&(e.sdp=((l,h,u,_)=>{const p=l.split(`\r
|
|
18
|
+
`);return p.forEach((b,g)=>{/^a=fmtp:\d*/.test(b)?p[g]+=`;x-google-max-bitrate=${h};x-google-min-bitrate=${u};x-google-start-bitrate=${_}`:/^a=mid:(1|video)/.test(b)&&(p[g]+=`\r
|
|
19
|
+
b=AS:${h}`)}),p.join(`\r
|
|
20
|
+
`)})(e.sdp,n,s,o)),r&&r.useSdpASBandwidthKbps&&r.sdpASBandwidthKbps!==null&&(e.sdp=((l,h)=>{let u="AS",_=h;return!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(u="TIAS",_=1e3*(h>>>0)),l.indexOf("b="+u+":")===-1?l.replace(/c=IN (.*)\r\n/,`c=IN $1\r
|
|
21
|
+
b=`+u+":"+_+`\r
|
|
22
|
+
`):l.replace(new RegExp("b="+u+`:.*\r
|
|
23
|
+
`),"b="+u+":"+_+`\r
|
|
24
|
+
`)})(e.sdp,r.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){at(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(Xt(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,U(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s}=t;const{micLabel:o=""}=t;s&&(s=yield Jt(s,o,De.AudioIn).catch(u=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s}));let{camId:r}=t,l=t.video;const{camLabel:h=""}=t;return r&&(r=yield Jt(r,h,De.Video).catch(u=>null),r&&(typeof l=="boolean"&&(l={}),l.deviceId={exact:r})),{audio:n,video:l}}));var t;return Kt(e)})}_isOffer(){return this.type===Ce.Offer}_isAnswer(){return this.type===Ce.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:t,forceRelayCandidate:n}=this.options,s={bundlePolicy:"max-compat",iceCandidatePoolSize:t?10:0,iceServers:e,iceTransportPolicy:n?"relay":"all"};return N.info("RTC config",s),s}close(){var e;return U(this,void 0,void 0,function*(){yield(e=this.statsReporter)===null||e===void 0?void 0:e.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const Qo=Ri;class bs{constructor(e,t){this.session=e,this.id="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=It.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._checkConferenceSerno=y=>{const w=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return w&&y>=0&&(this._lastSerno=y),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(w=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(var T in k.constraints)if(k.constraints.hasOwnProperty(T)&&k.constraints[T]!==w[T])return}k.callback(w)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:l,camLabel:h,localElement:u,remoteElement:_,options:p,mediaConstraints:{audio:b,video:g},ringtoneFile:x,ringbackFile:E}=e;this.options=Object.assign({},ko,{audio:b,video:g,iceServers:n,localElement:u,remoteElement:_,micId:o,micLabel:r,camId:l,camLabel:h,speakerId:s,ringtoneFile:x,ringbackFile:E,debug:p.debug,debugOutput:p.debugOutput},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=hs(this.options.ringtoneFile,"_ringtone"),this._ringback=hs(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}invite(){this.direction=je.Outbound,this.peer=new vs(Ce.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var t,n,s,o;this.stopRingtone(),this.options.video=(n=(t=e.video)!==null&&t!==void 0?t:this.options.video)!==null&&n!==void 0&&n,this.direction=je.Inbound,((s=e==null?void 0:e.customHeaders)===null||s===void 0?void 0:s.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),((o=e.preferred_codecs)===null||o===void 0?void 0:o.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new vs(Ce.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){us(this._ringtone)}stopRingtone(){ps(this._ringtone)}playRingback(){us(this._ringback)}stopRingback(){ps(this._ringback)}hangup(e,t){var n,s,o;let r=e||{},l=t!==!1;this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],this.setState(z.Hangup);const h=()=>{var u;return(u=this.peer)===null||u===void 0||u.close(),this.setState(z.Destroy)};if(this.stopRingtone(),this.stopRingback(),l){const u=new Ho({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(u).catch(_=>{N.error("telnyx_rtc.bye failed!",_),W(M.Error,{error:_,sessionId:this.session.sessionid},this.session.uuid)}).then(h.bind(this))}else h()}hold(){const e=new Li({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Li({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Li({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new _s({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},s=new _s({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){cs(this.options.localStream)}unmuteAudio(){ls(this.options.localStream)}toggleAudioMute(){ds(this.options.localStream)}setAudioInDevice(e){return U(this,void 0,void 0,function*(){const{instance:t}=this.peer,n=t.getSenders().find(({track:{kind:s}})=>s==="audio");if(n){const s=yield Ii({audio:{deviceId:{exact:e}}}),o=s.getAudioTracks()[0];n.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach(l=>l.stop()),r.getVideoTracks().forEach(l=>s.addTrack(l)),this.options.localStream=s}})}muteVideo(){var e;e=this.options.localStream,ht(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,ht(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,ht(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:t}=this.peer,n=t.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield Ii({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:l}=this.options;Yt(r,s),this.options.camId=e,l.getAudioTracks().forEach(h=>s.addTrack(h)),l.getVideoTracks().forEach(h=>h.stop()),this.options.localStream=s}})}deaf(){cs(this.options.remoteStream)}undeaf(){ls(this.options.remoteStream)}toggleDeaf(){ds(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void N.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void N.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===t);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),N.info("Parameters: ",r),N.info("Setting max ",t==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{N.info(t==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(l=>console.error(l))}else N.error("Could not set bandwidth (reason: no "+t+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),N.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Oe.callUpdate,call:this}),e){case z.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case z.Active:setTimeout(()=>{const{remoteElement:t,speakerId:n}=this.options;t&&n&&ts(t,n)},0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case Z.Answer:if(this.gotAnswer=!0,this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Z.Media:if(this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Z.Display:case Z.Attach:{const{display_name:o,display_number:r,display_direction:l}=n;this.extension=r;const h=l===je.Inbound?je.Outbound:je.Inbound,u={type:Oe[t],call:this,displayName:o,displayNumber:r,displayDirection:h};W(M.Notification,u,this.id)||W(M.Notification,u,this.session.uuid);break}case Z.Info:case Z.Event:{const o=Object.assign(Object.assign({},n),{type:Oe.generic,call:this});W(M.Notification,o,this.id)||W(M.Notification,o,this.session.uuid);break}case Z.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Z.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,t){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return N.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:l,infoChannel:h,modChannel:u,laName:_,conferenceMemberID:p,role:b}=t;this._dispatchConferenceUpdate({action:ve.Join,conferenceName:_,participantId:Number(p),role:b}),l&&(yield this._subscribeConferenceChat(l)),h&&(yield this._subscribeConferenceInfo(h)),u&&b===It.Moderator&&(yield this._subscribeConferenceModerator(u));const g=[];for(const x in s)g.push(Object.assign({callId:s[x][0],index:Number(x)},qt(s[x][1])));this._dispatchConferenceUpdate({action:ve.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ve.Add,callId:o,index:r},qt(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ve.Modify,callId:o,index:r},qt(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ve.Delete,callId:o,index:r},qt(s)));break;case"clear":this._dispatchConferenceUpdate({action:ve.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const t={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:l,message:h,type:u}=s.data;this._dispatchConferenceUpdate({action:ve.ChatMessage,direction:o,participantNumber:r,participantName:l,messageText:h,messageType:u,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch(s=>{N.error("ConfChat subscription error:",s)});Qt(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const t={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,gs(this.session,o)):N.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(t).catch(s=>{N.error("ConfInfo subscription error:",s)});Qt(n,e)&&this._addChannel(e)})}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return U(this,void 0,void 0,function*(){const t=(r,l=null,h=null)=>{const u=parseInt(l)||null;this._confControl(e,{command:r,id:u,value:h})},n=()=>{const{video:r}=this.options;if(typeof r=="boolean"&&!r||typeof r=="object"&&qn(r))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[e],handler:r=>{const{data:l}=r;if(l["conf-command"]==="list-videoLayouts"){if(l.responseData){const h=JSON.stringify(l.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:ve.LayoutList,layouts:JSON.parse(h)})}}else this._dispatchConferenceUpdate({action:ve.ModCmdResponse,command:l["conf-command"],response:l.response})}},o=yield this.session.vertoSubscribe(s).catch(r=>{N.error("ConfMod subscription error:",r)});Qt(o,e)&&(this.role=It.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:r=>{t("play",null,r)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:r=>{t("deaf",r)}},undeaf:{configurable:!0,value:r=>{t("undeaf",r)}},startRecord:{configurable:!0,value:r=>{t("recording",null,["start",r])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:r=>{n(),t("vid-write-png",null,r)}},setVideoLayout:{configurable:!0,value:(r,l)=>{n(),t("vid-layout",null,l?[r,l]:r)}},kick:{configurable:!0,value:r=>{t("kick",r)}},muteMic:{configurable:!0,value:r=>{t("tmute",r)}},muteVideo:{configurable:!0,value:r=>{n(),t("tvmute",r)}},presenter:{configurable:!0,value:r=>{n(),t("vid-res-id",r,"presenter")}},videoFloor:{configurable:!0,value:r=>{n(),t("vid-floor",r,"force")}},banner:{configurable:!0,value:(r,l)=>{n(),t("vid-banner",r,encodeURI(l))}},volumeDown:{configurable:!0,value:r=>{t("volume_out",r,"down")}},volumeUp:{configurable:!0,value:r=>{t("volume_out",r,"up")}},gainDown:{configurable:!0,value:r=>{t("volume_in",r,"down")}},gainUp:{configurable:!0,value:r=>{t("volume_in",r,"up")}},transfer:{configurable:!0,value:(r,l)=>{t("transfer",r,l)}}}))})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){return N.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=as(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=Ei(t));const n={sdp:t,type:Ce.Answer};this.peer.instance.setRemoteDescription(n).then(()=>{this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(s=>{N.error("Call setRemoteDescription Error: ",s),this.hangup()})}_requestAnotherLocalDescription(){at(this.peer.onSdpReadyTwice)?W(M.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return N.info(`No candidate - retry
|
|
25
|
+
`),void this._requestAnotherLocalDescription();(n=(t=this.peer)===null||t===void 0?void 0:t.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce);let r=null;const l={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${Qo}`};switch(o){case Ce.Offer:this.setState(z.Requesting),r=new Bo(l);break;case Ce.Answer:this.setState(z.Answering),r=this.options.attach===!0?new Fo(l):new $o(l);break;default:return N.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(r).then(h=>{const{node_id:u=null}=h;this._targetNodeId=u,o===Ce.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(h=>{N.error(`${this.id} - Sending ${o} error:`,h),this.hangup()}),console.timeEnd(jn)}_onIce(e){const{instance:t}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(t.localDescription),1e3)),e.candidate?N.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=t=>{this._iceDone||this._onIce(t)},e.addEventListener("addstream",t=>{this.options.remoteStream=t.stream}),e.addEventListener("track",t=>{this.options.remoteStream=t.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&Yt(n,s)})}_onMediaError(e){this._dispatchNotification({type:Oe.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Oe.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(W(M.Notification,e,this.id,!1)||W(M.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:n,onNotification:s}=this.options;e||(this.options.id=Ct()),this.id=this.options.id,t&&!qn(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,ct(M.MediaError,this._onMediaError,this.id),at(s)&&ct(M.Notification,s.bind(this),this.id),this.setState(z.New),N.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;Et(e),Et(t),dt(M.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),N.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),N.info("Stats stopped")}}bs.setStateTelnyx=i=>{if(i){switch(i._state){case z.Requesting:case z.Recovering:case z.Trying:case z.Early:i.state="connecting";break;case z.Active:i.state="active";break;case z.Held:i.state="held";break;case z.Hangup:case z.Destroy:i.state="done";break;case z.Answering:i.state="ringing";break;case z.New:i.state="new"}return i}};class Ye extends bs{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof Ye&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return U(this,void 0,void 0,function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach(u=>{u.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:l}=this.options,h=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${l} (Screen)`},e);return this.screenShare=new Ye(this.session,h),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Ye&&this.screenShare.hangup()}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&ts(t,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);N.setLevel(2),this._statsInterval=window.setInterval(()=>U(this,void 0,void 0,function*(){const t=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];t.forEach(r=>{s.includes(r.type)||(n+=`
|
|
26
|
+
${r.type}
|
|
27
|
+
`,Object.keys(r).forEach(l=>{o.includes(l)||(n+=` ${l}: ${r[l]}
|
|
28
|
+
`)}))}),N.info(n)}),2e3)}}class Zo extends No{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 U(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,t=!0){return U(this,void 0,void 0,function*(){try{const n=yield Kt({audio:e,video:t});return Et(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(t=>this.calls[t].setState(z.Purge)),this.calls={},yield e.disconnect.call(this)})}speedTest(e){return new Promise((t,n)=>{if(Jn(M.SpeedTest,r=>{const{upDur:l,downDur:h}=r,u=h?8*e/(h/1e3)/1024:0;t({upDur:l,downDur:h,upKps:(l?8*e/(l/1e3)/1024:0).toFixed(0),downKps:u.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Tt().catch(e=>(W(M.MediaError,e,this.uuid),[]))}getVideoDevices(){return Tt(De.Video).catch(e=>(W(M.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Tt(De.AudioIn).catch(e=>(W(M.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Tt(De.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),W(M.MediaError,e,this.uuid),[]))}validateDeviceId(e,t,n){return Jt(e,t,n)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(t=>U(void 0,void 0,void 0,function*(){const n=[],s=yield Kt({video:{deviceId:{exact:t}}}),o=s.getVideoTracks()[0];for(let r=0;r<is.length;r++){const[l,h]=is[r];(yield o.applyConstraints({width:{exact:l},height:{exact:h}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${l}x${h}`,width:l,height:h})}return Et(s),n}))(e)}catch(t){throw t}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:t,micLabel:n}=e,s=yi(e,["micId","micLabel"]);return ns(s),this._audioConstraints=yield ss(t,n,"audioinput",s),this.micId=t,this.micLabel=n,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:t,camLabel:n}=e,s=yi(e,["camId","camLabel"]);return ns(s),this._videoConstraints=yield ss(t,n,"videoinput",s),this.camId=t,this.camLabel=n,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[t]:[]:e||[So,wo,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=xt(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=xt(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const s=new Uo({sessid:this.sessionid,eventChannel:t,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:t=[],handler:n}){return U(this,void 0,void 0,function*(){if(!(t=t.filter(h=>h&&!this._existsSubscription(this.relayProtocol,h))).length)return{};const s=new Go({sessid:this.sessionid,eventChannel:t});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:l=[]}=Ti(o);return r.length&&r.forEach(h=>this._removeSubscription(this.relayProtocol,h)),l.forEach(h=>this._addSubscription(this.relayProtocol,n,h)),o})}vertoUnsubscribe({nodeId:e,channels:t=[]}){return U(this,void 0,void 0,function*(){if(!(t=t.filter(l=>l&&this._existsSubscription(this.relayProtocol,l))).length)return{};const n=new jo({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Ti(s);return o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),s})}static telnyxStateCall(e){return Ye.setStateTelnyx(e)}}class ys{constructor(e,t){this.code=t,this.message=e}}class er extends xe{constructor(){super(),this.method=Z.Ping,this.buildRequest({method:this.method,params:{}})}}class Te{constructor(e){this.session=e}_ack(e,t){const n=new Po(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*Xn(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:s,params:o={}}=e,r=o==null?void 0:o.callID,l=o==null?void 0:o.eventChannel,h=o==null?void 0:o.eventType,u=s===Z.Attach;if(h==="channelPvtData")return this._handlePvtEvent(o.pvtData);if(r&&t.calls.hasOwnProperty(r)){if(!u)return t.calls[r].handleMessage(e),void this._ack(n,s);t.calls[r].hangup({},!1)}const _=()=>{var g,x,E,y;const w={id:r,remoteSdp:o.sdp,destinationNumber:o.callee_id_number,remoteCallerName:o.caller_id_name,remoteCallerNumber:o.caller_id_number,callerName:o.callee_id_name,callerNumber:o.callee_id_number,attach:u,mediaSettings:o.mediaSettings,debug:(g=t.options.debug)!==null&&g!==void 0&&g,debugOutput:(x=t.options.debugOutput)!==null&&x!==void 0?x:"socket",prefetchIceCandidates:(E=t.options.prefetchIceCandidates)!==null&&E!==void 0&&E,forceRelayCandidate:(y=t.options.forceRelayCandidate)!==null&&y!==void 0&&y};o.telnyx_call_control_id&&(w.telnyxCallControlId=o.telnyx_call_control_id),o.telnyx_session_id&&(w.telnyxSessionId=o.telnyx_session_id),o.telnyx_leg_id&&(w.telnyxLegId=o.telnyx_leg_id),o.client_state&&(w.clientState=o.client_state),o.dialogParams&&o.dialogParams.custom_headers&&o.dialogParams.custom_headers.length&&(w.customHeaders=o.dialogParams.custom_headers);const k=new Ye(t,w);return k.nodeId=this.nodeId,k},p=new es,b=new er;switch(s){case Z.Ping:this.session.execute(b);break;case Z.Punt:t.disconnect();break;case Z.Invite:{const E=_();E.playRingtone(),E.setState(z.Ringing),E.direction=je.Inbound,this._ack(n,s);break}case Z.Attach:{const E=_();this.session.autoRecoverCalls?E.answer():E.setState(z.Recovering),E.handleMessage(e);break}case Z.Event:case"webrtc.event":if(!l)return void N.error("Verto received an unknown event:",o);const g=t.relayProtocol,x=l.split(".")[0];t._existsSubscription(g,l)?W(g,o,l):l===t.sessionid?this._handleSessionEvent(o.eventData):t._existsSubscription(g,x)?W(g,o,x):t.calls.hasOwnProperty(l)?t.calls[l].handleMessage(e):W(M.Notification,o,t.uuid);break;case Z.Info:o.type=Oe.generic,W(M.Notification,o,t.uuid);break;case Z.ClientReady:this.session.execute(p);break;default:{const E=Si(e);if(E){switch(E){case be.REGISTER:case be.REGED:t.connection.previousGatewayState!==be.REGED&&t.connection.previousGatewayState!==be.REGISTER&&(Te.retriedRegister=0,o.type=Oe.vertoClientReady,W(M.Ready,o,t.uuid));break;case be.UNREGED:case be.NOREG:if(Te.retriedRegister+=1,Te.retriedRegister===5){Te.retriedRegister=0,W(M.Error,{error:new ys("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:t.sessionid},t.uuid);break}setTimeout(()=>{this.session.execute(p)},this.reconnectDelay());break;case be.FAILED:case be.FAIL_WAIT:if(t.connection.previousGatewayState!==be.FAILED&&t.connection.previousGatewayState!==be.FAIL_WAIT){if(!this.session.hasAutoReconnect()){Te.retriedConnect=0,W(M.Error,{error:new ys("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:t.sessionid},t.uuid);break}if(Te.retriedConnect+=1,Te.retriedConnect===5){Te.retriedConnect=0,W(M.Error,{error:new Error("Connection Retry Failed"),sessionId:t.sessionid},t.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:N.warn("GatewayState message unknown method:",e)}break}N.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(t));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(this,void 0,void 0,function*(){const{session:t}=this,n=t.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:l,infoChannel:h,modChannel:u,conferenceMemberID:_,role:p,callID:b}=e;switch(s){case"conference-liveArray-join":{const g=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},x={nodeId:this.nodeId,channels:[o],handler:({data:y})=>{const w=b||this._retrieveCallId(y,o);if(w&&t.calls.hasOwnProperty(w)){const k=t.calls[w];k._addChannel(o),k.extension=r,k.handleConferenceUpdate(y,e).then(T=>{T==="INVALID_PACKET"&&g()})}}},E=yield t.vertoSubscribe(x).catch(y=>{N.error("liveArray subscription error:",y)});Qt(E,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&t._existsSubscription(n,o)){const{callId:E=null}=t.subscriptions[n][o];if(g=t.calls[E]||null,E!==null){const y={type:Oe.conferenceUpdate,action:ve.Leave,conferenceName:r,participantId:Number(_),role:p};W(M.Notification,y,E,!1)||W(M.Notification,y,t.uuid),g===null&&dt(M.Notification,null,E)}}const x=[o,l,h,u];t.vertoUnsubscribe({nodeId:this.nodeId,channels:x}).then(({unsubscribedChannels:E=[]})=>{g&&(g.channels=g.channels.filter(y=>!E.includes(y)))}).catch(E=>{N.error("liveArray unsubscribe error:",E)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":gs(this.session,e);break;case"logo-info":{const t={type:Oe.conferenceUpdate,action:ve.LogoInfo,logo:e.logoURL};W(M.Notification,t,this.session.uuid);break}}}}Te.retriedConnect=0,Te.retriedRegister=0;class tr extends xe{constructor(e,t,n,s={},o){super(),this.method="anonymous_login";const r={target_type:e,target_id:t,userVariables:s,reconnection:o,"User-Agent":{sdkVersion:Ri,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class ir extends Zo{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{login:t,password:n,passwd:s,login_token:o,userVariables:r,autoReconnect:l=!0}=this.options,h=new Do(t,n||s,o,this.sessionid,r,!!ki()),u=yield this.execute(h).catch(this._handleLoginError);u&&(this._autoReconnect=l,this.sessionid=u.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:t}=this.options,{target_type:n,target_id:s}=t,o=new tr(n,s,this.sessionid,this.options.userVariables,!!ki()),r=yield this.execute(o).catch(this._handleLoginError);r&&(this.sessionid=r.sessid)}),window.addEventListener("beforeunload",t=>{this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&this.calls[n].hangup({},!0)})})}validateOptions(){return wi(this.options)||Vt(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(jn);const t=new Ye(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Vt(this.options)||!!e.destinationNumber}_onSocketOpen(){return U(this,void 0,void 0,function*(){return wi(this.options)?this.handleLoginOnSocketOpen():Vt(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new Te(this).handleMessage(e)}}class nr extends ir{constructor(e){super(e),console.log(`SDK version: ${fs}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Oo()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:he.full},{browserName:"Firefox",features:["audio"],supported:he.partial},{browserName:"Safari",supported:he.not_supported},{browserName:"Edge",supported:he.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:he.not_supported},{browserName:"Firefox",supported:he.not_supported},{browserName:"Safari",features:["video","audio"],supported:he.full},{browserName:"Edge",supported:he.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:he.full},{browserName:"Firefox",features:["audio"],supported:he.partial},{browserName:"Safari",supported:he.not_supported},{browserName:"Edge",supported:he.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:he.full},{browserName:"Firefox",features:["audio"],supported:he.partial},{browserName:"Safari",features:["video","audio"],supported:he.full},{browserName:"Edge",features:["audio"],supported:he.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:he.full},{browserName:"Firefox",features:["audio"],supported:he.partial},{browserName:"Safari",supported:he.not_supported},{browserName:"Edge",features:["audio"],supported:he.partial}]}]}}function sr(i){if(!i||typeof i!="object")return!1;const e=i;return e.method==="ai_conversation"&&typeof e.params=="object"}function or(i){if(!i||typeof i!="object")return!1;const e=i;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function rr(i){if(!i||typeof i!="object")return!1;const e=i;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function ar(i){return or(i)?{id:i.params.item_id,role:"assistant",content:i.params.delta,timestamp:new Date}:null}function lr(i){return!rr(i)||i.params.item.role!=="user"||i.params.item.status!=="completed"?null:{id:i.params.item.id,role:i.params.item.role,content:i.params.item.content.map(e=>e.transcript).join(" "),timestamp:new Date}}function cr(i){const[e,t]=yt([]);return nt(()=>{if(!i)return;const n=s=>{if(sr(s))switch(s.params.type){case"response.text.delta":{t(o=>{const r=ar(s);return r?[...o,r]:o});return}case"conversation.item.created":{const o=lr(s);o&&t(r=>[...r,o]);return}}};return i.on(M.SocketMessage,n),()=>{i.off(M.SocketMessage,n)}},[i]),e}function ws(i){var e,t,n="";if(typeof i=="string"||typeof i=="number")n+=i;else if(typeof i=="object")if(Array.isArray(i)){var s=i.length;for(e=0;e<s;e++)i[e]&&(t=ws(i[e]))&&(n&&(n+=" "),n+=t)}else for(t in i)i[t]&&(n&&(n+=" "),n+=t);return n}function Ai(){for(var i,e,t=0,n="",s=arguments.length;t<s;t++)(i=arguments[t])&&(e=ws(i))&&(n&&(n+=" "),n+=e);return n}function dr({item:i}){const e=ui(null);return nt(()=>{e.current&&e.current.scrollIntoView({behavior:"smooth"})},[]),A("li",{className:Ai("flex flex-col gap-1 text-left",{"items-end":i.role==="user"}),ref:e,children:[A("span",{className:"text-xs text-[#969696]",children:i.timestamp.toLocaleTimeString()}),A("p",{className:Ai("text-white text-sm",{"bg-[#222227] px-2.5 py-2 rounded-md":i.role==="user"}),children:i.content})]})}const hr=({transcript:i})=>A("ul",{id:"transcript-log",className:"flex h-[400px] rounded-2xl overflow-y-auto max-h-full flex-col gap-4 w-[360px] max-w-full bg-[#3D3D46] p-4",children:i.map((e,t)=>A(dr,{item:e},e.id+t))}),Ss=({children:i,className:e,onClick:t})=>A("button",{onClick:t,className:Ai("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:i});/**
|
|
2
29
|
* @license lucide-preact v0.515.0 - ISC
|
|
3
30
|
*
|
|
4
31
|
* This source code is licensed under the ISC license.
|
|
5
32
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
33
|
+
*/const Cs=i=>i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ur=i=>i.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),xs=i=>{const e=ur(i);return e.charAt(0).toUpperCase()+e.slice(1)},pr=(...i)=>i.filter((e,t,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===t).join(" ").trim();/**
|
|
7
34
|
* @license lucide-preact v0.515.0 - ISC
|
|
8
35
|
*
|
|
9
36
|
* This source code is licensed under the ISC license.
|
|
10
37
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/var
|
|
38
|
+
*/var fr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
|
|
12
39
|
* @license lucide-preact v0.515.0 - ISC
|
|
13
40
|
*
|
|
14
41
|
* This source code is licensed under the ISC license.
|
|
15
42
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
43
|
+
*/const _r=({color:i="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...l})=>He("svg",{...fr,width:String(e),height:e,stroke:i,"stroke-width":n?Number(t)*24/Number(e):t,class:["lucide",r].join(" "),...l},[...o.map(([h,u])=>He(h,u)),...Ji(s)]);/**
|
|
17
44
|
* @license lucide-preact v0.515.0 - ISC
|
|
18
45
|
*
|
|
19
46
|
* This source code is licensed under the ISC license.
|
|
20
47
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
48
|
+
*/const Rt=(i,e)=>{const t=({class:n="",children:s,...o})=>He(_r,{...o,iconNode:e,class:pr(`lucide-${Cs(xs(i))}`,`lucide-${Cs(i)}`,n)},s);return t.displayName=xs(i),t};/**
|
|
22
49
|
* @license lucide-preact v0.515.0 - ISC
|
|
23
50
|
*
|
|
24
51
|
* This source code is licensed under the ISC license.
|
|
25
52
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
53
|
+
*/const gr=Rt("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
27
54
|
* @license lucide-preact v0.515.0 - ISC
|
|
28
55
|
*
|
|
29
56
|
* This source code is licensed under the ISC license.
|
|
30
57
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
58
|
+
*/const mr=Rt("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
|
|
32
59
|
* @license lucide-preact v0.515.0 - ISC
|
|
33
60
|
*
|
|
34
61
|
* This source code is licensed under the ISC license.
|
|
35
62
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
63
|
+
*/const vr=Rt("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
|
|
37
64
|
* @license lucide-preact v0.515.0 - ISC
|
|
38
65
|
*
|
|
39
66
|
* This source code is licensed under the ISC license.
|
|
40
67
|
* 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:
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
|
48
|
-
`,`Type: ${e.type}`,`
|
|
49
|
-
|
|
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
|
|
51
|
-
`);return p.forEach((b,m)=>{/^a=fmtp:\d*/.test(b)?p[m]+=`;x-google-max-bitrate=${d};x-google-min-bitrate=${h};x-google-start-bitrate=${g}`:/^a=mid:(1|video)/.test(b)&&(p[m]+=`\r
|
|
52
|
-
b=AS:${d}`)}),p.join(`\r
|
|
53
|
-
`)})(e.sdp,i,o,r)),s&&s.useSdpASBandwidthKbps&&s.sdpASBandwidthKbps!==null&&(e.sdp=((c,d)=>{let h="AS",g=d;return!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(h="TIAS",g=1e3*(d>>>0)),c.indexOf("b="+h+":")===-1?c.replace(/c=IN (.*)\r\n/,`c=IN $1\r
|
|
54
|
-
b=`+h+":"+g+`\r
|
|
55
|
-
`):c.replace(new RegExp("b="+h+`:.*\r
|
|
56
|
-
`),"b="+h+":"+g+`\r
|
|
57
|
-
`)})(e.sdp,s.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){ge(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return R(this,void 0,void 0,function*(){if(qe(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,R(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:o}=n;const{micLabel:r=""}=n;o&&(o=yield Je(o,r,ce.AudioIn).catch(h=>null),o&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:o}));let{camId:s}=n,c=n.video;const{camLabel:d=""}=n;return s&&(s=yield Je(s,d,ce.Video).catch(h=>null),s&&(typeof c=="boolean"&&(c={}),c.deviceId={exact:s})),{audio:i,video:c}}));var n;return Ke(e)})}_isOffer(){return this.type===Y.Offer}_isAnswer(){return this.type===Y.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:n,forceRelayCandidate:i}=this.options,o={bundlePolicy:"max-compat",iceCandidatePoolSize:n?10:0,iceServers:e,iceTransportPolicy:i?"relay":"all"};return I.info("RTC config",o),o}close(){var e;return R(this,void 0,void 0,function*(){yield(e=this.statsReporter)===null||e===void 0?void 0:e.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const Wi=vt;class $n{constructor(e,n){this.session=e,this.id="",this.state=M[M.New],this.prevState="",this.channels=[],this.role=Re.Participant,this.extension=null,this._state=M.New,this._prevState=M.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._checkConferenceSerno=y=>{const S=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return S&&y>=0&&(this._lastSerno=y),S},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(S=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(var L in k.constraints)if(k.constraints.hasOwnProperty(L)&&k.constraints[L]!==S[L])return}k.callback(S)}})})})};const{iceServers:i,speaker:o,micId:r,micLabel:s,camId:c,camLabel:d,localElement:h,remoteElement:g,options:p,mediaConstraints:{audio:b,video:m},ringtoneFile:C,ringbackFile:A}=e;this.options=Object.assign({},yi,{audio:b,video:m,iceServers:i,localElement:h,remoteElement:g,micId:r,micLabel:s,camId:c,camLabel:d,speakerId:o,ringtoneFile:C,ringbackFile:A,debug:p.debug,debugOutput:p.debugOutput},n),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=An(this.options.ringtoneFile,"_ringtone"),this._ringback=An(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}invite(){this.direction=de.Outbound,this.peer=new Pn(Y.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var n,i,o,r;this.stopRingtone(),this.options.video=(i=(n=e.video)!==null&&n!==void 0?n:this.options.video)!==null&&i!==void 0&&i,this.direction=de.Inbound,((o=e==null?void 0:e.customHeaders)===null||o===void 0?void 0:o.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),((r=e.preferred_codecs)===null||r===void 0?void 0:r.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new Pn(Y.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){Rn(this._ringtone)}stopRingtone(){Mn(this._ringtone)}playRingback(){Rn(this._ringback)}stopRingback(){Mn(this._ringback)}hangup(e,n){var i,o,r;let s=e||{},c=n!==!1;this.cause=s.cause||"NORMAL_CLEARING",this.causeCode=s.causeCode||16,this.sipCode=s.sipCode||null,this.sipReason=s.sipReason||null,this.sipCallId=s.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(r=(o=s==null?void 0:s.dialogParams)===null||o===void 0?void 0:o.customHeaders)!==null&&r!==void 0?r:[]],this.setState(M.Hangup);const d=()=>{var h;return(h=this.peer)===null||h===void 0||h.close(),this.setState(M.Destroy)};if(this.stopRingtone(),this.stopRingback(),c){const h=new Oi({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(h).catch(g=>{I.error("telnyx_rtc.bye failed!",g),N(E.Error,{error:g,sessionId:this.session.sessionid},this.session.uuid)}).then(d.bind(this))}else d()}hold(){const e=new bt({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new bt({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new bt({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new Ln({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},o=new Ln({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(o)}muteAudio(){En(this.options.localStream)}unmuteAudio(){In(this.options.localStream)}toggleAudioMute(){Tn(this.options.localStream)}setAudioInDevice(e){return R(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:o}})=>o==="audio");if(i){const o=yield gt({audio:{deviceId:{exact:e}}}),r=o.getAudioTracks()[0];i.replaceTrack(r),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach(c=>c.stop()),s.getVideoTracks().forEach(c=>o.addTrack(c)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,be(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,be(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,be(e,"video",null)}setVideoDevice(e){return R(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:o}})=>o==="video");if(i){const o=yield gt({video:{deviceId:{exact:e}}}),r=o.getVideoTracks()[0];i.replaceTrack(r);const{localElement:s,localStream:c}=this.options;We(s,o),this.options.camId=e,c.getAudioTracks().forEach(d=>o.addTrack(d)),c.getVideoTracks().forEach(d=>d.stop()),this.options.localStream=o}})}deaf(){En(this.options.remoteStream)}undeaf(){In(this.options.remoteStream)}toggleDeaf(){Tn(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return R(this,void 0,void 0,function*(){if(!this||!this.peer)return void I.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,o=i.getSenders();if(!o)return void I.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const r=o.find(({track:{kind:s}})=>s===n);if(r){const s=r.getParameters();s.encodings||(s.encodings=[{rid:"h"}]),I.info("Parameters: ",s),I.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),s.encodings[0].maxBitrate=e,yield r.setParameters(s).then(()=>{I.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",r.getParameters())}).catch(c=>console.error(c))}else I.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=M[this._state].toLowerCase(),this.prevState=M[this._prevState].toLowerCase(),I.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:ae.callUpdate,call:this}),e){case M.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case M.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&bn(n,i)},0);break;case M.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case $.Answer:if(this.gotAnswer=!0,this._state>=M.Active)return;this._state>=M.Early&&this.setState(M.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case $.Media:if(this._state>=M.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case $.Display:case $.Attach:{const{display_name:r,display_number:s,display_direction:c}=i;this.extension=s;const d=c===de.Inbound?de.Outbound:de.Inbound,h={type:ae[n],call:this,displayName:r,displayNumber:s,displayDirection:d};N(E.Notification,h,this.id)||N(E.Notification,h,this.session.uuid);break}case $.Info:case $.Event:{const r=Object.assign(Object.assign({},i),{type:ae.generic,call:this});N(E.Notification,r,this.id)||N(E.Notification,r,this.session.uuid);break}case $.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case $.Bye:const o=i.client_state||i.clientState;o&&(this.options.clientState=o),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,n){return R(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return I.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:o,hashKey:r=String(this._lastSerno),arrIndex:s}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:c,infoChannel:d,modChannel:h,laName:g,conferenceMemberID:p,role:b}=n;this._dispatchConferenceUpdate({action:W.Join,conferenceName:g,participantId:Number(p),role:b}),c&&(yield this._subscribeConferenceChat(c)),d&&(yield this._subscribeConferenceInfo(d)),h&&b===Re.Moderator&&(yield this._subscribeConferenceModerator(h));const m=[];for(const C in o)m.push(Object.assign({callId:o[C][0],index:Number(C)},Ve(o[C][1])));this._dispatchConferenceUpdate({action:W.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:W.Add,callId:r,index:s},Ve(o)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:W.Modify,callId:r,index:s},Ve(o)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:W.Delete,callId:r,index:s},Ve(o)));break;case"clear":this._dispatchConferenceUpdate({action:W.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:o,callId:r,index:s})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return R(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:o=>{const{direction:r,from:s,fromDisplay:c,message:d,type:h}=o.data;this._dispatchConferenceUpdate({action:W.ChatMessage,direction:r,participantNumber:s,participantName:c,messageText:d,messageType:h,messageId:o.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(o=>{I.error("ConfChat subscription error:",o)});Ye(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(o,r)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:o,type:r}})}}}))})}_subscribeConferenceInfo(e){return R(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:o=>{const{eventData:r}=o;r.contentType==="layout-info"?(r.callID=this.id,Dn(this.session,r)):I.error("Conference-Info unknown contentType",o)}},i=yield this.session.vertoSubscribe(n).catch(o=>{I.error("ConfInfo subscription error:",o)});Ye(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_subscribeConferenceModerator(e){return R(this,void 0,void 0,function*(){const n=(s,c=null,d=null)=>{const h=parseInt(c)||null;this._confControl(e,{command:s,id:h,value:d})},i=()=>{const{video:s}=this.options;if(typeof s=="boolean"&&!s||typeof s=="object"&&ln(s))throw`Conference ${this.id} has no video!`},o={nodeId:this.nodeId,channels:[e],handler:s=>{const{data:c}=s;if(c["conf-command"]==="list-videoLayouts"){if(c.responseData){const d=JSON.stringify(c.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:W.LayoutList,layouts:JSON.parse(d)})}}else this._dispatchConferenceUpdate({action:W.ModCmdResponse,command:c["conf-command"],response:c.response})}},r=yield this.session.vertoSubscribe(o).catch(s=>{I.error("ConfMod subscription error:",s)});Ye(r,e)&&(this.role=Re.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{n("list-videoLayouts")}},playMedia:{configurable:!0,value:s=>{n("play",null,s)}},stopMedia:{configurable:!0,value:()=>{n("stop",null,"all")}},deaf:{configurable:!0,value:s=>{n("deaf",s)}},undeaf:{configurable:!0,value:s=>{n("undeaf",s)}},startRecord:{configurable:!0,value:s=>{n("recording",null,["start",s])}},stopRecord:{configurable:!0,value:()=>{n("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:s=>{i(),n("vid-write-png",null,s)}},setVideoLayout:{configurable:!0,value:(s,c)=>{i(),n("vid-layout",null,c?[s,c]:s)}},kick:{configurable:!0,value:s=>{n("kick",s)}},muteMic:{configurable:!0,value:s=>{n("tmute",s)}},muteVideo:{configurable:!0,value:s=>{i(),n("tvmute",s)}},presenter:{configurable:!0,value:s=>{i(),n("vid-res-id",s,"presenter")}},videoFloor:{configurable:!0,value:s=>{i(),n("vid-floor",s,"force")}},banner:{configurable:!0,value:(s,c)=>{i(),n("vid-banner",s,encodeURI(c))}},volumeDown:{configurable:!0,value:s=>{n("volume_out",s,"down")}},volumeUp:{configurable:!0,value:s=>{n("volume_out",s,"up")}},gainDown:{configurable:!0,value:s=>{n("volume_in",s,"down")}},gainUp:{configurable:!0,value:s=>{n("volume_in",s,"up")}},transfer:{configurable:!0,value:(s,c)=>{n("transfer",s,c)}}}))})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(M.Active):this.setState(M.Held),!0}_handleChangeHoldStateError(e){return I.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let n=xn(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(n=_t(n));const i={sdp:n,type:Y.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState(M.Early),this.gotAnswer&&this.setState(M.Active)}).catch(o=>{I.error("Call setRemoteDescription Error: ",o),this.hangup()})}_requestAnotherLocalDescription(){ge(this.peer.onSdpReadyTwice)?N(E.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return I.info(`No candidate - retry
|
|
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
|
-
${s.type}
|
|
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})})();
|
|
68
|
+
*/const br=Rt("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
|
|
69
|
+
* @license lucide-preact v0.515.0 - ISC
|
|
70
|
+
*
|
|
71
|
+
* This source code is licensed under the ISC license.
|
|
72
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
73
|
+
*/const yr=Rt("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"}]]),wr=({call:i,client:e})=>{const t=cr(e),n=()=>{i.hangup()},s=()=>{i.toggleAudioMute()};return A("div",{className:"bg-black gap-3 overflow-hidden text-white border w-[360px] max-w-full rounded-4xl text-center flex items-center justify-center flex-col border-solid",children:[A("div",{className:"p-2",children:[A(_o,{stream:i.remoteStream}),A("div",{className:"flex items-center justify-center gap-2",children:[A(Ss,{onClick:s,className:"bg-[#3C3C3C]",children:A(vr,{className:"w-5 h-5"})}),A(Ss,{onClick:n,className:"bg-[#750000]",children:A(br,{className:"w-3.5 h-3.5"})})]})]}),A(Vs,{stream:i.remoteStream}),A(hr,{transcript:t})]})},Ni=()=>A("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:A("div",{className:"animate-spin rounded-full border-t-2 border-b-2 border-gray-900",children:A(mr,{})})}),Sr=({call:i,client:e})=>{switch(i==null?void 0:i.state){case"new":case"trying":case"requesting":return A(Ni,{});case"done":case"purged":case"destroy":return null;case"active":return A(wr,{client:e,call:i});default:return A(Ni,{})}},Cr=(i,e)=>{const[t,n]=yt(null);return nt(()=>{if(!i)return;const s=new nr({env:e||"production",anonymous_login:{target_id:i,target_type:"ai_assistant"}});n(s)},[i,e]),t},xr=(i,{onReady:e,onNotification:t,onError:n})=>(nt(()=>{if(i)return i.connect().then().catch(console.error),i.on(M.Ready,e),i.on(M.Notification,t),i.on(M.Error,n),()=>{i.off(M.Ready,e),i.off(M.Notification,t),i.off(M.Error,n),i.disconnect()}},[i]),null),kr=["agent-id","environment","position"],Ir=({className:i})=>A("svg",{className:i,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("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"}),A("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"}),A("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"}),A("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"}),A("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"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]}),Er=({client:i})=>A("button",{onClick:()=>{var s;if(!i){console.error("Client is not initialized.");return}const t=(s=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:s.codecs,n=t==null?void 0:t.find(o=>o.mimeType.toLowerCase().includes("opus"));i.newCall({destinationNumber:"xxx",preferred_codecs:[n]})},className:"bg-black cursor-pointer text-white px-4 py-2 rounded-full flex items-center text-xl font-medium",children:[A(Ir,{className:"w-8 h-8 mr-2"}),"Let's Talk"]}),Tr='@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}}}@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-black:#000;--color-white:#fff;--spacing:.25rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--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-md:.375rem;--radius-2xl:1rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--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}.static{position:static}.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-3\\.5{height:calc(var(--spacing)*3.5)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-\\[150px\\]{height:150px}.h-\\[400px\\]{height:400px}.max-h-full{max-height:100%}.w-3\\.5{width:calc(var(--spacing)*3.5)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.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%}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-center{justify-content:center}.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}.rounded-md{border-radius:var(--radius-md)}.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-gray-900{border-color:var(--color-gray-900)}.bg-\\[\\#3C3C3C\\]{background-color:#3c3c3c}.bg-\\[\\#3D3D46\\]{background-color:#3d3d46}.bg-\\[\\#222227\\]{background-color:#222227}.bg-\\[\\#750000\\]{background-color:#750000}.bg-black{background-color:var(--color-black)}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.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}.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))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.text-\\[\\#969696\\]{color:#969696}.text-green-400{color:var(--color-green-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)}}@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}@keyframes spin{to{transform:rotate(360deg)}}',Rr=({children:i})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-10 right-10 pointer-events-auto",children:i})}),Lr=({children:i,position:e="fixed"})=>A(vt,{children:[A("style",{children:Tr}),e==="fixed"?A(Rr,{children:i}):i]}),Ar=i=>A("div",{className:"bg-black rounded-2xl p-4 flex flex-col items-center justify-center text-white w-[344px] max-w-full",children:[A(gr,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"text-2xl font-medium mt-2 mb-4",children:"An error occurred"}),A("ul",{className:"list-disc ml-4 text-sm gap-4",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${i.agentId}?tab=telephony`,className:"font-medium text-green-400 underline inline-flex items-center gap-1",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",A(yr,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Nr({"agent-id":i,environment:e,position:t="fixed"}){const n=Cr(i,e),[s,o]=yt(null),[r,l]=yt(!0),[h,u]=yt(!1);return xr(n,{onReady:()=>l(!1),onNotification:x=>{var E;if(((E=x.call)==null?void 0:E.state)==="destroy")return o(null);o(x)},onError:()=>{l(!1),u(!0)}}),A(Lr,{position:t,children:i?h?A(Ar,{agentId:i}):r?A(Ni,{}):s!=null&&s.call?A(Sr,{call:s.call,client:n}):A(Er,{client:n}):A("div",{children:"Please provide an assistant ID."})})}Us(Nr,"telnyx-ai-agent",kr,{shadow:!0})})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telnyx/ai-agent-widget",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"description": "A widget for Telnyx AI Agent",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"author": "Telnyx",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@telnyx/webrtc": "^2.22.12",
|
|
24
|
+
"audiomotion-analyzer": "^4.5.1",
|
|
24
25
|
"clsx": "^2.1.1",
|
|
25
26
|
"lucide-preact": "^0.515.0",
|
|
26
27
|
"preact": "^10.25.3",
|