@telnyx/ai-agent-widget 0.4.0 → 0.5.0-beta.1

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.
Files changed (2) hide show
  1. package/dist/bundle.min.js +54 -31
  2. package/package.json +4 -2
@@ -1,73 +1,96 @@
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})};/**!
1
+ (function(){"use strict";var dn,q,Or,Ae,Vr,Nr,Br,Fr,Ni,Bi,Fi,jr,hn={},$r=[],Du=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,fn=Array.isArray;function Yt(e,t){for(var n in t)e[n]=t[n];return e}function ji(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Bt(e,t,n){var i,s,o,r={};for(o in t)o=="key"?i=t[o]:o=="ref"?s=t[o]:r[o]=t[o];if(arguments.length>2&&(r.children=arguments.length>3?dn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)r[o]===void 0&&(r[o]=e.defaultProps[o]);return pn(e,r,i,s,null)}function pn(e,t,n,i,s){var o={type:e,props:t,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Or,__i:-1,__u:0};return s==null&&q.vnode!=null&&q.vnode(o),o}function ue(e){return e.children}function Wt(e,t){this.props=e,this.context=t}function $e(e,t){if(t==null)return e.__?$e(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?$e(e):null}function Ur(e){var t,n;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null){e.__e=e.__c.base=n.__e;break}return Ur(e)}}function $i(e){(!e.__d&&(e.__d=!0)&&Ae.push(e)&&!Xn.__r++||Vr!=q.debounceRendering)&&((Vr=q.debounceRendering)||Nr)(Xn)}function Xn(){for(var e,t,n,i,s,o,r,a=1;Ae.length;)Ae.length>a&&Ae.sort(Br),e=Ae.shift(),a=Ae.length,e.__d&&(n=void 0,s=(i=(t=e).__v).__e,o=[],r=[],t.__P&&((n=Yt({},i)).__v=i.__v+1,q.vnode&&q.vnode(n),Ui(t.__P,n,i,t.__n,t.__P.namespaceURI,32&i.__u?[s]:null,o,s??$e(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,qr(o,n,r),n.__e!=s&&Ur(n)));Xn.__r=0}function Hr(e,t,n,i,s,o,r,a,l,c,d){var u,p,g,v,w,_,y=i&&i.__k||$r,x=t.length;for(l=Ou(n,t,y,l,x),u=0;u<x;u++)(g=n.__k[u])!=null&&(p=g.__i==-1?hn:y[g.__i]||hn,g.__i=u,_=Ui(e,g,p,s,o,r,a,l,c,d),v=g.__e,g.ref&&p.ref!=g.ref&&(p.ref&&Hi(p.ref,null,g),d.push(g.ref,g.__c||v,g)),w==null&&v!=null&&(w=v),4&g.__u||p.__k===g.__k?l=Gr(g,l,e):typeof g.type=="function"&&_!==void 0?l=_:v&&(l=v.nextSibling),g.__u&=-7);return n.__e=w,l}function Ou(e,t,n,i,s){var o,r,a,l,c,d=n.length,u=d,p=0;for(e.__k=new Array(s),o=0;o<s;o++)(r=t[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+p,(r=e.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?pn(null,r,null,null,null):fn(r)?pn(ue,{children:r},null,null,null):r.constructor==null&&r.__b>0?pn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=e,r.__b=e.__b+1,a=null,(c=r.__i=Vu(r,n,l,u))!=-1&&(u--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>d?p--:s<d&&p++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?p--:c==l+1?p++:(c>l?p--:p++,r.__u|=4))):e.__k[o]=null;if(u)for(o=0;o<d;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=$e(a)),Xr(a,a));return i}function Gr(e,t,n){var i,s;if(typeof e.type=="function"){for(i=e.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=e,t=Gr(i[s],t,n));return t}e.__e!=t&&(t&&e.type&&!n.contains(t)&&(t=$e(e)),n.insertBefore(e.__e,t||null),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Zt(e,t){return t=t||[],e==null||typeof e=="boolean"||(fn(e)?e.some(function(n){Zt(n,t)}):t.push(e)),t}function Vu(e,t,n,i){var s,o,r=e.key,a=e.type,l=t[n];if(l===null&&e.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<t.length;){if(s>=0){if((l=t[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<t.length){if((l=t[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function Wr(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Du.test(t)?n:n+"px"}function Yn(e,t,n,i,s){var o,r;t:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof i=="string"&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||Wr(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||Wr(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Fr,"$1")),r=t.toLowerCase(),t=r in e||t=="onFocusOut"||t=="onFocusIn"?r.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?i?n.u=i.u:(n.u=Ni,e.addEventListener(t,o?Fi:Bi,o)):e.removeEventListener(t,o?Fi:Bi,o);else{if(s=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break t}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function zr(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=Ni++;else if(t.t<n.u)return;return n(q.event?q.event(t):t)}}}function Ui(e,t,n,i,s,o,r,a,l,c){var d,u,p,g,v,w,_,y,x,S,k,M,O,I,A,f,m,h=t.type;if(t.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=t.__e=n.__e]),(d=q.__b)&&d(t);t:if(typeof h=="function")try{if(y=t.props,x="prototype"in h&&h.prototype.render,S=(d=h.contextType)&&i[d.__c],k=d?S?S.props.value:d.__:i,n.__c?_=(u=t.__c=n.__c).__=u.__E:(x?t.__c=u=new h(y,k):(t.__c=u=new Wt(y,k),u.constructor=h,u.render=Bu),S&&S.sub(u),u.props=y,u.state||(u.state={}),u.context=k,u.__n=i,p=u.__d=!0,u.__h=[],u._sb=[]),x&&u.__s==null&&(u.__s=u.state),x&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=Yt({},u.__s)),Yt(u.__s,h.getDerivedStateFromProps(y,u.__s))),g=u.props,v=u.state,u.__v=t,p)x&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),x&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(x&&h.getDerivedStateFromProps==null&&y!==g&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,k),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,k)===!1||t.__v==n.__v){for(t.__v!=n.__v&&(u.props=y,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(b){b&&(b.__=t)}),M=0;M<u._sb.length;M++)u.__h.push(u._sb[M]);u._sb=[],u.__h.length&&r.push(u);break t}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,k),x&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(g,v,w)})}if(u.context=k,u.props=y,u.__P=e,u.__e=!1,O=q.__r,I=0,x){for(u.state=u.__s,u.__d=!1,O&&O(t),d=u.render(u.props,u.state,u.context),A=0;A<u._sb.length;A++)u.__h.push(u._sb[A]);u._sb=[]}else do u.__d=!1,O&&O(t),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++I<25);u.state=u.__s,u.getChildContext!=null&&(i=Yt(Yt({},i),u.getChildContext())),x&&!p&&u.getSnapshotBeforeUpdate!=null&&(w=u.getSnapshotBeforeUpdate(g,v)),f=d,d!=null&&d.type===ue&&d.key==null&&(f=Kr(d.props.children)),a=Hr(e,fn(f)?f:[f],t,n,i,s,o,r,a,l,c),u.base=t.__e,t.__u&=-161,u.__h.length&&r.push(u),_&&(u.__E=u.__=null)}catch(b){if(t.__v=null,l||o!=null)if(b.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,t.__e=a}else for(m=o.length;m--;)ji(o[m]);else t.__e=n.__e,t.__k=n.__k;q.__e(b,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=Nu(n.__e,t,n,i,s,o,r,l,c);return(d=q.diffed)&&d(t),128&t.__u?void 0:a}function qr(e,t,n){for(var i=0;i<n.length;i++)Hi(n[i],n[++i],n[++i]);q.__c&&q.__c(t,e),e.some(function(s){try{e=s.__h,s.__h=[],e.some(function(o){o.call(s)})}catch(o){q.__e(o,s.__v)}})}function Kr(e){return typeof e!="object"||e==null||e.__b&&e.__b>0?e:fn(e)?e.map(Kr):Yt({},e)}function Nu(e,t,n,i,s,o,r,a,l){var c,d,u,p,g,v,w,_=n.props,y=t.props,x=t.type;if(x=="svg"?s="http://www.w3.org/2000/svg":x=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!x&&(x?g.localName==x:g.nodeType==3)){e=g,o[c]=null;break}}if(e==null){if(x==null)return document.createTextNode(y);e=document.createElementNS(s,x,y.is&&y),a&&(q.__m&&q.__m(t,o),a=!1),o=null}if(x==null)_===y||a&&e.data==y||(e.data=y);else{if(o=o&&dn.call(e.childNodes),_=n.props||hn,!a&&o!=null)for(_={},c=0;c<e.attributes.length;c++)_[(g=e.attributes[c]).name]=g.value;for(c in _)if(g=_[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Yn(e,c,null,g,s)}}for(c in y)g=y[c],c=="children"?p=g:c=="dangerouslySetInnerHTML"?d=g:c=="value"?v=g:c=="checked"?w=g:a&&typeof g!="function"||_[c]===g||Yn(e,c,g,_[c],s);if(d)a||u&&(d.__html==u.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(u&&(e.innerHTML=""),Hr(t.type=="template"?e.content:e,fn(p)?p:[p],t,n,i,x=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&$e(n,0),a,l),o!=null)for(c=o.length;c--;)ji(o[c]);a||(c="value",x=="progress"&&v==null?e.removeAttribute("value"):v!=null&&(v!==e[c]||x=="progress"&&!v||x=="option"&&v!=_[c])&&Yn(e,c,v,_[c],s),c="checked",w!=null&&w!=e[c]&&Yn(e,c,w,_[c],s))}return e}function Hi(e,t,n){try{if(typeof e=="function"){var i=typeof e.__u=="function";i&&e.__u(),i&&t==null||(e.__u=e(t))}else e.current=t}catch(s){q.__e(s,n)}}function Xr(e,t,n){var i,s;if(q.unmount&&q.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||Hi(i,null,t)),(i=e.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){q.__e(o,t)}i.base=i.__P=null}if(i=e.__k)for(s=0;s<i.length;s++)i[s]&&Xr(i[s],t,n||typeof e.type!="function");n||ji(e.__e),e.__c=e.__=e.__e=void 0}function Bu(e,t,n){return this.constructor(e,n)}function Zn(e,t,n){var i,s,o,r;t==document&&(t=document.documentElement),q.__&&q.__(e,t),s=(i=typeof n=="function")?null:n&&n.__k||t.__k,o=[],r=[],Ui(t,e=(!i&&n||t).__k=Bt(ue,null,[e]),s||hn,hn,t.namespaceURI,!i&&n?[n]:s?null:t.firstChild?dn.call(t.childNodes):null,o,!i&&n?n:s?s.__e:t.firstChild,i,r),qr(o,e,r)}function Yr(e,t){Zn(e,t,Yr)}function Gi(e,t,n){var i,s,o,r,a=Yt({},e.props);for(o in e.type&&e.type.defaultProps&&(r=e.type.defaultProps),t)o=="key"?i=t[o]:o=="ref"?s=t[o]:a[o]=t[o]===void 0&&r!=null?r[o]:t[o];return arguments.length>2&&(a.children=arguments.length>3?dn.call(arguments,2):n),pn(e.type,a,i||e.key,s||e.ref,null)}function Ue(e){function t(n){var i,s;return this.getChildContext||(i=new Set,(s={})[t.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&i.forEach(function(r){r.__e=!0,$i(r)})},this.sub=function(o){i.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){i&&i.delete(o),r&&r.call(o)}}),n.children}return t.__c="__cC"+jr++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,i){return n.children(i)}).contextType=t,t}dn=$r.slice,q={__e:function(e,t,n,i){for(var s,o,r;t=t.__;)if((s=t.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(e)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(e,i||{}),r=s.__d),r)return s.__E=s}catch(a){e=a}throw e}},Or=0,Wt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Yt({},this.state),typeof e=="function"&&(e=e(Yt({},n),this.props)),e&&Yt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),$i(this))},Wt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),$i(this))},Wt.prototype.render=ue,Ae=[],Nr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Br=function(e,t){return e.__v.__b-t.__v.__b},Xn.__r=0,Fr=/(PointerCapture)$|Capture$/i,Ni=0,Bi=zr(!1),Fi=zr(!0),jr=0;var Fu=0;function P(e,t,n,i,s,o){t||(t={});var r,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?r=t[a]:l[a]=t[a];var c={type:e,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Fu,__i:-1,__u:0,__source:s,__self:o};if(typeof e=="function"&&(r=e.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return q.vnode&&q.vnode(c),c}function Wi(){return(Wi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}).apply(this,arguments)}var ju=["context","children"];function $u(e){this.getChildContext=function(){return e.context};var t=e.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(e,ju);return Gi(t,n)}function Uu(){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Bt($u,Wi({},this._props,{context:e.detail.context}),function t(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Zr(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=t(l[r],null),d=l[r].slot;d?o[d]=Bt(Jr,{name:d},c):s[r]=c}var u=i?Bt(Jr,null,s):s;return Bt(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Yr:Zn)(this._vdom,this._root)}function Zr(e){return e.replace(/-(\w)/g,function(t,n){return n?n.toUpperCase():""})}function Hu(e,t,n){if(this._vdom){var i={};i[e]=n=n??void 0,i[Zr(e)]=n,this._vdom=Gi(this._vdom,i),Zn(this._vdom,this._root)}}function Gu(){Zn(this._vdom=null,this._root)}function Jr(e,t){var n=this;return Bt("slot",Wi({},e,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=t},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Wu(e,t,n,i){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=e,o._root=i&&i.shadow?o.attachShadow({mode:i.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=Uu,s.prototype.attributeChangedCallback=Hu,s.prototype.disconnectedCallback=Gu,n=n||e.observedAttributes||Object.keys(e.propTypes||{}),s.observedAttributes=n,n.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 a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(t,s)}var ge,at,zi,Qr,mn=0,to=[],vt=q,eo=vt.__b,no=vt.__r,io=vt.diffed,so=vt.__c,ro=vt.unmount,oo=vt.__;function He(e,t){vt.__h&&vt.__h(at,e,mn||t),mn=0;var n=at.__H||(at.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function de(e){return mn=1,zu(uo,e)}function zu(e,t,n){var i=He(ge++,2);if(i.t=e,!i.__c&&(i.__=[n?n(t):uo(void 0,t),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=at,!at.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(p){return!!p.__c});if(d.every(function(p){return!p.__N}))return!o||o.call(this,a,l,c);var u=i.__c.props!==a;return d.forEach(function(p){if(p.__N){var g=p.__[0];p.__=p.__N,p.__N=void 0,g!==p.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};at.__f=!0;var o=at.shouldComponentUpdate,r=at.componentWillUpdate;at.componentWillUpdate=function(a,l,c){if(this.__e){var d=o;o=void 0,s(a,l,c),o=d}r&&r.call(this,a,l,c)},at.shouldComponentUpdate=s}return i.__N||i.__}function Jt(e,t){var n=He(ge++,3);!vt.__s&&Xi(n.__H,t)&&(n.__=e,n.u=t,at.__H.__h.push(n))}function ao(e,t){var n=He(ge++,4);!vt.__s&&Xi(n.__H,t)&&(n.__=e,n.u=t,at.__h.push(n))}function zt(e){return mn=5,Qt(function(){return{current:e}},[])}function Qt(e,t){var n=He(ge++,7);return Xi(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function lo(e,t){return mn=8,Qt(function(){return e},t)}function xt(e){var t=at.context[e.__c],n=He(ge++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(at)),t.props.value):e.__}function qi(){var e=He(ge++,11);if(!e.__){for(var t=at.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function qu(){for(var e;e=to.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Jn),e.__H.__h.forEach(Ki),e.__H.__h=[]}catch(t){e.__H.__h=[],vt.__e(t,e.__v)}}vt.__b=function(e){at=null,eo&&eo(e)},vt.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),oo&&oo(e,t)},vt.__r=function(e){no&&no(e),ge=0;var t=(at=e.__c).__H;t&&(zi===at?(t.__h=[],at.__h=[],t.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.forEach(Jn),t.__h.forEach(Ki),t.__h=[],ge=0)),zi=at},vt.diffed=function(e){io&&io(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(to.push(t)!==1&&Qr===vt.requestAnimationFrame||((Qr=vt.requestAnimationFrame)||Ku)(qu)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),zi=at=null},vt.__c=function(e,t){t.some(function(n){try{n.__h.forEach(Jn),n.__h=n.__h.filter(function(i){return!i.__||Ki(i)})}catch(i){t.some(function(s){s.__h&&(s.__h=[])}),t=[],vt.__e(i,n.__v)}}),so&&so(e,t)},vt.unmount=function(e){ro&&ro(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{Jn(i)}catch(s){t=s}}),n.__H=void 0,t&&vt.__e(t,n.__v))};var co=typeof requestAnimationFrame=="function";function Ku(e){var t,n=function(){clearTimeout(i),co&&cancelAnimationFrame(t),setTimeout(e)},i=setTimeout(n,35);co&&(t=requestAnimationFrame(n))}function Jn(e){var t=at,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),at=t}function Ki(e){var t=at;e.__c=e.__(),at=t}function Xi(e,t){return!e||e.length!==t.length||t.some(function(n,i){return n!==e[i]})}function uo(e,t){return typeof t=="function"?t(e):t}function ho(e,t){for(var n in t)e[n]=t[n];return e}function fo(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var i in t)if(i!=="__source"&&e[i]!==t[i])return!0;return!1}var po=ao;function mo(e,t){this.props=e,this.context=t}(mo.prototype=new Wt).isPureReactComponent=!0,mo.prototype.shouldComponentUpdate=function(e,t){return fo(this.props,e)||fo(this.state,t)};var go=q.__b;q.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),go&&go(e)};var Xu=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Yu(e){function t(n){var i=ho({},n);return delete i.ref,e(i,n.ref||null)}return t.$$typeof=Xu,t.render=t,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var vo=function(e,t){return e==null?null:Zt(Zt(e).map(t))},Zu={map:vo,forEach:vo,count:function(e){return e?Zt(e).length:0},only:function(e){var t=Zt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Zt},Ju=q.__e;q.__e=function(e,t,n,i){if(e.then){for(var s,o=t;o=o.__;)if((s=o.__c)&&s.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),s.__c(e,t)}Ju(e,t,n,i)};var yo=q.unmount;function _o(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),e.__c.__H=null),(e=ho({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(i){return _o(i,t,n)})),e}function bo(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(i){return bo(i,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Yi(){this.__u=0,this.o=null,this.__b=null}function wo(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function Qn(){this.i=null,this.l=null}q.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),yo&&yo(e)},(Yi.prototype=new Wt).__c=function(e,t){var n=t.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=wo(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=bo(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&t.__u||i.setState({__a:i.__b=i.__v.__k[0]}),e.then(r,r)},Yi.prototype.componentWillUnmount=function(){this.o=[]},Yi.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=_o(this.__b,n,i.__O=i.__P)}this.__b=null}var s=t.__a&&Bt(ue,null,e.fallback);return s&&(s.__u&=-33),[Bt(ue,null,t.__a?null:e.children),s]};var xo=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};(Qn.prototype=new Wt).__a=function(e){var t=this,n=wo(t.__v),i=t.l.get(e);return i[0]++,function(s){var o=function(){t.props.revealOrder?(i.push(s),xo(t,e,i)):s()};n?n(o):o()}},Qn.prototype.render=function(e){this.i=null,this.l=new Map;var t=Zt(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},Qn.prototype.componentDidUpdate=Qn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){xo(e,n,t)})};var So=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Qu=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,td=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ed=/[A-Z0-9]/g,nd=typeof document<"u",id=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};Wt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Wt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Co=q.event;function sd(){}function rd(){return this.cancelBubble}function od(){return this.defaultPrevented}q.event=function(e){return Co&&(e=Co(e)),e.persist=sd,e.isPropagationStopped=rd,e.isDefaultPrevented=od,e.nativeEvent=e};var ad={enumerable:!1,configurable:!0,get:function(){return this.class}},To=q.vnode;q.vnode=function(e){typeof e.type=="string"&&function(t){var n=t.props,i=t.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||nd&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||id(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":td.test(r)&&(r=l):l=r="oninput":o&&Qu.test(r)?r=r.replace(ed,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=Zt(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=Zt(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",ad)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),t.props=s}(e),e.$$typeof=So,To&&To(e)};var ko=q.__r;q.__r=function(e){ko&&ko(e),e.__c};var Ao=q.diffed;q.diffed=function(e){Ao&&Ao(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value)};function Eo(e){return!!e&&e.$$typeof===So}function ld(e){return Eo(e)?Gi.apply(null,arguments):e}const Zi=Ue({});function ti(e){const t=zt(null);return t.current===null&&(t.current=e()),t.current}const Ji=typeof window<"u",Io=Ji?ao:Jt,ei=Ue(null);function Qi(e,t){e.indexOf(t)===-1&&e.push(t)}function ts(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const he=(e,t,n)=>n>t?t:n<e?e:n;let es=()=>{};const fe={},Ro=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Po(e){return typeof e=="object"&&e!==null}const Mo=e=>/^0[^.\s]+$/u.test(e);function ns(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ft=e=>e,cd=(e,t)=>n=>t(e(n)),gn=(...e)=>e.reduce(cd),vn=(e,t,n)=>{const i=t-e;return i===0?1:(n-e)/i};class is{constructor(){this.subscriptions=[]}add(t){return Qi(this.subscriptions,t),()=>ts(this.subscriptions,t)}notify(t,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](t,n,i);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(t,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const te=e=>e*1e3,ee=e=>e/1e3;function Lo(e,t){return t?e*(1e3/t):0}const Do=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,ud=1e-7,dd=12;function hd(e,t,n,i,s){let o,r,a=0;do r=t+(n-t)/2,o=Do(r,i,s)-e,o>0?n=r:t=r;while(Math.abs(o)>ud&&++a<dd);return r}function yn(e,t,n,i){if(e===t&&n===i)return Ft;const s=o=>hd(o,0,1,e,n);return o=>o===0||o===1?o:Do(s(o),t,i)}const Oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Vo=e=>t=>1-e(1-t),No=yn(.33,1.53,.69,.99),ss=Vo(No),Bo=Oo(ss),Fo=e=>(e*=2)<1?.5*ss(e):.5*(2-Math.pow(2,-10*(e-1))),rs=e=>1-Math.sin(Math.acos(e)),jo=Vo(rs),$o=Oo(rs),fd=yn(.42,0,1,1),pd=yn(0,0,.58,1),Uo=yn(.42,0,.58,1),md=e=>Array.isArray(e)&&typeof e[0]!="number",Ho=e=>Array.isArray(e)&&typeof e[0]=="number",gd={linear:Ft,easeIn:fd,easeInOut:Uo,easeOut:pd,circIn:rs,circInOut:$o,circOut:jo,backIn:ss,backInOut:Bo,backOut:No,anticipate:Fo},vd=e=>typeof e=="string",Go=e=>{if(Ho(e)){es(e.length===4);const[t,n,i,s]=e;return yn(t,n,i,s)}else if(vd(e))return gd[e];return e},ni=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Wo={value:null};function yd(e,t){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(u){r.has(u)&&(d.schedule(u),e()),l++,u(a)}const d={schedule:(u,p=!1,g=!1)=>{const w=g&&s?n:i;return p&&r.add(u),w.has(u)||w.add(u),u},cancel:u=>{i.delete(u),r.delete(u)},process:u=>{if(a=u,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),t&&Wo.value&&Wo.value.frameloop[t].push(l),l=0,n.clear(),s=!1,o&&(o=!1,d.process(u))}};return d}const _d=40;function zo(e,t){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=ni.reduce((S,k)=>(S[k]=yd(o,t?k:void 0),S),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:p,render:g,postRender:v}=r,w=()=>{const S=fe.useManualTiming?s.timestamp:performance.now();n=!1,fe.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(S-s.timestamp,_d),1)),s.timestamp=S,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),d.process(s),u.process(s),p.process(s),g.process(s),v.process(s),s.isProcessing=!1,n&&t&&(i=!1,e(w))},_=()=>{n=!0,i=!0,s.isProcessing||e(w)};return{schedule:ni.reduce((S,k)=>{const M=r[k];return S[k]=(O,I=!1,A=!1)=>(n||_(),M.schedule(O,I,A)),S},{}),cancel:S=>{for(let k=0;k<ni.length;k++)r[ni[k]].cancel(S)},state:s,steps:r}}const{schedule:ut,cancel:ve,state:St,steps:os}=zo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ft,!0);let ii;function bd(){ii=void 0}const Mt={now:()=>(ii===void 0&&Mt.set(St.isProcessing||fe.useManualTiming?St.timestamp:performance.now()),ii),set:e=>{ii=e,queueMicrotask(bd)}},qo=e=>t=>typeof t=="string"&&t.startsWith(e),as=qo("--"),wd=qo("var(--"),ls=e=>wd(e)?xd.test(e.split("/*")[0].trim()):!1,xd=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ge={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},_n={...Ge,transform:e=>he(0,1,e)},si={...Ge,default:1},bn=e=>Math.round(e*1e5)/1e5,cs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Sd(e){return e==null}const Cd=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,us=(e,t)=>n=>!!(typeof n=="string"&&Cd.test(n)&&n.startsWith(e)||t&&!Sd(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ko=(e,t,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(cs);return{[e]:parseFloat(s),[t]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Td=e=>he(0,255,e),ds={...Ge,transform:e=>Math.round(Td(e))},Ee={test:us("rgb","red"),parse:Ko("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:i=1})=>"rgba("+ds.transform(e)+", "+ds.transform(t)+", "+ds.transform(n)+", "+bn(_n.transform(i))+")"};function kd(e){let t="",n="",i="",s="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),i=e.substring(5,7),s=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),i=e.substring(3,4),s=e.substring(4,5),t+=t,n+=n,i+=i,s+=s),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const hs={test:us("#"),parse:kd,transform:Ee.transform},wn=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),ye=wn("deg"),ne=wn("%"),U=wn("px"),Ad=wn("vh"),Ed=wn("vw"),Xo={...ne,parse:e=>ne.parse(e)/100,transform:e=>ne.transform(e*100)},We={test:us("hsl","hue"),parse:Ko("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:i=1})=>"hsla("+Math.round(e)+", "+ne.transform(bn(t))+", "+ne.transform(bn(n))+", "+bn(_n.transform(i))+")"},_t={test:e=>Ee.test(e)||hs.test(e)||We.test(e),parse:e=>Ee.test(e)?Ee.parse(e):We.test(e)?We.parse(e):hs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Ee.transform(e):We.transform(e),getAnimatableNone:e=>{const t=_t.parse(e);return t.alpha=0,_t.transform(t)}},Id=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Rd(e){var t,n;return isNaN(e)&&typeof e=="string"&&(((t=e.match(cs))==null?void 0:t.length)||0)+(((n=e.match(Id))==null?void 0:n.length)||0)>0}const Yo="number",Zo="color",Pd="var",Md="var(",Jo="${}",Ld=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function xn(e){const t=e.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=t.replace(Ld,l=>(_t.test(l)?(i.color.push(o),s.push(Zo),n.push(_t.parse(l))):l.startsWith(Md)?(i.var.push(o),s.push(Pd),n.push(l)):(i.number.push(o),s.push(Yo),n.push(parseFloat(l))),++o,Jo)).split(Jo);return{values:n,split:a,indexes:i,types:s}}function Qo(e){return xn(e).values}function ta(e){const{split:t,types:n}=xn(e),i=t.length;return s=>{let o="";for(let r=0;r<i;r++)if(o+=t[r],s[r]!==void 0){const a=n[r];a===Yo?o+=bn(s[r]):a===Zo?o+=_t.transform(s[r]):o+=s[r]}return o}}const Dd=e=>typeof e=="number"?0:_t.test(e)?_t.getAnimatableNone(e):e;function Od(e){const t=Qo(e);return ta(e)(t.map(Dd))}const _e={test:Rd,parse:Qo,createTransformer:ta,getAnimatableNone:Od};function fs(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Vd({hue:e,saturation:t,lightness:n,alpha:i}){e/=360,t/=100,n/=100;let s=0,o=0,r=0;if(!t)s=o=r=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;s=fs(l,a,e+1/3),o=fs(l,a,e),r=fs(l,a,e-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function ri(e,t){return n=>n>0?t:e}const pt=(e,t,n)=>e+(t-e)*n,ps=(e,t,n)=>{const i=e*e,s=n*(t*t-i)+i;return s<0?0:Math.sqrt(s)},Nd=[hs,Ee,We],Bd=e=>Nd.find(t=>t.test(e));function ea(e){const t=Bd(e);if(!t)return!1;let n=t.parse(e);return t===We&&(n=Vd(n)),n}const na=(e,t)=>{const n=ea(e),i=ea(t);if(!n||!i)return ri(e,t);const s={...n};return o=>(s.red=ps(n.red,i.red,o),s.green=ps(n.green,i.green,o),s.blue=ps(n.blue,i.blue,o),s.alpha=pt(n.alpha,i.alpha,o),Ee.transform(s))},ms=new Set(["none","hidden"]);function Fd(e,t){return ms.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function jd(e,t){return n=>pt(e,t,n)}function gs(e){return typeof e=="number"?jd:typeof e=="string"?ls(e)?ri:_t.test(e)?na:Hd:Array.isArray(e)?ia:typeof e=="object"?_t.test(e)?na:$d:ri}function ia(e,t){const n=[...e],i=n.length,s=e.map((o,r)=>gs(o)(o,t[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function $d(e,t){const n={...e,...t},i={};for(const s in n)e[s]!==void 0&&t[s]!==void 0&&(i[s]=gs(e[s])(e[s],t[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function Ud(e,t){const n=[],i={color:0,var:0,number:0};for(let s=0;s<t.values.length;s++){const o=t.types[s],r=e.indexes[o][i[o]],a=e.values[r]??0;n[s]=a,i[o]++}return n}const Hd=(e,t)=>{const n=_e.createTransformer(t),i=xn(e),s=xn(t);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?ms.has(e)&&!s.values.length||ms.has(t)&&!i.values.length?Fd(e,t):gn(ia(Ud(i,s),s.values),n):ri(e,t)};function sa(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?pt(e,t,n):gs(e)(e,t)}const Gd=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ut.update(t,n),stop:()=>ve(t),now:()=>St.isProcessing?St.timestamp:Mt.now()}},ra=(e,t,n=10)=>{let i="";const s=Math.max(Math.round(t/n),2);for(let o=0;o<s;o++)i+=Math.round(e(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},oi=2e4;function vs(e){let t=0;const n=50;let i=e.next(t);for(;!i.done&&t<oi;)t+=n,i=e.next(t);return t>=oi?1/0:t}function Wd(e,t=100,n){const i=n({...e,keyframes:[0,t]}),s=Math.min(vs(i),oi);return{type:"keyframes",ease:o=>i.next(s*o).value/t,duration:ee(s)}}const zd=5;function oa(e,t,n){const i=Math.max(t-zd,0);return Lo(n-e(i),t-i)}const mt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},ys=.001;function qd({duration:e=mt.duration,bounce:t=mt.bounce,velocity:n=mt.velocity,mass:i=mt.mass}){let s,o,r=1-t;r=he(mt.minDamping,mt.maxDamping,r),e=he(mt.minDuration,mt.maxDuration,ee(e)),r<1?(s=c=>{const d=c*r,u=d*e,p=d-n,g=_s(c,r),v=Math.exp(-u);return ys-p/g*v},o=c=>{const u=c*r*e,p=u*n+n,g=Math.pow(r,2)*Math.pow(c,2)*e,v=Math.exp(-u),w=_s(Math.pow(c,2),r);return(-s(c)+ys>0?-1:1)*((p-g)*v)/w}):(s=c=>{const d=Math.exp(-c*e),u=(c-n)*e+1;return-ys+d*u},o=c=>{const d=Math.exp(-c*e),u=(n-c)*(e*e);return d*u});const a=5/e,l=Xd(s,o,a);if(e=te(e),isNaN(l))return{stiffness:mt.stiffness,damping:mt.damping,duration:e};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:e}}}const Kd=12;function Xd(e,t,n){let i=n;for(let s=1;s<Kd;s++)i=i-e(i)/t(i);return i}function _s(e,t){return e*Math.sqrt(1-t*t)}const Yd=["duration","bounce"],Zd=["stiffness","damping","mass"];function aa(e,t){return t.some(n=>e[n]!==void 0)}function Jd(e){let t={velocity:mt.velocity,stiffness:mt.stiffness,damping:mt.damping,mass:mt.mass,isResolvedFromDuration:!1,...e};if(!aa(e,Zd)&&aa(e,Yd))if(e.visualDuration){const n=e.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*he(.05,1,1-(e.bounce||0))*Math.sqrt(s);t={...t,mass:mt.mass,stiffness:s,damping:o}}else{const n=qd(e);t={...t,...n,mass:mt.mass},t.isResolvedFromDuration=!0}return t}function ai(e=mt.visualDuration,t=mt.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:d,duration:u,velocity:p,isResolvedFromDuration:g}=Jd({...n,velocity:-ee(n.velocity||0)}),v=p||0,w=c/(2*Math.sqrt(l*d)),_=r-o,y=ee(Math.sqrt(l/d)),x=Math.abs(_)<5;i||(i=x?mt.restSpeed.granular:mt.restSpeed.default),s||(s=x?mt.restDelta.granular:mt.restDelta.default);let S;if(w<1){const M=_s(y,w);S=O=>{const I=Math.exp(-w*y*O);return r-I*((v+w*y*_)/M*Math.sin(M*O)+_*Math.cos(M*O))}}else if(w===1)S=M=>r-Math.exp(-y*M)*(_+(v+y*_)*M);else{const M=y*Math.sqrt(w*w-1);S=O=>{const I=Math.exp(-w*y*O),A=Math.min(M*O,300);return r-I*((v+w*y*_)*Math.sinh(A)+M*_*Math.cosh(A))/M}}const k={calculatedDuration:g&&u||null,next:M=>{const O=S(M);if(g)a.done=M>=u;else{let I=M===0?v:0;w<1&&(I=M===0?te(v):oa(S,M,O));const A=Math.abs(I)<=i,f=Math.abs(r-O)<=s;a.done=A&&f}return a.value=a.done?r:O,a},toString:()=>{const M=Math.min(vs(k),oi),O=ra(I=>k.next(M*I).value,M,30);return M+"ms "+O},toTransition:()=>{}};return k}ai.applyToOptions=e=>{const t=Wd(e,100,ai);return e.ease=t.ease,e.duration=te(t.duration),e.type="keyframes",e};function bs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:d}){const u=e[0],p={done:!1,value:u},g=A=>a!==void 0&&A<a||l!==void 0&&A>l,v=A=>a===void 0?l:l===void 0||Math.abs(a-A)<Math.abs(l-A)?a:l;let w=n*t;const _=u+w,y=r===void 0?_:r(_);y!==_&&(w=y-u);const x=A=>-w*Math.exp(-A/i),S=A=>y+x(A),k=A=>{const f=x(A),m=S(A);p.done=Math.abs(f)<=c,p.value=p.done?y:m};let M,O;const I=A=>{g(p.value)&&(M=A,O=ai({keyframes:[p.value,v(p.value)],velocity:oa(S,A,p.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return I(0),{calculatedDuration:null,next:A=>{let f=!1;return!O&&M===void 0&&(f=!0,k(A),I(A)),M!==void 0&&A>=M?O.next(A-M):(!f&&k(A),p)}}}function Qd(e,t,n){const i=[],s=n||fe.mix||sa,o=e.length-1;for(let r=0;r<o;r++){let a=s(e[r],e[r+1]);if(t){const l=Array.isArray(t)?t[r]||Ft:t;a=gn(l,a)}i.push(a)}return i}function th(e,t,{clamp:n=!0,ease:i,mixer:s}={}){const o=e.length;if(es(o===t.length),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const r=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Qd(t,i,s),l=a.length,c=d=>{if(r&&d<e[0])return t[0];let u=0;if(l>1)for(;u<e.length-2&&!(d<e[u+1]);u++);const p=vn(e[u],e[u+1],d);return a[u](p)};return n?d=>c(he(e[0],e[o-1],d)):c}function eh(e,t){const n=e[e.length-1];for(let i=1;i<=t;i++){const s=vn(0,t,i);e.push(pt(n,1,s))}}function nh(e){const t=[0];return eh(t,e.length-1),t}function ih(e,t){return e.map(n=>n*t)}function sh(e,t){return e.map(()=>t||Uo).splice(0,e.length-1)}function Sn({duration:e=300,keyframes:t,times:n,ease:i="easeInOut"}){const s=md(i)?i.map(Go):Go(i),o={done:!1,value:t[0]},r=ih(n&&n.length===t.length?n:nh(t),e),a=th(r,t,{ease:Array.isArray(s)?s:sh(t,s)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const rh=e=>e!==null;function ws(e,{repeat:t,repeatType:n="loop"},i,s=1){const o=e.filter(rh),a=s<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const oh={decay:bs,inertia:bs,tween:Sn,keyframes:Sn,spring:ai};function la(e){typeof e.type=="string"&&(e.type=oh[e.type])}class xs{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const ah=e=>e/100;class Ss extends xs{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,s;const{motionValue:n}=this.options;n&&n.updatedAt!==Mt.now()&&this.tick(Mt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;la(t);const{type:n=Sn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=t;let{keyframes:a}=t;const l=n||Sn;l!==Sn&&typeof a[0]!="number"&&(this.mixKeyframes=gn(ah,sa(a[0],a[1])),a=[0,100]);const c=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=vs(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:d,repeat:u,repeatType:p,repeatDelay:g,type:v,onUpdate:w,finalKeyframe:_}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-s/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),x=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let S=this.currentTime,k=i;if(u){const A=Math.min(this.currentTime,s)/a;let f=Math.floor(A),m=A%1;!m&&A>=1&&(m=1),m===1&&f--,f=Math.min(f,u+1),!!(f%2)&&(p==="reverse"?(m=1-m,g&&(m-=g/a)):p==="mirror"&&(k=r)),S=he(0,1,m)*a}const M=x?{done:!1,value:d[0]}:k.next(S);o&&(M.value=o(M.value));let{done:O}=M;!x&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return I&&v!==bs&&(M.value=ws(d,this.options,_,this.speed)),w&&w(M.value),I&&this.finish(),M}then(t,n){return this.finished.then(t,n)}get duration(){return ee(this.calculatedDuration)}get time(){return ee(this.currentTime)}set time(t){var n;t=te(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Mt.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ee(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:t=Gd,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Mt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function lh(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Ie=e=>e*180/Math.PI,Cs=e=>{const t=Ie(Math.atan2(e[1],e[0]));return Ts(t)},ch={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Cs,rotateZ:Cs,skewX:e=>Ie(Math.atan(e[1])),skewY:e=>Ie(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ts=e=>(e=e%360,e<0&&(e+=360),e),ca=Cs,ua=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),da=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),uh={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ua,scaleY:da,scale:e=>(ua(e)+da(e))/2,rotateX:e=>Ts(Ie(Math.atan2(e[6],e[5]))),rotateY:e=>Ts(Ie(Math.atan2(-e[2],e[0]))),rotateZ:ca,rotate:ca,skewX:e=>Ie(Math.atan(e[4])),skewY:e=>Ie(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ks(e){return e.includes("scale")?1:0}function As(e,t){if(!e||e==="none")return ks(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=uh,s=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=ch,s=a}if(!s)return ks(t);const o=i[t],r=s[1].split(",").map(hh);return typeof o=="function"?o(r):r[o]}const dh=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return As(n,t)};function hh(e){return parseFloat(e.trim())}const ze=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],qe=new Set(ze),ha=e=>e===Ge||e===U,fh=new Set(["x","y","z"]),ph=ze.filter(e=>!fh.has(e));function mh(e){const t=[];return ph.forEach(n=>{const i=e.getValue(n);i!==void 0&&(t.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),t}const Re={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>As(t,"x"),y:(e,{transform:t})=>As(t,"y")};Re.translateX=Re.x,Re.translateY=Re.y;const Pe=new Set;let Es=!1,Is=!1,Rs=!1;function fa(){if(Is){const e=Array.from(Pe).filter(i=>i.needsMeasurement),t=new Set(e.map(i=>i.element)),n=new Map;t.forEach(i=>{const s=mh(i);s.length&&(n.set(i,s),i.render())}),e.forEach(i=>i.measureInitialState()),t.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([o,r])=>{var a;(a=i.getValue(o))==null||a.set(r)})}),e.forEach(i=>i.measureEndState()),e.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}Is=!1,Es=!1,Pe.forEach(e=>e.complete(Rs)),Pe.clear()}function pa(){Pe.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Is=!0)})}function gh(){Rs=!0,pa(),fa(),Rs=!1}class Ps{constructor(t,n,i,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=i,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Pe.add(this),Es||(Es=!0,ut.read(pa),ut.resolveKeyframes(fa))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:i,motionValue:s}=this;if(t[0]===null){const o=s==null?void 0:s.get(),r=t[t.length-1];if(o!==void 0)t[0]=o;else if(i&&n){const a=i.readValue(n,r);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=r),s&&o===void 0&&s.set(t[0])}lh(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Pe.delete(this)}cancel(){this.state==="scheduled"&&(Pe.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const vh=e=>e.startsWith("--");function yh(e,t,n){vh(t)?e.style.setProperty(t,n):e.style[t]=n}const _h=ns(()=>window.ScrollTimeline!==void 0),bh={};function wh(e,t){const n=ns(e);return()=>bh[t]??n()}const ma=wh(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Cn=([e,t,n,i])=>`cubic-bezier(${e}, ${t}, ${n}, ${i})`,ga={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Cn([0,.65,.55,1]),circOut:Cn([.55,0,1,.45]),backIn:Cn([.31,.01,.66,-.59]),backOut:Cn([.33,1.53,.69,.99])};function va(e,t){if(e)return typeof e=="function"?ma()?ra(e,t):"ease-out":Ho(e)?Cn(e):Array.isArray(e)?e.map(n=>va(n,t)||ga.easeOut):ga[e]}function xh(e,t,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[t]:n};l&&(d.offset=l);const u=va(a,s);Array.isArray(u)&&(d.easing=u);const p={delay:i,duration:s,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(p.pseudoElement=c),e.animate(d,p)}function ya(e){return typeof e=="function"&&"applyToOptions"in e}function Sh({type:e,...t}){return ya(e)&&ma()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Ch extends xs{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=t;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=t,es(typeof t.type!="string");const c=Sh(t);this.animation=xh(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=ws(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):yh(n,i,d),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,n;(n=(t=this.animation).finish)==null||n.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var t,n;this.isPseudoElement||(n=(t=this.animation).commitStyles)==null||n.call(t)}get duration(){var n,i;const t=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return ee(Number(t))}get time(){return ee(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=te(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&_h()?(this.animation.timeline=t,Ft):n(this)}}const _a={anticipate:Fo,backInOut:Bo,circInOut:$o};function Th(e){return e in _a}function kh(e){typeof e.ease=="string"&&Th(e.ease)&&(e.ease=_a[e.ease])}const ba=10;class Ah extends Ch{constructor(t){kh(t),la(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:i,onComplete:s,element:o,...r}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Ss({...r,autoplay:!1}),l=te(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-ba).value,a.sample(l).value,ba),a.stop()}}const wa=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(_e.test(e)||e==="0")&&!e.startsWith("url("));function Eh(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function Ih(e,t,n,i){const s=e[0];if(s===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],r=wa(s,t),a=wa(o,t);return!r||!a?!1:Eh(e)||(n==="spring"||ya(n))&&i}function Ms(e){return Po(e)&&"offsetHeight"in e}const Rh=new Set(["opacity","clipPath","filter","transform"]),Ph=ns(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Mh(e){var c;const{motionValue:t,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=e;if(!Ms((c=t==null?void 0:t.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=t.owner.getProps();return Ph()&&n&&Rh.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const Lh=40;class Dh extends xs{constructor({autoplay:t=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:d,...u}){var v;super(),this.stop=()=>{var w,_;this._animation&&(this._animation.stop(),(w=this.stopTimeline)==null||w.call(this)),(_=this.keyframeResolver)==null||_.cancel()},this.createdAt=Mt.now();const p={autoplay:t,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},g=(d==null?void 0:d.KeyframeResolver)||Ps;this.keyframeResolver=new g(a,(w,_,y)=>this.onKeyframesResolved(w,_,p,!y),l,c,d),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(t,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:d}=i;this.resolvedAt=Mt.now(),Ih(t,o,r,a)||((fe.instantAnimations||!l)&&(d==null||d(ws(t,i,n))),t[0]=t[t.length-1],i.duration=0,i.repeat=0);const p={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Lh?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:t},g=!c&&Mh(p)?new Ah({...p,element:p.motionValue.owner.current}):new Ss(p);g.finished.then(()=>this.notifyFinished()).catch(Ft),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),gh()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var t;this._animation&&this.animation.cancel(),(t=this.keyframeResolver)==null||t.cancel()}}const Oh=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vh(e){const t=Oh.exec(e);if(!t)return[,];const[,n,i,s]=t;return[`--${n??i}`,s]}function xa(e,t,n=1){const[i,s]=Vh(e);if(!i)return;const o=window.getComputedStyle(t).getPropertyValue(i);if(o){const r=o.trim();return Ro(r)?parseFloat(r):r}return ls(s)?xa(s,t,n+1):s}function Ls(e,t){return(e==null?void 0:e[t])??(e==null?void 0:e.default)??e}const Sa=new Set(["width","height","top","left","right","bottom",...ze]),Nh={test:e=>e==="auto",parse:e=>e},Ca=e=>t=>t.test(e),Ta=[Ge,U,ne,ye,Ed,Ad,Nh],ka=e=>Ta.find(Ca(e));function Bh(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Mo(e):!0}const Fh=new Set(["brightness","contrast","saturate","opacity"]);function jh(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[i]=n.match(cs)||[];if(!i)return e;const s=n.replace(i,"");let o=Fh.has(t)?1:0;return i!==n&&(o*=100),t+"("+o+s+")"}const $h=/\b([a-z-]*)\(.*?\)/gu,Ds={..._e,getAnimatableNone:e=>{const t=e.match($h);return t?t.map(jh).join(" "):e}},Aa={...Ge,transform:Math.round},Os={borderWidth:U,borderTopWidth:U,borderRightWidth:U,borderBottomWidth:U,borderLeftWidth:U,borderRadius:U,radius:U,borderTopLeftRadius:U,borderTopRightRadius:U,borderBottomRightRadius:U,borderBottomLeftRadius:U,width:U,maxWidth:U,height:U,maxHeight:U,top:U,right:U,bottom:U,left:U,padding:U,paddingTop:U,paddingRight:U,paddingBottom:U,paddingLeft:U,margin:U,marginTop:U,marginRight:U,marginBottom:U,marginLeft:U,backgroundPositionX:U,backgroundPositionY:U,...{rotate:ye,rotateX:ye,rotateY:ye,rotateZ:ye,scale:si,scaleX:si,scaleY:si,scaleZ:si,skew:ye,skewX:ye,skewY:ye,distance:U,translateX:U,translateY:U,translateZ:U,x:U,y:U,z:U,perspective:U,transformPerspective:U,opacity:_n,originX:Xo,originY:Xo,originZ:U},zIndex:Aa,fillOpacity:_n,strokeOpacity:_n,numOctaves:Aa},Uh={...Os,color:_t,backgroundColor:_t,outlineColor:_t,fill:_t,stroke:_t,borderColor:_t,borderTopColor:_t,borderRightColor:_t,borderBottomColor:_t,borderLeftColor:_t,filter:Ds,WebkitFilter:Ds},Ea=e=>Uh[e];function Ia(e,t){let n=Ea(e);return n!==Ds&&(n=_e),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Hh=new Set(["auto","none","0"]);function Gh(e,t,n){let i=0,s;for(;i<e.length&&!s;){const o=e[i];typeof o=="string"&&!Hh.has(o)&&xn(o).values.length&&(s=e[i]),i++}if(s&&n)for(const o of t)e[o]=Ia(n,s)}class Wh extends Ps{constructor(t,n,i,s,o){super(t,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let c=t[l];if(typeof c=="string"&&(c=c.trim(),ls(c))){const d=xa(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Sa.has(i)||t.length!==2)return;const[s,o]=t,r=ka(s),a=ka(o);if(r!==a)if(ha(r)&&ha(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else Re[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,i=[];for(let s=0;s<t.length;s++)(t[s]===null||Bh(t[s]))&&i.push(s);i.length&&Gh(t,i,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:i}=this;if(!t||!t.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Re[i](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&t.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:t,name:n,unresolvedKeyframes:i}=this;if(!t||!t.current)return;const s=t.getValue(n);s&&s.jump(this.measuredOrigin,!1);const o=i.length-1,r=i[o];i[o]=Re[n](t.measureViewportBox(),window.getComputedStyle(t.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{t.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function zh(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let i=document;const s=(n==null?void 0:n[e])??i.querySelectorAll(e);return s?Array.from(s):[]}return Array.from(e)}const Ra=(e,t)=>t&&typeof e=="number"?t.transform(e):e,Pa=30,qh=e=>!isNaN(parseFloat(e));class Kh{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Mt.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Mt.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=qh(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new is);const i=this.events[t].add(n);return t==="change"?()=>{i(),ut.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t,n=!0){!n||!this.passiveEffect?this.updateAndNotify(t,n):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-i}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Mt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Pa)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Pa);return Lo(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ke(e,t){return new Kh(e,t)}const{schedule:Vs}=zo(queueMicrotask,!1),qt={x:!1,y:!1};function Ma(){return qt.x||qt.y}function Xh(e){return e==="x"||e==="y"?qt[e]?null:(qt[e]=!0,()=>{qt[e]=!1}):qt.x||qt.y?null:(qt.x=qt.y=!0,()=>{qt.x=qt.y=!1})}function La(e,t){const n=zh(e),i=new AbortController,s={passive:!0,...t,signal:i.signal};return[n,s,()=>i.abort()]}function Da(e){return!(e.pointerType==="touch"||Ma())}function Yh(e,t,n={}){const[i,s,o]=La(e,n),r=a=>{if(!Da(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=u=>{Da(u)&&(c(u),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Oa=(e,t)=>t?e===t?!0:Oa(e,t.parentElement):!1,Ns=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Zh=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Jh(e){return Zh.has(e.tagName)||e.tabIndex!==-1}const li=new WeakSet;function Va(e){return t=>{t.key==="Enter"&&e(t)}}function Bs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Qh=(e,t)=>{const n=e.currentTarget;if(!n)return;const i=Va(()=>{if(li.has(n))return;Bs(n,"down");const s=Va(()=>{Bs(n,"up")}),o=()=>Bs(n,"cancel");n.addEventListener("keyup",s,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",i,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),t)};function Na(e){return Ns(e)&&!Ma()}function tf(e,t,n={}){const[i,s,o]=La(e,n),r=a=>{const l=a.currentTarget;if(!Na(a))return;li.add(l);const c=t(l,a),d=(g,v)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",p),li.has(l)&&li.delete(l),Na(g)&&typeof c=="function"&&c(g,{success:v})},u=g=>{d(g,l===window||l===document||n.useGlobalTarget||Oa(l,g.target))},p=g=>{d(g,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",p,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Ms(a)&&(a.addEventListener("focus",c=>Qh(c,s)),!Jh(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Ba(e){return Po(e)&&"ownerSVGElement"in e}function ef(e){return Ba(e)&&e.tagName==="svg"}const Tt=e=>!!(e&&e.getVelocity),nf=[...Ta,_t,_e],sf=e=>nf.find(Ca(e)),Tn=Ue({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class rf extends Wt{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=Ms(i)&&i.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function of({children:e,isPresent:t,anchorX:n,root:i}){const s=qi(),o=zt(null),r=zt({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=xt(Tn);return po(()=>{const{width:l,height:c,top:d,left:u,right:p}=r.current;if(t||!o.current||!l||!c)return;const g=n==="left"?`left: ${u}`:`right: ${p}`;o.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const w=i??document.head;return w.appendChild(v),v.sheet&&v.sheet.insertRule(`
2
+ [data-motion-pop-id="${s}"] {
3
+ position: absolute !important;
4
+ width: ${l}px !important;
5
+ height: ${c}px !important;
6
+ ${g}px !important;
7
+ top: ${d}px !important;
8
+ }
9
+ `),()=>{w.removeChild(v),w.contains(v)&&w.removeChild(v)}},[t]),P(rf,{isPresent:t,childRef:o,sizeRef:r,children:ld(e,{ref:o})})}const af=({children:e,initial:t,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=ti(lf),d=qi();let u=!0,p=Qt(()=>(u=!1,{id:d,initial:t,isPresent:n,custom:s,onExitComplete:g=>{c.set(g,!0);for(const v of c.values())if(!v)return;i&&i()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[n,c,i]);return o&&u&&(p={...p}),Qt(()=>{c.forEach((g,v)=>c.set(v,!1))},[n]),Jt(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(e=P(of,{isPresent:n,anchorX:a,root:l,children:e})),P(ei.Provider,{value:p,children:e})};function lf(){return new Map}function Fa(e=!0){const t=xt(ei);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=t,o=qi();Jt(()=>{if(e)return s(o)},[e]);const r=lo(()=>e&&i&&i(o),[o,i,e]);return!n&&i?[!1,r]:[!0]}const ci=e=>e.key||"";function ja(e){const t=[];return Zu.forEach(e,n=>{Eo(n)&&t.push(n)}),t}const cf=({children:e,custom:t,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,d]=Fa(r),u=Qt(()=>ja(e),[e]),p=r&&!c?[]:u.map(ci),g=zt(!0),v=zt(u),w=ti(()=>new Map),[_,y]=de(u),[x,S]=de(u);Io(()=>{g.current=!1,v.current=u;for(let O=0;O<x.length;O++){const I=ci(x[O]);p.includes(I)?w.delete(I):w.get(I)!==!0&&w.set(I,!1)}},[x,p.length,p.join("-")]);const k=[];if(u!==_){let O=[...u];for(let I=0;I<x.length;I++){const A=x[I],f=ci(A);p.includes(f)||(O.splice(I,0,A),k.push(A))}return o==="wait"&&k.length&&(O=k),S(ja(O)),y(u),null}const{forceRender:M}=xt(Zi);return P(ue,{children:x.map(O=>{const I=ci(O),A=r&&!c?!1:u===x||p.includes(I),f=()=>{if(w.has(I))w.set(I,!0);else return;let m=!0;w.forEach(h=>{h||(m=!1)}),m&&(M==null||M(),S(v.current),r&&(d==null||d()),i&&i())};return P(af,{isPresent:A,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:A?void 0:f,anchorX:a,children:O},I)})})},$a=Ue({strict:!1}),Ua={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Xe={};for(const e in Ua)Xe[e]={isEnabled:t=>Ua[e].some(n=>!!t[n])};function uf(e){for(const t in e)Xe[t]={...Xe[t],...e[t]}}const df=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ui(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||df.has(e)}let Ha=e=>!ui(e);function Ga(e){typeof e=="function"&&(Ha=t=>t.startsWith("on")?!ui(t):e(t))}try{Ga(require("@emotion/is-prop-valid").default)}catch{}function hf(e,t,n){const i={};for(const s in e)s==="values"&&typeof e.values=="object"||(Ha(s)||n===!0&&ui(s)||!t&&!ui(s)||e.draggable&&s.startsWith("onDrag"))&&(i[s]=e[s]);return i}function ff({children:e,isValidProp:t,...n}){t&&Ga(t),n={...xt(Tn),...n},n.isStatic=ti(()=>n.isStatic);const i=Qt(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return P(Tn.Provider,{value:i,children:e})}function pf(e){if(typeof Proxy>"u")return e;const t=new Map,n=(...i)=>e(...i);return new Proxy(n,{get:(i,s)=>s==="create"?e:(t.has(s)||t.set(s,e(s)),t.get(s))})}const di=Ue({});function hi(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function kn(e){return typeof e=="string"||Array.isArray(e)}const Fs=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],js=["initial",...Fs];function fi(e){return hi(e.animate)||js.some(t=>kn(e[t]))}function Wa(e){return!!(fi(e)||e.variants)}function mf(e,t){if(fi(e)){const{initial:n,animate:i}=e;return{initial:n===!1||kn(n)?n:void 0,animate:kn(i)?i:void 0}}return e.inherit!==!1?t:{}}function gf(e){const{initial:t,animate:n}=mf(e,xt(di));return Qt(()=>({initial:t,animate:n}),[za(t),za(n)])}function za(e){return Array.isArray(e)?e.join(" "):e}const vf=Symbol.for("motionComponentSymbol");function Ye(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function yf(e,t,n){return lo(i=>{i&&e.onMount&&e.onMount(i),t&&(i?t.mount(i):t.unmount()),n&&(typeof n=="function"?n(i):Ye(n)&&(n.current=i))},[t])}const $s=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),qa="data-"+$s("framerAppearId"),Ka=Ue({});function _f(e,t,n,i,s){var w,_;const{visualElement:o}=xt(di),r=xt($a),a=xt(ei),l=xt(Tn).reducedMotion,c=zt(null);i=i||r.renderer,!c.current&&i&&(c.current=i(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,u=xt(Ka);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&bf(c.current,n,s,u);const p=zt(!1);po(()=>{d&&p.current&&d.update(n,a)});const g=n[qa],v=zt(!!g&&!((w=window.MotionHandoffIsComplete)!=null&&w.call(window,g))&&((_=window.MotionHasOptimisedAnimation)==null?void 0:_.call(window,g)));return Io(()=>{d&&(p.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),Vs.render(d.render),v.current&&d.animationState&&d.animationState.animateChanges())}),Jt(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),v.current=!1))}),d}function bf(e,t,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Xa(e.parent)),e.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Ye(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:d,layoutScroll:l,layoutRoot:c})}function Xa(e){if(e)return e.options.allowProjection!==!1?e.projection:Xa(e.parent)}function wf({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:i,Component:s}){e&&uf(e);function o(a,l){let c;const d={...xt(Tn),...a,layoutId:xf(a)},{isStatic:u}=d,p=gf(a),g=i(a,u);if(!u&&Ji){Sf();const v=Cf(d);c=v.MeasureLayout,p.visualElement=_f(s,g,d,t,v.ProjectionNode)}return P(di.Provider,{value:p,children:[c&&p.visualElement?P(c,{visualElement:p.visualElement,...d}):null,n(s,a,yf(g,p.visualElement,l),g,u,p.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Yu(o);return r[vf]=s,r}function xf({layoutId:e}){const t=xt(Zi).id;return t&&e!==void 0?t+"-"+e:e}function Sf(e,t){xt($a).strict}function Cf(e){const{drag:t,layout:n}=Xe;if(!t&&!n)return{};const i={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const An={};function Tf(e){for(const t in e)An[t]=e[t],as(t)&&(An[t].isCSSVariable=!0)}function Ya(e,{layout:t,layoutId:n}){return qe.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!An[e]||e==="opacity")}const kf={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Af=ze.length;function Ef(e,t,n){let i="",s=!0;for(let o=0;o<Af;o++){const r=ze[o],a=e[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Ra(a,Os[r]);if(!l){s=!1;const d=kf[r]||r;i+=`${d}(${c}) `}n&&(t[r]=c)}}return i=i.trim(),n?i=n(t,s?"":i):s&&(i="none"),i}function Us(e,t,n){const{style:i,vars:s,transformOrigin:o}=e;let r=!1,a=!1;for(const l in t){const c=t[l];if(qe.has(l)){r=!0;continue}else if(as(l)){s[l]=c;continue}else{const d=Ra(c,Os[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(t.transform||(r||n?i.transform=Ef(t,e.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;i.transformOrigin=`${l} ${c} ${d}`}}const Hs=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Za(e,t,n){for(const i in t)!Tt(t[i])&&!Ya(i,n)&&(e[i]=t[i])}function If({transformTemplate:e},t){return Qt(()=>{const n=Hs();return Us(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Rf(e,t){const n=e.style||{},i={};return Za(i,n,e),Object.assign(i,If(e,t)),i}function Pf(e,t){const n={},i=Rf(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=i,n}const Mf={offset:"stroke-dashoffset",array:"stroke-dasharray"},Lf={offset:"strokeDashoffset",array:"strokeDasharray"};function Df(e,t,n=1,i=0,s=!0){e.pathLength=1;const o=s?Mf:Lf;e[o.offset]=U.transform(-i);const r=U.transform(t),a=U.transform(n);e[o.array]=`${r} ${a}`}function Ja(e,{attrX:t,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(Us(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:u,style:p}=e;u.transform&&(p.transform=u.transform,delete u.transform),(p.transform||u.transformOrigin)&&(p.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),p.transform&&(p.transformBox=(d==null?void 0:d.transformBox)??"fill-box",delete u.transformBox),t!==void 0&&(u.x=t),n!==void 0&&(u.y=n),i!==void 0&&(u.scale=i),s!==void 0&&Df(u,s,o,r,!1)}const Qa=()=>({...Hs(),attrs:{}}),tl=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Of(e,t,n,i){const s=Qt(()=>{const o=Qa();return Ja(o,t,tl(i),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Za(o,e.style,e),s.style={...o,...s.style}}return s}const Vf=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Gs(e){return typeof e!="string"||e.includes("-")?!1:!!(Vf.indexOf(e)>-1||/[A-Z]/u.test(e))}function Nf(e=!1){return(n,i,s,{latestValues:o},r)=>{const l=(Gs(n)?Of:Pf)(i,o,r,n),c=hf(i,typeof n=="string",e),d=n!==ue?{...c,...l,ref:s}:{},{children:u}=i,p=Qt(()=>Tt(u)?u.get():u,[u]);return Bt(n,{...d,children:p})}}function el(e){const t=[{},{}];return e==null||e.values.forEach((n,i)=>{t[0][i]=n.get(),t[1][i]=n.getVelocity()}),t}function Ws(e,t,n,i){if(typeof t=="function"){const[s,o]=el(i);t=t(n!==void 0?n:e.custom,s,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[s,o]=el(i);t=t(n!==void 0?n:e.custom,s,o)}return t}function pi(e){return Tt(e)?e.get():e}function Bf({scrapeMotionValuesFromProps:e,createRenderState:t},n,i,s){return{latestValues:Ff(n,i,s,e),renderState:t()}}const nl=e=>(t,n)=>{const i=xt(di),s=xt(ei),o=()=>Bf(e,t,i,s);return n?o():ti(o)};function Ff(e,t,n,i){const s={},o=i(e,{});for(const p in o)s[p]=pi(o[p]);let{initial:r,animate:a}=e;const l=fi(e),c=Wa(e);t&&c&&!l&&e.inherit!==!1&&(r===void 0&&(r=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||r===!1;const u=d?a:r;if(u&&typeof u!="boolean"&&!hi(u)){const p=Array.isArray(u)?u:[u];for(let g=0;g<p.length;g++){const v=Ws(e,p[g]);if(v){const{transitionEnd:w,transition:_,...y}=v;for(const x in y){let S=y[x];if(Array.isArray(S)){const k=d?S.length-1:0;S=S[k]}S!==null&&(s[x]=S)}for(const x in w)s[x]=w[x]}}}return s}function zs(e,t,n){var o;const{style:i}=e,s={};for(const r in i)(Tt(i[r])||t.style&&Tt(t.style[r])||Ya(r,e)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const jf={useVisualState:nl({scrapeMotionValuesFromProps:zs,createRenderState:Hs})};function il(e,t,n){const i=zs(e,t,n);for(const s in e)if(Tt(e[s])||Tt(t[s])){const o=ze.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=e[s]}return i}const $f={useVisualState:nl({scrapeMotionValuesFromProps:il,createRenderState:Qa})};function Uf(e,t){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Gs(i)?$f:jf,preloadedFeatures:e,useRender:Nf(s),createVisualElement:t,Component:i};return wf(r)}}function En(e,t,n){const i=e.getProps();return Ws(i,t,n!==void 0?n:i.custom,e)}const qs=e=>Array.isArray(e);function Hf(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Ke(n))}function Gf(e){return qs(e)?e[e.length-1]||0:e}function Wf(e,t){const n=En(e,t);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=Gf(o[r]);Hf(e,r,a)}}function zf(e){return!!(Tt(e)&&e.add)}function Ks(e,t){const n=e.getValue("willChange");if(zf(n))return n.add(t);if(!n&&fe.WillChange){const i=new fe.WillChange("auto");e.addValue("willChange",i),i.add(t)}}function sl(e){return e.props[qa]}const qf=e=>e!==null;function Kf(e,{repeat:t,repeatType:n="loop"},i){const s=e.filter(qf),o=t&&n!=="loop"&&t%2===1?0:s.length-1;return s[o]}const Xf={type:"spring",stiffness:500,damping:25,restSpeed:10},Yf=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Zf={type:"keyframes",duration:.8},Jf={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Qf=(e,{keyframes:t})=>t.length>2?Zf:qe.has(e)?e.startsWith("scale")?Yf(t[1]):Xf:Jf;function tp({when:e,delay:t,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Xs=(e,t,n,i={},s,o)=>r=>{const a=Ls(i,e)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-te(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:p=>{t.set(p),a.onUpdate&&a.onUpdate(p)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:s};tp(a)||Object.assign(d,Qf(e,d)),d.duration&&(d.duration=te(d.duration)),d.repeatDelay&&(d.repeatDelay=te(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let u=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(d.duration=0,d.delay===0&&(u=!0)),(fe.instantAnimations||fe.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&t.get()!==void 0){const p=Kf(d.keyframes,a);if(p!==void 0){ut.update(()=>{d.onUpdate(p),d.onComplete()});return}}return a.isSync?new Ss(d):new Dh(d)};function ep({protectedKeys:e,needsAnimating:t},n){const i=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,i}function rl(e,t,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:r,...a}=t;i&&(o=i);const l=[],c=s&&e.animationState&&e.animationState.getState()[s];for(const d in a){const u=e.getValue(d,e.latestValues[d]??null),p=a[d];if(p===void 0||c&&ep(c,d))continue;const g={delay:n,...Ls(o||{},d)},v=u.get();if(v!==void 0&&!u.isAnimating&&!Array.isArray(p)&&p===v&&!g.velocity)continue;let w=!1;if(window.MotionHandoffAnimation){const y=sl(e);if(y){const x=window.MotionHandoffAnimation(y,d,ut);x!==null&&(g.startTime=x,w=!0)}}Ks(e,d),u.start(Xs(d,u,p,e.shouldReduceMotion&&Sa.has(d)?{type:!1}:g,e,w));const _=u.animation;_&&l.push(_)}return r&&Promise.all(l).then(()=>{ut.update(()=>{r&&Wf(e,r)})}),l}function Ys(e,t,n={}){var l;const i=En(e,t,n.type==="exit"?(l=e.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=e.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(rl(e,i,n)):()=>Promise.resolve(),r=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:p}=s;return np(e,t,c,d,u,p,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,d]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>d())}else return Promise.all([o(),r(n.delay)])}function np(e,t,n=0,i=0,s=0,o=1,r){const a=[],l=e.variantChildren.size,c=(l-1)*s,d=typeof i=="function",u=d?p=>i(p,l):o===1?(p=0)=>p*s:(p=0)=>c-p*s;return Array.from(e.variantChildren).sort(ip).forEach((p,g)=>{p.notify("AnimationStart",t),a.push(Ys(p,t,{...r,delay:n+(d?0:i)+u(g)}).then(()=>p.notify("AnimationComplete",t)))}),Promise.all(a)}function ip(e,t){return e.sortNodePosition(t)}function sp(e,t,n={}){e.notify("AnimationStart",t);let i;if(Array.isArray(t)){const s=t.map(o=>Ys(e,o,n));i=Promise.all(s)}else if(typeof t=="string")i=Ys(e,t,n);else{const s=typeof t=="function"?En(e,t,n.custom):t;i=Promise.all(rl(e,s,n))}return i.then(()=>{e.notify("AnimationComplete",t)})}function ol(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}const rp=js.length;function al(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?al(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<rp;n++){const i=js[n],s=e.props[i];(kn(s)||s===!1)&&(t[i]=s)}return t}const op=[...Fs].reverse(),ap=Fs.length;function lp(e){return t=>Promise.all(t.map(({animation:n,options:i})=>sp(e,n,i)))}function cp(e){let t=lp(e),n=ll(),i=!0;const s=l=>(c,d)=>{var p;const u=En(e,d,l==="exit"?(p=e.presenceContext)==null?void 0:p.custom:void 0);if(u){const{transition:g,transitionEnd:v,...w}=u;c={...c,...w,...v}}return c};function o(l){t=l(e)}function r(l){const{props:c}=e,d=al(e.parent)||{},u=[],p=new Set;let g={},v=1/0;for(let _=0;_<ap;_++){const y=op[_],x=n[y],S=c[y]!==void 0?c[y]:d[y],k=kn(S),M=y===l?x.isActive:null;M===!1&&(v=_);let O=S===d[y]&&S!==c[y]&&k;if(O&&i&&e.manuallyAnimateOnMount&&(O=!1),x.protectedKeys={...g},!x.isActive&&M===null||!S&&!x.prevProp||hi(S)||typeof S=="boolean")continue;const I=up(x.prevProp,S);let A=I||y===l&&x.isActive&&!O&&k||_>v&&k,f=!1;const m=Array.isArray(S)?S:[S];let h=m.reduce(s(y),{});M===!1&&(h={});const{prevResolvedValues:b={}}=x,C={...b,...h},E=L=>{A=!0,p.has(L)&&(f=!0,p.delete(L)),x.needsAnimating[L]=!0;const V=e.getValue(L);V&&(V.liveStyle=!1)};for(const L in C){const V=h[L],J=b[L];if(g.hasOwnProperty(L))continue;let N=!1;qs(V)&&qs(J)?N=!ol(V,J):N=V!==J,N?V!=null?E(L):p.add(L):V!==void 0&&p.has(L)?E(L):x.protectedKeys[L]=!0}x.prevProp=S,x.prevResolvedValues=h,x.isActive&&(g={...g,...h}),i&&e.blockInitialAnimation&&(A=!1),A&&(!(O&&I)||f)&&u.push(...m.map(L=>({animation:L,options:{type:y}})))}if(p.size){const _={};if(typeof c.initial!="boolean"){const y=En(e,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(_.transition=y.transition)}p.forEach(y=>{const x=e.getBaseTarget(y),S=e.getValue(y);S&&(S.liveStyle=!0),_[y]=x??null}),u.push({animation:_})}let w=!!u.length;return i&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(w=!1),i=!1,w?t(u):Promise.resolve()}function a(l,c){var u;if(n[l].isActive===c)return Promise.resolve();(u=e.variantChildren)==null||u.forEach(p=>{var g;return(g=p.animationState)==null?void 0:g.setActive(l,c)}),n[l].isActive=c;const d=r(l);for(const p in n)n[p].protectedKeys={};return d}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=ll(),i=!0}}}function up(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!ol(t,e):!1}function Me(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ll(){return{animate:Me(!0),whileInView:Me(),whileHover:Me(),whileTap:Me(),whileDrag:Me(),whileFocus:Me(),exit:Me()}}class be{constructor(t){this.isMounted=!1,this.node=t}update(){}}class dp extends be{constructor(t){super(t),t.animationState||(t.animationState=cp(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();hi(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let hp=0;class fp extends be{constructor(){super(...arguments),this.id=hp++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const s=this.node.animationState.setActive("exit",!t);n&&!t&&s.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const pp={animation:{Feature:dp},exit:{Feature:fp}};function In(e,t,n,i={passive:!0}){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n)}function Rn(e){return{point:{x:e.pageX,y:e.pageY}}}const mp=e=>t=>Ns(t)&&e(t,Rn(t));function Pn(e,t,n,i){return In(e,t,mp(n),i)}function cl({top:e,left:t,right:n,bottom:i}){return{x:{min:t,max:n},y:{min:e,max:i}}}function gp({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function vp(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),i=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const ul=1e-4,yp=1-ul,_p=1+ul,dl=.01,bp=0-dl,wp=0+dl;function At(e){return e.max-e.min}function xp(e,t,n){return Math.abs(e-t)<=n}function hl(e,t,n,i=.5){e.origin=i,e.originPoint=pt(t.min,t.max,e.origin),e.scale=At(n)/At(t),e.translate=pt(n.min,n.max,e.origin)-e.originPoint,(e.scale>=yp&&e.scale<=_p||isNaN(e.scale))&&(e.scale=1),(e.translate>=bp&&e.translate<=wp||isNaN(e.translate))&&(e.translate=0)}function Mn(e,t,n,i){hl(e.x,t.x,n.x,i?i.originX:void 0),hl(e.y,t.y,n.y,i?i.originY:void 0)}function fl(e,t,n){e.min=n.min+t.min,e.max=e.min+At(t)}function Sp(e,t,n){fl(e.x,t.x,n.x),fl(e.y,t.y,n.y)}function pl(e,t,n){e.min=t.min-n.min,e.max=e.min+At(t)}function Ln(e,t,n){pl(e.x,t.x,n.x),pl(e.y,t.y,n.y)}const ml=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ze=()=>({x:ml(),y:ml()}),gl=()=>({min:0,max:0}),yt=()=>({x:gl(),y:gl()});function jt(e){return[e("x"),e("y")]}function Zs(e){return e===void 0||e===1}function Js({scale:e,scaleX:t,scaleY:n}){return!Zs(e)||!Zs(t)||!Zs(n)}function Le(e){return Js(e)||vl(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function vl(e){return yl(e.x)||yl(e.y)}function yl(e){return e&&e!=="0%"}function mi(e,t,n){const i=e-n,s=t*i;return n+s}function _l(e,t,n,i,s){return s!==void 0&&(e=mi(e,s,i)),mi(e,n,i)+t}function Qs(e,t=0,n=1,i,s){e.min=_l(e.min,t,n,i,s),e.max=_l(e.max,t,n,i,s)}function bl(e,{x:t,y:n}){Qs(e.x,t.translate,t.scale,t.originPoint),Qs(e.y,n.translate,n.scale,n.originPoint)}const wl=.999999999999,xl=1.0000000000001;function Cp(e,t,n,i=!1){const s=n.length;if(!s)return;t.x=t.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Qe(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(t.x*=r.x.scale,t.y*=r.y.scale,bl(e,r)),i&&Le(o.latestValues)&&Qe(e,o.latestValues))}t.x<xl&&t.x>wl&&(t.x=1),t.y<xl&&t.y>wl&&(t.y=1)}function Je(e,t){e.min=e.min+t,e.max=e.max+t}function Sl(e,t,n,i,s=.5){const o=pt(e.min,e.max,s);Qs(e,t,n,o,i)}function Qe(e,t){Sl(e.x,t.x,t.scaleX,t.scale,t.originX),Sl(e.y,t.y,t.scaleY,t.scale,t.originY)}function Cl(e,t){return cl(vp(e.getBoundingClientRect(),t))}function Tp(e,t,n){const i=Cl(e,n),{scroll:s}=t;return s&&(Je(i.x,s.offset.x),Je(i.y,s.offset.y)),i}const Tl=({current:e})=>e?e.ownerDocument.defaultView:null,kl=(e,t)=>Math.abs(e-t);function kp(e,t){const n=kl(e.x,t.x),i=kl(e.y,t.y);return Math.sqrt(n**2+i**2)}class Al{constructor(t,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const p=er(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=kp(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:w}=p,{timestamp:_}=St;this.history.push({...w,timestamp:_});const{onStart:y,onMove:x}=this.handlers;g||(y&&y(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),x&&x(this.lastMoveEvent,p)},this.handlePointerMove=(p,g)=>{this.lastMoveEvent=p,this.lastMoveEventInfo=tr(g,this.transformPagePoint),ut.update(this.updatePoint,!0)},this.handlePointerUp=(p,g)=>{this.end();const{onEnd:v,onSessionEnd:w,resumeAnimation:_}=this.handlers;if(this.dragSnapToOrigin&&_&&_(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=er(p.type==="pointercancel"?this.lastMoveEventInfo:tr(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(p,y),w&&w(p,y)},!Ns(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Rn(t),l=tr(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=St;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(t,er(l,this.history)),this.removeListeners=gn(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),ve(this.updatePoint)}}function tr(e,t){return t?{point:t(e.point)}:e}function El(e,t){return{x:e.x-t.x,y:e.y-t.y}}function er({point:e},t){return{point:e,delta:El(e,Il(t)),offset:El(e,Ap(t)),velocity:Ep(t,.1)}}function Ap(e){return e[0]}function Il(e){return e[e.length-1]}function Ep(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const s=Il(e);for(;n>=0&&(i=e[n],!(s.timestamp-i.timestamp>te(t)));)n--;if(!i)return{x:0,y:0};const o=ee(s.timestamp-i.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-i.x)/o,y:(s.y-i.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function Ip(e,{min:t,max:n},i){return t!==void 0&&e<t?e=i?pt(t,e,i.min):Math.max(e,t):n!==void 0&&e>n&&(e=i?pt(n,e,i.max):Math.min(e,n)),e}function Rl(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Rp(e,{top:t,left:n,bottom:i,right:s}){return{x:Rl(e.x,n,s),y:Rl(e.y,t,i)}}function Pl(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,i]=[i,n]),{min:n,max:i}}function Pp(e,t){return{x:Pl(e.x,t.x),y:Pl(e.y,t.y)}}function Mp(e,t){let n=.5;const i=At(e),s=At(t);return s>i?n=vn(t.min,t.max-i,e.min):i>s&&(n=vn(e.min,e.max-s,t.min)),he(0,1,n)}function Lp(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const nr=.35;function Dp(e=nr){return e===!1?e=0:e===!0&&(e=nr),{x:Ml(e,"left","right"),y:Ml(e,"top","bottom")}}function Ml(e,t,n){return{min:Ll(e,t),max:Ll(e,n)}}function Ll(e,t){return typeof e=="number"?e:e[t]||0}const Op=new WeakMap;class Vp{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=yt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=u=>{const{dragSnapToOrigin:p}=this.getProps();p?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Rn(u).point)},r=(u,p)=>{const{drag:g,dragPropagation:v,onDragStart:w}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Xh(g),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),jt(y=>{let x=this.getAxisMotionValue(y).get()||0;if(ne.test(x)){const{projection:S}=this.visualElement;if(S&&S.layout){const k=S.layout.layoutBox[y];k&&(x=At(k)*(parseFloat(x)/100))}}this.originPoint[y]=x}),w&&ut.postRender(()=>w(u,p)),Ks(this.visualElement,"transform");const{animationState:_}=this.visualElement;_&&_.setActive("whileDrag",!0)},a=(u,p)=>{this.latestPointerEvent=u,this.latestPanInfo=p;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:w,onDrag:_}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=p;if(v&&this.currentDirection===null){this.currentDirection=Np(y),this.currentDirection!==null&&w&&w(this.currentDirection);return}this.updateAxis("x",p.point,y),this.updateAxis("y",p.point,y),this.visualElement.render(),_&&_(u,p)},l=(u,p)=>{this.latestPointerEvent=u,this.latestPanInfo=p,this.stop(u,p),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>jt(u=>{var p;return this.getAnimationState(u)==="paused"&&((p=this.getAxisMotionValue(u).animation)==null?void 0:p.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new Al(t,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:i,contextWindow:Tl(this.visualElement)})}stop(t,n){const i=t||this.latestPointerEvent,s=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!i)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&ut.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,i){const{drag:s}=this.getProps();if(!i||!gi(t,s,this.currentDirection))return;const o=this.getAxisMotionValue(t);let r=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(r=Ip(r,this.constraints[t],this.elastic[t])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:t,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;t&&Ye(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&i?this.constraints=Rp(i.layoutBox,t):this.constraints=!1,this.elastic=Dp(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&jt(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Lp(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ye(t))return!1;const i=t.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Tp(i,s.root,this.visualElement.getTransformPagePoint());let r=Pp(s.layout.layoutBox,o);if(n){const a=n(gp(r));this.hasMutatedConstraints=!!a,a&&(r=cl(a))}return r}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=jt(d=>{if(!gi(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const p=s?200:1e6,g=s?40:1e7,v={type:"inertia",velocity:i?t[d]:0,bounceStiffness:p,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...u};return this.startAxisValueAnimation(d,v)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return Ks(this.visualElement,t),i.start(Xs(t,i,0,n,this.visualElement,!1))}stopAnimation(){jt(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){jt(t=>{var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){jt(n=>{const{drag:i}=this.getProps();if(!gi(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(n);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[n];o.set(t[n]-pt(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!Ye(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};jt(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=Mp({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),jt(r=>{if(!gi(r,t,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(pt(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;Op.set(this.visualElement,this);const t=this.visualElement.current,n=Pn(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();Ye(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ut.read(i);const r=In(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(jt(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=l[d].translate,u.set(u.get()+l[d].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=nr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function gi(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Np(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Bp extends be{constructor(t){super(t),this.removeGroupControls=Ft,this.removeListeners=Ft,this.controls=new Vp(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ft}unmount(){this.removeGroupControls(),this.removeListeners()}}const Dl=e=>(t,n)=>{e&&ut.postRender(()=>e(t,n))};class Fp extends be{constructor(){super(...arguments),this.removePointerDownListener=Ft}onPointerDown(t){this.session=new Al(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Tl(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Dl(t),onStart:Dl(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&ut.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=Pn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const vi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ol(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Dn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(U.test(e))e=parseFloat(e);else return e;const n=Ol(e,t.target.x),i=Ol(e,t.target.y);return`${n}% ${i}%`}},jp={correct:(e,{treeScale:t,projectionDelta:n})=>{const i=e,s=_e.parse(e);if(s.length>5)return i;const o=_e.createTransformer(e),r=typeof s[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;s[0+r]/=a,s[1+r]/=l;const c=pt(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Vl=!1;class $p extends Wt{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=t;Tf(Up),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Vl&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),vi.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Vl=!0,s||t.layoutDependency!==n||n===void 0||t.isPresent!==o?r.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?r.promote():r.relegate()||ut.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Vs.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=t;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Nl(e){const[t,n]=Fa(),i=xt(Zi);return P($p,{...e,layoutGroup:i,switchLayoutGroup:xt(Ka),isPresent:t,safeToRemove:n})}const Up={borderRadius:{...Dn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Dn,borderTopRightRadius:Dn,borderBottomLeftRadius:Dn,borderBottomRightRadius:Dn,boxShadow:jp};function Hp(e,t,n){const i=Tt(e)?e:Ke(e);return i.start(Xs("",i,t,n)),i.animation}const Gp=(e,t)=>e.depth-t.depth;class Wp{constructor(){this.children=[],this.isDirty=!1}add(t){Qi(this.children,t),this.isDirty=!0}remove(t){ts(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Gp),this.isDirty=!1,this.children.forEach(t)}}function zp(e,t){const n=Mt.now(),i=({timestamp:s})=>{const o=s-n;o>=t&&(ve(i),e(o-t))};return ut.setup(i,!0),()=>ve(i)}const Bl=["TopLeft","TopRight","BottomLeft","BottomRight"],qp=Bl.length,Fl=e=>typeof e=="string"?parseFloat(e):e,jl=e=>typeof e=="number"||U.test(e);function Kp(e,t,n,i,s,o){s?(e.opacity=pt(0,n.opacity??1,Xp(i)),e.opacityExit=pt(t.opacity??1,0,Yp(i))):o&&(e.opacity=pt(t.opacity??1,n.opacity??1,i));for(let r=0;r<qp;r++){const a=`border${Bl[r]}Radius`;let l=$l(t,a),c=$l(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||jl(l)===jl(c)?(e[a]=Math.max(pt(Fl(l),Fl(c),i),0),(ne.test(c)||ne.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=pt(t.rotate||0,n.rotate||0,i))}function $l(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Xp=Ul(0,.5,jo),Yp=Ul(.5,.95,Ft);function Ul(e,t,n){return i=>i<e?0:i>t?1:n(vn(e,t,i))}function Hl(e,t){e.min=t.min,e.max=t.max}function $t(e,t){Hl(e.x,t.x),Hl(e.y,t.y)}function Gl(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Wl(e,t,n,i,s){return e-=t,e=mi(e,1/n,i),s!==void 0&&(e=mi(e,1/s,i)),e}function Zp(e,t=0,n=1,i=.5,s,o=e,r=e){if(ne.test(t)&&(t=parseFloat(t),t=pt(r.min,r.max,t/100)-r.min),typeof t!="number")return;let a=pt(o.min,o.max,i);e===o&&(a-=t),e.min=Wl(e.min,t,n,a,s),e.max=Wl(e.max,t,n,a,s)}function zl(e,t,[n,i,s],o,r){Zp(e,t[n],t[i],t[s],t.scale,o,r)}const Jp=["x","scaleX","originX"],Qp=["y","scaleY","originY"];function ql(e,t,n,i){zl(e.x,t,Jp,n?n.x:void 0,i?i.x:void 0),zl(e.y,t,Qp,n?n.y:void 0,i?i.y:void 0)}function Kl(e){return e.translate===0&&e.scale===1}function Xl(e){return Kl(e.x)&&Kl(e.y)}function Yl(e,t){return e.min===t.min&&e.max===t.max}function tm(e,t){return Yl(e.x,t.x)&&Yl(e.y,t.y)}function Zl(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Jl(e,t){return Zl(e.x,t.x)&&Zl(e.y,t.y)}function Ql(e){return At(e.x)/At(e.y)}function tc(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class em{constructor(){this.members=[]}add(t){Qi(this.members,t),t.scheduleRender()}remove(t){if(ts(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(s=>t===s);if(n===0)return!1;let i;for(let s=n;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){i=o;break}}return i?(this.promote(i),!0):!1}promote(t,n){const i=this.lead;if(t!==i&&(this.prevLead=i,this.lead=t,t.show(),i)){i.instance&&i.scheduleRender(),t.scheduleRender(),t.resumeFrom=i,n&&(t.resumeFrom.preserveOpacity=!0),i.snapshot&&(t.snapshot=i.snapshot,t.snapshot.latestValues=i.animationValues||i.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:s}=t.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:i}=t;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function nm(e,t,n){let i="";const s=e.x.translate/t.x,o=e.y.translate/t.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(t.x!==1||t.y!==1)&&(i+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:u,rotateY:p,skewX:g,skewY:v}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),p&&(i+=`rotateY(${p}deg) `),g&&(i+=`skewX(${g}deg) `),v&&(i+=`skewY(${v}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const ir=["","X","Y","Z"],im=1e3;let sm=0;function sr(e,t,n,i){const{latestValues:s}=t;s[e]&&(n[e]=s[e],t.setStaticValue(e,0),i&&(i[e]=0))}function ec(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=sl(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ut,!(s||o))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&ec(i)}function nc({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=t==null?void 0:t()){this.id=sm++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(am),this.nodes.forEach(dm),this.nodes.forEach(hm),this.nodes.forEach(lm)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Wp)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new is),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=Ba(r)&&!ef(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let d,u=0;const p=()=>this.root.updateBlockedByResize=!1;ut.read(()=>{u=window.innerWidth}),e(r,()=>{const g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,d&&d(),d=zp(p,250),vi.hasAnimatedSinceResize&&(vi.hasAnimatedSinceResize=!1,this.nodes.forEach(rc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:p,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||vm,{onLayoutAnimationStart:w,onLayoutAnimationComplete:_}=c.getProps(),y=!this.targetLayout||!Jl(this.targetLayout,g),x=!u&&p;if(this.options.layoutRoot||this.resumeFrom||x||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...Ls(v,"layout"),onPlay:w,onComplete:_};(c.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(d,x)}else u||rc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),ve(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(fm),this.animationId++)}getTransformTemplate(){const{visualElement:r}=this.options;return r&&r.getProps().transformTemplate}willUpdate(r=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&ec(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const u=this.path[d];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ic);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(sc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(um),this.nodes.forEach(rm),this.nodes.forEach(om)):this.nodes.forEach(sc),this.clearAllSnapshots();const a=Mt.now();St.delta=he(0,1e3/60,a-St.timestamp),St.timestamp=a,St.isProcessing=!0,os.update.process(St),os.preRender.process(St),os.render.process(St),St.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Vs.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(cm),this.sharedNodes.forEach(pm)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ut.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ut.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!At(this.snapshot.measuredBox.x)&&!At(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=yt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Xl(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Le(this.latestValues)||d)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),ym(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return yt();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(_m))){const{scroll:d}=this.root;d&&(Je(a.x,d.offset.x),Je(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=yt();if($t(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const d=this.path[c],{scroll:u,options:p}=d;d!==this.root&&u&&p.layoutScroll&&(u.wasRoot&&$t(a,r),Je(a.x,u.offset.x),Je(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=yt();$t(l,r);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Qe(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Le(d.latestValues)&&Qe(l,d.latestValues)}return Le(this.latestValues)&&Qe(l,this.latestValues),l}removeTransform(r){const a=yt();$t(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Le(c.latestValues))continue;Js(c.latestValues)&&c.updateSnapshot();const d=yt(),u=c.measurePageBox();$t(d,u),ql(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Le(this.latestValues)&&ql(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==St.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var p;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(p=this.parent)!=null&&p.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:u}=this.options;if(!(!this.layout||!(d||u))){if(this.resolvedRelativeTargetAt=St.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=yt(),this.relativeTargetOrigin=yt(),Ln(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),$t(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=yt(),this.targetWithTransforms=yt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Sp(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):$t(this.target,this.layout.layoutBox),bl(this.target,this.targetDelta)):$t(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=yt(),this.relativeTargetOrigin=yt(),Ln(this.relativeTargetOrigin,this.target,g.target),$t(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Js(this.parent.latestValues)||vl(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var v;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(v=this.parent)!=null&&v.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===St.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;$t(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,p=this.treeScale.y;Cp(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=yt());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Gl(this.prevProjectionDelta.x,this.projectionDelta.x),Gl(this.prevProjectionDelta.y,this.projectionDelta.y)),Mn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==p||!tc(this.projectionDelta.x,this.prevProjectionDelta.x)||!tc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Ze(),this.projectionDelta=Ze(),this.projectionDeltaWithTransform=Ze()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=Ze();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const p=yt(),g=l?l.source:void 0,v=this.layout?this.layout.source:void 0,w=g!==v,_=this.getStack(),y=!_||_.members.length<=1,x=!!(w&&!y&&this.options.crossfade===!0&&!this.path.some(gm));this.animationProgress=0;let S;this.mixTargetDelta=k=>{const M=k/1e3;oc(u.x,r.x,M),oc(u.y,r.y,M),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Ln(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox),mm(this.relativeTarget,this.relativeTargetOrigin,p,M),S&&tm(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=yt()),$t(S,this.relativeTarget)),w&&(this.animationValues=d,Kp(d,c,this.latestValues,M,x,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=M},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(ve(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ut.update(()=>{vi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ke(0)),this.currentAnimation=Hp(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:d=>{this.mixTargetDelta(d),r.onUpdate&&r.onUpdate(d)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(im),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&dc(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||yt();const u=At(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const p=At(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+p}$t(a,l),Qe(a,d),Mn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new em),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&sr("z",r,c,this.animationValues);for(let d=0;d<ir.length;d++)sr(`rotate${ir[d]}`,r,c,this.animationValues),sr(`skew${ir[d]}`,r,c,this.animationValues);r.render();for(const d in c)r.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=pi(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=pi(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Le(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=nm(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:p,y:g}=this.projectionDelta;r.transformOrigin=`${p.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const v in An){if(d[v]===void 0)continue;const{correct:w,applyTo:_,isCSSVariable:y}=An[v],x=u==="none"?d[v]:w(d[v],c);if(_){const S=_.length;for(let k=0;k<S;k++)r[_[k]]=x}else y?this.options.visualElement.renderState.vars[v]=x:r[v]=x}this.options.layoutId&&(r.pointerEvents=c===this?pi(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(r=>{var a;return(a=r.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(ic),this.root.sharedNodes.clear()}}}function rm(e){e.updateLayout()}function om(e){var n;const t=((n=e.resumeFrom)==null?void 0:n.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=e.layout,{animationType:o}=e.options,r=t.source!==e.layout.source;o==="size"?jt(u=>{const p=r?t.measuredBox[u]:t.layoutBox[u],g=At(p);p.min=i[u].min,p.max=p.min+g}):dc(o,t.layoutBox,i)&&jt(u=>{const p=r?t.measuredBox[u]:t.layoutBox[u],g=At(i[u]);p.max=p.min+g,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[u].max=e.relativeTarget[u].min+g)});const a=Ze();Mn(a,i,t.layoutBox);const l=Ze();r?Mn(l,e.applyTransform(s,!0),t.measuredBox):Mn(l,i,t.layoutBox);const c=!Xl(a);let d=!1;if(!e.resumeFrom){const u=e.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:p,layout:g}=u;if(p&&g){const v=yt();Ln(v,t.layoutBox,p.layoutBox);const w=yt();Ln(w,i,g.layoutBox),Jl(v,w)||(d=!0),u.options.layoutRoot&&(e.relativeTarget=w,e.relativeTargetOrigin=v,e.relativeParent=u)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:t,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:d})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function am(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function lm(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function cm(e){e.clearSnapshot()}function ic(e){e.clearMeasurements()}function sc(e){e.isLayoutDirty=!1}function um(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function rc(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function dm(e){e.resolveTargetDelta()}function hm(e){e.calcProjection()}function fm(e){e.resetSkewAndRotation()}function pm(e){e.removeLeadSnapshot()}function oc(e,t,n){e.translate=pt(t.translate,0,n),e.scale=pt(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function ac(e,t,n,i){e.min=pt(t.min,n.min,i),e.max=pt(t.max,n.max,i)}function mm(e,t,n,i){ac(e.x,t.x,n.x,i),ac(e.y,t.y,n.y,i)}function gm(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const vm={duration:.45,ease:[.4,0,.1,1]},lc=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),cc=lc("applewebkit/")&&!lc("chrome/")?Math.round:Ft;function uc(e){e.min=cc(e.min),e.max=cc(e.max)}function ym(e){uc(e.x),uc(e.y)}function dc(e,t,n){return e==="position"||e==="preserve-aspect"&&!xp(Ql(t),Ql(n),.2)}function _m(e){var t;return e!==e.root&&((t=e.scroll)==null?void 0:t.wasRoot)}const bm=nc({attachResizeListener:(e,t)=>In(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),rr={current:void 0},hc=nc({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!rr.current){const e=new bm({});e.mount(window),e.setOptions({layoutScroll:!0}),rr.current=e}return rr.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),wm={pan:{Feature:Fp},drag:{Feature:Bp,ProjectionNode:hc,MeasureLayout:Nl}};function fc(e,t,n){const{props:i}=e;e.animationState&&i.whileHover&&e.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,o=i[s];o&&ut.postRender(()=>o(t,Rn(t)))}class xm extends be{mount(){const{current:t}=this.node;t&&(this.unmount=Yh(t,(n,i)=>(fc(this.node,i,"Start"),s=>fc(this.node,s,"End"))))}unmount(){}}class Sm extends be{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=gn(In(this.node.current,"focus",()=>this.onFocus()),In(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function pc(e,t,n){const{props:i}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&i.whileTap&&e.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),o=i[s];o&&ut.postRender(()=>o(t,Rn(t)))}class Cm extends be{mount(){const{current:t}=this.node;t&&(this.unmount=tf(t,(n,i)=>(pc(this.node,i,"Start"),(s,{success:o})=>pc(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const or=new WeakMap,ar=new WeakMap,Tm=e=>{const t=or.get(e.target);t&&t(e)},km=e=>{e.forEach(Tm)};function Am({root:e,...t}){const n=e||document;ar.has(n)||ar.set(n,{});const i=ar.get(n),s=JSON.stringify(t);return i[s]||(i[s]=new IntersectionObserver(km,{root:e,...t})),i[s]}function Em(e,t,n){const i=Am(t);return or.set(e,n),i.observe(e),()=>{or.delete(e),i.unobserve(e)}}const Im={some:0,all:1};class Rm extends be{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:o}=t,r={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Im[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),p=c?d:u;p&&p(l)};return Em(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Pm(t,n))&&this.startObserver()}unmount(){}}function Pm({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Mm={inView:{Feature:Rm},tap:{Feature:Cm},focus:{Feature:Sm},hover:{Feature:xm}},Lm={layout:{ProjectionNode:hc,MeasureLayout:Nl}},lr={current:null},mc={current:!1};function Dm(){if(mc.current=!0,!!Ji)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>lr.current=e.matches;e.addEventListener("change",t),t()}else lr.current=!1}const Om=new WeakMap;function Vm(e,t,n){for(const i in t){const s=t[i],o=n[i];if(Tt(s))e.addValue(i,s);else if(Tt(o))e.addValue(i,Ke(s,{owner:e}));else if(o!==s)if(e.hasValue(i)){const r=e.getValue(i);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=e.getStaticValue(i);e.addValue(i,Ke(r!==void 0?r:s,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const gc=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Nm{scrapeMotionValuesFromProps(t,n,i){return{}}constructor({parent:t,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ps,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const p=Mt.now();this.renderScheduledAt<p&&(this.renderScheduledAt=p,ut.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=t,this.props=n,this.presenceContext=i,this.depth=t?t.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=fi(n),this.isVariantNode=Wa(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(n,{},this);for(const p in u){const g=u[p];l[p]!==void 0&&Tt(g)&&g.set(l[p],!1)}}mount(t){this.current=t,Om.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),mc.current||Dm(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),ve(this.notifyUpdate),ve(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const i=qe.has(t);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[t]=a,this.props.onUpdate&&ut.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{s(),o(),r&&r(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Xe){const n=Xe[t];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[t]&&s&&i(this.props)&&(this.features[t]=new s(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):yt()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<gc.length;i++){const s=gc[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=t[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=Vm(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const i=this.values.get(t);n!==i&&(i&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let i=this.values.get(t);return i===void 0&&n!==void 0&&(i=Ke(n===null?void 0:n,{owner:this}),this.addValue(t,i)),i}readValue(t,n){let i=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return i!=null&&(typeof i=="string"&&(Ro(i)||Mo(i))?i=parseFloat(i):!sf(i)&&_e.test(n)&&(i=Ia(t,n)),this.setBaseTarget(t,Tt(i)?i.get():i)),Tt(i)?i.get():i}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var o;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const r=Ws(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);r&&(i=r[t])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,t);return s!==void 0&&!Tt(s)?s:this.initialValues[t]!==void 0&&i===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new is),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class vc extends Nm{constructor(){super(...arguments),this.KeyframeResolver=Wh}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:i}){delete n[t],delete i[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Tt(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function yc(e,{style:t,vars:n},i,s){const o=e.style;let r;for(r in t)o[r]=t[r];s==null||s.applyProjectionStyles(o,i);for(r in n)o.setProperty(r,n[r])}function Bm(e){return window.getComputedStyle(e)}class Fm extends vc{constructor(){super(...arguments),this.type="html",this.renderInstance=yc}readValueFromInstance(t,n){var i;if(qe.has(n))return(i=this.projection)!=null&&i.isProjecting?ks(n):dh(t,n);{const s=Bm(t),o=(as(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Cl(t,n)}build(t,n,i){Us(t,n,i.transformTemplate)}scrapeMotionValuesFromProps(t,n,i){return zs(t,n,i)}}const _c=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function jm(e,t,n,i){yc(e,t,void 0,i);for(const s in t.attrs)e.setAttribute(_c.has(s)?s:$s(s),t.attrs[s])}class $m extends vc{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=yt}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(qe.has(n)){const i=Ea(n);return i&&i.default||0}return n=_c.has(n)?n:$s(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,i){return il(t,n,i)}build(t,n,i){Ja(t,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(t,n,i,s){jm(t,n,i,s)}mount(t){this.isSVGTag=tl(t.tagName),super.mount(t)}}const Um=(e,t)=>Gs(e)?new $m(t):new Fm(t,{allowProjection:e!==ue}),Hm=Uf({...pp,...Mm,...wm,...Lm},Um),On=pf(Hm),bc=({stream:e})=>{const t=zt(null);return Jt(()=>{!t.current||!e||(t.current.srcObject=e)},[e]),P("audio",{muted:!0,ref:t,autoPlay:!0})};/**!
2
10
  * audioMotion-analyzer
3
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
4
12
  *
5
13
  * @version 4.5.1
6
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
7
15
  * @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});/**
16
+ */const Gm="4.5.1",cr=Math.PI,tn=2*cr,ur=cr/2,wc=8.17579892,xc="dual-combined",yi="dual-horizontal",pe="single",ie="dual-vertical",Sc="bar-index",Cc="bar-level",_i="gradient",Tc=60,kc="click",Wm="fullscreenchange",Ac="resize",zm="#111",Ec="",Ic="A",Rc="B",Pc="C",Mc="D",Lc="468",bi="sans-serif",qm="#0f0",Km="#7f7f7f22",en=10,Dc="create",Oc="fschange",Xm="lores",Ym=Ac,dr="user",Zm="#000c",Vc="#fff",Jm="#4f4",Nc="#888",Qm="#555",hr="bark",Vn="linear",nn="log",fr="mel",Bc=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Fc=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Bc}],["rainbow",{dir:"h",colorStops:["#817",...Bc,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Nn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:pe,colorMode:_i,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:nn,gradient:Fc[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:Ec,width:void 0},tg=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],eg=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],ng=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],pr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],ig=["ERR_INVALID_MODE","Invalid mode"],sg=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],rg=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],og=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],ag=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],lg=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ut extends Error{constructor(t,n){const[i,s]=t;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const jc=(e,t)=>console.warn(`${e} is deprecated. Use ${t} instead.`),$c=e=>{for(const t in e)return!1;return!0},wi=(e,t,n="toLowerCase")=>t[Math.max(0,t.indexOf((""+e)[n]()))],cg=(e,t,n,i,s)=>t+(i-t)*(s-e)/(n-e);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(e){let t=this.length;for(;t-- >0;)if(e(this[t]))return t;return-1});class ug{constructor(t,n={}){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=[],t instanceof Element||($c(n)&&!$c(t)&&(n=t),t=null),this._ownCanvas=!(n.canvas instanceof HTMLCanvasElement);const i=this._ownCanvas?document.createElement("canvas"):n.canvas;i.style="max-width: 100%;",this._ctx=i.getContext("2d");for(const[u,p]of Fc)this.registerGradient(u,p);this._container=t||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Ut(tg)}}if(!s.createGain)throw new Ut(eg);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const u of[0,1])r.connect(o[u],u);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const u of["_scaleX","_scaleR"])this[u]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Ym),this._fsTimeout=0)},Tc))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Ac,l,{signal:c}),i.addEventListener(Wm,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Oc),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Tc)},{signal:c});const d=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(kc,d))};window.addEventListener(kc,d),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Dc)}get alphaBars(){return this._alphaBars}set alphaBars(t){this._alphaBars=!!t,this._calcBars()}get ansiBands(){return this._ansiBands}set ansiBands(t){this._ansiBands=!!t,this._calcBars()}get barSpace(){return this._barSpace}set barSpace(t){this._barSpace=+t||0,this._calcBars()}get channelLayout(){return this._chLayout}set channelLayout(t){this._chLayout=wi(t,[pe,yi,ie,xc]),this._input.disconnect(),this._input.connect(this._chLayout!=pe?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=pe?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(t){this._colorMode=wi(t,[_i,Sc,Cc])}get fadePeaks(){return this._fadePeaks}set fadePeaks(t){this._fadePeaks=!!t}get fftSize(){return this._analyzer[0].fftSize}set fftSize(t){for(const i of[0,1])this._analyzer[i].fftSize=t;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(t){this._frequencyScale=wi(t,[nn,hr,fr,Vn]),this._calcBars()}get gradient(){return this._selectedGrads[0]}set gradient(t){this._setGradient(t)}get gradientLeft(){return this._selectedGrads[0]}set gradientLeft(t){this._setGradient(t,0)}get gradientRight(){return this._selectedGrads[1]}set gradientRight(t){this._setGradient(t,1)}get gravity(){return this._gravity}set gravity(t){this._gravity=t>0?+t:this._gravity||Nn.gravity}get height(){return this._height}set height(t){this._height=t,this._setCanvas(dr)}get ledBars(){return this._showLeds}set ledBars(t){this._showLeds=!!t,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(t){this._linearAmplitude=!!t}get linearBoost(){return this._linearBoost}set linearBoost(t){this._linearBoost=t>=1?+t:1}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=+t||0}get loRes(){return this._loRes}set loRes(t){this._loRes=!!t,this._setCanvas(Xm)}get lumiBars(){return this._lumiBars}set lumiBars(t){this._lumiBars=!!t,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(t){for(const n of[0,1])this._analyzer[n].maxDecibels=t}get maxFPS(){return this._maxFPS}set maxFPS(t){this._maxFPS=t<0?0:+t||0}get maxFreq(){return this._maxFreq}set maxFreq(t){if(t<1)throw new Ut(pr);this._maxFreq=Math.min(t,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(t){for(const n of[0,1])this._analyzer[n].minDecibels=t}get minFreq(){return this._minFreq}set minFreq(t){if(t<1)throw new Ut(pr);this._minFreq=+t,this._calcBars()}get mirror(){return this._mirror}set mirror(t){this._mirror=Math.sign(t)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(t){const n=t|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new Ut(ig,t)}get noteLabels(){return this._noteLabels}set noteLabels(t){this._noteLabels=!!t,this._createScales()}get outlineBars(){return this._outlineBars}set outlineBars(t){this._outlineBars=!!t,this._calcBars()}get peakFadeTime(){return this._peakFadeTime}set peakFadeTime(t){this._peakFadeTime=t>=0?+t:this._peakFadeTime||Nn.peakFadeTime}get peakHoldTime(){return this._peakHoldTime}set peakHoldTime(t){this._peakHoldTime=+t||0}get peakLine(){return this._peakLine}set peakLine(t){this._peakLine=!!t}get radial(){return this._radial}set radial(t){this._radial=!!t,this._calcBars(),this._makeGrad()}get radialInvert(){return this._radialInvert}set radialInvert(t){this._radialInvert=!!t,this._calcBars(),this._makeGrad()}get radius(){return this._radius}set radius(t){this._radius=+t||0,this._calcBars(),this._makeGrad()}get reflexRatio(){return this._reflexRatio}set reflexRatio(t){if(t=+t||0,t<0||t>=1)throw new Ut(sg);this._reflexRatio=t,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(t){this._roundBars=!!t,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(t){for(const n of[0,1])this._analyzer[n].smoothingTimeConstant=t}get spinSpeed(){return this._spinSpeed}set spinSpeed(t){t=+t||0,(this._spinSpeed===void 0||t==0)&&(this._spinAngle=-ur),this._spinSpeed=t}get splitGradient(){return this._splitGradient}set splitGradient(t){this._splitGradient=!!t,this._makeGrad()}get stereo(){return jc("stereo","channelLayout"),this._chLayout!=pe}set stereo(t){jc("stereo","channelLayout"),this.channelLayout=t?ie:pe}get trueLeds(){return this._trueLeds}set trueLeds(t){this._trueLeds=!!t}get volume(){return this._output.gain.value}set volume(t){this._output.gain.value=t}get weightingFilter(){return this._weightingFilter}set weightingFilter(t){this._weightingFilter=wi(t,[Ec,Ic,Rc,Pc,Mc,Lc],"toUpperCase")}get width(){return this._width}set width(t){this._width=t,this._setCanvas(dr)}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 Gm}connectInput(t){const n=t instanceof HTMLMediaElement;if(!(n||t.connect))throw new Ut(rg);const i=n?this.audioCtx.createMediaElementSource(t):t;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(t=this.audioCtx.destination){if(!this._outNodes.includes(t)&&(this._output.connect(t),this._outNodes.push(t),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==pe&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:t,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&t.close(),a&&n.remove(),this._calcBars()}disconnectInput(t,n){t?Array.isArray(t)||(t=[t]):t=Array.from(this._sources);for(const i of t){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const o of i.mediaStream.getAudioTracks())o.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(t){if(!(t&&!this._outNodes.includes(t))&&(this._output.disconnect(t),this._outNodes=t?this._outNodes.filter(n=>n!==t):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:t,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:t,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(t,n){if(t===void 0)return this._energy.val;if(t!=+t){if(t=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[t])return null;[t,n]=a[t]}const i=this._freqToBin(t),s=n?this._freqToBin(n):i,o=this._chLayout==pe?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(t){Array.isArray(t)||(t=[t]);let n={};for(const i of Object.keys(Nn))t.includes(i)||(i=="gradient"&&this.gradientLeft!=this.gradientRight?(n.gradientLeft=this.gradientLeft,n.gradientRight=this.gradientRight):i!="start"&&(n[i]=this[i]));return n}registerGradient(t,n){if(typeof t!="string"||t.trim().length==0)throw new Ut(og);if(typeof n!="object")throw new Ut(ag);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ut(lg);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[t]={bgColor:n.bgColor||zm,dir:n.dir,colorStops:i},this._selectedGrads.includes(t)&&this._makeGrad()}setCanvasSize(t,n){this._width=t,this._height=n,this._setCanvas(dr)}setFreqRange(t,n){if(t<1||n<1)throw new Ut(pr);this._minFreq=Math.min(t,n),this.maxFreq=Math.max(t,n)}setLedParams(t){let n,i,s;t&&(n=t.maxLeds|0,i=+t.spaceV,s=+t.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(t){this._setProps(t)}setSensitivity(t,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(t,n),this._analyzer[i].maxDecibels=Math.max(t,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(t){const n=this.isOn;return t===void 0&&(t=!n),n&&!t?(cancelAnimationFrame(this._runId),this._runId=0):!n&&t&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const t=this._fsEl;if(!t)return;t.requestFullscreen?t.requestFullscreen():t.webkitRequestFullscreen&&t.webkitRequestFullscreen()}}_binToFreq(t){return t*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const t=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:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:d,_radialInvert:u,_reflexRatio:p}=this,g=s.width>>1,v=s.height>>1,w=o==ie&&!d,_=o==yi,y=c%10!=0,x=y&&this._frequencyScale==nn,S=this._showLeds&&y&&!d,k=this._lumiBars&&y&&!d,M=this._alphaBars&&!k&&c!=en,O=this._outlineBars&&y&&!k&&!S,I=this._roundBars&&y&&!k&&!S,A=o!=ie||p>0&&!k,f=s.height-(w&&!S?.5:0)>>w,m=f*(k||d?1:1-p)|0,h=s.width-g*(_||l!=0),b=w?s.height-f*2:0,C=g*(l==-1&&!_&&!d);let E=Math.min(s.width,s.height)*.375*(o==ie?1:this._radius)|0,T=Math.min(g,v);u&&o!=ie&&([E,T]=[T,E]);const R=W=>t.push({...W,peak:[0,0],hold:[0],alpha:[0],value:[0]}),L=W=>{const X=this._freqToBin(W,"floor"),Y=this._binToFreq(X),tt=this._binToFreq(X+1),dt=Math.log2(W/Y)/Math.log2(tt/Y);return[X,dt]};let V,J,N;if(x){const W=(st,ft,it)=>+st.toPrecision(it?Math.max(ft,1+Math.log10(st)|0):ft),X=st=>{const ft=[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],it=Math.log10(st)|0,oe=st/10**it;let Kt=1;for(;Kt<ft.length&&oe>ft[Kt];)Kt++;return oe-ft[Kt-1]<ft[Kt]-oe&&Kt--,(ft[Kt]*10**(it+5)|0)/1e5},Y=[0,24,12,8,6,4,3,2,1][c],tt=n?10**(3/(Y*10)):2**(1/Y),dt=tt**.5;let Rt=n?7.94328235/(Y%2?1:dt):wc;do{let st=Rt;const ft=W(st/dt,4,!0),it=W(st*dt,4,!0),[oe,Kt]=L(ft),[Wn,ae]=L(it);n?st=Y<4?X(st):W(st,st.toString()[0]<5?3:2):st=W(st,4,!0),st>=a&&R({posX:0,freq:st,freqLo:ft,freqHi:it,binLo:oe,binHi:Wn,ratioLo:Kt,ratioHi:ae}),Rt*=tt}while(Rt<=r);V=h/t.length,t.forEach((st,ft)=>st.posX=C+ft*V);const ht=t[0],kt=t[t.length-1];J=this._freqScaling(ht.freqLo),N=h/(this._freqScaling(kt.freqHi)-J),ht.freqLo<a&&(ht.freqLo=a,[ht.binLo,ht.ratioLo]=L(a)),kt.freqHi>r&&(kt.freqHi=r,[kt.binHi,kt.ratioHi]=L(r))}else if(y){const W=[0,24,12,8,6,4,3,2,1][c]*10,X=Y=>{switch(this._frequencyScale){case hr:return 1960/(26.81/(Y+.53)-1);case fr:return 700*(2**Y-1);case Vn:return Y}};V=h/W,J=this._freqScaling(a),N=h/(this._freqScaling(r)-J);for(let Y=0,tt=0;Y<W;Y++,tt+=V){const dt=X(J+tt/N),Rt=X(J+(tt+V/2)/N),ht=X(J+(tt+V)/N),[kt,st]=L(dt),[ft,it]=L(ht);R({posX:C+tt,freq:Rt,freqLo:dt,freqHi:ht,binLo:kt,binHi:ft,ratioLo:st,ratioHi:it})}}else{V=1,J=this._freqScaling(a),N=h/(this._freqScaling(r)-J);const W=this._freqToBin(a,"floor"),X=this._freqToBin(r);let Y=-999;for(let tt=W;tt<=X;tt++){const dt=this._binToFreq(tt),Rt=C+Math.round(N*(this._freqScaling(dt)-J));if(Rt>Y)R({posX:Rt,freq:dt,freqLo:dt,freqHi:dt,binLo:tt,binHi:tt,ratioLo:0,ratioHi:0}),Y=Rt;else if(t.length){const ht=t[t.length-1];ht.binHi=tt,ht.freqHi=dt,ht.freq=(ht.freqLo*dt)**.5}}}let rt=0,Q=0;if(S){const W=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),X=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Y=this._ledParams,[tt,dt,Rt]=Y||X[c];let ht,kt=m;if(Y){const st=2*W;let ft;ht=tt+1;do ht--,ft=kt/ht/(1+dt),Q=ft*dt;while((ft<st||Q<st)&&ht>1)}else{const st=540/dt;Q=Math.min(dt*W,Math.max(2,kt/st+.1|0))}A&&(kt+=Q),Y||(ht=Math.min(tt,kt/(Q*2)|0)),rt=Rt>=1?Rt:V*Rt,this._leds=[ht,rt,Q,kt/ht-Q]}const j=Math.min(V-1,i*(i>0&&i<1?V:1));y&&(V-=Math.max(S?rt:0,j)),t.forEach((W,X)=>{let Y=W.posX,tt=V;y&&(i==0&&!S?(Y|=0,tt|=0,X>0&&Y>t[X-1].posX+t[X-1].width&&(Y--,tt++)):Y+=Math.max(S?rt:0,j)/2,W.posX=Y),W.barCenter=Y+(V==1?0:tt/2),W.width=tt});const lt=[];for(const W of[0,1]){const X=o==ie?(f+b)*W:0,Y=X+f,tt=X+m-(!S||A?0:Q);lt.push({channelTop:X,channelBottom:Y,analyzerBottom:tt})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:v,channelCoords:lt,channelHeight:f,channelGap:b,initialX:C,innerRadius:E,outerRadius:T,scaleMin:J,unitWidth:N},this._flg={isAlpha:M,isBands:y,isLeds:S,isLumi:k,isOctaves:x,isOutline:O,isRound:I,noLedGap:A},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:t,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:p}=this,g=u.canvas,v=p.canvas,w=[],_=this._chLayout==yi,y=this._chLayout==ie,x=Math.min(r.width,r.height),S=["C",,"D",,"E","F",,"G",,"A",,"B"],k=x/34|0,M=g.height>>1,O=k>>1,I=M*(c?.7:1.5),A=O*(c?1:2),f=2**(1/12);if(!c&&(this._ansiBands||a!=nn))w.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Vn?w.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):w.push(8e3,16e3);else{let T=wc;for(let R=-1;R<11;R++)for(let L=0;L<12;L++){if(T>=this._minFreq&&T<=this._maxFreq){const V=S[L],J=V=="C";(V&&c&&!l&&!_||J)&&w.push(c?[T,V+(J?R:"")]:T)}T*=f}}v.width=v.height=Math.max(x*.15,(i<<1)+y*k);const m=v.width>>1,h=m-k*.7,b=(T,R)=>{const L=tn*(T/r.width),V=L-ur,J=h*Math.cos(V),N=h*Math.sin(V);p.save(),p.translate(m+J,m+N),p.rotate(L),p.fillText(R,0,0),p.restore()};g.width|=0,u.fillStyle=p.strokeStyle=Zm,u.fillRect(0,0,g.width,g.height),p.arc(m,m,m-k/2,0,tn),p.lineWidth=k,p.stroke(),u.fillStyle=p.fillStyle=Vc,u.font=`${M}px ${bi}`,p.font=`${O}px ${bi}`,u.textAlign=p.textAlign="center";let C=-I/4,E=-A;for(const T of w){const[R,L]=Array.isArray(T)?T:[T,T<1e3?T|0:`${(T/100|0)/10}k`],V=o*(this._freqScaling(R)-s),J=g.height*.75,N=L[0]=="C",rt=M*(c&&!l&&!_?N?1.2:.6:3);if(u.fillStyle=p.fillStyle=N&&!l&&!_?Jm:Vc,c){const Q=a==nn,j=a==Vn;let lt=["C"];if((Q||R>2e3||!j&&R>250||(!d||y)&&(!j&&R>125||R>1e3))&&lt.push("G"),(Q||R>4e3||!j&&R>500||(!d||y)&&(!j&&R>250||R>2e3))&&lt.push("E"),(j&&R>4e3||(!d||y)&&(Q||R>2e3||!j&&R>500))&&lt.push("D","F","A","B"),!lt.includes(L[0]))continue}V>=C+I/2&&V<=t&&(u.fillText(L,_&&l==-1?t-V:n+V,J,rt),(_||l&&(V>I||l==1))&&u.fillText(L,_&&l!=1?t+V:(n||r.width)-V,J,rt),C=V+Math.min(rt,u.measureText(L).width)/2),V>=E+A&&V<t-A&&(b(_&&l==1?t-V:V,L),(_||l&&(V>A||l==1))&&b(_&&l!=-1?t+V:-V,L),E=V)}}_draw(t){this._runId=requestAnimationFrame(D=>this._draw(D));const n=t-this._time,i=t-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=t-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=t);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:d,isRound:u,noLedGap:p}=this._flg,{analyzerHeight:g,centerX:v,centerY:w,channelCoords:_,channelHeight:y,channelGap:x,initialX:S,innerRadius:k,outerRadius:M}=this._aux,{_bars:O,canvas:I,_canvasGradients:A,_chLayout:f,_colorMode:m,_ctx:h,_energy:b,_fadePeaks:C,fillAlpha:E,_fps:T,_linearAmplitude:R,_lineWidth:L,maxDecibels:V,minDecibels:J,_mirror:N,_mode:rt,overlay:Q,_radial:j,showBgColor:lt,showPeaks:W,useCanvas:X,_weightingFilter:Y}=this,tt=this._scaleX.canvas,dt=this._scaleR.canvas,Rt=T*this._peakFadeTime/1e3,ht=T**2,kt=this._gravity*1e3,st=T*this._peakHoldTime/1e3,ft=f==xc,it=f==yi,oe=f==ie,Kt=f==pe,Wn=a&&this._trueLeds&&m==_i,ae=j?I.width:this._aux.analyzerWidth,Ar=S+ae,zn=W&&this._peakLine&&rt==en,Se=j?M-k:g,Dv=Se/this._pixelRatio,[Ov,Uv,qn,Er]=this._leds||[];b.val>0&&T>0&&(this._spinAngle+=this._spinSpeed*tn/60/T);const Vv=D=>{if(this._reflexRatio>0&&!l&&!j){let et,le;this.reflexFit||oe?(et=oe&&D==0?y+x:0,le=y-g):(et=I.height-g*2,le=g),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,I.height),h.drawImage(I,0,_[D].channelTop,I.width,g,0,et,I.width,le),h.restore()}},Nv=()=>{this.showScaleX&&(j?(h.save(),h.translate(v,w),this._spinSpeed&&h.rotate(this._spinAngle+ur),h.drawImage(dt,-dt.width>>1,-dt.width>>1),h.restore()):h.drawImage(tt,0,I.height-tt.height))},Bv=D=>{const et=D**2,le=424.36,Ct=11599.29,Di=25122.25,Ce=544496.41,me=148693636,Ve=Ne=>20*Math.log10(Ne);switch(Y){case Ic:const Ne=me*et**2/((et+le)*Math.sqrt((et+Ct)*(et+Ce))*(et+me));return 2+Ve(Ne);case Rc:const Be=me*et*D/((et+le)*Math.sqrt(et+Di)*(et+me));return .17+Ve(Be);case Pc:const Pr=me*et/((et+le)*(et+me));return .06+Ve(Pr);case Mc:const Oi=((103791848e-2-et)**2+108076816e-2*et)/((9837328-et)**2+11723776*et),Mr=D/68966888496476e-18*Math.sqrt(Oi/((et+79919.29)*(et+1345600)));return Ve(Mr);case Lc:const Vi=-4737338981378384e-39*D**6+2043828333606125e-30*D**4-1363894795463638e-22*et+1,Fe=1306612257412824e-34*D**5-2118150887518656e-26*D**3+.0005559488023498642*D,Nt=.0001246332637532143*D/Math.hypot(Vi,Fe);return 18.2+Ve(Nt)}return 0},Ir=(D,et,le)=>{h.beginPath(),h.moveTo(D,et),h.lineTo(D,le),h.stroke()},Rr=D=>{if(D&&L){const et=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=et}},Oe=D=>Math.max(0,(D*Ov|0)*(Er+qn)-qn),Fv=D=>{b.val=D,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*kt/ht/I.height*this._pixelRatio)),D>=b.peak&&(b.peak=D,b.hold=st)};Q&&h.clearRect(0,0,I.width,I.height);let Iu=0;const Ru=O.length,Pu=Kt?1:2;for(let D=0;D<Pu;D++){const{channelTop:et,channelBottom:le,analyzerBottom:Ct}=_[D],Di=this._gradients[this._selectedGrads[D]],Ce=Di.colorStops,me=Ce.length,Ve=!lt||a&&!Q?"#000":Di.bgColor,Ne=oe&&j&&D?-1:1,Be=!D&&N==-1||D&&N==1,Pr=!it||D&&N!=1?0:ae>>(D||!Be),Oi=it&&Be?-1:1,Mr=()=>{const $=tt.height,H=$>>1,z=R?100:V,ct=R?0:J,bt=R?20:5,Vt=g/(z-ct),ce=N!=-1&&(!it||D==0||N==1),Te=N!=1&&(!it||D!=N);h.save(),h.fillStyle=Nc,h.font=`${H}px ${bi}`,h.textAlign="right",h.lineWidth=1;for(let ke=z;ke>ct;ke-=bt){const cn=et+(z-ke)*Vt,wt=ke%2==0|0;if(wt){const Pt=cn+H*(cn==et?.8:.35);ce&&h.fillText(ke,$*.85,Pt),Te&&h.fillText(ke,(it?ae:I.width)-$*.1,Pt),h.strokeStyle=Nc,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=Qm,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(S+$*wt*ce,~~cn+.5),h.lineTo(Ar-$*wt*Te,~~cn+.5),h.stroke()}h.restore()},Vi=($,H)=>{const z=Xt[$]+($<Xt.length-1?(Xt[$+1]-Xt[$])*H:0);return isNaN(z)?-1/0:z},Fe=($,H=Oi)=>H*tn*(($+Pr)/I.width)+this._spinAngle,Nt=($,H,z)=>{const ct=k+H*Ne,bt=Fe($,z);return[v+ct*Math.cos(bt),w+ct*Math.sin(bt)]},Lr=($,H,z,ct,bt)=>{h.beginPath();for(const Vt of N&&!it?[1,-1]:[Oi]){const[ce,Te]=u?[Fe($,Vt),Fe($+z,Vt)]:[];h.moveTo(...Nt($,H,Vt)),h.lineTo(...Nt($,H+ct,Vt)),u?h.arc(v,w,k+(H+ct)*Ne,ce,Te,Vt!=1):h.lineTo(...Nt($+z,H+ct,Vt)),h.lineTo(...Nt($+z,H,Vt)),u&&!bt&&h.arc(v,w,k+H*Ne,Te,ce,Vt==1)}Rr(bt),h.fill()},Dr=($=0,H=0)=>{let z;if(m==_i&&!Wn||rt==en)z=A[D];else{const ct=m==Sc?H%me:Ce.findLastIndex(bt=>a?Oe($)<=Oe(bt.level):$<=bt.level);z=Ce[ct].color}h.fillStyle=h.strokeStyle=z};if(X){if(it&&!j){const $=ae*(D+Be),H=Be?-1:1;h.setTransform(H,0,0,1,$,0)}if((!Q||lt)&&(Q&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Ve,(D==0||!j&&!ft)&&h.fillRect(S,et-x,ae,(Q&&this.reflexAlpha==1?g:y)+x),h.globalAlpha=1),this.showScaleY&&!l&&!j&&(D==0||!ft)&&Mr(),a?(h.setLineDash([Er,qn]),h.lineWidth=O[0].width):h.lineWidth=d?Math.min(L,O[0].width/2):L,h.save(),!j){const $=new Path2D;$.rect(0,et,I.width,g),h.clip($)}}let Xt=this._fftData[D];this._analyzer[D].getFloatFrequencyData(Xt),Y&&(Xt=Xt.map(($,H)=>$+Bv(this._binToFreq(H)))),h.beginPath();let Kn=[];for(let $=0;$<Ru;$++){const H=O[$],{posX:z,barCenter:ct,width:bt,freq:Vt,binLo:ce,binHi:Te,ratioLo:ke,ratioHi:cn}=H;let wt=Math.max(Vi(ce,ke),Vi(Te,cn));for(let ot=ce+1;ot<Te;ot++)Xt[ot]>wt&&(wt=Xt[ot]);if(wt=this._normalizedB(wt),H.value[D]=wt,Iu+=wt,H.peak[D]>0&&H.alpha[D]>0&&(H.hold[D]--,H.hold[D]<0)){if(C&&!zn){const ot=!o||d&&L>0?1:o?H.peak[D]:E;H.alpha[D]=ot*(1+H.hold[D]/Rt)}else H.peak[D]+=H.hold[D]*kt/ht/Dv;H.alpha[D]<=0&&(H.peak[D]=0)}if(wt>=H.peak[D]&&(H.peak[D]=wt,H.hold[D]=st,H.alpha[D]=!o||d&&L>0?1:o?wt:E),!X)continue;h.globalAlpha=l||o?wt:d?E:1,Dr(wt,$);const Pt=l?Se:a?Oe(wt):wt*Se|0;if(rt==en){const ot=$?0:(this._normalizedB(Xt[O[1].binLo])*Se+Pt)/2;if(j){if($==0&&(it&&h.moveTo(...Nt(0,0)),h.lineTo(...Nt(0,z<0?ot:Pt))),z>=0){const Gt=[z,Pt];h.lineTo(...Nt(...Gt)),Kn.push(Gt)}}else{if($==0)if(N==-1&&!it)h.moveTo(S,Ct-(z<S?ot:Pt));else{const Gt=ce?this._normalizedB(Xt[ce-1])*Se:Pt;h.moveTo(S-L,Ct-Gt)}(it||N!=-1||z>=S)&&h.lineTo(z,Ct-Pt)}}else if(a){if(lt&&!Q&&(D==0||!ft)){const ot=h.globalAlpha;h.strokeStyle=Km,h.globalAlpha=1,Ir(ct,et,Ct),h.strokeStyle=h.fillStyle,h.globalAlpha=ot}if(Wn){const ot=l?0:Ce.findLastIndex(je=>Oe(wt)<=Oe(je.level));let Gt=Ct;for(let je=me-1;je>=ot;je--){h.strokeStyle=Ce[je].color;let Lu=Ct-(je==ot?Pt:Oe(Ce[je].level));Ir(ct,Gt,Lu),Gt=Lu-qn}}else Ir(ct,Ct,Ct-Pt)}else if(z>=S)if(j)Lr(z,0,bt,Pt,d);else if(u){const ot=bt/2,Gt=Ct+ot;h.beginPath(),h.moveTo(z,Gt),h.lineTo(z,Gt-Pt),h.arc(ct,Gt-Pt,ot,cr,tn),h.lineTo(z+bt,Gt),Rr(d),h.fill()}else{const ot=d?h.lineWidth:0;h.beginPath(),h.rect(z,Ct+ot,bt,-Pt-ot),Rr(d),h.fill()}const un=H.peak[D],Mu=H.alpha[D];if(un>0&&Mu>0&&W&&!zn&&!l&&z>=S&&z<Ar){if(C?h.globalAlpha=Mu:d&&L>0?h.globalAlpha=1:o&&(h.globalAlpha=un),(m==Cc||Wn)&&Dr(un),a){const ot=Oe(un);ot>=qn&&h.fillRect(z,Ct-ot,bt,Er)}else if(!j)h.fillRect(z,Ct-un*Se,bt,2);else if(rt!=en){const ot=un*Se;Lr(z,ot,bt,!this._radialInvert||oe||ot+k>=2?-2:2)}}}if(X){if(h.globalAlpha=1,rt==en){if(Dr(),j&&!it){if(N){let $;for(;$=Kn.pop();)h.lineTo(...Nt(...$,-1))}h.closePath()}if(L>0&&h.stroke(),E>0){if(j){const $=it?Fe(ae>>1):0,H=it?Fe(ae):tn;h.moveTo(...Nt(it?ae>>1:0,0)),h.arc(v,w,k,$,H,it?!Be:!0)}else h.lineTo(Ar,Ct),h.lineTo(S,Ct);h.globalAlpha=E,h.fill(),h.globalAlpha=1}if((zn||j&&W)&&(Kn=[],h.beginPath(),O.forEach(($,H)=>{let z=$.posX,ct=$.peak[D],bt=H?"lineTo":"moveTo";if(j&&z<0){const Vt=O[H+1];ct=cg(z,ct,Vt.posX,Vt.peak[D],0),z=0}ct*=Se,zn?(h[bt](...j?Nt(z,ct):[z,Ct-ct]),j&&N&&!it&&Kn.push([z,ct])):ct>0&&Lr(z,ct,1,-2)}),zn)){let $;for(;$=Kn.pop();)h.lineTo(...Nt(...$,-1));h.lineWidth=1,h.stroke()}}h.restore(),it&&!j&&h.setTransform(1,0,0,1,0,0),(!it&&!ft||D)&&Vv(D)}}if(Fv(Iu/(Ru<<Pu-1)),X&&(N&&!j&&!it&&(h.setTransform(-1,0,0,1,I.width-S,0),h.drawImage(I,S,0,v,I.height,0,0,v,I.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),Nv()),this.showFPS){const D=tt.height;h.font=`bold ${D}px ${bi}`,h.fillStyle=qm,h.textAlign="right",h.fillText(Math.round(T),I.width-D,D*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=A[0],this.onCanvasDraw(this,{timestamp:t,canvasGradients:A}),h.restore())}_freqScaling(t){switch(this._frequencyScale){case nn:return Math.log2(t);case hr:return 26.81*t/(1960+t)-.53;case fr:return Math.log2(1+t/700);case Vn:return t}}_freqToBin(t,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](t*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:t,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:d}=this._aux,{isLumi:u}=this._flg,p=this._chLayout==ie,g=1-s,v=u?t.height:t.height*(1-s*!p)|0;for(const w of[0,1]){const _=this._gradients[this._selectedGrads[w]],y=_.colorStops,x=_.dir=="h";let S;if(i?S=n.createRadialGradient(r,a,d,r,a,c-(d-c)*p):S=n.createLinearGradient(...x?[l,0,l+o,0]:[0,0,0,v]),y){const k=p&&!this._splitGradient&&(!x||i);for(let M=0;M<1+k;M++){const O=y.length-1;y.forEach((I,A)=>{let f=I.pos;if(k&&(f/=2),p&&!u&&!i&&!x&&(f*=g,!k&&f>.5*g&&(f+=.5*s)),M==1)if(i||u){const m=O-A;I=y[m],f=1-I.pos/2}else A==0&&f>0&&S.addColorStop(.5,I.color),f+=.5;S.addColorStop(f,I.color),p&&A==O&&f<.5&&S.addColorStop(.5,I.color)})}}this._canvasGradients[w]=S}}_normalizedB(t){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,d)=>l<=c?c:l>=d?d:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),t=o(t)**i),s((t-a)/(r-a)**i,0,1)}_setCanvas(t){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==n,d=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,u=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(t!=Dc&&n.width==d&&n.height==u)&&(n.width=d,n.height=u,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,d,u)),i.lineJoin="bevel",s.width=d,s.height=Math.max(20*o,Math.min(d,u)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(t=Oc),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(t,this))}_setGradient(t,n){if(!this._gradients.hasOwnProperty(t))throw new Ut(ng,t);[0,1].includes(n)||(this._selectedGrads[1]=t,n=0),this._selectedGrads[n]=t,this._makeGrad()}_setProps(t,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(Nn).filter(r=>r!="start").concat(i,s);(n||t===void 0)&&(t={...Nn,...t});for(const r of Object.keys(t))i.includes(r)&&typeof t[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=t[r]);t.start!==void 0&&this.toggleAnalyzer(t.start)}}function Uc(e){var t,n,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(n=Uc(e[t]))&&(i&&(i+=" "),i+=n)}else for(n in e)e[n]&&(i&&(i+=" "),i+=n);return i}function Bn(){for(var e,t,n=0,i="",s=arguments.length;n<s;n++)(e=arguments[n])&&(t=Uc(e))&&(i&&(i+=" "),i+=t);return i}const Hc=({stream:e,className:t,onClick:n})=>{const i=zt(null);return Jt(()=>{if(!i.current||!e)return;const s=new AudioContext,o=s.createMediaStreamSource(e),r=new ug(i.current,{source:o,audioCtx:s,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,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:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return r.registerGradient("gradient",{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]}),r.gradient="gradient",()=>{r.disconnectInput()}},[e]),P("div",{onClick:n,className:Bn("w-full",t),ref:i})},dg=["agent-id","environment","position"],xi="widget-layout-id";/**
17
+ * @license lucide-preact v0.515.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const Gc=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),hg=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,i)=>i?i.toUpperCase():n.toLowerCase()),Wc=e=>{const t=hg(e);return t.charAt(0).toUpperCase()+t.slice(1)},fg=(...e)=>e.filter((t,n,i)=>!!t&&t.trim()!==""&&i.indexOf(t)===n).join(" ").trim();/**
22
+ * @license lucide-preact v0.515.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */var pg={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"};/**
29
27
  * @license lucide-preact v0.515.0 - ISC
30
28
  *
31
29
  * This source code is licensed under the ISC license.
32
30
  * See the LICENSE file in the root directory of this source tree.
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();/**
31
+ */const mg=({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>Bt("svg",{...pg,width:String(t),height:t,stroke:e,"stroke-width":i?Number(n)*24/Number(t):n,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Bt(l,c)),...Zt(s)]);/**
34
32
  * @license lucide-preact v0.515.0 - ISC
35
33
  *
36
34
  * This source code is licensed under the ISC license.
37
35
  * See the LICENSE file in the root directory of this source tree.
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"};/**
36
+ */const we=(e,t)=>{const n=({class:i="",children:s,...o})=>Bt(mg,{...o,iconNode:t,class:fg(`lucide-${Gc(Wc(e))}`,`lucide-${Gc(e)}`,i)},s);return n.displayName=Wc(e),n};/**
39
37
  * @license lucide-preact v0.515.0 - ISC
40
38
  *
41
39
  * This source code is licensed under the ISC license.
42
40
  * See the LICENSE file in the root directory of this source tree.
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)]);/**
41
+ */const gg=we("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"}]]);/**
44
42
  * @license lucide-preact v0.515.0 - ISC
45
43
  *
46
44
  * This source code is licensed under the ISC license.
47
45
  * See the LICENSE file in the root directory of this source tree.
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};/**
46
+ */const vg=we("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
49
47
  * @license lucide-preact v0.515.0 - ISC
50
48
  *
51
49
  * This source code is licensed under the ISC license.
52
50
  * See the LICENSE file in the root directory of this source tree.
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"}]]);/**
51
+ */const yg=we("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
54
52
  * @license lucide-preact v0.515.0 - ISC
55
53
  *
56
54
  * This source code is licensed under the ISC license.
57
55
  * See the LICENSE file in the root directory of this source tree.
58
- */const mr=Rt("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
56
+ */const _g=we("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"}]]);/**
59
57
  * @license lucide-preact v0.515.0 - ISC
60
58
  *
61
59
  * This source code is licensed under the ISC license.
62
60
  * See the LICENSE file in the root directory of this source tree.
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"}]]);/**
61
+ */const bg=we("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"}]]);/**
64
62
  * @license lucide-preact v0.515.0 - ISC
65
63
  *
66
64
  * This source code is licensed under the ISC license.
67
65
  * See the LICENSE file in the root directory of this source tree.
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"}]]);/**
66
+ */const wg=we("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
69
67
  * @license lucide-preact v0.515.0 - ISC
70
68
  *
71
69
  * This source code is licensed under the ISC license.
72
70
  * 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})})();
71
+ */const xg=we("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"}]]);/**
72
+ * @license lucide-preact v0.515.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const Sg=we("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Si=({children:e,className:t,onClick:n})=>P("button",{onClick:n,className:Bn("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",t),children:e}),zc=({call:e})=>{const[t,n]=de(!1),i=()=>{n(o=>{const r=!o;return r?e.muteAudio():e.unmuteAudio(),r})},s=()=>{e.hangup()};return P("div",{className:"flex items-center justify-center gap-2",children:[P(Si,{onClick:i,className:Bn(t?"bg-[#750000]":"bg-[#3C3C3C]"),children:t?P(yg,{className:"w-5 h-5"}):P(_g,{className:"w-5 h-5"})}),P(Si,{onClick:s,className:"bg-[#750000]",children:P(bg,{className:"w-4 h-4"})})]})},qc=({call:e,onExpand:t})=>P(On.div,{layoutId:xi,className:"p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center bg-black text-white shadow-lg shadow-[#38383878] gap-3",children:[P(Hc,{onClick:t,className:"h-[72px] cursor-pointer",stream:e.remoteStream}),P(bc,{stream:e.remoteStream}),P("h1",{className:"text-xs",children:"Speak to interrupt"}),P(zc,{call:e})]});function Cg({item:e}){const t=zt(null);return Jt(()=>{t.current&&t.current.scrollIntoView({behavior:"smooth"})},[]),P("li",{className:Bn("flex flex-col gap-1 text-left",{"items-end":e.role==="user"}),ref:t,children:[P("span",{className:"text-xs text-[#969696]",children:e.timestamp.toLocaleTimeString()}),P("p",{className:Bn("text-white text-sm",{"bg-[#222227] px-2.5 py-2 rounded-md":e.role==="user"}),children:e.content})]})}const Tg=({transcript:e})=>P("div",{className:"h-[320px] sm:h-[400px] bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[P("ul",{className:"overflow-y-auto flex flex-col gap-4 p-4 flex-1",children:e.map((t,n)=>P(Cg,{item:t},t.id+n))}),P("div",{className:"flex items-center h-8 bg-[#222227] rounded-full p-2 gap-2",children:[P("input",{type:"text",placeholder:"Type something here",className:"w-full outline-none text-sm"}),P(Si,{children:P(wg,{className:"text-[#969696] w-4 h-4"})})]})]});function kg({onCollapse:e}){return P("div",{className:"flex items-center justify-between w-full",children:P(Si,{className:"ml-auto",onClick:e,children:P(Sg,{})})})}const Ag=({call:e,onCollapse:t,transcript:n})=>P(cf,{children:P(On.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-black gap-3 text-white w-full max-w-[400px] rounded-t-3xl sm:rounded-3xl text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878] origin-bottom-right",children:[P("div",{className:"p-4",children:[P(kg,{onCollapse:t}),P(Hc,{className:"h-[144px]",stream:e.remoteStream}),P("h1",{className:"mb-4",children:"Speak or text to interrupt"}),P(zc,{call:e})]}),P(bc,{stream:e.remoteStream}),P(Tg,{transcript:n})]})});function mr(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function G(e,t,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(d){o(d)}}function a(c){try{l(i.throw(c))}catch(d){o(d)}}function l(c){var d;c.done?s(c.value):(d=c.value,d instanceof n?d:new n(function(u){u(d)})).then(r,a)}l((i=i.apply(e,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var Kc=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Eg=new Uint8Array(16);function Ig(){if(!Kc)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Kc(Eg)}for(var Xc=[],Ci=0;Ci<256;++Ci)Xc[Ci]=(Ci+256).toString(16).substr(1);function Fn(e,t,n){var i=t&&n||0;typeof e=="string"&&(t=e==="binary"?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||Ig)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var o=0;o<16;++o)t[i+o]=s[o];return t||function(r,a){var l=0,c=Xc;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}var Rg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yc(e,t){return e(t={exports:{}},t.exports),t.exports}var Pg=Yc(function(e){var t,n;t=Rg,n=function(){var i=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(_,y){var x=_[y];if(typeof x.bind=="function")return x.bind(_);try{return Function.prototype.bind.call(x,_)}catch{return function(){return Function.prototype.apply.apply(x,[_,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(_,y){for(var x=0;x<r.length;x++){var S=r[x];this[S]=x<_?i:this.methodFactory(S,_,y)}this.log=this.debug}function d(_,y,x){return function(){typeof console!==s&&(c.call(this,y,x),this[_].apply(this,arguments))}}function u(_,y,x){return function(S){return S==="debug"&&(S="log"),typeof console!==s&&(S==="trace"&&o?l:console[S]!==void 0?a(console,S):console.log!==void 0?a(console,"log"):i)}(_)||d.apply(this,arguments)}function p(_,y,x){var S,k=this;y=y??"WARN";var M="loglevel";function O(){var A;if(typeof window!==s&&M){try{A=window.localStorage[M]}catch{}if(typeof A===s)try{var f=window.document.cookie,m=f.indexOf(encodeURIComponent(M)+"=");m!==-1&&(A=/^([^;]+)/.exec(f.slice(m))[1])}catch{}return k.levels[A]===void 0&&(A=void 0),A}}typeof _=="string"?M+=":"+_:typeof _=="symbol"&&(M=void 0),k.name=_,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=x||u,k.getLevel=function(){return S},k.setLevel=function(A,f){if(typeof A=="string"&&k.levels[A.toUpperCase()]!==void 0&&(A=k.levels[A.toUpperCase()]),!(typeof A=="number"&&A>=0&&A<=k.levels.SILENT))throw"log.setLevel() called with invalid level: "+A;if(S=A,f!==!1&&function(m){var h=(r[m]||"silent").toUpperCase();if(typeof window!==s&&M){try{return void(window.localStorage[M]=h)}catch{}try{window.document.cookie=encodeURIComponent(M)+"="+h+";"}catch{}}}(A),c.call(k,A,_),typeof console===s&&A<k.levels.SILENT)return"No console available for logging"},k.setDefaultLevel=function(A){y=A,O()||k.setLevel(A,!1)},k.resetLevel=function(){k.setLevel(y,!1),function(){if(typeof window!==s&&M){try{return void window.localStorage.removeItem(M)}catch{}try{window.document.cookie=encodeURIComponent(M)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},k.enableAll=function(A){k.setLevel(k.levels.TRACE,A)},k.disableAll=function(A){k.setLevel(k.levels.SILENT,A)};var I=O();I==null&&(I=y),k.setLevel(I,!1)}var g=new p,v={};g.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var y=v[_];return y||(y=v[_]=new p(_,g.getLevel(),g.methodFactory)),y};var w=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=w),g},g.getLoggers=function(){return v},g.default=g,g},e.exports?e.exports=n():t.log=n()});const B=Pg.getLogger("telnyx"),Mg=B.methodFactory;B.methodFactory=(e,t,n)=>{const i=Mg(e,t,n);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);i.apply(void 0,s)}},B.setLevel(B.getLevel());const Zc="Time to call invite",Jc="wss://rtc.telnyx.com",Lg={urls:"stun:stun.telnyx.com:3478"},Dg={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var F;(function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"})(F||(F={}));const Qc=e=>Object.keys(e).length===0,Ti=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{B.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},tu=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},sn=e=>e instanceof Function||typeof e=="function",jn=e=>typeof document=="object"&&"getElementById"in document?typeof e=="string"?document.getElementById(e)||null:typeof e=="function"?e():e instanceof HTMLMediaElement?e:null:null,Og=/^(ws|wss):\/\//,eu=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(s===null)return t!==null&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?eu(a,r):{result:s}},nu=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),gr=({login:e,passwd:t,password:n,login_token:i})=>!!(e&&(t||n)||i),ki=({anonymous_login:e})=>!!e&&!!e.target_id&&!!e.target_type,vr=e=>{var t,n,i,s,o,r;let a="",l="";return!((n=(t=e==null?void 0:e.result)===null||t===void 0?void 0:t.params)===null||n===void 0)&&n.state&&(a=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=e==null?void 0:e.params)===null||o===void 0)&&o.state&&(l=(r=e==null?void 0:e.params)===null||r===void 0?void 0:r.state),a||l};function iu({debounceTime:e}){let t,n;return{promise:new Promise((i,s)=>{t=e?Vg(i,e):i,n=s}),resolve:t,reject:n}}const Vg=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{e(...i)},t)}},rn="GLOBAL",Lt={},$n=(e,t)=>`${e}|${t}`,su=(e,t=rn)=>$n(e,t)in Lt,on=(e,t,n=rn)=>{const i=$n(e,n);i in Lt||(Lt[i]=[]),Lt[i].push(t)},ru=(e,t,n=rn)=>{const i=function(s){an(e,i,n),t(s)};return i.prototype.targetRef=t,on(e,i,n)},an=(e,t,n=rn)=>{if(!su(e,n))return!1;const i=$n(e,n);if(sn(t))for(let s=Lt[i].length-1;s>=0;s--){const o=Lt[i][s];(t===o||o.prototype&&t===o.prototype.targetRef)&&Lt[i].splice(s,1)}else Lt[i]=[];return Lt[i].length===0&&delete Lt[i],!0},Z=(e,t,n=rn,i=!0)=>{const s=i&&n!==rn;if(!su(e,n))return s&&Z(e,t),!1;const o=$n(e,n),r=Lt[o].length;if(!r)return s&&Z(e,t),!1;for(let a=r-1;a>=0;a--)Lt[o][a](t);return s&&Z(e,t),!0},yr=e=>{const t=$n(e,"");Object.keys(Lt).filter(n=>n.indexOf(t)===0).forEach(n=>delete Lt[n])};var Dt,xe,nt;(function(e){e.Offer="offer",e.Answer="answer"})(Dt||(Dt={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(xe||(xe={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.Display="telnyx_rtc.display",e.Media="telnyx_rtc.media",e.Event="telnyx_rtc.event",e.Bye="telnyx_rtc.bye",e.Punt="telnyx_rtc.punt",e.Broadcast="telnyx_rtc.broadcast",e.Subscribe="telnyx_rtc.subscribe",e.Unsubscribe="telnyx_rtc.unsubscribe",e.ClientReady="telnyx_rtc.clientReady",e.Modify="telnyx_rtc.modify",e.Ringing="telnyx_rtc.ringing",e.GatewayState="telnyx_rtc.gatewayState",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(nt||(nt={}));const se={generic:"event",[nt.Display]:"participantData",[nt.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},Ng={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 K,Un,Et,re,It;(function(e){e[e.New=0]="New",e[e.Requesting=1]="Requesting",e[e.Trying=2]="Trying",e[e.Recovering=3]="Recovering",e[e.Ringing=4]="Ringing",e[e.Answering=5]="Answering",e[e.Early=6]="Early",e[e.Active=7]="Active",e[e.Held=8]="Held",e[e.Hangup=9]="Hangup",e[e.Destroy=10]="Destroy",e[e.Purge=11]="Purge"})(K||(K={})),function(e){e.Participant="participant",e.Moderator="moderator"}(Un||(Un={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(Et||(Et={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(re||(re={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(It||(It={}));const _r="telnyx-voice-sdk-id";function br(){return sessionStorage.getItem(_r)}typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(_r)});let Bg=typeof WebSocket<"u"?WebSocket:null;const Fg=0,jg=1,$g=2,Ug=3;class ou{constructor(t){this.session=t,this.previousGatewayState="",this._wsClient=null,this._host=Jc,this._timers={},this.upDur=null,this.downDur=null;const{host:n,env:i,region:s}=t.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Jc),n&&(this._host=(o=>`${Og.test(o)?"":"wss://"}${o}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`))}get connected(){return this._wsClient&&this._wsClient.readyState===jg}get connecting(){return this._wsClient&&this._wsClient.readyState===Fg}get closing(){return this._wsClient&&this._wsClient.readyState===$g}get closed(){return this._wsClient&&this._wsClient.readyState===Ug}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const t=new URL(this._host),n=br();n&&t.searchParams.set("voice_sdk_id",n),this._wsClient=new Bg(t.toString()),this._wsClient.onopen=i=>Z(F.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Z(F.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Z(F.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=tu(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(_r,a)),this._unsetTimer(r.id),B.debug(`RECV:
77
+ `,JSON.stringify(r,null,2),`
78
+ `),It[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!Z(r.id,r)){const l=vr(r);Z(F.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}sendRawText(t){this._wsClient.send(t)}send(t){const{request:n}=t,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();ru(n.id,r=>{const{result:a,error:l}=eu(r);return l?o(l):s(a)})});return B.debug(`SEND:
79
+ `,JSON.stringify(n,null,2),`
80
+ `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(sn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(t){clearTimeout(this._timers[t]),delete this._timers[t]}_handleStringResponse(t){if(/^#SP/.test(t))switch(t[3]){case"U":this.upDur=parseInt(t.substring(4));break;case"D":this.downDur=parseInt(t.substring(4)),Z(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else B.warn("Unknown message from socket",t)}}class Ai{buildRequest(t){this.request=Object.assign({jsonrpc:"2.0",id:Fn()},t)}}const au={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 Ot extends Ai{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=mr(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in au)i&&n.hasOwnProperty(i)&&(n[au[i]]=n[i],delete n[i]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class lu extends Ot{constructor(){super(),this.method=nt.GatewayState,this.buildRequest({method:this.method,params:{}})}}class Hg{constructor(t){this.pendingRequestId=null,this.onSocketMessage=n=>G(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(vr(n))}),this.getIsRegistered=()=>G(this,void 0,void 0,function*(){const n=new lu;this.pendingRequestId=n.request.id,this.gatewayStateTask=iu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[It.REGISTER,It.REGED].includes(i)}),this.session=t,this.gatewayStateTask=iu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Gg{constructor(t){if(this.options=t,this.uuid=Fn(),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 ou(this),this.registerAgent=new Hg(this)}get __logger(){return B}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*nu(2,6)}execute(t){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:t})):this.connected?this.connection.send(t):new Promise(n=>{this._executeQueue.push({resolve:n,msg:t}),this.connect()})}executeRaw(t){this._idle?this._executeQueue.push({msg:t}):this.connection.sendRawText(t)}validateOptions(){return gr(this.options)||ki(this.options)}broadcast(t){}disconnect(){return G(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(t,n){return on(t,n,this.uuid),this}off(t,n){return an(t,n,this.uuid),this}connect(){return G(this,void 0,void 0,function*(){this.connection||(this.connection=new ou(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(t){Z(F.Error,{error:t,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return G(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&yr(this.relayProtocol);for(const t in this.subscriptions)yr(t);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(t){}_removeSubscription(t,n){this._existsSubscription(t,n)&&(n?(delete this.subscriptions[t][n],an(t,null,n)):(delete this.subscriptions[t],yr(t)))}_addSubscription(t,n=null,i){this._existsSubscription(t,i)||(this._existsSubscription(t)||(this.subscriptions[t]={}),this.subscriptions[t][i]={},sn(n)&&on(t,n,i))}_existsSubscription(t,n){return!(!this.subscriptions.hasOwnProperty(t)||!(!n||n&&this.subscriptions[t].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:t,msg:n})=>{typeof n=="string"?this.executeRaw(n):t(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){this._doKeepAlive===!0&&(this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),3e4))}static on(t,n){on(t,n)}static off(t){an(t)}static uuid(){return Fn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const wr=e=>navigator.mediaDevices.getUserMedia(e),Ei=e=>e&&e instanceof MediaStream,Ii=(e,t)=>{const n=jn(e);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},cu=(e,t)=>G(void 0,void 0,void 0,function*(){const n=jn(e);if(n===null)return B.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof t!="string")return B.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch{return!1}}),Wg=e=>{e&&e.readyState==="live"&&e.stop()},Hn=e=>{Ei(e)&&e.getTracks().forEach(Wg),e=null},Ri=e=>G(void 0,void 0,void 0,function*(){B.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield wr(e)}catch(i){throw B.error("getUserMedia error: ",i),i}}),Gn=(e=null,t=!1)=>G(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===re.AudioIn||s===re.AudioOut,video:!s||s===re.Video}))(e)).catch(s=>(console.error(s),null));if(i){if(Hn(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter(o=>o.kind===e)),t===!0)return n;const s=[];n=n.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return n}),uu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Pi=(e,t,n)=>G(void 0,void 0,void 0,function*(){const i=yield Gn(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(e===o||t===r)return o}return null}),du=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(n=>{t.hasOwnProperty(n)&&e[n]!==null&&e[n]!==void 0||delete e[n]})},hu=(e,t,n,i)=>G(void 0,void 0,void 0,function*(){const{deviceId:s}=i;if(s===void 0&&(e||t)){const o=yield Pi(e,t,n).catch(r=>null);o&&(i.deviceId={exact:o})}return i}),xr=e=>{const t=`\r
81
+ `,n=e.split(t),i=n.findIndex(a=>/^a=rtpmap/.test(a)&&/opus\/48000/.test(a));if(i<0)return e;const s=(a=>{const l=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),c=a.match(l);return c&&c.length==2?c[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex(a=>o.test(a));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},fu=e=>/^m=audio/.test(e),pu=e=>/^m=video/.test(e),mu=(e,t)=>{const n=`\r
82
+ `,i=t.split(n);if(i.findIndex(fu)<i.findIndex(pu))return e;const s=e.split(n),o=s.findIndex(fu),r=s.findIndex(pu),a=s.slice(o,r),l=s.slice(r,s.length-1);return[...s.slice(0,o),...l,...a,""].join(n)},Mi=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Sr(e);return n.includes(t)||i.includes(t)},Sr=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(n=>{t[n]=e[`${n}Channels`]||[]}),t},ln=(e,t=null,n=null)=>{if(!Ei(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},gu=e=>{ln(e,"audio",!0)},vu=e=>{ln(e,"audio",!1)},yu=e=>{ln(e,"audio",null)};function zg(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/safari/gim)[0],u=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const d=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Ri}}catch(e){return e.message}}var gt;function _u(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function bu(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then(()=>{e._playFulfilled=!0}).catch(t=>{console.error("playAudio",t),e._playFulfilled=!0}))}function wu(e){e&&(e._playFulfilled?(e.pause(),e.currentTime=0):e._promise&&e._promise.then?e._promise.then(()=>{e.pause(),e.currentTime=0}):setTimeout(()=>{e.pause(),e.currentTime=0},1e3))}(function(e){e.not_supported="not supported",e.full="full",e.partial="partial"})(gt||(gt={}));var xu="2.22.12",Cr=xu;class qg extends Ot{constructor(t,n,i,s,o={},r){super(),this.method="login";const a={login:t,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Cr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Kg extends Ot{constructor(t,n){super(),this.buildRequest({id:t,result:{method:n}})}}class Xg extends Ot{toString(){return nt.Invite}}class Yg extends Ot{toString(){return nt.Answer}}class Zg extends Ot{toString(){return nt.Attach}}class Jg extends Ot{toString(){return nt.Bye}}class Tr extends Ot{toString(){return nt.Modify}}class Su extends Ot{toString(){return nt.Info}}class Qg extends Ot{toString(){return nt.Broadcast}}class tv extends Ot{toString(){return nt.Subscribe}}class ev extends Ot{toString(){return nt.Unsubscribe}}const Cu=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:se.conferenceUpdate,call:e.calls[s],canvasInfo:nv(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:Et.LayerInfo},a);Z(F.Notification,l,e.uuid);break}case"layout-info":{const l=Object.assign({action:Et.LayoutInfo},a);Z(F.Notification,l,e.uuid);break}}},nv=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return tu(t)};var Li,Tu=Yc(function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,m,h,b){var C,E,T;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((E=f._events)?(E.newListener&&(f.emit("newListener",m,h.listener?h.listener:h),E=f._events),T=E[m]):(E=f._events=new i,f._eventsCount=0),T){if(typeof T=="function"?T=E[m]=b?[h,T]:[T,h]:b?T.unshift(h):T.push(h),!T.warned&&(C=o(f))&&0<C&&T.length>C){T.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+T.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=f,R.type=m,R.count=T.length,function(L){typeof console.warn=="function"?console.warn(L):console.log(L)}(R)}}else T=E[m]=h,++f._eventsCount;return f}function a(f,m,h){function b(){f.removeListener(m,b),C||(C=!0,h.apply(f,arguments))}var C=!1;return b.listener=h,b}function l(f){var m=this._events;if(m){var h=m[f];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(f,m){for(var h=Array(m);m--;)h[m]=f[m];return h}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var m,h,b,C,E,T,R,L=f==="error";if(T=this._events)L=L&&T.error==null;else if(!L)return!1;if(R=this.domain,L){if(m=arguments[1],!R){if(m instanceof Error)throw m;var V=new Error('Uncaught, unspecified "error" event. ('+m+")");throw V.context=m,V}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=R,m.domainThrown=!1,R.emit("error",m),!1}if(!(h=T[f]))return!1;var J=typeof h=="function";switch(b=arguments.length){case 1:(function(N,rt,Q){if(rt)N.call(Q);else for(var j=N.length,lt=c(N,j),W=0;W<j;++W)lt[W].call(Q)})(h,J,this);break;case 2:(function(N,rt,Q,j){if(rt)N.call(Q,j);else for(var lt=N.length,W=c(N,lt),X=0;X<lt;++X)W[X].call(Q,j)})(h,J,this,arguments[1]);break;case 3:(function(N,rt,Q,j,lt){if(rt)N.call(Q,j,lt);else for(var W=N.length,X=c(N,W),Y=0;Y<W;++Y)X[Y].call(Q,j,lt)})(h,J,this,arguments[1],arguments[2]);break;case 4:(function(N,rt,Q,j,lt,W){if(rt)N.call(Q,j,lt,W);else for(var X=N.length,Y=c(N,X),tt=0;tt<X;++tt)Y[tt].call(Q,j,lt,W)})(h,J,this,arguments[1],arguments[2],arguments[3]);break;default:for(C=Array(b-1),E=1;E<b;E++)C[E-1]=arguments[E];(function(N,rt,Q,j){if(rt)N.apply(Q,j);else for(var lt=N.length,W=c(N,lt),X=0;X<lt;++X)W[X].apply(Q,j)})(h,J,this,C)}return!0},s.prototype.addListener=function(f,m){return r(this,f,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,m){return r(this,f,m,!0)},s.prototype.once=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,m)),this},s.prototype.prependOnceListener=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,m)),this},s.prototype.removeListener=function(f,m){var h,b,C,E,T;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[f]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete b[f],b.removeListener&&this.emit("removeListener",f,h.listener||m));else if(typeof h!="function"){for(C=-1,E=h.length;0<E--;)if(h[E]===m||h[E].listener&&h[E].listener===m){T=h[E].listener,C=E;break}if(0>C)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[f]}else(function(R,L){for(var V=L,J=V+1,N=R.length;J<N;V+=1,J+=1)R[V]=R[J];R.pop()})(h,C);b.removeListener&&this.emit("removeListener",f,T||m)}return this},s.prototype.removeAllListeners=function(f){var m,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[f]&&(--this._eventsCount==0?this._events=new i:delete h[f]),this;if(arguments.length===0){for(var b,C=Object.keys(h),E=0;E<C.length;++E)(b=C[E])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[f])=="function")this.removeListener(f,m);else if(m)do this.removeListener(f,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(f){var m,h,b=this._events;return b?h=(m=b[f])?typeof m=="function"?[m.listener||m]:function(C){for(var E=Array(C.length),T=0;T<E.length;++T)E[T]=C[T].listener||C[T];return E}(m):[]:h=[],h},s.listenerCount=function(f,m){return typeof f.listenerCount=="function"?f.listenerCount(m):l.call(f,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function p(){if(!d&&!(d=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 d(u)}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,v=[],w=0;256>w;++w)v.push((w+256).toString(16).substr(1));function _(f){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(v[f[m+0]]+v[f[m+1]]+v[f[m+2]]+v[f[m+3]]+"-"+v[f[m+4]]+v[f[m+5]]+"-"+v[f[m+6]]+v[f[m+7]]+"-"+v[f[m+8]]+v[f[m+9]]+"-"+v[f[m+10]]+v[f[m+11]]+v[f[m+12]]+v[f[m+13]]+v[f[m+14]]+v[f[m+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&g.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(f,m,h){var b=(f=f||{}).random||(f.rng||p)();return b[6]=64|15&b[6],b[8]=128|63&b[8],_(b)}function x(f,m){if(!f||!m)return{};const h={...f};if(h.localCandidateId){const b=m.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=m.get(h.remoteCandidateId);h.remote={...b}}return h}function S(f,m,h){return 8*function(b,C,E){const T=b[E],R=C?C[E]:null;return T===null||R===null?null:(T-R)/(b.timestamp-C.timestamp)*1e3}(f,m,h)}function k(f){if(!f.entries)return f;const m={};return f.forEach(function(h,b){m[b]=h}),m}function M(f,m,h={}){if(!f)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const C of f.values())switch(C.type){case"outbound-rtp":{const E=C.mediaType||C.kind,T={};let R={};if(!["audio","video"].includes(E))continue;if(C.codecId){const L=f.get(C.codecId);L&&(T.clockRate=L.clockRate,T.mimeType=L.mimeType,T.payloadType=L.payloadType)}R=f.get(C.mediaSourceId)||f.get(C.trackId)||{},b[E].outbound.push({...C,...T,track:{...R}});break}case"inbound-rtp":{let E=C.mediaType||C.kind,T={};const R={};if(!["audio","video"].includes(E))if(C.id.includes("Video"))E="video";else{if(!C.id.includes("Audio"))continue;E="audio"}if(C.codecId){const L=f.get(C.codecId);L&&(R.clockRate=L.clockRate,R.mimeType=L.mimeType,R.payloadType=L.payloadType)}if(!b.connection.id&&C.transportId){const L=f.get(C.transportId);if(L&&L.selectedCandidatePairId){const V=f.get(L.selectedCandidatePairId);b.connection=x(V,f)}}T=f.get(C.mediaSourceId)||f.get(C.trackId)||{},b[E].inbound.push({...C,...R,track:{...T}});break}case"peer-connection":b.connection.dataChannelsClosed=C.dataChannelsClosed,b.connection.dataChannelsOpened=C.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let E=C.mediaType||C.kind;const T={};if(!["audio","video"].includes(E))if(C.id.includes("Video"))E="video";else{if(!C.id.includes("Audio"))continue;E="audio"}if(C.codecId){const R=f.get(C.codecId);R&&(T.clockRate=R.clockRate,T.mimeType=R.mimeType,T.payloadType=R.payloadType)}if(!b.connection.id&&C.transportId){const R=f.get(C.transportId);if(R&&R.selectedCandidatePairId){const L=f.get(R.selectedCandidatePairId);b.connection=x(L,f)}}b.remote[E].inbound.push({...C,...T});break}case"remote-outbound-rtp":{if(!h.remote)break;const E=C.mediaType||C.kind,T={};if(!["audio","video"].includes(E))continue;if(C.codecId){const R=f.get(C.codecId);R&&(T.clockRate=R.clockRate,T.mimeType=R.mimeType,T.payloadType=R.payloadType)}b.remote[E].outbound.push({...C,...T});break}}if(!b.connection.id)for(const C of f.values())C.type==="candidate-pair"&&C.nominated&&C.state==="succeeded"&&(b.connection=x(C,f));return b=function(C,E){return E&&(C.audio.inbound.map(T=>{let R=E.audio.inbound.find(L=>L.id===T.id);T.bitrate=S(T,R,"bytesReceived"),T.packetRate=S(T,R,"packetsReceived")}),C.audio.outbound.map(T=>{let R=E.audio.outbound.find(L=>L.id===T.id);T.bitrate=S(T,R,"bytesSent"),T.packetRate=S(T,R,"packetsSent")}),C.video.inbound.map(T=>{let R=E.video.inbound.find(L=>L.id===T.id);T.bitrate=S(T,R,"bytesReceived"),T.packetRate=S(T,R,"packetsReceived")}),C.video.outbound.map(T=>{let R=E.video.outbound.find(L=>L.id===T.id);T.bitrate=S(T,R,"bytesSent"),T.packetRate=S(T,R,"packetsSent")})),C}(b,m),b}let O,I={},A=[];t.WebRTCStats=class extends s{constructor(f){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 m={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:m})}async addConnection(f){const{pc:m,peerId:h}=f;let{connectionId:b,remote:C}=f;if(C=typeof C=="boolean"?C:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let T in this.peersToMonitor[h]){const R=this.peersToMonitor[h][T];if(R.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);R.pc.connectionState==="closed"&&this.removeConnection({pc:R.pc})}}const E=m.getConfiguration();return E.iceServers&&E.iceServers.forEach(function(T){delete T.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:f,peerConfiguration:E}}),this.monitorPeer({peerId:h,connectionId:b,pc:m,remote:C}),{connectionId:b}}getTimeline(f){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),f?this.timeline.filter(m=>m.tag===f):this.timeline}get logger(){const f=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(f){let m,{connectionId:h,pc:b}=f;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let C in this.peersToMonitor)h in this.peersToMonitor[C]&&(b=this.peersToMonitor[C][h].pc,m=C)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let C in this.peersToMonitor)for(let E in this.peersToMonitor[C])this.peersToMonitor[C][E].pc===b&&(h=E,m=C)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:h}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let m in this.peersToMonitor[f]){let h=this.peersToMonitor[f][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),A.forEach(f=>{this.removeTrackEventListeners(f)}),A=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(f){let{peerId:m,connectionId:h,pc:b,remote:C}=f;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const E={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:C}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=E}else this.peersToMonitor[m]={[h]:E};this.addPeerConnectionEventListeners(m,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let m={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);m[f]=this.peersToMonitor[f]}else m=this.peersToMonitor;let h=[];for(const b in m)for(const C in m[b]){const E=m[b][C],T=E.pc;if(T&&!this.checkIfConnectionIsClosed(b,C,T))try{const R=this.getTimestamp(),L=T.getStats(null);if(L){const V=await L,J=this.getTimestamp(),N=k(V),rt={remote:E.options.remote},Q=M(V,E.stats.parsed,rt),j={event:"stats",tag:"stats",peerId:b,connectionId:C,timeTaken:J-R,data:Q};this.rawStats===!0&&(j.rawStats=V),this.statsObject===!0&&(j.statsObject=N),this.filteredStats===!0&&(j.filteredStats=this.filteroutStats(N)),h.push(j),E.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(R){this.logger.error(R)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const m in this.peersToMonitor[f]){const h=this.peersToMonitor[f][m].pc;this.checkIfConnectionIsClosed(f,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,m,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let C=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:C,peerId:f,connectionId:m,tag:"connection",data:"closed"})}return b}isConnectionClosed(f){return f.connectionState==="closed"||f.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."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(f({stream:m}),m),m=>(f({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const m={...f};for(const b in m){var h=m[b];this.statsToMonitor.includes(h.type)||delete m[b]}return m}get peerConnectionListeners(){return{icecandidate:(f,m,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:m,data:b.candidate})},track:(f,m,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,b);const C=b.track,E=b.streams[0];f in this.peersToMonitor&&m in this.peersToMonitor[f]&&(this.peersToMonitor[f][m].stream=E),this.addTrackEventListeners(C,m),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:m,data:{stream:E?this.getStreamDetails(E):null,track:C?this.getMediaTrackDetails(C):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(T){return"stream:"+T.id})}})},signalingstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(f,m,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:m,error:{errorCode:b.errorCode}})},connectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.connectionState})},negotiationneeded:(f,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:m})},datachannel:(f,m,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:m,data:b.channel})}}}addPeerConnectionEventListeners(f,m,h){this.logger.debug(`Adding event listeners for peer ${f} and connection ${m}.`),I[m]={},Object.keys(this.peerConnectionListeners).forEach(b=>{I[m][b]=this.peerConnectionListeners[b].bind(this,f,m,h),h.addEventListener(b,I[m][b],!1)})}parseGetUserMedia(f){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(m.data.details=this.parseStream(f.stream),f.stream.getTracks().map(h=>{this.addTrackEventListeners(h),A.push(h)})),this.emitEvent(m)}catch{}}parseStream(f){const m={audio:[],video:[]};return f.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(f,m){I[f.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(b=>{I[f.id][b]=h[b].bind(this),f.addEventListener(b,I[f.id][b])}),I[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(b)}},1e3)}removeTrackEventListeners(f){if(f.id in I){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{f.removeEventListener(h,I[f.id][h])}),clearInterval(I[f.id].readyState),delete I[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const m={...f,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,m){f in I&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,I[f][h],!1)}),delete I[f]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(Li=Tu)&&Li.__esModule&&Object.prototype.hasOwnProperty.call(Li,"default")&&Li.default;var iv=Tu.WebRTCStats;function sv(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(c){const{jitter:d,rtt:u}=c,p=d+u/2;return .024*p+.11*(p-177.3)*(p>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,p=d/(u+d)*100;return 20*Math.log(1+p)}({packetsLost:t,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function rv(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class ov extends Ai{constructor(t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:t,debug_report_version:1})}}class av extends Ai{constructor(t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:t,debug_report_version:1})}}class lv extends Ai{constructor(t,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:t,debug_report_version:1,debug_report_data:n})}}function cv(e){const t=Fn(),n=new iv({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>G(this,void 0,void 0,function*(){s.event==="stats"&&Z(F.StatsFrame,function({data:o}){var r,a,l,c,d,u,p,g;const{audio:v,remote:w}=o,{audio:_}=w,y=(a=(r=_.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,x=(c=(l=_.inbound[0])===null||l===void 0?void 0:l.roundTripTime)!==null&&c!==void 0?c:1/0,S=(u=(d=v.inbound[0])===null||d===void 0?void 0:d.packetsReceived)!==null&&u!==void 0?u:-1,k=(g=(p=v.inbound[0])===null||p===void 0?void 0:p.packetsLost)!==null&&g!==void 0?g:-1,M=sv({jitter:1e3*y,rtt:1e3*x,packetsLost:k,packetsReceived:S});return{jitter:y,rtt:x,mos:M,quality:rv(M),inboundAudio:v.inbound[0],outboundAudio:v.outbound[0],remoteInboundAudio:_.inbound[0],remoteOutboundAudio:_.outbound[0]}}(s),e.uuid),yield e.execute(new lv(t,s))});return{start:(s,o,r)=>G(this,void 0,void 0,function*(){yield e.execute(new ov(t)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>G(this,void 0,void 0,function*(){const o=n.getTimeline();Z(F.StatsReport,o,e.uuid),s==="file"&&function(r,a){const l=new Blob([JSON.stringify(r)],{type:"application/json"}),c=URL.createObjectURL(l),d=document.createElement("a");d.href=c,d.download=`${a}.json`,d.click(),URL.revokeObjectURL(c)}(o,`webrtc-stats-${t}-${Date.now()}`),yield e.execute(new av(t)),n.removeAllPeers(),n.destroy()})}}class ku{constructor(t,n,i){this.type=t,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=s=>G(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},B.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=cv(i))}get isOffer(){return this.type===Dt.Offer}get isAnswer(){return this.type===Dt.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(){B.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((t,n)=>{B.info(`>> Transceiver [${n}]:`,t.mid,t.direction,t.stopped),B.info(`>> Sender Params [${n}]:`,JSON.stringify(t.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(t){switch(B.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(){B.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(t){const{streams:[n]}=t,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Ii(i,o)}createPeerConnection(){return G(this,void 0,void 0,function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),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=>(Z(F.MediaError,n,this.options.id),null))})}_init(){var t;return G(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(t=this.statsReporter)===null||t===void 0?void 0:t.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Ei(i)){const o=i.getAudioTracks();B.info("Local audio tracks: ",o);const r=i.getVideoTracks();if(B.info("Local video tracks: ",r),this.isOffer&&typeof this.instance.addTransceiver=="function"){const a={direction:"sendrecv",streams:[i]};o.forEach(l=>{this.options.userVariables.microphoneLabel=l.label;const c=this.instance.addTransceiver(l,a);this._setAudioCodec(c)}),console.debug("Applying video transceiverParams",a),r.forEach(l=>{this.options.userVariables.cameraLabel=l.label,this.instance.addTransceiver(l,a)})}else typeof this.instance.addTrack=="function"?(o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label,this.instance.addTrack(a,i)}),this.instance.getTransceivers().forEach(a=>this._setAudioCodec(a)),r.forEach(a=>{this.options.userVariables.cameraLabel=a.label,this.instance.addTrack(a,i)})):this.instance.addStream(i);s===!1&&((a=>{const l=jn(a);l&&(l.muted=!0)})(n),Ii(n,i))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),this._logTransceivers()})}_getSenderByKind(t){return this.instance.getSenders().find(({track:n})=>n&&n.kind===t)}_checkMediaToNegotiate(t){if(!this._getSenderByKind(t)){const n=this.instance.addTransceiver(t);B.info("Add transceiver",t,n)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,B.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(t=>B.error("Peer _createOffer error:",t)))}_setRemoteDescription(t){this.options.useStereo&&(t.sdp=xr(t.sdp)),this.instance.localDescription&&(t.sdp=mu(t.sdp,this.instance.localDescription.sdp));const n=t;return B.info(`REMOTE SDP
83
+ `,`Type: ${t.type}`,`
84
+
85
+ `,t.sdp),this.instance.setRemoteDescription(n)}_createAnswer(){return G(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:Dt.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Dt.Offer}),this._logTransceivers();const t=yield this.instance.createAnswer();yield this._setLocalDescription(t)})}_setLocalDescription(t){const{useStereo:n,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:o,mediaSettings:r}=this.options;return n&&(t.sdp=xr(t.sdp)),i&&s&&o&&(t.sdp=((a,l,c,d)=>{const u=a.split(`\r
86
+ `);return u.forEach((p,g)=>{/^a=fmtp:\d*/.test(p)?u[g]+=`;x-google-max-bitrate=${l};x-google-min-bitrate=${c};x-google-start-bitrate=${d}`:/^a=mid:(1|video)/.test(p)&&(u[g]+=`\r
87
+ b=AS:${l}`)}),u.join(`\r
88
+ `)})(t.sdp,i,s,o)),r&&r.useSdpASBandwidthKbps&&r.sdpASBandwidthKbps!==null&&(t.sdp=((a,l)=>{let c="AS",d=l;return!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(c="TIAS",d=1e3*(l>>>0)),a.indexOf("b="+c+":")===-1?a.replace(/c=IN (.*)\r\n/,`c=IN $1\r
89
+ b=`+c+":"+d+`\r
90
+ `):a.replace(new RegExp("b="+c+`:.*\r
91
+ `),"b="+c+":"+d+`\r
92
+ `)})(t.sdp,r.sdpASBandwidthKbps)),this.instance.setLocalDescription(t)}_sdpReady(){sn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return G(this,void 0,void 0,function*(){if(Ei(this.options.localStream))return this.options.localStream;const t=yield(n=this.options,G(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s}=n;const{micLabel:o=""}=n;s&&(s=yield Pi(s,o,re.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s}));let{camId:r}=n,a=n.video;const{camLabel:l=""}=n;return r&&(r=yield Pi(r,l,re.Video).catch(c=>null),r&&(typeof a=="boolean"&&(a={}),a.deviceId={exact:r})),{audio:i,video:a}}));var n;return Ri(t)})}_isOffer(){return this.type===Dt.Offer}_isAnswer(){return this.type===Dt.Answer}_config(){const{iceServers:t=[],prefetchIceCandidates:n,forceRelayCandidate:i}=this.options,s={bundlePolicy:"max-compat",iceCandidatePoolSize:n?10:0,iceServers:t,iceTransportPolicy:i?"relay":"all"};return B.info("RTC config",s),s}close(){var t;return G(this,void 0,void 0,function*(){yield(t=this.statsReporter)===null||t===void 0?void 0:t.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const uv=Cr;class Au{constructor(t,n){this.session=t,this.id="",this.state=K[K.New],this.prevState="",this.channels=[],this.role=Un.Participant,this.extension=null,this._state=K.New,this._prevState=K.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._checkConferenceSerno=_=>{const y=_<0||!this._lastSerno||this._lastSerno&&_===this._lastSerno+1;return y&&_>=0&&(this._lastSerno=_),y},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(_=>{_.forEach(y=>{this._statsBindings.forEach(x=>{if(x.callback){if(x.constraints){for(var S in x.constraints)if(x.constraints.hasOwnProperty(S)&&x.constraints[S]!==y[S])return}x.callback(y)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:d,options:u,mediaConstraints:{audio:p,video:g},ringtoneFile:v,ringbackFile:w}=t;this.options=Object.assign({},Ng,{audio:p,video:g,iceServers:i,localElement:c,remoteElement:d,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:v,ringbackFile:w,debug:u.debug,debugOutput:u.debugOutput},n),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=_u(this.options.ringtoneFile,"_ringtone"),this._ringback=_u(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(t){this._targetNodeId=t}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=xe.Outbound,this.peer=new ku(Dt.Offer,this.options,this.session),this._registerPeerEvents()}answer(t={}){var n,i,s,o;this.stopRingtone(),this.options.video=(i=(n=t.video)!==null&&n!==void 0?n:this.options.video)!==null&&i!==void 0&&i,this.direction=xe.Inbound,((s=t==null?void 0:t.customHeaders)===null||s===void 0?void 0:s.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:t.customHeaders})),((o=t.preferred_codecs)===null||o===void 0?void 0:o.length)>0&&(this.options.preferred_codecs=t.preferred_codecs),this.peer=new ku(Dt.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){bu(this._ringtone)}stopRingtone(){wu(this._ringtone)}playRingback(){bu(this._ringback)}stopRingback(){wu(this._ringback)}hangup(t,n){var i,s,o;let r=t||{},a=n!==!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=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],this.setState(K.Hangup);const l=()=>{var c;return(c=this.peer)===null||c===void 0||c.close(),this.setState(K.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const c=new Jg({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(c).catch(d=>{B.error("telnyx_rtc.bye failed!",d),Z(F.Error,{error:d,sessionId:this.session.sessionid},this.session.uuid)}).then(l.bind(this))}else l()}hold(){const t=new Tr({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const t=new Tr({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const t=new Tr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(t){const n=new Su({sessid:this.session.sessionid,dtmf:t,dialogParams:this.options});this._execute(n)}message(t,n){const i={from:this.session.options.login,to:t,body:n},s=new Su({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){vu(this.options.localStream)}unmuteAudio(){gu(this.options.localStream)}toggleAudioMute(){yu(this.options.localStream)}setAudioInDevice(t){return G(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="audio");if(i){const s=yield wr({audio:{deviceId:{exact:t}}}),o=s.getAudioTracks()[0];i.replaceTrack(o),this.options.micId=t;const{localStream:r}=this.options;r.getAudioTracks().forEach(a=>a.stop()),r.getVideoTracks().forEach(a=>s.addTrack(a)),this.options.localStream=s}})}muteVideo(){var t;t=this.options.localStream,ln(t,"video",!1)}unmuteVideo(){var t;t=this.options.localStream,ln(t,"video",!0)}toggleVideoMute(){var t;t=this.options.localStream,ln(t,"video",null)}setVideoDevice(t){return G(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield wr({video:{deviceId:{exact:t}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Ii(r,s),this.options.camId=t,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){vu(this.options.remoteStream)}undeaf(){gu(this.options.remoteStream)}toggleDeaf(){yu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(t,n){return G(this,void 0,void 0,function*(){if(!this||!this.peer)return void B.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,s=i.getSenders();if(!s)return void B.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===n);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),B.info("Parameters: ",r),B.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",t," [bps]"),r.encodings[0].maxBitrate=t,yield o.setParameters(r).then(()=>{B.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>console.error(a))}else B.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(t){this.setBandwidthEncodingsMaxBps(t,"audio")}setVideoBandwidthEncodingsMaxBps(t){this.setBandwidthEncodingsMaxBps(t,"video")}getStats(t,n){if(!t)return;const i={callback:t,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(t){switch(this._prevState=this._state,this._state=t,this.state=K[this._state].toLowerCase(),this.prevState=K[this._prevState].toLowerCase(),B.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:se.callUpdate,call:this}),t){case K.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case K.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&cu(n,i)},0);break;case K.Destroy:this._finalize()}}handleMessage(t){const{method:n,params:i}=t;switch(n){case nt.Answer:if(this.gotAnswer=!0,this._state>=K.Active)return;this._state>=K.Early&&this.setState(K.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case nt.Media:if(this._state>=K.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case nt.Display:case nt.Attach:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===xe.Inbound?xe.Outbound:xe.Inbound,c={type:se[n],call:this,displayName:o,displayNumber:r,displayDirection:l};Z(F.Notification,c,this.id)||Z(F.Notification,c,this.session.uuid);break}case nt.Info:case nt.Event:{const o=Object.assign(Object.assign({},i),{type:se.generic,call:this});Z(F.Notification,o,this.id)||Z(F.Notification,o,this.session.uuid);break}case nt.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 nt.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(t,n){return G(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(t.wireSerno)&&t.name!==n.laName)return B.error("ConferenceUpdate invalid wireSerno or packet name:",t),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=t;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:d,conferenceMemberID:u,role:p}=n;this._dispatchConferenceUpdate({action:Et.Join,conferenceName:d,participantId:Number(u),role:p}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l)),c&&p===Un.Moderator&&(yield this._subscribeConferenceModerator(c));const g=[];for(const v in s)g.push(Object.assign({callId:s[v][0],index:Number(v)},Ti(s[v][1])));this._dispatchConferenceUpdate({action:Et.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Et.Add,callId:o,index:r},Ti(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Et.Modify,callId:o,index:r},Ti(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Et.Delete,callId:o,index:r},Ti(s)));break;case"clear":this._dispatchConferenceUpdate({action:Et.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:o,index:r})}})}_addChannel(t){this.channels.includes(t)||this.channels.push(t);const n=this.session.relayProtocol;this.session._existsSubscription(n,t)&&(this.session.subscriptions[n][t]=Object.assign(Object.assign({},this.session.subscriptions[n][t]),{callId:this.id}))}_subscribeConferenceChat(t){return G(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[t],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Et.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{B.error("ConfChat subscription error:",s)});Mi(i,t)&&(this._addChannel(t),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:t,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(t){return G(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[t],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,Cu(this.session,o)):B.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{B.error("ConfInfo subscription error:",s)});Mi(i,t)&&this._addChannel(t)})}_confControl(t,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:t,data:i})}_subscribeConferenceModerator(t){return G(this,void 0,void 0,function*(){const n=(r,a=null,l=null)=>{const c=parseInt(a)||null;this._confControl(t,{command:r,id:c,value:l})},i=()=>{const{video:r}=this.options;if(typeof r=="boolean"&&!r||typeof r=="object"&&Qc(r))throw`Conference ${this.id} has no video!`},s={nodeId:this.nodeId,channels:[t],handler:r=>{const{data:a}=r;if(a["conf-command"]==="list-videoLayouts"){if(a.responseData){const l=JSON.stringify(a.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:Et.LayoutList,layouts:JSON.parse(l)})}}else this._dispatchConferenceUpdate({action:Et.ModCmdResponse,command:a["conf-command"],response:a.response})}},o=yield this.session.vertoSubscribe(s).catch(r=>{B.error("ConfMod subscription error:",r)});Mi(o,t)&&(this.role=Un.Moderator,this._addChannel(t),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{n("list-videoLayouts")}},playMedia:{configurable:!0,value:r=>{n("play",null,r)}},stopMedia:{configurable:!0,value:()=>{n("stop",null,"all")}},deaf:{configurable:!0,value:r=>{n("deaf",r)}},undeaf:{configurable:!0,value:r=>{n("undeaf",r)}},startRecord:{configurable:!0,value:r=>{n("recording",null,["start",r])}},stopRecord:{configurable:!0,value:()=>{n("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:r=>{i(),n("vid-write-png",null,r)}},setVideoLayout:{configurable:!0,value:(r,a)=>{i(),n("vid-layout",null,a?[r,a]:r)}},kick:{configurable:!0,value:r=>{n("kick",r)}},muteMic:{configurable:!0,value:r=>{n("tmute",r)}},muteVideo:{configurable:!0,value:r=>{i(),n("tvmute",r)}},presenter:{configurable:!0,value:r=>{i(),n("vid-res-id",r,"presenter")}},videoFloor:{configurable:!0,value:r=>{i(),n("vid-floor",r,"force")}},banner:{configurable:!0,value:(r,a)=>{i(),n("vid-banner",r,encodeURI(a))}},volumeDown:{configurable:!0,value:r=>{n("volume_out",r,"down")}},volumeUp:{configurable:!0,value:r=>{n("volume_out",r,"up")}},gainDown:{configurable:!0,value:r=>{n("volume_in",r,"down")}},gainUp:{configurable:!0,value:r=>{n("volume_in",r,"up")}},transfer:{configurable:!0,value:(r,a)=>{n("transfer",r,a)}}}))})}_handleChangeHoldStateSuccess(t){return t.holdState==="active"?this.setState(K.Active):this.setState(K.Held),!0}_handleChangeHoldStateError(t){return B.error(`Failed to ${t.action} on call ${this.id}`),!1}_onRemoteSdp(t){let n=mu(t,this.peer.instance.localDescription.sdp);this.options.useStereo&&(n=xr(n));const i={sdp:n,type:Dt.Answer};this.peer.instance.setRemoteDescription(i).then(()=>{this.gotEarly&&this.setState(K.Early),this.gotAnswer&&this.setState(K.Active)}).catch(s=>{B.error("Call setRemoteDescription Error: ",s),this.hangup()})}_requestAnotherLocalDescription(){sn(this.peer.onSdpReadyTwice)?Z(F.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(t){var n,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=t;if(s.indexOf("candidate")===-1)return B.info(`No candidate - retry
93
+ `),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 r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${uv}`};switch(o){case Dt.Offer:this.setState(K.Requesting),r=new Xg(a);break;case Dt.Answer:this.setState(K.Answering),r=this.options.attach===!0?new Zg(a):new Yg(a);break;default:return B.error(`${this.id} - Unknown local SDP type:`,t),this.hangup({},!1)}this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Dt.Offer?this.setState(K.Trying):this.setState(K.Active)}).catch(l=>{B.error(`${this.id} - Sending ${o} error:`,l),this.hangup()}),console.timeEnd(Zc)}_onIce(t){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),t.candidate?B.debug("RTCPeer Candidate:",t.candidate):this._onIceSdp(n.localDescription)}_registerPeerEvents(){const{instance:t}=this.peer;this._iceDone=!1,t.onicecandidate=n=>{this._iceDone||this._onIce(n)},t.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),t.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Ii(i,s)})}_onMediaError(t){this._dispatchNotification({type:se.userMediaError,error:t}),this.hangup({},!1)}_dispatchConferenceUpdate(t){this._dispatchNotification(Object.assign({type:se.conferenceUpdate,call:this},t))}_dispatchNotification(t){this.options.screenShare!==!0&&(Z(F.Notification,t,this.id,!1)||Z(F.Notification,t,this.session.uuid))}_execute(t){return this.nodeId&&(t.targetNodeId=this.nodeId),this.session.execute(t)}_init(){const{id:t,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;t||(this.options.id=Fn()),this.id=this.options.id,n&&!Qc(n)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,on(F.MediaError,this._onMediaError,this.id),sn(s)&&on(F.Notification,s.bind(this),this.id),this.setState(K.New),B.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:t,localStream:n}=this.options;Hn(t),Hn(n),an(F.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(t){this._statsIntervalId=setInterval(this._doStats,t),B.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),B.info("Stats stopped")}}Au.setStateTelnyx=e=>{if(e){switch(e._state){case K.Requesting:case K.Recovering:case K.Trying:case K.Early:e.state="connecting";break;case K.Active:e.state="active";break;case K.Held:e.state="held";break;case K.Hangup:case K.Destroy:e.state="done";break;case K.Answering:e.state="ringing";break;case K.New:e.state="new"}return e}};class De extends Au{constructor(){super(...arguments),this._statsInterval=null}hangup(t={},n=!0){this.screenShare instanceof De&&this.screenShare.hangup(t,n),super.hangup(t,n)}startScreenShare(t){return G(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},t);return this.screenShare=new De(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof De&&this.screenShare.hangup()}setAudioOutDevice(t){return G(this,void 0,void 0,function*(){this.options.speakerId=t;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&cu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(t=!0){if(t===!1)return clearInterval(this._statsInterval);B.setLevel(2),this._statsInterval=window.setInterval(()=>G(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
94
+ ${r.type}
95
+ `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
96
+ `)}))}),B.info(i)}),2e3)}}class dv extends Gg{constructor(t){super(t),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=t.iceServers,this.ringtoneFile=t.ringtoneFile,this.ringbackFile=t.ringbackFile}get reconnectDelay(){return 1e3}connect(){const t=Object.create(null,{connect:{get:()=>super.connect}});return G(this,void 0,void 0,function*(){t.connect.call(this)})}checkPermissions(t=!0,n=!0){return G(this,void 0,void 0,function*(){try{const i=yield Ri({audio:t,video:n});return Hn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const t=Object.create(null,{disconnect:{get:()=>super.disconnect}});return G(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(K.Purge)),this.calls={},yield t.disconnect.call(this)})}speedTest(t){return new Promise((n,i)=>{if(ru(F.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*t/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*t/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(t=Number(t)))return i(`Invalid parameter 'bytes': ${t}`);this.executeRaw(`#SPU ${t}`);let s=t/1024;t%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Gn().catch(t=>(Z(F.MediaError,t,this.uuid),[]))}getVideoDevices(){return Gn(re.Video).catch(t=>(Z(F.MediaError,t,this.uuid),[]))}getAudioInDevices(){return Gn(re.AudioIn).catch(t=>(Z(F.MediaError,t,this.uuid),[]))}getAudioOutDevices(){return Gn(re.AudioOut).catch(t=>(console.error("getAudioOutDevices",t),Z(F.MediaError,t,this.uuid),[]))}validateDeviceId(t,n,i){return Pi(t,n,i)}getDeviceResolutions(t){return G(this,void 0,void 0,function*(){try{return yield(n=>G(void 0,void 0,void 0,function*(){const i=[],s=yield Ri({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<uu.length;r++){const[a,l]=uu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return Hn(s),i}))(t)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=t,s=mr(t,["micId","micLabel"]);return du(s),this._audioConstraints=yield hu(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=t,s=mr(t,["camId","camLabel"]);return du(s),this._videoConstraints=yield hu(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(t){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof t=="boolean"?t?[n]:[]:t||[Dg,Lg,n]}get iceServers(){return this._iceServers}set speaker(t){this._speaker=t}get speaker(){return this._speaker}set localElement(t){this._localElement=jn(t)}get localElement(){return this._localElement}set remoteElement(t){this._remoteElement=jn(t)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:t,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new Qg({sessid:this.sessionid,eventChannel:n,data:i});t&&(s.targetNodeId=t),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:t,channels:n=[],handler:i}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new tv({sessid:this.sessionid,eventChannel:n});t&&(s.targetNodeId=t);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Sr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:t,channels:n=[]}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new ev({sessid:this.sessionid,eventChannel:n});t&&(i.targetNodeId=t);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Sr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(t){return De.setStateTelnyx(t)}}class Eu{constructor(t,n){this.code=n,this.message=t}}class hv extends Ot{constructor(){super(),this.method=nt.Ping,this.buildRequest({method:this.method,params:{}})}}class Ht{constructor(t){this.session=t}_ack(t,n){const i=new Kg(t,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*nu(2,6)}handleMessage(t){const{session:n}=this,{id:i,method:s,params:o={}}=t,r=o==null?void 0:o.callID,a=o==null?void 0:o.eventChannel,l=o==null?void 0:o.eventType,c=s===nt.Attach;if(l==="channelPvtData")return this._handlePvtEvent(o.pvtData);if(r&&n.calls.hasOwnProperty(r)){if(!c)return n.calls[r].handleMessage(t),void this._ack(i,s);n.calls[r].hangup({},!1)}const d=()=>{var g,v,w,_;const y={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:c,mediaSettings:o.mediaSettings,debug:(g=n.options.debug)!==null&&g!==void 0&&g,debugOutput:(v=n.options.debugOutput)!==null&&v!==void 0?v:"socket",prefetchIceCandidates:(w=n.options.prefetchIceCandidates)!==null&&w!==void 0&&w,forceRelayCandidate:(_=n.options.forceRelayCandidate)!==null&&_!==void 0&&_};o.telnyx_call_control_id&&(y.telnyxCallControlId=o.telnyx_call_control_id),o.telnyx_session_id&&(y.telnyxSessionId=o.telnyx_session_id),o.telnyx_leg_id&&(y.telnyxLegId=o.telnyx_leg_id),o.client_state&&(y.clientState=o.client_state),o.dialogParams&&o.dialogParams.custom_headers&&o.dialogParams.custom_headers.length&&(y.customHeaders=o.dialogParams.custom_headers);const x=new De(n,y);return x.nodeId=this.nodeId,x},u=new lu,p=new hv;switch(s){case nt.Ping:this.session.execute(p);break;case nt.Punt:n.disconnect();break;case nt.Invite:{const w=d();w.playRingtone(),w.setState(K.Ringing),w.direction=xe.Inbound,this._ack(i,s);break}case nt.Attach:{const w=d();this.session.autoRecoverCalls?w.answer():w.setState(K.Recovering),w.handleMessage(t);break}case nt.Event:case"webrtc.event":if(!a)return void B.error("Verto received an unknown event:",o);const g=n.relayProtocol,v=a.split(".")[0];n._existsSubscription(g,a)?Z(g,o,a):a===n.sessionid?this._handleSessionEvent(o.eventData):n._existsSubscription(g,v)?Z(g,o,v):n.calls.hasOwnProperty(a)?n.calls[a].handleMessage(t):Z(F.Notification,o,n.uuid);break;case nt.Info:o.type=se.generic,Z(F.Notification,o,n.uuid);break;case nt.ClientReady:this.session.execute(u);break;default:{const w=vr(t);if(w){switch(w){case It.REGISTER:case It.REGED:n.connection.previousGatewayState!==It.REGED&&n.connection.previousGatewayState!==It.REGISTER&&(Ht.retriedRegister=0,o.type=se.vertoClientReady,Z(F.Ready,o,n.uuid));break;case It.UNREGED:case It.NOREG:if(Ht.retriedRegister+=1,Ht.retriedRegister===5){Ht.retriedRegister=0,Z(F.Error,{error:new Eu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:n.sessionid},n.uuid);break}setTimeout(()=>{this.session.execute(u)},this.reconnectDelay());break;case It.FAILED:case It.FAIL_WAIT:if(n.connection.previousGatewayState!==It.FAILED&&n.connection.previousGatewayState!==It.FAIL_WAIT){if(!this.session.hasAutoReconnect()){Ht.retriedConnect=0,Z(F.Error,{error:new Eu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(Ht.retriedConnect+=1,Ht.retriedConnect===5){Ht.retriedConnect=0,Z(F.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:B.warn("GatewayState message unknown method:",t)}break}B.warn("Verto message unknown method:",t);break}}}_retrieveCallId(t,n){const i=Object.keys(this.session.calls);if(t.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=t.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(t){return G(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:p}=t;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},v={nodeId:this.nodeId,channels:[o],handler:({data:_})=>{const y=p||this._retrieveCallId(_,o);if(y&&n.calls.hasOwnProperty(y)){const x=n.calls[y];x._addChannel(o),x.extension=r,x.handleConferenceUpdate(_,t).then(S=>{S==="INVALID_PACKET"&&g()})}}},w=yield n.vertoSubscribe(v).catch(_=>{B.error("liveArray subscription error:",_)});Mi(w,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:w=null}=n.subscriptions[i][o];if(g=n.calls[w]||null,w!==null){const _={type:se.conferenceUpdate,action:Et.Leave,conferenceName:r,participantId:Number(d),role:u};Z(F.Notification,_,w,!1)||Z(F.Notification,_,n.uuid),g===null&&an(F.Notification,null,w)}}const v=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:w=[]})=>{g&&(g.channels=g.channels.filter(_=>!w.includes(_)))}).catch(w=>{B.error("liveArray unsubscribe error:",w)});break}}})}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":Cu(this.session,t);break;case"logo-info":{const n={type:se.conferenceUpdate,action:Et.LogoInfo,logo:t.logoURL};Z(F.Notification,n,this.session.uuid);break}}}}Ht.retriedConnect=0,Ht.retriedRegister=0;class fv extends Ot{constructor(t,n,i,s={},o){super(),this.method="anonymous_login";const r={target_type:t,target_id:n,userVariables:s,reconnection:o,"User-Agent":{sdkVersion:Cr,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class pv extends dv{constructor(t){super(t),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,l=new qg(n,i||s,o,this.sessionid,r,!!br()),c=yield this.execute(l).catch(this._handleLoginError);c&&(this._autoReconnect=a,this.sessionid=c.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,{target_type:i,target_id:s}=n,o=new fv(i,s,this.sessionid,this.options.userVariables,!!br()),r=yield this.execute(o).catch(this._handleLoginError);r&&(this.sessionid=r.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&this.calls[i].hangup({},!0)})})}validateOptions(){return gr(this.options)||ki(this.options)}newCall(t){if(!this.validateCallOptions(t))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(Zc);const n=new De(this,t);return n.invite(),n}broadcast(t){return this.vertoBroadcast(t)}subscribe(t){return this.vertoSubscribe(t)}unsubscribe(t){return this.vertoUnsubscribe(t)}validateCallOptions(t){return!!ki(this.options)||!!t.destinationNumber}_onSocketOpen(){return G(this,void 0,void 0,function*(){return gr(this.options)?this.handleLoginOnSocketOpen():ki(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(t){new Ht(this).handleMessage(t)}}class mv extends pv{constructor(t){super(t),console.log(`SDK version: ${xu}`)}newCall(t){return super.newCall(t)}static webRTCInfo(){return zg()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:gt.full},{browserName:"Firefox",features:["audio"],supported:gt.partial},{browserName:"Safari",supported:gt.not_supported},{browserName:"Edge",supported:gt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:gt.not_supported},{browserName:"Firefox",supported:gt.not_supported},{browserName:"Safari",features:["video","audio"],supported:gt.full},{browserName:"Edge",supported:gt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:gt.full},{browserName:"Firefox",features:["audio"],supported:gt.partial},{browserName:"Safari",supported:gt.not_supported},{browserName:"Edge",supported:gt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:gt.full},{browserName:"Firefox",features:["audio"],supported:gt.partial},{browserName:"Safari",features:["video","audio"],supported:gt.full},{browserName:"Edge",features:["audio"],supported:gt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:gt.full},{browserName:"Firefox",features:["audio"],supported:gt.partial},{browserName:"Safari",supported:gt.not_supported},{browserName:"Edge",features:["audio"],supported:gt.partial}]}]}}function gv(e){if(!e||typeof e!="object")return!1;const t=e;return t.method==="ai_conversation"&&typeof t.params=="object"}function vv(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="response.text.delta"?!1:!!t.params.delta}function yv(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="conversation.item.created"?!1:!!t.params.item.content}function _v(e){return vv(e)?{id:e.params.item_id,role:"assistant",content:e.params.delta,timestamp:new Date}:null}function bv(e){return!yv(e)||e.params.item.role!=="user"||e.params.item.status!=="completed"?null:{id:e.params.item.id,role:e.params.item.role,content:e.params.item.content.map(t=>t.transcript).join(" "),timestamp:new Date}}function wv(e){const[t,n]=de([]);return Jt(()=>{if(!e)return;const i=s=>{if(gv(s))switch(s.params.type){case"response.text.delta":{n(o=>{const r=_v(s);return r?[...o,r]:o});return}case"conversation.item.created":{const o=bv(s);o&&n(r=>[...r,o]);return}}};return e.on(F.SocketMessage,i),()=>{e.off(F.SocketMessage,i)}},[e]),t}const xv=({call:e,client:t})=>{const[n,i]=de("collapsed"),s=()=>i("expanded"),o=()=>i("collapsed"),r=wv(t);switch(n){case"collapsed":return P(qc,{onExpand:s,call:e,client:t});case"expanded":return P(Ag,{transcript:r,onCollapse:o,call:e});default:return P(qc,{onExpand:s,call:e,client:t})}},kr=()=>P(On.div,{layoutId:xi,className:"bg-black gap-3 text-white border w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:P("div",{className:"animate-spin rounded-full border-t-2 border-b-2 border-gray-900",children:P(vg,{})})}),Sv=({call:e,client:t})=>{switch(e==null?void 0:e.state){case"new":case"trying":case"requesting":return P(kr,{});case"done":case"purged":case"destroy":return null;case"active":return P(xv,{client:t,call:e});default:return P(kr,{})}},Cv=(e,t)=>{const[n,i]=de(null);return Jt(()=>{if(!e)return;const s=new mv({env:t||"production",anonymous_login:{target_id:e,target_type:"ai_assistant"}});i(s)},[e,t]),n},Tv=(e,{onReady:t,onNotification:n,onError:i})=>(Jt(()=>{if(e)return e.connect().then().catch(console.error),e.on(F.Ready,t),e.on(F.Notification,n),e.on(F.Error,i),()=>{e.off(F.Ready,t),e.off(F.Notification,n),e.off(F.Error,i),e.disconnect()}},[e]),null),kv=({className:e})=>P("svg",{className:e,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[P("g",{clipPath:"url(#:R5lfm:)",children:[P("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"}),P("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"}),P("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"}),P("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"}),P("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"})]}),P("defs",{children:P("clipPath",{id:":R5lfm:",children:P("rect",{width:"236",height:"211",fill:"currentColor"})})})]}),Av=({client:e})=>{const t=()=>{var s;if(!e){console.error("Client is not initialized.");return}const n=(s=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:s.codecs,i=n==null?void 0:n.find(o=>o.mimeType.toLowerCase().includes("opus"));e.newCall({destinationNumber:"xxx",preferred_codecs:[i]})};return P(On.button,{layoutId:xi,onClick:t,className:"bg-black cursor-pointer text-white px-4 py-2 rounded-full flex items-center text-xl font-medium shadow-lg",children:[P(kv,{className:"w-8 h-8 mr-2"}),"Let's Talk"]})},Ev='@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-divide-y-reverse:0;--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-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia: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-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;--font-weight-semibold:600;--radius-md:.375rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.right-0{right:calc(var(--spacing)*0)}.bottom-0{bottom:calc(var(--spacing)*0)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index: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)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[320px\\]{height:320px}.min-h-\\[180px\\]{min-height:180px}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-\\[400px\\]{max-width:400px}.max-w-full{max-width:100%}.flex-1{flex:1}.origin-bottom-right{transform-origin:100% 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-between{justify-content:space-between}.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)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.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-\\[\\#38383C96\\]{background-color:#38383c96}.bg-\\[\\#38383C\\]{background-color:#38383c}.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)}.py-3{padding-block:calc(var(--spacing)*3)}.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)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.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)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px 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)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (min-width:40rem){.sm\\:h-\\[400px\\]{height:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@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-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',Iv=({children:e})=>P("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:P("div",{className:"absolute bottom-0 right-0 md:bottom-10 md:right-10 pointer-events-auto",children:e})}),Rv={duration:.1,ease:"circOut"},Pv=({children:e,position:t="fixed"})=>P(ff,{transition:Rv,children:[P("style",{children:Ev}),t==="fixed"?P(Iv,{children:e}):e]}),Mv=e=>P(On.div,{layoutId:xi,className:"bg-black rounded-2xl p-4 flex flex-col items-center justify-center text-white w-[344px] max-w-full",children:[P(gg,{className:"w-8 h-8 text-red-400"}),P("h1",{className:"text-2xl font-medium mt-2 mb-4",children:"An error occurred"}),P("ul",{className:"list-disc ml-4 text-sm gap-4",children:[P("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),P("li",{children:["Make sure that the"," ",P("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${e.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"," ",P(xg,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Lv({"agent-id":e,environment:t,position:n="fixed"}){const i=Cv(e,t),[s,o]=de(null),[r,a]=de(!0),[l,c]=de(!1);return Tv(i,{onReady:()=>a(!1),onNotification:v=>{var w;if(((w=v.call)==null?void 0:w.state)==="destroy")return o(null);o(v)},onError:()=>{a(!1),c(!0)}}),P(Pv,{position:n,children:e?l?P(Mv,{agentId:e}):r?P(kr,{}):s!=null&&s.call?P(Sv,{call:s.call,client:i}):P(Av,{client:i}):P("div",{children:"Please provide an assistant ID."})})}Wu(Lv,"telnyx-ai-agent",dg,{shadow:!0})})();