@telnyx/ai-agent-widget 0.24.0-beta.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bundle.min.js +28 -36
  2. package/package.json +2 -3
@@ -1,122 +1,114 @@
1
- var N_=Object.defineProperty;var V_=(Ye,q,Lt)=>q in Ye?N_(Ye,q,{enumerable:!0,configurable:!0,writable:!0,value:Lt}):Ye[q]=Lt;var ye=(Ye,q,Lt)=>V_(Ye,typeof q!="symbol"?q+"":q,Lt);(function(){"use strict";var Ye,q,Lt,Dt,lo,uo,ho,fo,es,ts,ns,po,bn={},mo=[],Hu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,wn=Array.isArray;function nt(t,e){for(var n in e)t[n]=e[n];return t}function is(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function He(t,e,n){var i,s,o,r={};for(o in e)o=="key"?i=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?Ye.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return xn(t,r,i,s,null)}function xn(t,e,n,i,s){var o={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Lt,__i:-1,__u:0};return s==null&&q.vnode!=null&&q.vnode(o),o}function it(t){return t.children}function Ze(t,e){this.props=t,this.context=e}function Jt(t,e){if(e==null)return t.__?Jt(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?Jt(t):null}function go(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return go(t)}}function ss(t){(!t.__d&&(t.__d=!0)&&Dt.push(t)&&!oi.__r++||lo!=q.debounceRendering)&&((lo=q.debounceRendering)||uo)(oi)}function oi(){for(var t,e,n,i,s,o,r,a=1;Dt.length;)Dt.length>a&&Dt.sort(ho),t=Dt.shift(),a=Dt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=nt({},i)).__v=i.__v+1,q.vnode&&q.vnode(n),rs(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??Jt(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,wo(o,n,r),n.__e!=s&&go(n)));oi.__r=0}function vo(t,e,n,i,s,o,r,a,c,d,f){var p,m,v,_,C,S,w=i&&i.__k||mo,T=e.length;for(c=Wu(n,e,w,c,T),p=0;p<T;p++)(v=n.__k[p])!=null&&(m=v.__i==-1?bn:w[v.__i]||bn,v.__i=p,S=rs(t,v,m,s,o,r,a,c,d,f),_=v.__e,v.ref&&m.ref!=v.ref&&(m.ref&&os(m.ref,null,v),f.push(v.ref,v.__c||_,v)),C==null&&_!=null&&(C=_),4&v.__u||m.__k===v.__k?c=yo(v,c,t):typeof v.type=="function"&&S!==void 0?c=S:_&&(c=_.nextSibling),v.__u&=-7);return n.__e=C,c}function Wu(t,e,n,i,s){var o,r,a,c,d,f=n.length,p=f,m=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(c=o+m,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?xn(null,r,null,null,null):wn(r)?xn(it,{children:r},null,null,null):r.constructor==null&&r.__b>0?xn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(d=r.__i=zu(r,n,c,p))!=-1&&(p--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(s>f?m--:s<f&&m++),typeof r.type!="function"&&(r.__u|=4)):d!=c&&(d==c-1?m--:d==c+1?m++:(d>c?m--:m++,r.__u|=4))):t.__k[o]=null;if(p)for(o=0;o<f;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=Jt(a)),So(a,a));return i}function yo(t,e,n){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=yo(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=Jt(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function st(t,e){return e=e||[],t==null||typeof t=="boolean"||(wn(t)?t.some(function(n){st(n,e)}):e.push(t)),e}function zu(t,e,n,i){var s,o,r=t.key,a=t.type,c=e[n];if(c===null&&t.key==null||c&&r==c.key&&a==c.type&&(2&c.__u)==0)return n;if(i>(c!=null&&(2&c.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((c=e[s])&&(2&c.__u)==0&&r==c.key&&a==c.type)return s;s--}if(o<e.length){if((c=e[o])&&(2&c.__u)==0&&r==c.key&&a==c.type)return o;o++}}return-1}function _o(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Hu.test(e)?n:n+"px"}function ai(t,e,n,i,s){var o,r;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||_o(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||_o(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(fo,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?i?n.u=i.u:(n.u=es,t.addEventListener(e,o?ns:ts,o)):t.removeEventListener(e,o?ns:ts,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 t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function bo(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=es++;else if(e.t<n.u)return;return n(q.event?q.event(e):e)}}}function rs(t,e,n,i,s,o,r,a,c,d){var f,p,m,v,_,C,S,w,T,I,R,L,D,b,k,l,u,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),o=[a=e.__e=n.__e]),(f=q.__b)&&f(e);e:if(typeof h=="function")try{if(w=e.props,T="prototype"in h&&h.prototype.render,I=(f=h.contextType)&&i[f.__c],R=f?I?I.props.value:f.__:i,n.__c?S=(p=e.__c=n.__c).__=p.__E:(T?e.__c=p=new h(w,R):(e.__c=p=new Ze(w,R),p.constructor=h,p.render=Ku),I&&I.sub(p),p.props=w,p.state||(p.state={}),p.context=R,p.__n=i,m=p.__d=!0,p.__h=[],p._sb=[]),T&&p.__s==null&&(p.__s=p.state),T&&h.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=nt({},p.__s)),nt(p.__s,h.getDerivedStateFromProps(w,p.__s))),v=p.props,_=p.state,p.__v=e,m)T&&h.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),T&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(T&&h.getDerivedStateFromProps==null&&w!==v&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(w,R),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(w,p.__s,R)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(p.props=w,p.state=p.__s,p.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(g){g&&(g.__=e)}),L=0;L<p._sb.length;L++)p.__h.push(p._sb[L]);p._sb=[],p.__h.length&&r.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(w,p.__s,R),T&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(v,_,C)})}if(p.context=R,p.props=w,p.__P=t,p.__e=!1,D=q.__r,b=0,T){for(p.state=p.__s,p.__d=!1,D&&D(e),f=p.render(p.props,p.state,p.context),k=0;k<p._sb.length;k++)p.__h.push(p._sb[k]);p._sb=[]}else do p.__d=!1,D&&D(e),f=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++b<25);p.state=p.__s,p.getChildContext!=null&&(i=nt(nt({},i),p.getChildContext())),T&&!m&&p.getSnapshotBeforeUpdate!=null&&(C=p.getSnapshotBeforeUpdate(v,_)),l=f,f!=null&&f.type===it&&f.key==null&&(l=xo(f.props.children)),a=vo(t,wn(l)?l:[l],e,n,i,s,o,r,a,c,d),p.base=e.__e,e.__u&=-161,p.__h.length&&r.push(p),S&&(p.__E=p.__=null)}catch(g){if(e.__v=null,c||o!=null)if(g.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(u=o.length;u--;)is(o[u]);else e.__e=n.__e,e.__k=n.__k;q.__e(g,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=qu(n.__e,e,n,i,s,o,r,c,d);return(f=q.diffed)&&f(e),128&e.__u?void 0:a}function wo(t,e,n){for(var i=0;i<n.length;i++)os(n[i],n[++i],n[++i]);q.__c&&q.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){q.__e(o,s.__v)}})}function xo(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:wn(t)?t.map(xo):nt({},t)}function qu(t,e,n,i,s,o,r,a,c){var d,f,p,m,v,_,C,S=n.props,w=e.props,T=e.type;if(T=="svg"?s="http://www.w3.org/2000/svg":T=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(d=0;d<o.length;d++)if((v=o[d])&&"setAttribute"in v==!!T&&(T?v.localName==T:v.nodeType==3)){t=v,o[d]=null;break}}if(t==null){if(T==null)return document.createTextNode(w);t=document.createElementNS(s,T,w.is&&w),a&&(q.__m&&q.__m(e,o),a=!1),o=null}if(T==null)S===w||a&&t.data==w||(t.data=w);else{if(o=o&&Ye.call(t.childNodes),S=n.props||bn,!a&&o!=null)for(S={},d=0;d<t.attributes.length;d++)S[(v=t.attributes[d]).name]=v.value;for(d in S)if(v=S[d],d!="children"){if(d=="dangerouslySetInnerHTML")p=v;else if(!(d in w)){if(d=="value"&&"defaultValue"in w||d=="checked"&&"defaultChecked"in w)continue;ai(t,d,null,v,s)}}for(d in w)v=w[d],d=="children"?m=v:d=="dangerouslySetInnerHTML"?f=v:d=="value"?_=v:d=="checked"?C=v:a&&typeof v!="function"||S[d]===v||ai(t,d,v,S[d],s);if(f)a||p&&(f.__html==p.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(p&&(t.innerHTML=""),vo(e.type=="template"?t.content:t,wn(m)?m:[m],e,n,i,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&Jt(n,0),a,c),o!=null)for(d=o.length;d--;)is(o[d]);a||(d="value",T=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[d]||T=="progress"&&!_||T=="option"&&_!=S[d])&&ai(t,d,_,S[d],s),d="checked",C!=null&&C!=t[d]&&ai(t,d,C,S[d],s))}return t}function os(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){q.__e(s,n)}}function So(t,e,n){var i,s;if(q.unmount&&q.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||os(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){q.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&So(i[s],e,n||typeof t.type!="function");n||is(t.__e),t.__c=t.__=t.__e=void 0}function Ku(t,e,n){return this.constructor(t,n)}function ci(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),q.__&&q.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],rs(e,t=(!i&&n||e).__k=He(it,null,[t]),s||bn,bn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?Ye.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),wo(o,t,r)}function Co(t,e){ci(t,e,Co)}function as(t,e,n){var i,s,o,r,a=nt({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?i=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?Ye.call(arguments,2):n),xn(t.type,a,i||t.key,s||t.ref,null)}function pt(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__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,ss(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 e.__c="__cC"+po++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}Ye=mo.slice,q={__e:function(t,e,n,i){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Lt=0,Ze.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=nt({},this.state),typeof t=="function"&&(t=t(nt({},n),this.props)),t&&nt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),ss(this))},Ze.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ss(this))},Ze.prototype.render=it,Dt=[],uo=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ho=function(t,e){return t.__v.__b-e.__v.__b},oi.__r=0,fo=/(PointerCapture)$|Capture$/i,es=0,ts=bo(!1),ns=bo(!0),po=0;var Xu=0;function M(t,e,n,i,s,o){e||(e={});var r,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?r=e[a]:c[a]=e[a];var d={type:t,props:c,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Xu,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)c[a]===void 0&&(c[a]=r[a]);return q.vnode&&q.vnode(d),d}function cs(){return(cs=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var Yu=["context","children"];function Zu(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},c=Object.keys(i);for(r=0;r<c.length;r++)s.indexOf(o=c[r])>=0||(a[o]=i[o]);return a}(t,Yu);return as(e,n)}function Ju(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=He(Zu,cs({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,c=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[ko(a[r].name)]=a[r].value);for(r=c.length;r--;){var d=e(c[r],null),f=c[r].slot;f?o[f]=He(To,{name:f},d):s[r]=d}var p=i?He(To,null,s):s;return He(i||n.nodeName.toLowerCase(),o,p)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Co:ci)(this._vdom,this._root)}function ko(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Qu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[ko(t)]=n,this._vdom=as(this._vdom,i),ci(this._vdom,this._root)}}function eh(){ci(this._vdom=null,this._root)}function To(t,e){var n=this;return He("slot",cs({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function th(t,e,n,i){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,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=Ju,s.prototype.attributeChangedCallback=Qu,s.prototype.disconnectedCallback=eh,n=n||t.observedAttributes||Object.keys(t.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(e,s)}var xt,ce,ls,Eo,Sn=0,Io=[],pe=q,Ao=pe.__b,Ro=pe.__r,Po=pe.diffed,Mo=pe.__c,Lo=pe.unmount,Do=pe.__;function Qt(t,e){pe.__h&&pe.__h(ce,t,Sn||e),Sn=0;var n=ce.__H||(ce.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ce(t){return Sn=1,Oo(Fo,t)}function Oo(t,e,n){var i=Qt(xt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Fo(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],d=i.t(c,a);c!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=ce,!ce.__f)){var s=function(a,c,d){if(!i.__c.__H)return!0;var f=i.__c.__H.__.filter(function(m){return!!m.__c});if(f.every(function(m){return!m.__N}))return!o||o.call(this,a,c,d);var p=i.__c.props!==a;return f.forEach(function(m){if(m.__N){var v=m.__[0];m.__=m.__N,m.__N=void 0,v!==m.__[0]&&(p=!0)}}),o&&o.call(this,a,c,d)||p};ce.__f=!0;var o=ce.shouldComponentUpdate,r=ce.componentWillUpdate;ce.componentWillUpdate=function(a,c,d){if(this.__e){var f=o;o=void 0,s(a,c,d),o=f}r&&r.call(this,a,c,d)},ce.shouldComponentUpdate=s}return i.__N||i.__}function Ve(t,e){var n=Qt(xt++,3);!pe.__s&&hs(n.__H,e)&&(n.__=t,n.u=e,ce.__H.__h.push(n))}function No(t,e){var n=Qt(xt++,4);!pe.__s&&hs(n.__H,e)&&(n.__=t,n.u=e,ce.__h.push(n))}function ke(t){return Sn=5,rt(function(){return{current:t}},[])}function rt(t,e){var n=Qt(xt++,7);return hs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function St(t,e){return Sn=8,rt(function(){return t},e)}function xe(t){var e=ce.context[t.__c],n=Qt(xt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ce)),e.props.value):t.__}function nh(t,e){pe.useDebugValue&&pe.useDebugValue(e?e(t):t)}function ds(){var t=Qt(xt++,11);if(!t.__){for(var e=ce.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function ih(){for(var t;t=Io.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(li),t.__H.__h.forEach(us),t.__H.__h=[]}catch(e){t.__H.__h=[],pe.__e(e,t.__v)}}pe.__b=function(t){ce=null,Ao&&Ao(t)},pe.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Do&&Do(t,e)},pe.__r=function(t){Ro&&Ro(t),xt=0;var e=(ce=t.__c).__H;e&&(ls===ce?(e.__h=[],ce.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(li),e.__h.forEach(us),e.__h=[],xt=0)),ls=ce},pe.diffed=function(t){Po&&Po(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Io.push(e)!==1&&Eo===pe.requestAnimationFrame||((Eo=pe.requestAnimationFrame)||sh)(ih)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ls=ce=null},pe.__c=function(t,e){e.some(function(n){try{n.__h.forEach(li),n.__h=n.__h.filter(function(i){return!i.__||us(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],pe.__e(i,n.__v)}}),Mo&&Mo(t,e)},pe.unmount=function(t){Lo&&Lo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{li(i)}catch(s){e=s}}),n.__H=void 0,e&&pe.__e(e,n.__v))};var Vo=typeof requestAnimationFrame=="function";function sh(t){var e,n=function(){clearTimeout(i),Vo&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Vo&&(e=requestAnimationFrame(n))}function li(t){var e=ce,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ce=e}function us(t){var e=ce;t.__c=t.__(),ce=e}function hs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Fo(t,e){return typeof e=="function"?e(t):e}const Cn={},Bo=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,jo=t=>"init"in t,fs=t=>!!t.write,Uo=t=>"v"in t||"e"in t,di=t=>{if("e"in t)throw t.e;if((Cn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},ui=new WeakMap,$o=t=>{var e;return hi(t)&&!!((e=ui.get(t))!=null&&e[0])},rh=t=>{const e=ui.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Go=(t,e)=>{let n=ui.get(t);if(!n){n=[!0,new Set],ui.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},hi=t=>typeof(t==null?void 0:t.then)=="function",Ho=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},ps=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(hi(e))for(const r of i.d.keys())Ho(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,hi(o)&&rh(o))},Wo=(t,e,n)=>{var i;const s=new Set;for(const o of((i=n.get(t))==null?void 0:i.t)||[])n.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},oh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},ms=()=>{const t={},e=new WeakMap,n=i=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(i)),(o=e.get(i))==null||o.forEach(r=>r())};return n.add=(i,s)=>{const o=i||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},n},ah=t=>(t.c||(t.c=ms()),t.m||(t.m=ms()),t.u||(t.u=ms()),t.f||(t.f=oh()),t),ch=Symbol(),zo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(m,...v)=>m.read(...v),c=(m,...v)=>m.write(...v),d=(m,v)=>{var _;return(_=m.unstable_onInit)==null?void 0:_.call(m,v)},f=(m,v)=>{var _;return(_=m.onMount)==null?void 0:_.call(m,v)},...p)=>{const m=p[0]||(b=>{if((Cn?"production":void 0)!=="production"&&!b)throw new Error("Atom is undefined or null");let k=t.get(b);return k||(k={d:new Map,p:new Set,n:0},t.set(b,k),d==null||d(b,D)),k}),v=p[1]||(()=>{const b=[],k=l=>{try{l()}catch(u){b.push(u)}};do{r.f&&k(r.f);const l=new Set,u=l.add.bind(l);i.forEach(h=>{var g;return(g=e.get(h))==null?void 0:g.l.forEach(u)}),i.clear(),o.forEach(u),o.clear(),s.forEach(u),s.clear(),l.forEach(k),i.size&&_()}while(i.size||o.size||s.size);if(b.length)throw new AggregateError(b)}),_=p[2]||(()=>{const b=[],k=new WeakSet,l=new WeakSet,u=Array.from(i);for(;u.length;){const h=u[u.length-1],g=m(h);if(l.has(h)){u.pop();continue}if(k.has(h)){if(n.get(h)===g.n)b.push([h,g]);else if((Cn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");l.add(h),u.pop();continue}k.add(h);for(const y of Wo(h,g,e))k.has(y)||u.push(y)}for(let h=b.length-1;h>=0;--h){const[g,y]=b[h];let E=!1;for(const x of y.d.keys())if(x!==g&&i.has(x)){E=!0;break}E&&(C(g),T(g)),n.delete(g)}}),C=p[3]||(b=>{var k;const l=m(b);if(Uo(l)&&(e.has(b)&&n.get(b)!==l.n||Array.from(l.d).every(([P,V])=>C(P).n===V)))return l;l.d.clear();let u=!0;const h=()=>{e.has(b)&&(T(b),_(),v())},g=P=>{var V;if(Bo(b,P)){const N=m(P);if(!Uo(N))if(jo(P))ps(P,P.init,m);else throw new Error("no atom init");return di(N)}const H=C(P);try{return di(H)}finally{l.d.set(P,H.n),$o(l.v)&&Ho(b,l.v,H),(V=e.get(P))==null||V.t.add(b),u||h()}};let y,E;const x={get signal(){return y||(y=new AbortController),y.signal},get setSelf(){return(Cn?"production":void 0)!=="production"&&!fs(b)&&console.warn("setSelf function cannot be used with read-only atom"),!E&&fs(b)&&(E=(...P)=>{if((Cn?"production":void 0)!=="production"&&u&&console.warn("setSelf function cannot be called in sync"),!u)try{return w(b,...P)}finally{_(),v()}}),E}},A=l.n;try{const P=a(b,g,x);return ps(b,P,m),hi(P)&&(Go(P,()=>y==null?void 0:y.abort()),P.then(h,h)),l}catch(P){return delete l.v,l.e=P,++l.n,l}finally{u=!1,A!==l.n&&n.get(b)===A&&(n.set(b,l.n),i.add(b),(k=r.c)==null||k.call(r,b))}}),S=p[4]||(b=>{const k=[b];for(;k.length;){const l=k.pop(),u=m(l);for(const h of Wo(l,u,e)){const g=m(h);n.set(h,g.n),k.push(h)}}}),w=p[5]||((b,...k)=>{let l=!0;const u=g=>di(C(g)),h=(g,...y)=>{var E;const x=m(g);try{if(Bo(b,g)){if(!jo(g))throw new Error("atom not writable");const A=x.n,P=y[0];ps(g,P,m),T(g),A!==x.n&&(i.add(g),(E=r.c)==null||E.call(r,g),S(g));return}else return w(g,...y)}finally{l||(_(),v())}};try{return c(b,u,h,...k)}finally{l=!1}}),T=p[6]||(b=>{var k;const l=m(b),u=e.get(b);if(u&&!$o(l.v)){for(const[h,g]of l.d)if(!u.d.has(h)){const y=m(h);I(h).t.add(b),u.d.add(h),g!==y.n&&(i.add(h),(k=r.c)==null||k.call(r,h),S(h))}for(const h of u.d||[])if(!l.d.has(h)){u.d.delete(h);const g=R(h);g==null||g.t.delete(b)}}}),I=p[7]||(b=>{var k;const l=m(b);let u=e.get(b);if(!u){C(b);for(const h of l.d.keys())I(h).t.add(b);if(u={l:new Set,d:new Set(l.d.keys()),t:new Set},e.set(b,u),(k=r.m)==null||k.call(r,b),fs(b)){const h=()=>{let g=!0;const y=(...E)=>{try{return w(b,...E)}finally{g||(_(),v())}};try{const E=f(b,y);E&&(u.u=()=>{g=!0;try{E()}finally{g=!1}})}finally{g=!1}};s.add(h)}}return u}),R=p[8]||(b=>{var k;const l=m(b);let u=e.get(b);if(u&&!u.l.size&&!Array.from(u.t).some(h=>{var g;return(g=e.get(h))==null?void 0:g.d.has(b)})){u.u&&o.add(u.u),u=void 0,e.delete(b),(k=r.u)==null||k.call(r,b);for(const h of l.d.keys()){const g=R(h);g==null||g.t.delete(b)}return}return u}),L=[t,e,n,i,s,o,r,a,c,d,f,m,v,_,C,S,w,T,I,R],D={get:b=>di(C(b)),set:(b,...k)=>{try{return w(b,...k)}finally{_(),v()}},sub:(b,k)=>{const u=I(b).l;return u.add(k),v(),()=>{u.delete(k),R(b),v()}}};return Object.defineProperty(D,ch,{value:L}),D},lh=ah,qo=Go,gs={};let dh=0;function vs(t,e){const n=`atom${++dh}`,i={toString(){return(gs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=uh,i.write=hh),i}function uh(t){return t(this)}function hh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const fh=()=>{let t=0;const e=lh({}),n=new WeakMap,i=new WeakMap,s=zo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,c,d,...f)=>t?d(a,...f):a.write(c,d,...f)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const c=n.get(a);c.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const c=n.get(a);delete c.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const c={read:()=>null,write:(d,f)=>{++t;try{for(const[p,m]of a)"init"in p&&f(p,m)}finally{--t}}};s.set(c)}})};function ph(){return(gs?"production":void 0)!=="production"?fh():zo()}let kn;function mh(){return kn||(kn=ph(),(gs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=kn),globalThis.__JOTAI_DEFAULT_STORE__!==kn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),kn}function Ko(t,e){for(var n in e)t[n]=e[n];return t}function Xo(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}var Yo=No;function Zo(t,e){this.props=t,this.context=e}(Zo.prototype=new Ze).isPureReactComponent=!0,Zo.prototype.shouldComponentUpdate=function(t,e){return Xo(this.props,t)||Xo(this.state,e)};var Jo=q.__b;q.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Jo&&Jo(t)};var gh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function vh(t){function e(n){var i=Ko({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=gh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Qo=function(t,e){return t==null?null:st(st(t).map(e))},yh={map:Qo,forEach:Qo,count:function(t){return t?st(t).length:0},only:function(t){var e=st(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:st},_h=q.__e;q.__e=function(t,e,n,i){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}_h(t,e,n,i)};var ea=q.unmount;function ta(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=Ko({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return ta(i,e,n)})),t}function na(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return na(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function ys(){this.__u=0,this.o=null,this.__b=null}function ia(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function fi(){this.i=null,this.l=null}q.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),ea&&ea(t)},(ys.prototype=new Ze).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=ia(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 c=i.state.__a;i.__v.__k[0]=na(c,c.__c.__P,c.__c.__O)}var d;for(i.setState({__a:i.__b=null});d=i.o.pop();)d.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},ys.prototype.componentWillUnmount=function(){this.o=[]},ys.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=ta(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&He(it,null,t.fallback);return s&&(s.__u&=-33),[He(it,null,e.__a?null:t.children),s]};var sa=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(fi.prototype=new Ze).__a=function(t){var e=this,n=ia(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),sa(e,t,i)):s()};n?n(o):o()}},fi.prototype.render=function(t){this.i=null,this.l=new Map;var e=st(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},fi.prototype.componentDidUpdate=fi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){sa(t,n,e)})};var ra=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,bh=/^(?: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]/,wh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,xh=/[A-Z0-9]/g,Sh=typeof document<"u",Ch=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};Ze.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(Ze.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var oa=q.event;function kh(){}function Th(){return this.cancelBubble}function Eh(){return this.defaultPrevented}q.event=function(t){return oa&&(t=oa(t)),t.persist=kh,t.isPropagationStopped=Th,t.isDefaultPrevented=Eh,t.nativeEvent=t};var Ih={enumerable:!1,configurable:!0,get:function(){return this.class}},aa=q.vnode;q.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||Sh&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var c=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?r="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||Ch(n.type)?c==="onfocus"?r="onfocusin":c==="onblur"?r="onfocusout":wh.test(r)&&(r=c):c=r="oninput":o&&bh.test(r)?r=r.replace(xh,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&s[r=c]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=st(n.children).forEach(function(d){d.props.selected=s.value.indexOf(d.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=st(n.children).forEach(function(d){d.props.selected=s.multiple?s.defaultValue.indexOf(d.props.value)!=-1:s.defaultValue==d.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",Ih)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ra,aa&&aa(t)};var ca=q.__r;q.__r=function(t){ca&&ca(t),t.__c};var la=q.diffed;q.diffed=function(t){la&&la(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value)};function da(t){return!!t&&t.$$typeof===ra}function Ah(t){return da(t)?as.apply(null,arguments):t}var ua={};const Rh={},Ph=pt(void 0);function ha(t){return xe(Ph)||mh()}const _s=t=>typeof(t==null?void 0:t.then)=="function",bs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Mh=ua.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(bs(t),t)}),ws=new WeakMap,fa=(t,e)=>{let n=ws.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=d=>f=>{o===d&&i(f)},a=d=>f=>{o===d&&s(f)},c=()=>{try{const d=e();_s(d)?(ws.set(d,n),o=d,d.then(r(d),a(d)),qo(d,c)):i(d)}catch(d){s(d)}};t.then(r(t),a(t)),qo(t,c)}),ws.set(t,n)),n};function pa(t,e){const{delay:n,unstable_promiseStatus:i=!ua.use}={},s=ha(),[[o,r,a],c]=Oo(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((r!==s||a!==t)&&(c(),d=s.get(t)),Ve(()=>{const f=s.sub(t,()=>{if(i)try{const p=s.get(t);_s(p)&&bs(fa(p,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(c,n);return}c()});return c(),f},[s,t,n,i]),nh(d),_s(d)){const f=fa(d,()=>s.get(t));return i&&bs(f),Mh(f)}return d}function xs(t,e){const n=ha();return St((...s)=>{if((Rh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function ma(t,e){return[pa(t),xs(t)]}const Ss=pt({});function pi(t){const e=ke(null);return e.current===null&&(e.current=t()),e.current}const Cs=typeof window<"u",ga=Cs?No:Ve,mi=pt(null);function ks(t,e){t.indexOf(e)===-1&&t.push(e)}function Ts(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const mt=(t,e,n)=>n>e?e:n<t?t:n;let Es=()=>{};const gt={},va=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function ya(t){return typeof t=="object"&&t!==null}const _a=t=>/^0[^.\s]+$/u.test(t);function Is(t){let e;return()=>(e===void 0&&(e=t()),e)}const We=t=>t,Lh=(t,e)=>n=>e(t(n)),Tn=(...t)=>t.reduce(Lh),En=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class As{constructor(){this.subscriptions=[]}add(e){return ks(this.subscriptions,e),()=>Ts(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ot=t=>t*1e3,at=t=>t/1e3;function ba(t,e){return e?t*(1e3/e):0}const wa=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Dh=1e-7,Oh=12;function Nh(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=wa(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>Dh&&++a<Oh);return r}function In(t,e,n,i){if(t===e&&n===i)return We;const s=o=>Nh(o,0,1,t,n);return o=>o===0||o===1?o:wa(s(o),e,i)}const xa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Sa=t=>e=>1-t(1-e),Ca=In(.33,1.53,.69,.99),Rs=Sa(Ca),ka=xa(Rs),Ta=t=>(t*=2)<1?.5*Rs(t):.5*(2-Math.pow(2,-10*(t-1))),Ps=t=>1-Math.sin(Math.acos(t)),Ea=Sa(Ps),Ia=xa(Ps),Vh=In(.42,0,1,1),Fh=In(0,0,.58,1),Aa=In(.42,0,.58,1),Bh=t=>Array.isArray(t)&&typeof t[0]!="number",Ra=t=>Array.isArray(t)&&typeof t[0]=="number",jh={linear:We,easeIn:Vh,easeInOut:Aa,easeOut:Fh,circIn:Ps,circInOut:Ia,circOut:Ea,backIn:Rs,backInOut:ka,backOut:Ca,anticipate:Ta},Uh=t=>typeof t=="string",Pa=t=>{if(Ra(t)){Es(t.length===4);const[e,n,i,s]=t;return In(e,n,i,s)}else if(Uh(t))return jh[t];return t},gi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Ma={value:null};function $h(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},c=0;function d(p){r.has(p)&&(f.schedule(p),t()),c++,p(a)}const f={schedule:(p,m=!1,v=!1)=>{const C=v&&s?n:i;return m&&r.add(p),C.has(p)||C.add(p),p},cancel:p=>{i.delete(p),r.delete(p)},process:p=>{if(a=p,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(d),e&&Ma.value&&Ma.value.frameloop[e].push(c),c=0,n.clear(),s=!1,o&&(o=!1,f.process(p))}};return f}const Gh=40;function La(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=gi.reduce((I,R)=>(I[R]=$h(o,e?R:void 0),I),{}),{setup:a,read:c,resolveKeyframes:d,preUpdate:f,update:p,preRender:m,render:v,postRender:_}=r,C=()=>{const I=gt.useManualTiming?s.timestamp:performance.now();n=!1,gt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(I-s.timestamp,Gh),1)),s.timestamp=I,s.isProcessing=!0,a.process(s),c.process(s),d.process(s),f.process(s),p.process(s),m.process(s),v.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(C))},S=()=>{n=!0,i=!0,s.isProcessing||t(C)};return{schedule:gi.reduce((I,R)=>{const L=r[R];return I[R]=(D,b=!1,k=!1)=>(n||S(),L.schedule(D,b,k)),I},{}),cancel:I=>{for(let R=0;R<gi.length;R++)r[gi[R]].cancel(I)},state:s,steps:r}}const{schedule:de,cancel:Ct,state:Te,steps:Ms}=La(typeof requestAnimationFrame<"u"?requestAnimationFrame:We,!0);let vi;function Hh(){vi=void 0}const Fe={now:()=>(vi===void 0&&Fe.set(Te.isProcessing||gt.useManualTiming?Te.timestamp:performance.now()),vi),set:t=>{vi=t,queueMicrotask(Hh)}},Da=t=>e=>typeof e=="string"&&e.startsWith(t),Ls=Da("--"),Wh=Da("var(--"),Ds=t=>Wh(t)?zh.test(t.split("/*")[0].trim()):!1,zh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,en={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},An={...en,transform:t=>mt(0,1,t)},yi={...en,default:1},Rn=t=>Math.round(t*1e5)/1e5,Os=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function qh(t){return t==null}const Kh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ns=(t,e)=>n=>!!(typeof n=="string"&&Kh.test(n)&&n.startsWith(t)||e&&!qh(n)&&Object.prototype.hasOwnProperty.call(n,e)),Oa=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Os);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Xh=t=>mt(0,255,t),Vs={...en,transform:t=>Math.round(Xh(t))},Ot={test:Ns("rgb","red"),parse:Oa("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Vs.transform(t)+", "+Vs.transform(e)+", "+Vs.transform(n)+", "+Rn(An.transform(i))+")"};function Yh(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const Fs={test:Ns("#"),parse:Yh,transform:Ot.transform},Pn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),kt=Pn("deg"),ct=Pn("%"),K=Pn("px"),Zh=Pn("vh"),Jh=Pn("vw"),Na={...ct,parse:t=>ct.parse(t)/100,transform:t=>ct.transform(t*100)},tn={test:Ns("hsl","hue"),parse:Oa("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ct.transform(Rn(e))+", "+ct.transform(Rn(n))+", "+Rn(An.transform(i))+")"},be={test:t=>Ot.test(t)||Fs.test(t)||tn.test(t),parse:t=>Ot.test(t)?Ot.parse(t):tn.test(t)?tn.parse(t):Fs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ot.transform(t):tn.transform(t),getAnimatableNone:t=>{const e=be.parse(t);return e.alpha=0,be.transform(e)}},Qh=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ef(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Os))==null?void 0:e.length)||0)+(((n=t.match(Qh))==null?void 0:n.length)||0)>0}const Va="number",Fa="color",tf="var",nf="var(",Ba="${}",sf=/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 Mn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(sf,c=>(be.test(c)?(i.color.push(o),s.push(Fa),n.push(be.parse(c))):c.startsWith(nf)?(i.var.push(o),s.push(tf),n.push(c)):(i.number.push(o),s.push(Va),n.push(parseFloat(c))),++o,Ba)).split(Ba);return{values:n,split:a,indexes:i,types:s}}function ja(t){return Mn(t).values}function Ua(t){const{split:e,types:n}=Mn(t),i=e.length;return s=>{let o="";for(let r=0;r<i;r++)if(o+=e[r],s[r]!==void 0){const a=n[r];a===Va?o+=Rn(s[r]):a===Fa?o+=be.transform(s[r]):o+=s[r]}return o}}const rf=t=>typeof t=="number"?0:be.test(t)?be.getAnimatableNone(t):t;function of(t){const e=ja(t);return Ua(t)(e.map(rf))}const Tt={test:ef,parse:ja,createTransformer:Ua,getAnimatableNone:of};function Bs(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function af({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;s=Bs(c,a,t+1/3),o=Bs(c,a,t),r=Bs(c,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function _i(t,e){return n=>n>0?e:t}const me=(t,e,n)=>t+(e-t)*n,js=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},cf=[Fs,Ot,tn],lf=t=>cf.find(e=>e.test(t));function $a(t){const e=lf(t);if(!e)return!1;let n=e.parse(t);return e===tn&&(n=af(n)),n}const Ga=(t,e)=>{const n=$a(t),i=$a(e);if(!n||!i)return _i(t,e);const s={...n};return o=>(s.red=js(n.red,i.red,o),s.green=js(n.green,i.green,o),s.blue=js(n.blue,i.blue,o),s.alpha=me(n.alpha,i.alpha,o),Ot.transform(s))},Us=new Set(["none","hidden"]);function df(t,e){return Us.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function uf(t,e){return n=>me(t,e,n)}function $s(t){return typeof t=="number"?uf:typeof t=="string"?Ds(t)?_i:be.test(t)?Ga:pf:Array.isArray(t)?Ha:typeof t=="object"?be.test(t)?Ga:hf:_i}function Ha(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>$s(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function hf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=$s(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function ff(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][i[o]],a=t.values[r]??0;n[s]=a,i[o]++}return n}const pf=(t,e)=>{const n=Tt.createTransformer(e),i=Mn(t),s=Mn(e);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?Us.has(t)&&!s.values.length||Us.has(e)&&!i.values.length?df(t,e):Tn(Ha(ff(i,s),s.values),n):_i(t,e)};function Wa(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?me(t,e,n):$s(t)(t,e)}const mf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>de.update(e,n),stop:()=>Ct(e),now:()=>Te.isProcessing?Te.timestamp:Fe.now()}},za=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},bi=2e4;function Gs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<bi;)e+=n,i=t.next(e);return e>=bi?1/0:e}function gf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Gs(i),bi);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:at(s)}}const vf=5;function qa(t,e,n){const i=Math.max(e-vf,0);return ba(n-t(i),e-i)}const ge={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},Hs=.001;function yf({duration:t=ge.duration,bounce:e=ge.bounce,velocity:n=ge.velocity,mass:i=ge.mass}){let s,o,r=1-e;r=mt(ge.minDamping,ge.maxDamping,r),t=mt(ge.minDuration,ge.maxDuration,at(t)),r<1?(s=d=>{const f=d*r,p=f*t,m=f-n,v=Ws(d,r),_=Math.exp(-p);return Hs-m/v*_},o=d=>{const p=d*r*t,m=p*n+n,v=Math.pow(r,2)*Math.pow(d,2)*t,_=Math.exp(-p),C=Ws(Math.pow(d,2),r);return(-s(d)+Hs>0?-1:1)*((m-v)*_)/C}):(s=d=>{const f=Math.exp(-d*t),p=(d-n)*t+1;return-Hs+f*p},o=d=>{const f=Math.exp(-d*t),p=(n-d)*(t*t);return f*p});const a=5/t,c=bf(s,o,a);if(t=ot(t),isNaN(c))return{stiffness:ge.stiffness,damping:ge.damping,duration:t};{const d=Math.pow(c,2)*i;return{stiffness:d,damping:r*2*Math.sqrt(i*d),duration:t}}}const _f=12;function bf(t,e,n){let i=n;for(let s=1;s<_f;s++)i=i-t(i)/e(i);return i}function Ws(t,e){return t*Math.sqrt(1-e*e)}const wf=["duration","bounce"],xf=["stiffness","damping","mass"];function Ka(t,e){return e.some(n=>t[n]!==void 0)}function Sf(t){let e={velocity:ge.velocity,stiffness:ge.stiffness,damping:ge.damping,mass:ge.mass,isResolvedFromDuration:!1,...t};if(!Ka(t,xf)&&Ka(t,wf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*mt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ge.mass,stiffness:s,damping:o}}else{const n=yf(t);e={...e,...n,mass:ge.mass},e.isResolvedFromDuration=!0}return e}function wi(t=ge.visualDuration,e=ge.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:d,mass:f,duration:p,velocity:m,isResolvedFromDuration:v}=Sf({...n,velocity:-at(n.velocity||0)}),_=m||0,C=d/(2*Math.sqrt(c*f)),S=r-o,w=at(Math.sqrt(c/f)),T=Math.abs(S)<5;i||(i=T?ge.restSpeed.granular:ge.restSpeed.default),s||(s=T?ge.restDelta.granular:ge.restDelta.default);let I;if(C<1){const L=Ws(w,C);I=D=>{const b=Math.exp(-C*w*D);return r-b*((_+C*w*S)/L*Math.sin(L*D)+S*Math.cos(L*D))}}else if(C===1)I=L=>r-Math.exp(-w*L)*(S+(_+w*S)*L);else{const L=w*Math.sqrt(C*C-1);I=D=>{const b=Math.exp(-C*w*D),k=Math.min(L*D,300);return r-b*((_+C*w*S)*Math.sinh(k)+L*S*Math.cosh(k))/L}}const R={calculatedDuration:v&&p||null,next:L=>{const D=I(L);if(v)a.done=L>=p;else{let b=L===0?_:0;C<1&&(b=L===0?ot(_):qa(I,L,D));const k=Math.abs(b)<=i,l=Math.abs(r-D)<=s;a.done=k&&l}return a.value=a.done?r:D,a},toString:()=>{const L=Math.min(Gs(R),bi),D=za(b=>R.next(L*b).value,L,30);return L+"ms "+D},toTransition:()=>{}};return R}wi.applyToOptions=t=>{const e=gf(t,100,wi);return t.ease=e.ease,t.duration=ot(e.duration),t.type="keyframes",t};function zs({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:c,restDelta:d=.5,restSpeed:f}){const p=t[0],m={done:!1,value:p},v=k=>a!==void 0&&k<a||c!==void 0&&k>c,_=k=>a===void 0?c:c===void 0||Math.abs(a-k)<Math.abs(c-k)?a:c;let C=n*e;const S=p+C,w=r===void 0?S:r(S);w!==S&&(C=w-p);const T=k=>-C*Math.exp(-k/i),I=k=>w+T(k),R=k=>{const l=T(k),u=I(k);m.done=Math.abs(l)<=d,m.value=m.done?w:u};let L,D;const b=k=>{v(m.value)&&(L=k,D=wi({keyframes:[m.value,_(m.value)],velocity:qa(I,k,m.value),damping:s,stiffness:o,restDelta:d,restSpeed:f}))};return b(0),{calculatedDuration:null,next:k=>{let l=!1;return!D&&L===void 0&&(l=!0,R(k),b(k)),L!==void 0&&k>=L?D.next(k-L):(!l&&R(k),m)}}}function Cf(t,e,n){const i=[],s=n||gt.mix||Wa,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const c=Array.isArray(e)?e[r]||We:e;a=Tn(c,a)}i.push(a)}return i}function kf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Es(o===e.length),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Cf(e,i,s),c=a.length,d=f=>{if(r&&f<t[0])return e[0];let p=0;if(c>1)for(;p<t.length-2&&!(f<t[p+1]);p++);const m=En(t[p],t[p+1],f);return a[p](m)};return n?f=>d(mt(t[0],t[o-1],f)):d}function Tf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=En(0,e,i);t.push(me(n,1,s))}}function Ef(t){const e=[0];return Tf(e,t.length-1),e}function If(t,e){return t.map(n=>n*e)}function Af(t,e){return t.map(()=>e||Aa).splice(0,t.length-1)}function Ln({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Bh(i)?i.map(Pa):Pa(i),o={done:!1,value:e[0]},r=If(n&&n.length===e.length?n:Ef(e),t),a=kf(r,e,{ease:Array.isArray(s)?s:Af(e,s)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const Rf=t=>t!==null;function qs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Rf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Pf={decay:zs,inertia:zs,tween:Ln,keyframes:Ln,spring:wi};function Xa(t){typeof t.type=="string"&&(t.type=Pf[t.type])}class Ks{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const Mf=t=>t/100;class Xs extends Ks{constructor(e){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!==Fe.now()&&this.tick(Fe.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Xa(e);const{type:n=Ln,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const c=n||Ln;c!==Ln&&typeof a[0]!="number"&&(this.mixKeyframes=Tn(Mf,Wa(a[0],a[1])),a=[0,100]);const d=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-r})),d.calculatedDuration===null&&(d.calculatedDuration=Gs(d));const{calculatedDuration:f}=d;this.calculatedDuration=f,this.resolvedDuration=f+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=d}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:d=0,keyframes:f,repeat:p,repeatType:m,repeatDelay:v,type:_,onUpdate:C,finalKeyframe:S}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const w=this.currentTime-d*(this.playbackSpeed>=0?1:-1),T=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let I=this.currentTime,R=i;if(p){const k=Math.min(this.currentTime,s)/a;let l=Math.floor(k),u=k%1;!u&&k>=1&&(u=1),u===1&&l--,l=Math.min(l,p+1),!!(l%2)&&(m==="reverse"?(u=1-u,v&&(u-=v/a)):m==="mirror"&&(R=r)),I=mt(0,1,u)*a}const L=T?{done:!1,value:f[0]}:R.next(I);o&&(L.value=o(L.value));let{done:D}=L;!T&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const b=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return b&&_!==zs&&(L.value=qs(f,this.options,S,this.speed)),C&&C(L.value),b&&this.finish(),L}then(e,n){return this.finished.then(e,n)}get duration(){return at(this.calculatedDuration)}get time(){return at(this.currentTime)}set time(e){var n;e=ot(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Fe.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=at(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=mf,startTime:n}=this.options;this.driver||(this.driver=e(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(Fe.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function Lf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Nt=t=>t*180/Math.PI,Ys=t=>{const e=Nt(Math.atan2(t[1],t[0]));return Zs(e)},Df={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ys,rotateZ:Ys,skewX:t=>Nt(Math.atan(t[1])),skewY:t=>Nt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Zs=t=>(t=t%360,t<0&&(t+=360),t),Ya=Ys,Za=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ja=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Of={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Za,scaleY:Ja,scale:t=>(Za(t)+Ja(t))/2,rotateX:t=>Zs(Nt(Math.atan2(t[6],t[5]))),rotateY:t=>Zs(Nt(Math.atan2(-t[2],t[0]))),rotateZ:Ya,rotate:Ya,skewX:t=>Nt(Math.atan(t[4])),skewY:t=>Nt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Js(t){return t.includes("scale")?1:0}function Qs(t,e){if(!t||t==="none")return Js(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Of,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Df,s=a}if(!s)return Js(e);const o=i[e],r=s[1].split(",").map(Vf);return typeof o=="function"?o(r):r[o]}const Nf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Qs(n,e)};function Vf(t){return parseFloat(t.trim())}const nn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],sn=new Set(nn),Qa=t=>t===en||t===K,Ff=new Set(["x","y","z"]),Bf=nn.filter(t=>!Ff.has(t));function jf(t){const e=[];return Bf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Vt={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Qs(e,"x"),y:(t,{transform:e})=>Qs(e,"y")};Vt.translateX=Vt.x,Vt.translateY=Vt.y;const Ft=new Set;let er=!1,tr=!1,nr=!1;function ec(){if(tr){const t=Array.from(Ft).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=jf(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([o,r])=>{var a;(a=i.getValue(o))==null||a.set(r)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}tr=!1,er=!1,Ft.forEach(t=>t.complete(nr)),Ft.clear()}function tc(){Ft.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(tr=!0)})}function Uf(){nr=!0,tc(),ec(),nr=!1}class ir{constructor(e,n,i,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Ft.add(this),er||(er=!0,de.read(tc),de.resolveKeyframes(ec))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(i&&n){const a=i.readValue(n,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Lf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Ft.delete(this)}cancel(){this.state==="scheduled"&&(Ft.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const $f=t=>t.startsWith("--");function Gf(t,e,n){$f(e)?t.style.setProperty(e,n):t.style[e]=n}const Hf=Is(()=>window.ScrollTimeline!==void 0),Wf={};function zf(t,e){const n=Is(t);return()=>Wf[e]??n()}const nc=zf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Dn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,ic={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Dn([0,.65,.55,1]),circOut:Dn([.55,0,1,.45]),backIn:Dn([.31,.01,.66,-.59]),backOut:Dn([.33,1.53,.69,.99])};function sc(t,e){if(t)return typeof t=="function"?nc()?za(t,e):"ease-out":Ra(t)?Dn(t):Array.isArray(t)?t.map(n=>sc(n,e)||ic.easeOut):ic[t]}function qf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:c}={},d=void 0){const f={[e]:n};c&&(f.offset=c);const p=sc(a,s);Array.isArray(p)&&(f.easing=p);const m={delay:i,duration:s,easing:Array.isArray(p)?"linear":p,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return d&&(m.pseudoElement=d),t.animate(f,m)}function rc(t){return typeof t=="function"&&"applyToOptions"in t}function Kf({type:t,...e}){return rc(t)&&nc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Xf extends Ks{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Es(typeof e.type!="string");const d=Kf(e);this.animation=qf(n,i,s,d,o),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const f=qs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(f):Gf(n,i,f),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return at(Number(e))}get time(){return at(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=ot(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Hf()?(this.animation.timeline=e,We):n(this)}}const oc={anticipate:Ta,backInOut:ka,circInOut:Ia};function Yf(t){return t in oc}function Zf(t){typeof t.ease=="string"&&Yf(t.ease)&&(t.ease=oc[t.ease])}const ac=10;class Jf extends Xf{constructor(e){Zf(e),Xa(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:o,...r}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new Xs({...r,autoplay:!1}),c=ot(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-ac).value,a.sample(c).value,ac),a.stop()}}const cc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Tt.test(t)||t==="0")&&!t.startsWith("url("));function Qf(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function ep(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=cc(s,e),a=cc(o,e);return!r||!a?!1:Qf(t)||(n==="spring"||rc(n))&&i}function sr(t){return ya(t)&&"offsetHeight"in t}const tp=new Set(["opacity","clipPath","filter","transform"]),np=Is(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function ip(t){var d;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!sr((d=e==null?void 0:e.owner)==null?void 0:d.current))return!1;const{onUpdate:a,transformTemplate:c}=e.owner.getProps();return np()&&n&&tp.has(n)&&(n!=="transform"||!c)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const sp=40;class rp extends Ks{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:c,motionValue:d,element:f,...p}){var _;super(),this.stop=()=>{var C,S;this._animation&&(this._animation.stop(),(C=this.stopTimeline)==null||C.call(this)),(S=this.keyframeResolver)==null||S.cancel()},this.createdAt=Fe.now();const m={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:c,motionValue:d,element:f,...p},v=(f==null?void 0:f.KeyframeResolver)||ir;this.keyframeResolver=new v(a,(C,S,w)=>this.onKeyframesResolved(C,S,m,!w),c,d,f),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:c,isHandoff:d,onUpdate:f}=i;this.resolvedAt=Fe.now(),ep(e,o,r,a)||((gt.instantAnimations||!c)&&(f==null||f(qs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const m={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>sp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},v=!d&&ip(m)?new Jf({...m,element:m.motionValue.owner.current}):new Xs(m);v.finished.then(()=>this.notifyFinished()).catch(We),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Uf()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const op=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ap(t){const e=op.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function lc(t,e,n=1){const[i,s]=ap(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return va(r)?parseFloat(r):r}return Ds(s)?lc(s,e,n+1):s}function rr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const dc=new Set(["width","height","top","left","right","bottom",...nn]),cp={test:t=>t==="auto",parse:t=>t},uc=t=>e=>e.test(t),hc=[en,K,ct,kt,Jh,Zh,cp],fc=t=>hc.find(uc(t));function lp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||_a(t):!0}const dp=new Set(["brightness","contrast","saturate","opacity"]);function up(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Os)||[];if(!i)return t;const s=n.replace(i,"");let o=dp.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const hp=/\b([a-z-]*)\(.*?\)/gu,or={...Tt,getAnimatableNone:t=>{const e=t.match(hp);return e?e.map(up).join(" "):t}},pc={...en,transform:Math.round},ar={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:kt,rotateX:kt,rotateY:kt,rotateZ:kt,scale:yi,scaleX:yi,scaleY:yi,scaleZ:yi,skew:kt,skewX:kt,skewY:kt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:An,originX:Na,originY:Na,originZ:K},zIndex:pc,fillOpacity:An,strokeOpacity:An,numOctaves:pc},fp={...ar,color:be,backgroundColor:be,outlineColor:be,fill:be,stroke:be,borderColor:be,borderTopColor:be,borderRightColor:be,borderBottomColor:be,borderLeftColor:be,filter:or,WebkitFilter:or},mc=t=>fp[t];function gc(t,e){let n=mc(t);return n!==or&&(n=Tt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const pp=new Set(["auto","none","0"]);function mp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!pp.has(o)&&Mn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=gc(n,s)}class gp extends ir{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let d=e[c];if(typeof d=="string"&&(d=d.trim(),Ds(d))){const f=lc(d,n.current);f!==void 0&&(e[c]=f),c===e.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!dc.has(i)||e.length!==2)return;const[s,o]=e,r=fc(s),a=fc(o);if(r!==a)if(Qa(r)&&Qa(a))for(let c=0;c<e.length;c++){const d=e[c];typeof d=="string"&&(e[c]=parseFloat(d))}else Vt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||lp(e[s]))&&i.push(s);i.length&&mp(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Vt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const o=i.length-1,r=i[o];i[o]=Vt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,d])=>{e.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function vp(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const s=(n==null?void 0:n[t])??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const vc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,yc=30,yp=t=>!isNaN(parseFloat(t));class _p{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Fe.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 c of this.dependents)c.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Fe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=yp(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new As);const i=this.events[e].add(n);return e==="change"?()=>{i(),de.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e,n=!0){!n||!this.passiveEffect?this.updateAndNotify(e,n):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Fe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>yc)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,yc);return ba(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(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 e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function rn(t,e){return new _p(t,e)}const{schedule:cr}=La(queueMicrotask,!1),Je={x:!1,y:!1};function _c(){return Je.x||Je.y}function bp(t){return t==="x"||t==="y"?Je[t]?null:(Je[t]=!0,()=>{Je[t]=!1}):Je.x||Je.y?null:(Je.x=Je.y=!0,()=>{Je.x=Je.y=!1})}function bc(t,e){const n=vp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function wc(t){return!(t.pointerType==="touch"||_c())}function wp(t,e,n={}){const[i,s,o]=bc(t,n),r=a=>{if(!wc(a))return;const{target:c}=a,d=e(c,a);if(typeof d!="function"||!c)return;const f=p=>{wc(p)&&(d(p),c.removeEventListener("pointerleave",f))};c.addEventListener("pointerleave",f,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const xc=(t,e)=>e?t===e?!0:xc(t,e.parentElement):!1,lr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,xp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Sp(t){return xp.has(t.tagName)||t.tabIndex!==-1}const xi=new WeakSet;function Sc(t){return e=>{e.key==="Enter"&&t(e)}}function dr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Cp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Sc(()=>{if(xi.has(n))return;dr(n,"down");const s=Sc(()=>{dr(n,"up")}),o=()=>dr(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function Cc(t){return lr(t)&&!_c()}function kp(t,e,n={}){const[i,s,o]=bc(t,n),r=a=>{const c=a.currentTarget;if(!Cc(a))return;xi.add(c);const d=e(c,a),f=(v,_)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",m),xi.has(c)&&xi.delete(c),Cc(v)&&typeof d=="function"&&d(v,{success:_})},p=v=>{f(v,c===window||c===document||n.useGlobalTarget||xc(c,v.target))},m=v=>{f(v,!1)};window.addEventListener("pointerup",p,s),window.addEventListener("pointercancel",m,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),sr(a)&&(a.addEventListener("focus",d=>Cp(d,s)),!Sp(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function kc(t){return ya(t)&&"ownerSVGElement"in t}function Tp(t){return kc(t)&&t.tagName==="svg"}const Ae=t=>!!(t&&t.getVelocity),Ep=[...hc,be,Tt],Ip=t=>Ep.find(uc(t)),On=pt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Ap extends Ze{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=sr(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 Rp({children:t,isPresent:e,anchorX:n,root:i}){const s=ds(),o=ke(null),r=ke({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=xe(On);return Yo(()=>{const{width:c,height:d,top:f,left:p,right:m}=r.current;if(e||!o.current||!c||!d)return;const v=n==="left"?`left: ${p}`:`right: ${m}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const C=i??document.head;return C.appendChild(_),_.sheet&&_.sheet.insertRule(`
1
+ var _y=Object.defineProperty;var yy=(Ye,H,Lt)=>H in Ye?_y(Ye,H,{enumerable:!0,configurable:!0,writable:!0,value:Lt}):Ye[H]=Lt;var _e=(Ye,H,Lt)=>yy(Ye,typeof H!="symbol"?H+"":H,Lt);(function(){"use strict";var Ye,H,Lt,Dt,ro,oo,ao,co,Yi,Ji,Zi,lo,wn={},uo=[],Ru=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,xn=Array.isArray;function nt(t,e){for(var n in e)t[n]=e[n];return t}function Qi(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ge(t,e,n){var i,s,o,r={};for(o in e)o=="key"?i=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?Ye.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Sn(t,r,i,s,null)}function Sn(t,e,n,i,s){var o={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Lt,__i:-1,__u:0};return s==null&&H.vnode!=null&&H.vnode(o),o}function it(t){return t.children}function Je(t,e){this.props=t,this.context=e}function Zt(t,e){if(e==null)return t.__?Zt(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?Zt(t):null}function ho(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return ho(t)}}function es(t){(!t.__d&&(t.__d=!0)&&Dt.push(t)&&!ai.__r++||ro!=H.debounceRendering)&&((ro=H.debounceRendering)||oo)(ai)}function ai(){for(var t,e,n,i,s,o,r,a=1;Dt.length;)Dt.length>a&&Dt.sort(ao),t=Dt.shift(),a=Dt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=nt({},i)).__v=i.__v+1,H.vnode&&H.vnode(n),ts(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??Zt(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,vo(o,n,r),n.__e!=s&&ho(n)));ai.__r=0}function fo(t,e,n,i,s,o,r,a,c,l,d){var u,h,g,v,y,x,w=i&&i.__k||uo,S=e.length;for(c=Pu(n,e,w,c,S),u=0;u<S;u++)(g=n.__k[u])!=null&&(h=g.__i==-1?wn:w[g.__i]||wn,g.__i=u,x=ts(t,g,h,s,o,r,a,c,l,d),v=g.__e,g.ref&&h.ref!=g.ref&&(h.ref&&ns(h.ref,null,g),d.push(g.ref,g.__c||v,g)),y==null&&v!=null&&(y=v),4&g.__u||h.__k===g.__k?c=po(g,c,t):typeof g.type=="function"&&x!==void 0?c=x:v&&(c=v.nextSibling),g.__u&=-7);return n.__e=y,c}function Pu(t,e,n,i,s){var o,r,a,c,l,d=n.length,u=d,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(c=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Sn(null,r,null,null,null):xn(r)?Sn(it,{children:r},null,null,null):r.constructor==null&&r.__b>0?Sn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(l=r.__i=Mu(r,n,c,u))!=-1&&(u--,(a=n[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(s>d?h--:s<d&&h++),typeof r.type!="function"&&(r.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?h--:h++,r.__u|=4))):t.__k[o]=null;if(u)for(o=0;o<d;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=Zt(a)),yo(a,a));return i}function po(t,e,n){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=po(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=Zt(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function st(t,e){return e=e||[],t==null||typeof t=="boolean"||(xn(t)?t.some(function(n){st(n,e)}):e.push(t)),e}function Mu(t,e,n,i){var s,o,r=t.key,a=t.type,c=e[n];if(c===null&&t.key==null||c&&r==c.key&&a==c.type&&(2&c.__u)==0)return n;if(i>(c!=null&&(2&c.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((c=e[s])&&(2&c.__u)==0&&r==c.key&&a==c.type)return s;s--}if(o<e.length){if((c=e[o])&&(2&c.__u)==0&&r==c.key&&a==c.type)return o;o++}}return-1}function mo(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ru.test(e)?n:n+"px"}function ci(t,e,n,i,s){var o,r;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||mo(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||mo(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(co,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?i?n.u=i.u:(n.u=Yi,t.addEventListener(e,o?Zi:Ji,o)):t.removeEventListener(e,o?Zi:Ji,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 t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function go(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Yi++;else if(e.t<n.u)return;return n(H.event?H.event(e):e)}}}function ts(t,e,n,i,s,o,r,a,c,l){var d,u,h,g,v,y,x,w,S,k,A,L,O,b,C,f,m,p=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),o=[a=e.__e=n.__e]),(d=H.__b)&&d(e);e:if(typeof p=="function")try{if(w=e.props,S="prototype"in p&&p.prototype.render,k=(d=p.contextType)&&i[d.__c],A=d?k?k.props.value:d.__:i,n.__c?x=(u=e.__c=n.__c).__=u.__E:(S?e.__c=u=new p(w,A):(e.__c=u=new Je(w,A),u.constructor=p,u.render=Du),k&&k.sub(u),u.props=w,u.state||(u.state={}),u.context=A,u.__n=i,h=u.__d=!0,u.__h=[],u._sb=[]),S&&u.__s==null&&(u.__s=u.state),S&&p.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=nt({},u.__s)),nt(u.__s,p.getDerivedStateFromProps(w,u.__s))),g=u.props,v=u.state,u.__v=e,h)S&&p.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),S&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(S&&p.getDerivedStateFromProps==null&&w!==g&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(w,A),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(w,u.__s,A)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=w,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(_){_&&(_.__=e)}),L=0;L<u._sb.length;L++)u.__h.push(u._sb[L]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(w,u.__s,A),S&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(g,v,y)})}if(u.context=A,u.props=w,u.__P=t,u.__e=!1,O=H.__r,b=0,S){for(u.state=u.__s,u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),C=0;C<u._sb.length;C++)u.__h.push(u._sb[C]);u._sb=[]}else do u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++b<25);u.state=u.__s,u.getChildContext!=null&&(i=nt(nt({},i),u.getChildContext())),S&&!h&&u.getSnapshotBeforeUpdate!=null&&(y=u.getSnapshotBeforeUpdate(g,v)),f=d,d!=null&&d.type===it&&d.key==null&&(f=_o(d.props.children)),a=fo(t,xn(f)?f:[f],e,n,i,s,o,r,a,c,l),u.base=e.__e,e.__u&=-161,u.__h.length&&r.push(u),x&&(u.__E=u.__=null)}catch(_){if(e.__v=null,c||o!=null)if(_.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(m=o.length;m--;)Qi(o[m]);else e.__e=n.__e,e.__k=n.__k;H.__e(_,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Lu(n.__e,e,n,i,s,o,r,c,l);return(d=H.diffed)&&d(e),128&e.__u?void 0:a}function vo(t,e,n){for(var i=0;i<n.length;i++)ns(n[i],n[++i],n[++i]);H.__c&&H.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){H.__e(o,s.__v)}})}function _o(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:xn(t)?t.map(_o):nt({},t)}function Lu(t,e,n,i,s,o,r,a,c){var l,d,u,h,g,v,y,x=n.props,w=e.props,S=e.type;if(S=="svg"?s="http://www.w3.org/2000/svg":S=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((g=o[l])&&"setAttribute"in g==!!S&&(S?g.localName==S:g.nodeType==3)){t=g,o[l]=null;break}}if(t==null){if(S==null)return document.createTextNode(w);t=document.createElementNS(s,S,w.is&&w),a&&(H.__m&&H.__m(e,o),a=!1),o=null}if(S==null)x===w||a&&t.data==w||(t.data=w);else{if(o=o&&Ye.call(t.childNodes),x=n.props||wn,!a&&o!=null)for(x={},l=0;l<t.attributes.length;l++)x[(g=t.attributes[l]).name]=g.value;for(l in x)if(g=x[l],l!="children"){if(l=="dangerouslySetInnerHTML")u=g;else if(!(l in w)){if(l=="value"&&"defaultValue"in w||l=="checked"&&"defaultChecked"in w)continue;ci(t,l,null,g,s)}}for(l in w)g=w[l],l=="children"?h=g:l=="dangerouslySetInnerHTML"?d=g:l=="value"?v=g:l=="checked"?y=g:a&&typeof g!="function"||x[l]===g||ci(t,l,g,x[l],s);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),fo(e.type=="template"?t.content:t,xn(h)?h:[h],e,n,i,S=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&Zt(n,0),a,c),o!=null)for(l=o.length;l--;)Qi(o[l]);a||(l="value",S=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[l]||S=="progress"&&!v||S=="option"&&v!=x[l])&&ci(t,l,v,x[l],s),l="checked",y!=null&&y!=t[l]&&ci(t,l,y,x[l],s))}return t}function ns(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){H.__e(s,n)}}function yo(t,e,n){var i,s;if(H.unmount&&H.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||ns(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){H.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&yo(i[s],e,n||typeof t.type!="function");n||Qi(t.__e),t.__c=t.__=t.__e=void 0}function Du(t,e,n){return this.constructor(t,n)}function li(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),H.__&&H.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],ts(e,t=(!i&&n||e).__k=Ge(it,null,[t]),s||wn,wn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?Ye.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),vo(o,t,r)}function bo(t,e){li(t,e,bo)}function is(t,e,n){var i,s,o,r,a=nt({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?i=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?Ye.call(arguments,2):n),Sn(t.type,a,i||t.key,s||t.ref,null)}function mt(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__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,es(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 e.__c="__cC"+lo++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}Ye=uo.slice,H={__e:function(t,e,n,i){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Lt=0,Je.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=nt({},this.state),typeof t=="function"&&(t=t(nt({},n),this.props)),t&&nt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),es(this))},Je.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),es(this))},Je.prototype.render=it,Dt=[],oo=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ao=function(t,e){return t.__v.__b-e.__v.__b},ai.__r=0,co=/(PointerCapture)$|Capture$/i,Yi=0,Ji=go(!1),Zi=go(!0),lo=0;var Ou=0;function E(t,e,n,i,s,o){e||(e={});var r,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?r=e[a]:c[a]=e[a];var l={type:t,props:c,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ou,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)c[a]===void 0&&(c[a]=r[a]);return H.vnode&&H.vnode(l),l}function ss(){return(ss=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var Nu=["context","children"];function Vu(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},c=Object.keys(i);for(r=0;r<c.length;r++)s.indexOf(o=c[r])>=0||(a[o]=i[o]);return a}(t,Nu);return is(e,n)}function Fu(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ge(Vu,ss({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,c=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[wo(a[r].name)]=a[r].value);for(r=c.length;r--;){var l=e(c[r],null),d=c[r].slot;d?o[d]=Ge(xo,{name:d},l):s[r]=l}var u=i?Ge(xo,null,s):s;return Ge(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?bo:li)(this._vdom,this._root)}function wo(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Bu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[wo(t)]=n,this._vdom=is(this._vdom,i),li(this._vdom,this._root)}}function ju(){li(this._vdom=null,this._root)}function xo(t,e){var n=this;return Ge("slot",ss({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Uu(t,e,n,i){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,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=Fu,s.prototype.attributeChangedCallback=Bu,s.prototype.disconnectedCallback=ju,n=n||t.observedAttributes||Object.keys(t.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(e,s)}var xt,ae,rs,So,Cn=0,Co=[],pe=H,ko=pe.__b,To=pe.__r,Eo=pe.diffed,Ao=pe.__c,Io=pe.unmount,Ro=pe.__;function Qt(t,e){pe.__h&&pe.__h(ae,t,Cn||e),Cn=0;var n=ae.__H||(ae.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function ke(t){return Cn=1,Po(Do,t)}function Po(t,e,n){var i=Qt(xt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Do(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,a);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=ae,!ae.__f)){var s=function(a,c,l){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(h){return!!h.__c});if(d.every(function(h){return!h.__N}))return!o||o.call(this,a,c,l);var u=i.__c.props!==a;return d.forEach(function(h){if(h.__N){var g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(u=!0)}}),o&&o.call(this,a,c,l)||u};ae.__f=!0;var o=ae.shouldComponentUpdate,r=ae.componentWillUpdate;ae.componentWillUpdate=function(a,c,l){if(this.__e){var d=o;o=void 0,s(a,c,l),o=d}r&&r.call(this,a,c,l)},ae.shouldComponentUpdate=s}return i.__N||i.__}function Ve(t,e){var n=Qt(xt++,3);!pe.__s&&cs(n.__H,e)&&(n.__=t,n.u=e,ae.__H.__h.push(n))}function Mo(t,e){var n=Qt(xt++,4);!pe.__s&&cs(n.__H,e)&&(n.__=t,n.u=e,ae.__h.push(n))}function Te(t){return Cn=5,rt(function(){return{current:t}},[])}function rt(t,e){var n=Qt(xt++,7);return cs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function St(t,e){return Cn=8,rt(function(){return t},e)}function Se(t){var e=ae.context[t.__c],n=Qt(xt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ae)),e.props.value):t.__}function $u(t,e){pe.useDebugValue&&pe.useDebugValue(e?e(t):t)}function os(){var t=Qt(xt++,11);if(!t.__){for(var e=ae.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function Hu(){for(var t;t=Co.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(di),t.__H.__h.forEach(as),t.__H.__h=[]}catch(e){t.__H.__h=[],pe.__e(e,t.__v)}}pe.__b=function(t){ae=null,ko&&ko(t)},pe.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ro&&Ro(t,e)},pe.__r=function(t){To&&To(t),xt=0;var e=(ae=t.__c).__H;e&&(rs===ae?(e.__h=[],ae.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(di),e.__h.forEach(as),e.__h=[],xt=0)),rs=ae},pe.diffed=function(t){Eo&&Eo(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Co.push(e)!==1&&So===pe.requestAnimationFrame||((So=pe.requestAnimationFrame)||Gu)(Hu)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),rs=ae=null},pe.__c=function(t,e){e.some(function(n){try{n.__h.forEach(di),n.__h=n.__h.filter(function(i){return!i.__||as(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],pe.__e(i,n.__v)}}),Ao&&Ao(t,e)},pe.unmount=function(t){Io&&Io(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{di(i)}catch(s){e=s}}),n.__H=void 0,e&&pe.__e(e,n.__v))};var Lo=typeof requestAnimationFrame=="function";function Gu(t){var e,n=function(){clearTimeout(i),Lo&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Lo&&(e=requestAnimationFrame(n))}function di(t){var e=ae,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ae=e}function as(t){var e=ae;t.__c=t.__(),ae=e}function cs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Do(t,e){return typeof e=="function"?e(t):e}const kn={},Oo=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,No=t=>"init"in t,ls=t=>!!t.write,Vo=t=>"v"in t||"e"in t,ui=t=>{if("e"in t)throw t.e;if((kn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},hi=new WeakMap,Fo=t=>{var e;return fi(t)&&!!((e=hi.get(t))!=null&&e[0])},Wu=t=>{const e=hi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Bo=(t,e)=>{let n=hi.get(t);if(!n){n=[!0,new Set],hi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},fi=t=>typeof(t==null?void 0:t.then)=="function",jo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},ds=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(fi(e))for(const r of i.d.keys())jo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,fi(o)&&Wu(o))},Uo=(t,e,n)=>{var i;const s=new Set;for(const o of((i=n.get(t))==null?void 0:i.t)||[])n.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},zu=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},us=()=>{const t={},e=new WeakMap,n=i=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(i)),(o=e.get(i))==null||o.forEach(r=>r())};return n.add=(i,s)=>{const o=i||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},n},qu=t=>(t.c||(t.c=us()),t.m||(t.m=us()),t.u||(t.u=us()),t.f||(t.f=zu()),t),Ku=Symbol(),$o=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(h,...g)=>h.read(...g),c=(h,...g)=>h.write(...g),l=(h,g)=>{var v;return(v=h.unstable_onInit)==null?void 0:v.call(h,g)},d=(h,g)=>{var v;return(v=h.onMount)==null?void 0:v.call(h,g)},...u)=>{const h=u[0]||(b=>{if((kn?"production":void 0)!=="production"&&!b)throw new Error("Atom is undefined or null");let C=t.get(b);return C||(C={d:new Map,p:new Set,n:0},t.set(b,C),l==null||l(b,O)),C}),g=u[1]||(()=>{const b=[],C=f=>{try{f()}catch(m){b.push(m)}};do{r.f&&C(r.f);const f=new Set,m=f.add.bind(f);i.forEach(p=>{var _;return(_=e.get(p))==null?void 0:_.l.forEach(m)}),i.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),f.forEach(C),i.size&&v()}while(i.size||o.size||s.size);if(b.length)throw new AggregateError(b)}),v=u[2]||(()=>{const b=[],C=new WeakSet,f=new WeakSet,m=Array.from(i);for(;m.length;){const p=m[m.length-1],_=h(p);if(f.has(p)){m.pop();continue}if(C.has(p)){if(n.get(p)===_.n)b.push([p,_]);else if((kn?"production":void 0)!=="production"&&n.has(p))throw new Error("[Bug] invalidated atom exists");f.add(p),m.pop();continue}C.add(p);for(const T of Uo(p,_,e))C.has(T)||m.push(T)}for(let p=b.length-1;p>=0;--p){const[_,T]=b[p];let P=!1;for(const I of T.d.keys())if(I!==_&&i.has(I)){P=!0;break}P&&(y(_),S(_)),n.delete(_)}}),y=u[3]||(b=>{var C;const f=h(b);if(Vo(f)&&(e.has(b)&&n.get(b)!==f.n||Array.from(f.d).every(([M,V])=>y(M).n===V)))return f;f.d.clear();let m=!0;const p=()=>{e.has(b)&&(S(b),v(),g())},_=M=>{var V;if(Oo(b,M)){const B=h(M);if(!Vo(B))if(No(M))ds(M,M.init,h);else throw new Error("no atom init");return ui(B)}const X=y(M);try{return ui(X)}finally{f.d.set(M,X.n),Fo(f.v)&&jo(b,f.v,X),(V=e.get(M))==null||V.t.add(b),m||p()}};let T,P;const I={get signal(){return T||(T=new AbortController),T.signal},get setSelf(){return(kn?"production":void 0)!=="production"&&!ls(b)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&ls(b)&&(P=(...M)=>{if((kn?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return w(b,...M)}finally{v(),g()}}),P}},D=f.n;try{const M=a(b,_,I);return ds(b,M,h),fi(M)&&(Bo(M,()=>T==null?void 0:T.abort()),M.then(p,p)),f}catch(M){return delete f.v,f.e=M,++f.n,f}finally{m=!1,D!==f.n&&n.get(b)===D&&(n.set(b,f.n),i.add(b),(C=r.c)==null||C.call(r,b))}}),x=u[4]||(b=>{const C=[b];for(;C.length;){const f=C.pop(),m=h(f);for(const p of Uo(f,m,e)){const _=h(p);n.set(p,_.n),C.push(p)}}}),w=u[5]||((b,...C)=>{let f=!0;const m=_=>ui(y(_)),p=(_,...T)=>{var P;const I=h(_);try{if(Oo(b,_)){if(!No(_))throw new Error("atom not writable");const D=I.n,M=T[0];ds(_,M,h),S(_),D!==I.n&&(i.add(_),(P=r.c)==null||P.call(r,_),x(_));return}else return w(_,...T)}finally{f||(v(),g())}};try{return c(b,m,p,...C)}finally{f=!1}}),S=u[6]||(b=>{var C;const f=h(b),m=e.get(b);if(m&&!Fo(f.v)){for(const[p,_]of f.d)if(!m.d.has(p)){const T=h(p);k(p).t.add(b),m.d.add(p),_!==T.n&&(i.add(p),(C=r.c)==null||C.call(r,p),x(p))}for(const p of m.d||[])if(!f.d.has(p)){m.d.delete(p);const _=A(p);_==null||_.t.delete(b)}}}),k=u[7]||(b=>{var C;const f=h(b);let m=e.get(b);if(!m){y(b);for(const p of f.d.keys())k(p).t.add(b);if(m={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(b,m),(C=r.m)==null||C.call(r,b),ls(b)){const p=()=>{let _=!0;const T=(...P)=>{try{return w(b,...P)}finally{_||(v(),g())}};try{const P=d(b,T);P&&(m.u=()=>{_=!0;try{P()}finally{_=!1}})}finally{_=!1}};s.add(p)}}return m}),A=u[8]||(b=>{var C;const f=h(b);let m=e.get(b);if(m&&!m.l.size&&!Array.from(m.t).some(p=>{var _;return(_=e.get(p))==null?void 0:_.d.has(b)})){m.u&&o.add(m.u),m=void 0,e.delete(b),(C=r.u)==null||C.call(r,b);for(const p of f.d.keys()){const _=A(p);_==null||_.t.delete(b)}return}return m}),L=[t,e,n,i,s,o,r,a,c,l,d,h,g,v,y,x,w,S,k,A],O={get:b=>ui(y(b)),set:(b,...C)=>{try{return w(b,...C)}finally{v(),g()}},sub:(b,C)=>{const m=k(b).l;return m.add(C),g(),()=>{m.delete(C),A(b),g()}}};return Object.defineProperty(O,Ku,{value:L}),O},Xu=qu,Ho=Bo,hs={};let Yu=0;function fs(t,e){const n=`atom${++Yu}`,i={toString(){return(hs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=Ju,i.write=Zu),i}function Ju(t){return t(this)}function Zu(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const Qu=()=>{let t=0;const e=Xu({}),n=new WeakMap,i=new WeakMap,s=$o(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,c,l,...d)=>t?l(a,...d):a.write(c,l,...d)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const c=n.get(a);c.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const c=n.get(a);delete c.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const c={read:()=>null,write:(l,d)=>{++t;try{for(const[u,h]of a)"init"in u&&d(u,h)}finally{--t}}};s.set(c)}})};function eh(){return(hs?"production":void 0)!=="production"?Qu():$o()}let Tn;function th(){return Tn||(Tn=eh(),(hs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Tn),globalThis.__JOTAI_DEFAULT_STORE__!==Tn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Tn}function Go(t,e){for(var n in e)t[n]=e[n];return t}function Wo(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}var zo=Mo;function qo(t,e){this.props=t,this.context=e}(qo.prototype=new Je).isPureReactComponent=!0,qo.prototype.shouldComponentUpdate=function(t,e){return Wo(this.props,t)||Wo(this.state,e)};var Ko=H.__b;H.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ko&&Ko(t)};var nh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ih(t){function e(n){var i=Go({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=nh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Xo=function(t,e){return t==null?null:st(st(t).map(e))},sh={map:Xo,forEach:Xo,count:function(t){return t?st(t).length:0},only:function(t){var e=st(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:st},rh=H.__e;H.__e=function(t,e,n,i){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}rh(t,e,n,i)};var Yo=H.unmount;function Jo(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=Go({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return Jo(i,e,n)})),t}function Zo(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return Zo(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function ps(){this.__u=0,this.o=null,this.__b=null}function Qo(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function pi(){this.i=null,this.l=null}H.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Yo&&Yo(t)},(ps.prototype=new Je).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=Qo(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 c=i.state.__a;i.__v.__k[0]=Zo(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},ps.prototype.componentWillUnmount=function(){this.o=[]},ps.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Jo(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&Ge(it,null,t.fallback);return s&&(s.__u&=-33),[Ge(it,null,e.__a?null:t.children),s]};var ea=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(pi.prototype=new Je).__a=function(t){var e=this,n=Qo(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),ea(e,t,i)):s()};n?n(o):o()}},pi.prototype.render=function(t){this.i=null,this.l=new Map;var e=st(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},pi.prototype.componentDidUpdate=pi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){ea(t,n,e)})};var ta=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,oh=/^(?: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]/,ah=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ch=/[A-Z0-9]/g,lh=typeof document<"u",dh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};Je.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(Je.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var na=H.event;function uh(){}function hh(){return this.cancelBubble}function fh(){return this.defaultPrevented}H.event=function(t){return na&&(t=na(t)),t.persist=uh,t.isPropagationStopped=hh,t.isDefaultPrevented=fh,t.nativeEvent=t};var ph={enumerable:!1,configurable:!0,get:function(){return this.class}},ia=H.vnode;H.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||lh&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var c=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?r="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||dh(n.type)?c==="onfocus"?r="onfocusin":c==="onblur"?r="onfocusout":ah.test(r)&&(r=c):c=r="oninput":o&&oh.test(r)?r=r.replace(ch,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&s[r=c]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=st(n.children).forEach(function(l){l.props.selected=s.value.indexOf(l.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=st(n.children).forEach(function(l){l.props.selected=s.multiple?s.defaultValue.indexOf(l.props.value)!=-1:s.defaultValue==l.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",ph)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ta,ia&&ia(t)};var sa=H.__r;H.__r=function(t){sa&&sa(t),t.__c};var ra=H.diffed;H.diffed=function(t){ra&&ra(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value)};function oa(t){return!!t&&t.$$typeof===ta}function mh(t){return oa(t)?is.apply(null,arguments):t}var aa={};const gh={},vh=mt(void 0);function ca(t){return Se(vh)||th()}const ms=t=>typeof(t==null?void 0:t.then)=="function",gs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},_h=aa.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(gs(t),t)}),vs=new WeakMap,la=(t,e)=>{let n=vs.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=l=>d=>{o===l&&i(d)},a=l=>d=>{o===l&&s(d)},c=()=>{try{const l=e();ms(l)?(vs.set(l,n),o=l,l.then(r(l),a(l)),Ho(l,c)):i(l)}catch(l){s(l)}};t.then(r(t),a(t)),Ho(t,c)}),vs.set(t,n)),n};function da(t,e){const{delay:n,unstable_promiseStatus:i=!aa.use}={},s=ca(),[[o,r,a],c]=Po(d=>{const u=s.get(t);return Object.is(d[0],u)&&d[1]===s&&d[2]===t?d:[u,s,t]},void 0,()=>[s.get(t),s,t]);let l=o;if((r!==s||a!==t)&&(c(),l=s.get(t)),Ve(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);ms(u)&&gs(la(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(c,n);return}c()});return c(),d},[s,t,n,i]),$u(l),ms(l)){const d=la(l,()=>s.get(t));return i&&gs(d),_h(d)}return l}function _s(t,e){const n=ca();return St((...s)=>{if((gh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function ua(t,e){return[da(t),_s(t)]}const ys=mt({});function mi(t){const e=Te(null);return e.current===null&&(e.current=t()),e.current}const bs=typeof window<"u",ha=bs?Mo:Ve,gi=mt(null);function ws(t,e){t.indexOf(e)===-1&&t.push(e)}function xs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const gt=(t,e,n)=>n>e?e:n<t?t:n;let Ss=()=>{};const vt={},fa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function pa(t){return typeof t=="object"&&t!==null}const ma=t=>/^0[^.\s]+$/u.test(t);function Cs(t){let e;return()=>(e===void 0&&(e=t()),e)}const We=t=>t,yh=(t,e)=>n=>e(t(n)),En=(...t)=>t.reduce(yh),An=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class ks{constructor(){this.subscriptions=[]}add(e){return ws(this.subscriptions,e),()=>xs(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ot=t=>t*1e3,at=t=>t/1e3;function ga(t,e){return e?t*(1e3/e):0}const va=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,bh=1e-7,wh=12;function xh(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=va(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>bh&&++a<wh);return r}function In(t,e,n,i){if(t===e&&n===i)return We;const s=o=>xh(o,0,1,t,n);return o=>o===0||o===1?o:va(s(o),e,i)}const _a=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ya=t=>e=>1-t(1-e),ba=In(.33,1.53,.69,.99),Ts=ya(ba),wa=_a(Ts),xa=t=>(t*=2)<1?.5*Ts(t):.5*(2-Math.pow(2,-10*(t-1))),Es=t=>1-Math.sin(Math.acos(t)),Sa=ya(Es),Ca=_a(Es),Sh=In(.42,0,1,1),Ch=In(0,0,.58,1),ka=In(.42,0,.58,1),kh=t=>Array.isArray(t)&&typeof t[0]!="number",Ta=t=>Array.isArray(t)&&typeof t[0]=="number",Th={linear:We,easeIn:Sh,easeInOut:ka,easeOut:Ch,circIn:Es,circInOut:Ca,circOut:Sa,backIn:Ts,backInOut:wa,backOut:ba,anticipate:xa},Eh=t=>typeof t=="string",Ea=t=>{if(Ta(t)){Ss(t.length===4);const[e,n,i,s]=t;return In(e,n,i,s)}else if(Eh(t))return Th[t];return t},vi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Aa={value:null};function Ah(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},c=0;function l(u){r.has(u)&&(d.schedule(u),t()),c++,u(a)}const d={schedule:(u,h=!1,g=!1)=>{const y=g&&s?n:i;return h&&r.add(u),y.has(u)||y.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(l),e&&Aa.value&&Aa.value.frameloop[e].push(c),c=0,n.clear(),s=!1,o&&(o=!1,d.process(u))}};return d}const Ih=40;function Ia(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=vi.reduce((k,A)=>(k[A]=Ah(o,e?A:void 0),k),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:d,update:u,preRender:h,render:g,postRender:v}=r,y=()=>{const k=vt.useManualTiming?s.timestamp:performance.now();n=!1,vt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(k-s.timestamp,Ih),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),c.process(s),l.process(s),d.process(s),u.process(s),h.process(s),g.process(s),v.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(y))},x=()=>{n=!0,i=!0,s.isProcessing||t(y)};return{schedule:vi.reduce((k,A)=>{const L=r[A];return k[A]=(O,b=!1,C=!1)=>(n||x(),L.schedule(O,b,C)),k},{}),cancel:k=>{for(let A=0;A<vi.length;A++)r[vi[A]].cancel(k)},state:s,steps:r}}const{schedule:de,cancel:Ct,state:Ee,steps:As}=Ia(typeof requestAnimationFrame<"u"?requestAnimationFrame:We,!0);let _i;function Rh(){_i=void 0}const Fe={now:()=>(_i===void 0&&Fe.set(Ee.isProcessing||vt.useManualTiming?Ee.timestamp:performance.now()),_i),set:t=>{_i=t,queueMicrotask(Rh)}},Ra=t=>e=>typeof e=="string"&&e.startsWith(t),Is=Ra("--"),Ph=Ra("var(--"),Rs=t=>Ph(t)?Mh.test(t.split("/*")[0].trim()):!1,Mh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,en={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Rn={...en,transform:t=>gt(0,1,t)},yi={...en,default:1},Pn=t=>Math.round(t*1e5)/1e5,Ps=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Lh(t){return t==null}const Dh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ms=(t,e)=>n=>!!(typeof n=="string"&&Dh.test(n)&&n.startsWith(t)||e&&!Lh(n)&&Object.prototype.hasOwnProperty.call(n,e)),Pa=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Ps);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Oh=t=>gt(0,255,t),Ls={...en,transform:t=>Math.round(Oh(t))},Ot={test:Ms("rgb","red"),parse:Pa("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ls.transform(t)+", "+Ls.transform(e)+", "+Ls.transform(n)+", "+Pn(Rn.transform(i))+")"};function Nh(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const Ds={test:Ms("#"),parse:Nh,transform:Ot.transform},Mn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),kt=Mn("deg"),ct=Mn("%"),G=Mn("px"),Vh=Mn("vh"),Fh=Mn("vw"),Ma={...ct,parse:t=>ct.parse(t)/100,transform:t=>ct.transform(t*100)},tn={test:Ms("hsl","hue"),parse:Pa("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ct.transform(Pn(e))+", "+ct.transform(Pn(n))+", "+Pn(Rn.transform(i))+")"},be={test:t=>Ot.test(t)||Ds.test(t)||tn.test(t),parse:t=>Ot.test(t)?Ot.parse(t):tn.test(t)?tn.parse(t):Ds.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ot.transform(t):tn.transform(t),getAnimatableNone:t=>{const e=be.parse(t);return e.alpha=0,be.transform(e)}},Bh=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function jh(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Ps))==null?void 0:e.length)||0)+(((n=t.match(Bh))==null?void 0:n.length)||0)>0}const La="number",Da="color",Uh="var",$h="var(",Oa="${}",Hh=/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 Ln(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Hh,c=>(be.test(c)?(i.color.push(o),s.push(Da),n.push(be.parse(c))):c.startsWith($h)?(i.var.push(o),s.push(Uh),n.push(c)):(i.number.push(o),s.push(La),n.push(parseFloat(c))),++o,Oa)).split(Oa);return{values:n,split:a,indexes:i,types:s}}function Na(t){return Ln(t).values}function Va(t){const{split:e,types:n}=Ln(t),i=e.length;return s=>{let o="";for(let r=0;r<i;r++)if(o+=e[r],s[r]!==void 0){const a=n[r];a===La?o+=Pn(s[r]):a===Da?o+=be.transform(s[r]):o+=s[r]}return o}}const Gh=t=>typeof t=="number"?0:be.test(t)?be.getAnimatableNone(t):t;function Wh(t){const e=Na(t);return Va(t)(e.map(Gh))}const Tt={test:jh,parse:Na,createTransformer:Va,getAnimatableNone:Wh};function Os(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function zh({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;s=Os(c,a,t+1/3),o=Os(c,a,t),r=Os(c,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function bi(t,e){return n=>n>0?e:t}const me=(t,e,n)=>t+(e-t)*n,Ns=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},qh=[Ds,Ot,tn],Kh=t=>qh.find(e=>e.test(t));function Fa(t){const e=Kh(t);if(!e)return!1;let n=e.parse(t);return e===tn&&(n=zh(n)),n}const Ba=(t,e)=>{const n=Fa(t),i=Fa(e);if(!n||!i)return bi(t,e);const s={...n};return o=>(s.red=Ns(n.red,i.red,o),s.green=Ns(n.green,i.green,o),s.blue=Ns(n.blue,i.blue,o),s.alpha=me(n.alpha,i.alpha,o),Ot.transform(s))},Vs=new Set(["none","hidden"]);function Xh(t,e){return Vs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Yh(t,e){return n=>me(t,e,n)}function Fs(t){return typeof t=="number"?Yh:typeof t=="string"?Rs(t)?bi:be.test(t)?Ba:Qh:Array.isArray(t)?ja:typeof t=="object"?be.test(t)?Ba:Jh:bi}function ja(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Fs(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function Jh(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Fs(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function Zh(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][i[o]],a=t.values[r]??0;n[s]=a,i[o]++}return n}const Qh=(t,e)=>{const n=Tt.createTransformer(e),i=Ln(t),s=Ln(e);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?Vs.has(t)&&!s.values.length||Vs.has(e)&&!i.values.length?Xh(t,e):En(ja(Zh(i,s),s.values),n):bi(t,e)};function Ua(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?me(t,e,n):Fs(t)(t,e)}const ef=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>de.update(e,n),stop:()=>Ct(e),now:()=>Ee.isProcessing?Ee.timestamp:Fe.now()}},$a=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},wi=2e4;function Bs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<wi;)e+=n,i=t.next(e);return e>=wi?1/0:e}function tf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Bs(i),wi);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:at(s)}}const nf=5;function Ha(t,e,n){const i=Math.max(e-nf,0);return ga(n-t(i),e-i)}const ge={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},js=.001;function sf({duration:t=ge.duration,bounce:e=ge.bounce,velocity:n=ge.velocity,mass:i=ge.mass}){let s,o,r=1-e;r=gt(ge.minDamping,ge.maxDamping,r),t=gt(ge.minDuration,ge.maxDuration,at(t)),r<1?(s=l=>{const d=l*r,u=d*t,h=d-n,g=Us(l,r),v=Math.exp(-u);return js-h/g*v},o=l=>{const u=l*r*t,h=u*n+n,g=Math.pow(r,2)*Math.pow(l,2)*t,v=Math.exp(-u),y=Us(Math.pow(l,2),r);return(-s(l)+js>0?-1:1)*((h-g)*v)/y}):(s=l=>{const d=Math.exp(-l*t),u=(l-n)*t+1;return-js+d*u},o=l=>{const d=Math.exp(-l*t),u=(n-l)*(t*t);return d*u});const a=5/t,c=of(s,o,a);if(t=ot(t),isNaN(c))return{stiffness:ge.stiffness,damping:ge.damping,duration:t};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:r*2*Math.sqrt(i*l),duration:t}}}const rf=12;function of(t,e,n){let i=n;for(let s=1;s<rf;s++)i=i-t(i)/e(i);return i}function Us(t,e){return t*Math.sqrt(1-e*e)}const af=["duration","bounce"],cf=["stiffness","damping","mass"];function Ga(t,e){return e.some(n=>t[n]!==void 0)}function lf(t){let e={velocity:ge.velocity,stiffness:ge.stiffness,damping:ge.damping,mass:ge.mass,isResolvedFromDuration:!1,...t};if(!Ga(t,cf)&&Ga(t,af))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*gt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ge.mass,stiffness:s,damping:o}}else{const n=sf(t);e={...e,...n,mass:ge.mass},e.isResolvedFromDuration=!0}return e}function xi(t=ge.visualDuration,e=ge.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:c,damping:l,mass:d,duration:u,velocity:h,isResolvedFromDuration:g}=lf({...n,velocity:-at(n.velocity||0)}),v=h||0,y=l/(2*Math.sqrt(c*d)),x=r-o,w=at(Math.sqrt(c/d)),S=Math.abs(x)<5;i||(i=S?ge.restSpeed.granular:ge.restSpeed.default),s||(s=S?ge.restDelta.granular:ge.restDelta.default);let k;if(y<1){const L=Us(w,y);k=O=>{const b=Math.exp(-y*w*O);return r-b*((v+y*w*x)/L*Math.sin(L*O)+x*Math.cos(L*O))}}else if(y===1)k=L=>r-Math.exp(-w*L)*(x+(v+w*x)*L);else{const L=w*Math.sqrt(y*y-1);k=O=>{const b=Math.exp(-y*w*O),C=Math.min(L*O,300);return r-b*((v+y*w*x)*Math.sinh(C)+L*x*Math.cosh(C))/L}}const A={calculatedDuration:g&&u||null,next:L=>{const O=k(L);if(g)a.done=L>=u;else{let b=L===0?v:0;y<1&&(b=L===0?ot(v):Ha(k,L,O));const C=Math.abs(b)<=i,f=Math.abs(r-O)<=s;a.done=C&&f}return a.value=a.done?r:O,a},toString:()=>{const L=Math.min(Bs(A),wi),O=$a(b=>A.next(L*b).value,L,30);return L+"ms "+O},toTransition:()=>{}};return A}xi.applyToOptions=t=>{const e=tf(t,100,xi);return t.ease=e.ease,t.duration=ot(e.duration),t.type="keyframes",t};function $s({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:c,restDelta:l=.5,restSpeed:d}){const u=t[0],h={done:!1,value:u},g=C=>a!==void 0&&C<a||c!==void 0&&C>c,v=C=>a===void 0?c:c===void 0||Math.abs(a-C)<Math.abs(c-C)?a:c;let y=n*e;const x=u+y,w=r===void 0?x:r(x);w!==x&&(y=w-u);const S=C=>-y*Math.exp(-C/i),k=C=>w+S(C),A=C=>{const f=S(C),m=k(C);h.done=Math.abs(f)<=l,h.value=h.done?w:m};let L,O;const b=C=>{g(h.value)&&(L=C,O=xi({keyframes:[h.value,v(h.value)],velocity:Ha(k,C,h.value),damping:s,stiffness:o,restDelta:l,restSpeed:d}))};return b(0),{calculatedDuration:null,next:C=>{let f=!1;return!O&&L===void 0&&(f=!0,A(C),b(C)),L!==void 0&&C>=L?O.next(C-L):(!f&&A(C),h)}}}function df(t,e,n){const i=[],s=n||vt.mix||Ua,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const c=Array.isArray(e)?e[r]||We:e;a=En(c,a)}i.push(a)}return i}function uf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Ss(o===e.length),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=df(e,i,s),c=a.length,l=d=>{if(r&&d<t[0])return e[0];let u=0;if(c>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const h=An(t[u],t[u+1],d);return a[u](h)};return n?d=>l(gt(t[0],t[o-1],d)):l}function hf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=An(0,e,i);t.push(me(n,1,s))}}function ff(t){const e=[0];return hf(e,t.length-1),e}function pf(t,e){return t.map(n=>n*e)}function mf(t,e){return t.map(()=>e||ka).splice(0,t.length-1)}function Dn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=kh(i)?i.map(Ea):Ea(i),o={done:!1,value:e[0]},r=pf(n&&n.length===e.length?n:ff(e),t),a=uf(r,e,{ease:Array.isArray(s)?s:mf(e,s)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const gf=t=>t!==null;function Hs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(gf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const vf={decay:$s,inertia:$s,tween:Dn,keyframes:Dn,spring:xi};function Wa(t){typeof t.type=="string"&&(t.type=vf[t.type])}class Gs{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const _f=t=>t/100;class Ws extends Gs{constructor(e){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!==Fe.now()&&this.tick(Fe.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Wa(e);const{type:n=Dn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const c=n||Dn;c!==Dn&&typeof a[0]!="number"&&(this.mixKeyframes=En(_f,Ua(a[0],a[1])),a=[0,100]);const l=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-r})),l.calculatedDuration===null&&(l.calculatedDuration=Bs(l));const{calculatedDuration:d}=l;this.calculatedDuration=d,this.resolvedDuration=d+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=l}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:d,repeat:u,repeatType:h,repeatDelay:g,type:v,onUpdate:y,finalKeyframe:x}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const w=this.currentTime-l*(this.playbackSpeed>=0?1:-1),S=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,A=i;if(u){const C=Math.min(this.currentTime,s)/a;let f=Math.floor(C),m=C%1;!m&&C>=1&&(m=1),m===1&&f--,f=Math.min(f,u+1),!!(f%2)&&(h==="reverse"?(m=1-m,g&&(m-=g/a)):h==="mirror"&&(A=r)),k=gt(0,1,m)*a}const L=S?{done:!1,value:d[0]}:A.next(k);o&&(L.value=o(L.value));let{done:O}=L;!S&&c!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const b=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return b&&v!==$s&&(L.value=Hs(d,this.options,x,this.speed)),y&&y(L.value),b&&this.finish(),L}then(e,n){return this.finished.then(e,n)}get duration(){return at(this.calculatedDuration)}get time(){return at(this.currentTime)}set time(e){var n;e=ot(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Fe.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=at(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=ef,startTime:n}=this.options;this.driver||(this.driver=e(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(Fe.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function yf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Nt=t=>t*180/Math.PI,zs=t=>{const e=Nt(Math.atan2(t[1],t[0]));return qs(e)},bf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:zs,rotateZ:zs,skewX:t=>Nt(Math.atan(t[1])),skewY:t=>Nt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},qs=t=>(t=t%360,t<0&&(t+=360),t),za=zs,qa=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ka=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),wf={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:qa,scaleY:Ka,scale:t=>(qa(t)+Ka(t))/2,rotateX:t=>qs(Nt(Math.atan2(t[6],t[5]))),rotateY:t=>qs(Nt(Math.atan2(-t[2],t[0]))),rotateZ:za,rotate:za,skewX:t=>Nt(Math.atan(t[4])),skewY:t=>Nt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Ks(t){return t.includes("scale")?1:0}function Xs(t,e){if(!t||t==="none")return Ks(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=wf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=bf,s=a}if(!s)return Ks(e);const o=i[e],r=s[1].split(",").map(Sf);return typeof o=="function"?o(r):r[o]}const xf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Xs(n,e)};function Sf(t){return parseFloat(t.trim())}const nn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],sn=new Set(nn),Xa=t=>t===en||t===G,Cf=new Set(["x","y","z"]),kf=nn.filter(t=>!Cf.has(t));function Tf(t){const e=[];return kf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Vt={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Xs(e,"x"),y:(t,{transform:e})=>Xs(e,"y")};Vt.translateX=Vt.x,Vt.translateY=Vt.y;const Ft=new Set;let Ys=!1,Js=!1,Zs=!1;function Ya(){if(Js){const t=Array.from(Ft).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Tf(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([o,r])=>{var a;(a=i.getValue(o))==null||a.set(r)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}Js=!1,Ys=!1,Ft.forEach(t=>t.complete(Zs)),Ft.clear()}function Ja(){Ft.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Js=!0)})}function Ef(){Zs=!0,Ja(),Ya(),Zs=!1}class Qs{constructor(e,n,i,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Ft.add(this),Ys||(Ys=!0,de.read(Ja),de.resolveKeyframes(Ya))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(i&&n){const a=i.readValue(n,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}yf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Ft.delete(this)}cancel(){this.state==="scheduled"&&(Ft.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Af=t=>t.startsWith("--");function If(t,e,n){Af(e)?t.style.setProperty(e,n):t.style[e]=n}const Rf=Cs(()=>window.ScrollTimeline!==void 0),Pf={};function Mf(t,e){const n=Cs(t);return()=>Pf[e]??n()}const Za=Mf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),On=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Qa={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:On([0,.65,.55,1]),circOut:On([.55,0,1,.45]),backIn:On([.31,.01,.66,-.59]),backOut:On([.33,1.53,.69,.99])};function ec(t,e){if(t)return typeof t=="function"?Za()?$a(t,e):"ease-out":Ta(t)?On(t):Array.isArray(t)?t.map(n=>ec(n,e)||Qa.easeOut):Qa[t]}function Lf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:c}={},l=void 0){const d={[e]:n};c&&(d.offset=c);const u=ec(a,s);Array.isArray(u)&&(d.easing=u);const h={delay:i,duration:s,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return l&&(h.pseudoElement=l),t.animate(d,h)}function tc(t){return typeof t=="function"&&"applyToOptions"in t}function Df({type:t,...e}){return tc(t)&&Za()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Of extends Gs{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:c}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Ss(typeof e.type!="string");const l=Df(e);this.animation=Lf(n,i,s,l,o),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Hs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):If(n,i,d),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return at(Number(e))}get time(){return at(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=ot(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Rf()?(this.animation.timeline=e,We):n(this)}}const nc={anticipate:xa,backInOut:wa,circInOut:Ca};function Nf(t){return t in nc}function Vf(t){typeof t.ease=="string"&&Nf(t.ease)&&(t.ease=nc[t.ease])}const ic=10;class Ff extends Of{constructor(e){Vf(e),Wa(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:o,...r}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new Ws({...r,autoplay:!1}),c=ot(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-ic).value,a.sample(c).value,ic),a.stop()}}const sc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Tt.test(t)||t==="0")&&!t.startsWith("url("));function Bf(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function jf(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=sc(s,e),a=sc(o,e);return!r||!a?!1:Bf(t)||(n==="spring"||tc(n))&&i}function er(t){return pa(t)&&"offsetHeight"in t}const Uf=new Set(["opacity","clipPath","filter","transform"]),$f=Cs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Hf(t){var l;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!er((l=e==null?void 0:e.owner)==null?void 0:l.current))return!1;const{onUpdate:a,transformTemplate:c}=e.owner.getProps();return $f()&&n&&Uf.has(n)&&(n!=="transform"||!c)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const Gf=40;class Wf extends Gs{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:c,motionValue:l,element:d,...u}){var v;super(),this.stop=()=>{var y,x;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(x=this.keyframeResolver)==null||x.cancel()},this.createdAt=Fe.now();const h={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:c,motionValue:l,element:d,...u},g=(d==null?void 0:d.KeyframeResolver)||Qs;this.keyframeResolver=new g(a,(y,x,w)=>this.onKeyframesResolved(y,x,h,!w),c,l,d),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:c,isHandoff:l,onUpdate:d}=i;this.resolvedAt=Fe.now(),jf(e,o,r,a)||((vt.instantAnimations||!c)&&(d==null||d(Hs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Gf?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!l&&Hf(h)?new Ff({...h,element:h.motionValue.owner.current}):new Ws(h);g.finished.then(()=>this.notifyFinished()).catch(We),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(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Ef()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const zf=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function qf(t){const e=zf.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function rc(t,e,n=1){const[i,s]=qf(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return fa(r)?parseFloat(r):r}return Rs(s)?rc(s,e,n+1):s}function tr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const oc=new Set(["width","height","top","left","right","bottom",...nn]),Kf={test:t=>t==="auto",parse:t=>t},ac=t=>e=>e.test(t),cc=[en,G,ct,kt,Fh,Vh,Kf],lc=t=>cc.find(ac(t));function Xf(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ma(t):!0}const Yf=new Set(["brightness","contrast","saturate","opacity"]);function Jf(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Ps)||[];if(!i)return t;const s=n.replace(i,"");let o=Yf.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const Zf=/\b([a-z-]*)\(.*?\)/gu,nr={...Tt,getAnimatableNone:t=>{const e=t.match(Zf);return e?e.map(Jf).join(" "):t}},dc={...en,transform:Math.round},ir={borderWidth:G,borderTopWidth:G,borderRightWidth:G,borderBottomWidth:G,borderLeftWidth:G,borderRadius:G,radius:G,borderTopLeftRadius:G,borderTopRightRadius:G,borderBottomRightRadius:G,borderBottomLeftRadius:G,width:G,maxWidth:G,height:G,maxHeight:G,top:G,right:G,bottom:G,left:G,padding:G,paddingTop:G,paddingRight:G,paddingBottom:G,paddingLeft:G,margin:G,marginTop:G,marginRight:G,marginBottom:G,marginLeft:G,backgroundPositionX:G,backgroundPositionY:G,...{rotate:kt,rotateX:kt,rotateY:kt,rotateZ:kt,scale:yi,scaleX:yi,scaleY:yi,scaleZ:yi,skew:kt,skewX:kt,skewY:kt,distance:G,translateX:G,translateY:G,translateZ:G,x:G,y:G,z:G,perspective:G,transformPerspective:G,opacity:Rn,originX:Ma,originY:Ma,originZ:G},zIndex:dc,fillOpacity:Rn,strokeOpacity:Rn,numOctaves:dc},Qf={...ir,color:be,backgroundColor:be,outlineColor:be,fill:be,stroke:be,borderColor:be,borderTopColor:be,borderRightColor:be,borderBottomColor:be,borderLeftColor:be,filter:nr,WebkitFilter:nr},uc=t=>Qf[t];function hc(t,e){let n=uc(t);return n!==nr&&(n=Tt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const ep=new Set(["auto","none","0"]);function tp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!ep.has(o)&&Ln(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=hc(n,s)}class np extends Qs{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<e.length;c++){let l=e[c];if(typeof l=="string"&&(l=l.trim(),Rs(l))){const d=rc(l,n.current);d!==void 0&&(e[c]=d),c===e.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!oc.has(i)||e.length!==2)return;const[s,o]=e,r=lc(s),a=lc(o);if(r!==a)if(Xa(r)&&Xa(a))for(let c=0;c<e.length;c++){const l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}else Vt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Xf(e[s]))&&i.push(s);i.length&&tp(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Vt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const o=i.length-1,r=i[o];i[o]=Vt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,l])=>{e.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function ip(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const s=(n==null?void 0:n[t])??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const fc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,pc=30,sp=t=>!isNaN(parseFloat(t));class rp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Fe.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 c of this.dependents)c.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Fe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=sp(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new ks);const i=this.events[e].add(n);return e==="change"?()=>{i(),de.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e,n=!0){!n||!this.passiveEffect?this.updateAndNotify(e,n):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Fe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>pc)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,pc);return ga(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(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 e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function rn(t,e){return new rp(t,e)}const{schedule:sr}=Ia(queueMicrotask,!1),Ze={x:!1,y:!1};function mc(){return Ze.x||Ze.y}function op(t){return t==="x"||t==="y"?Ze[t]?null:(Ze[t]=!0,()=>{Ze[t]=!1}):Ze.x||Ze.y?null:(Ze.x=Ze.y=!0,()=>{Ze.x=Ze.y=!1})}function gc(t,e){const n=ip(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function vc(t){return!(t.pointerType==="touch"||mc())}function ap(t,e,n={}){const[i,s,o]=gc(t,n),r=a=>{if(!vc(a))return;const{target:c}=a,l=e(c,a);if(typeof l!="function"||!c)return;const d=u=>{vc(u)&&(l(u),c.removeEventListener("pointerleave",d))};c.addEventListener("pointerleave",d,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const _c=(t,e)=>e?t===e?!0:_c(t,e.parentElement):!1,rr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,cp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function lp(t){return cp.has(t.tagName)||t.tabIndex!==-1}const Si=new WeakSet;function yc(t){return e=>{e.key==="Enter"&&t(e)}}function or(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const dp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=yc(()=>{if(Si.has(n))return;or(n,"down");const s=yc(()=>{or(n,"up")}),o=()=>or(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function bc(t){return rr(t)&&!mc()}function up(t,e,n={}){const[i,s,o]=gc(t,n),r=a=>{const c=a.currentTarget;if(!bc(a))return;Si.add(c);const l=e(c,a),d=(g,v)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",h),Si.has(c)&&Si.delete(c),bc(g)&&typeof l=="function"&&l(g,{success:v})},u=g=>{d(g,c===window||c===document||n.useGlobalTarget||_c(c,g.target))},h=g=>{d(g,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",h,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),er(a)&&(a.addEventListener("focus",l=>dp(l,s)),!lp(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function wc(t){return pa(t)&&"ownerSVGElement"in t}function hp(t){return wc(t)&&t.tagName==="svg"}const Re=t=>!!(t&&t.getVelocity),fp=[...cc,be,Tt],pp=t=>fp.find(ac(t)),Nn=mt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class mp extends Je{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=er(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 gp({children:t,isPresent:e,anchorX:n,root:i}){const s=os(),o=Te(null),r=Te({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Se(Nn);return zo(()=>{const{width:c,height:l,top:d,left:u,right:h}=r.current;if(e||!o.current||!c||!l)return;const g=n==="left"?`left: ${u}`:`right: ${h}`;o.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const y=i??document.head;return y.appendChild(v),v.sheet&&v.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${c}px !important;
5
- height: ${d}px !important;
6
- ${v}px !important;
7
- top: ${f}px !important;
5
+ height: ${l}px !important;
6
+ ${g}px !important;
7
+ top: ${d}px !important;
8
8
  }
9
- `),()=>{C.removeChild(_),C.contains(_)&&C.removeChild(_)}},[e]),M(Ap,{isPresent:e,childRef:o,sizeRef:r,children:Ah(t,{ref:o})})}const Pp=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:c})=>{const d=pi(Mp),f=ds();let p=!0,m=rt(()=>(p=!1,{id:f,initial:e,isPresent:n,custom:s,onExitComplete:v=>{d.set(v,!0);for(const _ of d.values())if(!_)return;i&&i()},register:v=>(d.set(v,!1),()=>d.delete(v))}),[n,d,i]);return o&&p&&(m={...m}),rt(()=>{d.forEach((v,_)=>d.set(_,!1))},[n]),Ve(()=>{!n&&!d.size&&i&&i()},[n]),r==="popLayout"&&(t=M(Rp,{isPresent:n,anchorX:a,root:c,children:t})),M(mi.Provider,{value:m,children:t})};function Mp(){return new Map}function Tc(t=!0){const e=xe(mi);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=ds();Ve(()=>{if(t)return s(o)},[t]);const r=St(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Si=t=>t.key||"";function Ec(t){const e=[];return yh.forEach(t,n=>{da(n)&&e.push(n)}),e}const Lp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:c})=>{const[d,f]=Tc(r),p=rt(()=>Ec(t),[t]),m=r&&!d?[]:p.map(Si),v=ke(!0),_=ke(p),C=pi(()=>new Map),[S,w]=Ce(p),[T,I]=Ce(p);ga(()=>{v.current=!1,_.current=p;for(let D=0;D<T.length;D++){const b=Si(T[D]);m.includes(b)?C.delete(b):C.get(b)!==!0&&C.set(b,!1)}},[T,m.length,m.join("-")]);const R=[];if(p!==S){let D=[...p];for(let b=0;b<T.length;b++){const k=T[b],l=Si(k);m.includes(l)||(D.splice(b,0,k),R.push(k))}return o==="wait"&&R.length&&(D=R),I(Ec(D)),w(p),null}const{forceRender:L}=xe(Ss);return M(it,{children:T.map(D=>{const b=Si(D),k=r&&!d?!1:p===T||m.includes(b),l=()=>{if(C.has(b))C.set(b,!0);else return;let u=!0;C.forEach(h=>{h||(u=!1)}),u&&(L==null||L(),I(_.current),r&&(f==null||f()),i&&i())};return M(Pp,{isPresent:k,initial:!v.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:c,onExitComplete:k?void 0:l,anchorX:a,children:D},b)})})},Ic=pt({strict:!1}),Ac={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"]},on={};for(const t in Ac)on[t]={isEnabled:e=>Ac[t].some(n=>!!e[n])};function Dp(t){for(const e in t)on[e]={...on[e],...t[e]}}const Op=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 Ci(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Op.has(t)}let Rc=t=>!Ci(t);function Pc(t){typeof t=="function"&&(Rc=e=>e.startsWith("on")?!Ci(e):t(e))}try{Pc(require("@emotion/is-prop-valid").default)}catch{}function Np(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Rc(s)||n===!0&&Ci(s)||!e&&!Ci(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Vp({children:t,isValidProp:e,...n}){e&&Pc(e),n={...xe(On),...n},n.isStatic=pi(()=>n.isStatic);const i=rt(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return M(On.Provider,{value:i,children:t})}function Fp(t){if(typeof Proxy>"u")return t;const e=new Map,n=(...i)=>t(...i);return new Proxy(n,{get:(i,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const ki=pt({});function Ti(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Nn(t){return typeof t=="string"||Array.isArray(t)}const ur=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],hr=["initial",...ur];function Ei(t){return Ti(t.animate)||hr.some(e=>Nn(t[e]))}function Mc(t){return!!(Ei(t)||t.variants)}function Bp(t,e){if(Ei(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Nn(n)?n:void 0,animate:Nn(i)?i:void 0}}return t.inherit!==!1?e:{}}function jp(t){const{initial:e,animate:n}=Bp(t,xe(ki));return rt(()=>({initial:e,animate:n}),[Lc(e),Lc(n)])}function Lc(t){return Array.isArray(t)?t.join(" "):t}const Up=Symbol.for("motionComponentSymbol");function an(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function $p(t,e,n){return St(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):an(n)&&(n.current=i))},[e])}const fr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Dc="data-"+fr("framerAppearId"),Oc=pt({});function Gp(t,e,n,i,s){var C,S;const{visualElement:o}=xe(ki),r=xe(Ic),a=xe(mi),c=xe(On).reducedMotion,d=ke(null);i=i||r.renderer,!d.current&&i&&(d.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const f=d.current,p=xe(Oc);f&&!f.projection&&s&&(f.type==="html"||f.type==="svg")&&Hp(d.current,n,s,p);const m=ke(!1);Yo(()=>{f&&m.current&&f.update(n,a)});const v=n[Dc],_=ke(!!v&&!((C=window.MotionHandoffIsComplete)!=null&&C.call(window,v))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,v)));return ga(()=>{f&&(m.current=!0,window.MotionIsMounted=!0,f.updateFeatures(),cr.render(f.render),_.current&&f.animationState&&f.animationState.animateChanges())}),Ve(()=>{f&&(!_.current&&f.animationState&&f.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,v)}),_.current=!1))}),f}function Hp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:c,layoutRoot:d,layoutCrossfade:f}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Nc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&an(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:f,layoutScroll:c,layoutRoot:d})}function Nc(t){if(t)return t.options.allowProjection!==!1?t.projection:Nc(t.parent)}function Wp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&Dp(t);function o(a,c){let d;const f={...xe(On),...a,layoutId:zp(a)},{isStatic:p}=f,m=jp(a),v=i(a,p);if(!p&&Cs){qp();const _=Kp(f);d=_.MeasureLayout,m.visualElement=Gp(s,v,f,e,_.ProjectionNode)}return M(ki.Provider,{value:m,children:[d&&m.visualElement?M(d,{visualElement:m.visualElement,...f}):null,n(s,a,$p(v,m.visualElement,c),v,p,m.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=vh(o);return r[Up]=s,r}function zp({layoutId:t}){const e=xe(Ss).id;return e&&t!==void 0?e+"-"+t:t}function qp(t,e){xe(Ic).strict}function Kp(t){const{drag:e,layout:n}=on;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e!=null&&e.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const Vn={};function Xp(t){for(const e in t)Vn[e]=t[e],Ls(e)&&(Vn[e].isCSSVariable=!0)}function Vc(t,{layout:e,layoutId:n}){return sn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Vn[t]||t==="opacity")}const Yp={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Zp=nn.length;function Jp(t,e,n){let i="",s=!0;for(let o=0;o<Zp;o++){const r=nn[o],a=t[r];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(r.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const d=vc(a,ar[r]);if(!c){s=!1;const f=Yp[r]||r;i+=`${f}(${d}) `}n&&(e[r]=d)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function pr(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const c in e){const d=e[c];if(sn.has(c)){r=!0;continue}else if(Ls(c)){s[c]=d;continue}else{const f=vc(d,ar[c]);c.startsWith("origin")?(a=!0,o[c]=f):i[c]=f}}if(e.transform||(r||n?i.transform=Jp(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:d="50%",originZ:f=0}=o;i.transformOrigin=`${c} ${d} ${f}`}}const mr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Fc(t,e,n){for(const i in e)!Ae(e[i])&&!Vc(i,n)&&(t[i]=e[i])}function Qp({transformTemplate:t},e){return rt(()=>{const n=mr();return pr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function em(t,e){const n=t.style||{},i={};return Fc(i,n,t),Object.assign(i,Qp(t,e)),i}function tm(t,e){const n={},i=em(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const nm={offset:"stroke-dashoffset",array:"stroke-dasharray"},im={offset:"strokeDashoffset",array:"strokeDasharray"};function sm(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?nm:im;t[o.offset]=K.transform(-i);const r=K.transform(e),a=K.transform(n);t[o.array]=`${r} ${a}`}function Bc(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},c,d,f){if(pr(t,a,d),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:m}=t;p.transform&&(m.transform=p.transform,delete p.transform),(m.transform||p.transformOrigin)&&(m.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),m.transform&&(m.transformBox=(f==null?void 0:f.transformBox)??"fill-box",delete p.transformBox),e!==void 0&&(p.x=e),n!==void 0&&(p.y=n),i!==void 0&&(p.scale=i),s!==void 0&&sm(p,s,o,r,!1)}const jc=()=>({...mr(),attrs:{}}),Uc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function rm(t,e,n,i){const s=rt(()=>{const o=jc();return Bc(o,e,Uc(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Fc(o,t.style,t),s.style={...o,...s.style}}return s}const om=["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 gr(t){return typeof t!="string"||t.includes("-")?!1:!!(om.indexOf(t)>-1||/[A-Z]/u.test(t))}function am(t=!1){return(n,i,s,{latestValues:o},r)=>{const c=(gr(n)?rm:tm)(i,o,r,n),d=Np(i,typeof n=="string",t),f=n!==it?{...d,...c,ref:s}:{},{children:p}=i,m=rt(()=>Ae(p)?p.get():p,[p]);return He(n,{...f,children:m})}}function $c(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function vr(t,e,n,i){if(typeof e=="function"){const[s,o]=$c(i);e=e(n!==void 0?n:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=$c(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function Ii(t){return Ae(t)?t.get():t}function cm({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:lm(n,i,s,t),renderState:e()}}const Gc=t=>(e,n)=>{const i=xe(ki),s=xe(mi),o=()=>cm(t,e,i,s);return n?o():pi(o)};function lm(t,e,n,i){const s={},o=i(t,{});for(const m in o)s[m]=Ii(o[m]);let{initial:r,animate:a}=t;const c=Ei(t),d=Mc(t);e&&d&&!c&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let f=n?n.initial===!1:!1;f=f||r===!1;const p=f?a:r;if(p&&typeof p!="boolean"&&!Ti(p)){const m=Array.isArray(p)?p:[p];for(let v=0;v<m.length;v++){const _=vr(t,m[v]);if(_){const{transitionEnd:C,transition:S,...w}=_;for(const T in w){let I=w[T];if(Array.isArray(I)){const R=f?I.length-1:0;I=I[R]}I!==null&&(s[T]=I)}for(const T in C)s[T]=C[T]}}}return s}function yr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Ae(i[r])||e.style&&Ae(e.style[r])||Vc(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const dm={useVisualState:Gc({scrapeMotionValuesFromProps:yr,createRenderState:mr})};function Hc(t,e,n){const i=yr(t,e,n);for(const s in t)if(Ae(t[s])||Ae(e[s])){const o=nn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const um={useVisualState:Gc({scrapeMotionValuesFromProps:Hc,createRenderState:jc})};function hm(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...gr(i)?um:dm,preloadedFeatures:t,useRender:am(s),createVisualElement:e,Component:i};return Wp(r)}}function Fn(t,e,n){const i=t.getProps();return vr(i,e,n!==void 0?n:i.custom,t)}const _r=t=>Array.isArray(t);function fm(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,rn(n))}function pm(t){return _r(t)?t[t.length-1]||0:t}function mm(t,e){const n=Fn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=pm(o[r]);fm(t,r,a)}}function gm(t){return!!(Ae(t)&&t.add)}function br(t,e){const n=t.getValue("willChange");if(gm(n))return n.add(e);if(!n&&gt.WillChange){const i=new gt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Wc(t){return t.props[Dc]}const vm=t=>t!==null;function ym(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(vm),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const _m={type:"spring",stiffness:500,damping:25,restSpeed:10},bm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),wm={type:"keyframes",duration:.8},xm={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Sm=(t,{keyframes:e})=>e.length>2?wm:sn.has(t)?t.startsWith("scale")?bm(e[1]):_m:xm;function Cm({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:c,elapsed:d,...f}){return!!Object.keys(f).length}const wr=(t,e,n,i={},s,o)=>r=>{const a=rr(i,t)||{},c=a.delay||i.delay||0;let{elapsed:d=0}=i;d=d-ot(c);const f={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-d,onUpdate:m=>{e.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Cm(a)||Object.assign(f,Sm(t,f)),f.duration&&(f.duration=ot(f.duration)),f.repeatDelay&&(f.repeatDelay=ot(f.repeatDelay)),f.from!==void 0&&(f.keyframes[0]=f.from);let p=!1;if((f.type===!1||f.duration===0&&!f.repeatDelay)&&(f.duration=0,f.delay===0&&(p=!0)),(gt.instantAnimations||gt.skipAnimations)&&(p=!0,f.duration=0,f.delay=0),f.allowFlatten=!a.type&&!a.ease,p&&!o&&e.get()!==void 0){const m=ym(f.keyframes,a);if(m!==void 0){de.update(()=>{f.onUpdate(m),f.onComplete()});return}}return a.isSync?new Xs(f):new rp(f)};function km({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function zc(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const c=[],d=s&&t.animationState&&t.animationState.getState()[s];for(const f in a){const p=t.getValue(f,t.latestValues[f]??null),m=a[f];if(m===void 0||d&&km(d,f))continue;const v={delay:n,...rr(o||{},f)},_=p.get();if(_!==void 0&&!p.isAnimating&&!Array.isArray(m)&&m===_&&!v.velocity)continue;let C=!1;if(window.MotionHandoffAnimation){const w=Wc(t);if(w){const T=window.MotionHandoffAnimation(w,f,de);T!==null&&(v.startTime=T,C=!0)}}br(t,f),p.start(wr(f,p,m,t.shouldReduceMotion&&dc.has(f)?{type:!1}:v,t,C));const S=p.animation;S&&c.push(S)}return r&&Promise.all(c).then(()=>{de.update(()=>{r&&mm(t,r)})}),c}function xr(t,e,n={}){var c;const i=Fn(t,e,n.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(zc(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(d=0)=>{const{delayChildren:f=0,staggerChildren:p,staggerDirection:m}=s;return Tm(t,e,d,f,p,m,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[d,f]=a==="beforeChildren"?[o,r]:[r,o];return d().then(()=>f())}else return Promise.all([o(),r(n.delay)])}function Tm(t,e,n=0,i=0,s=0,o=1,r){const a=[],c=t.variantChildren.size,d=(c-1)*s,f=typeof i=="function",p=f?m=>i(m,c):o===1?(m=0)=>m*s:(m=0)=>d-m*s;return Array.from(t.variantChildren).sort(Em).forEach((m,v)=>{m.notify("AnimationStart",e),a.push(xr(m,e,{...r,delay:n+(f?0:i)+p(v)}).then(()=>m.notify("AnimationComplete",e)))}),Promise.all(a)}function Em(t,e){return t.sortNodePosition(e)}function Im(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>xr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=xr(t,e,n);else{const s=typeof e=="function"?Fn(t,e,n.custom):e;i=Promise.all(zc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function qc(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const Am=hr.length;function Kc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Kc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Am;n++){const i=hr[n],s=t.props[i];(Nn(s)||s===!1)&&(e[i]=s)}return e}const Rm=[...ur].reverse(),Pm=ur.length;function Mm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Im(t,n,i)))}function Lm(t){let e=Mm(t),n=Xc(),i=!0;const s=c=>(d,f)=>{var m;const p=Fn(t,f,c==="exit"?(m=t.presenceContext)==null?void 0:m.custom:void 0);if(p){const{transition:v,transitionEnd:_,...C}=p;d={...d,...C,..._}}return d};function o(c){e=c(t)}function r(c){const{props:d}=t,f=Kc(t.parent)||{},p=[],m=new Set;let v={},_=1/0;for(let S=0;S<Pm;S++){const w=Rm[S],T=n[w],I=d[w]!==void 0?d[w]:f[w],R=Nn(I),L=w===c?T.isActive:null;L===!1&&(_=S);let D=I===f[w]&&I!==d[w]&&R;if(D&&i&&t.manuallyAnimateOnMount&&(D=!1),T.protectedKeys={...v},!T.isActive&&L===null||!I&&!T.prevProp||Ti(I)||typeof I=="boolean")continue;const b=Dm(T.prevProp,I);let k=b||w===c&&T.isActive&&!D&&R||S>_&&R,l=!1;const u=Array.isArray(I)?I:[I];let h=u.reduce(s(w),{});L===!1&&(h={});const{prevResolvedValues:g={}}=T,y={...g,...h},E=P=>{k=!0,m.has(P)&&(l=!0,m.delete(P)),T.needsAnimating[P]=!0;const V=t.getValue(P);V&&(V.liveStyle=!1)};for(const P in y){const V=h[P],H=g[P];if(v.hasOwnProperty(P))continue;let N=!1;_r(V)&&_r(H)?N=!qc(V,H):N=V!==H,N?V!=null?E(P):m.add(P):V!==void 0&&m.has(P)?E(P):T.protectedKeys[P]=!0}T.prevProp=I,T.prevResolvedValues=h,T.isActive&&(v={...v,...h}),i&&t.blockInitialAnimation&&(k=!1),k&&(!(D&&b)||l)&&p.push(...u.map(P=>({animation:P,options:{type:w}})))}if(m.size){const S={};if(typeof d.initial!="boolean"){const w=Fn(t,Array.isArray(d.initial)?d.initial[0]:d.initial);w&&w.transition&&(S.transition=w.transition)}m.forEach(w=>{const T=t.getBaseTarget(w),I=t.getValue(w);I&&(I.liveStyle=!0),S[w]=T??null}),p.push({animation:S})}let C=!!p.length;return i&&(d.initial===!1||d.initial===d.animate)&&!t.manuallyAnimateOnMount&&(C=!1),i=!1,C?e(p):Promise.resolve()}function a(c,d){var p;if(n[c].isActive===d)return Promise.resolve();(p=t.variantChildren)==null||p.forEach(m=>{var v;return(v=m.animationState)==null?void 0:v.setActive(c,d)}),n[c].isActive=d;const f=r(c);for(const m in n)n[m].protectedKeys={};return f}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Xc(),i=!0}}}function Dm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!qc(e,t):!1}function Bt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Xc(){return{animate:Bt(!0),whileInView:Bt(),whileHover:Bt(),whileTap:Bt(),whileDrag:Bt(),whileFocus:Bt(),exit:Bt()}}class Et{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Om extends Et{constructor(e){super(e),e.animationState||(e.animationState=Lm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ti(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Nm=0;class Vm extends Et{constructor(){super(...arguments),this.id=Nm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Fm={animation:{Feature:Om},exit:{Feature:Vm}};function Bn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function jn(t){return{point:{x:t.pageX,y:t.pageY}}}const Bm=t=>e=>lr(e)&&t(e,jn(e));function Un(t,e,n,i){return Bn(t,e,Bm(n),i)}function Yc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function jm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Um(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const Zc=1e-4,$m=1-Zc,Gm=1+Zc,Jc=.01,Hm=0-Jc,Wm=0+Jc;function Le(t){return t.max-t.min}function zm(t,e,n){return Math.abs(t-e)<=n}function Qc(t,e,n,i=.5){t.origin=i,t.originPoint=me(e.min,e.max,t.origin),t.scale=Le(n)/Le(e),t.translate=me(n.min,n.max,t.origin)-t.originPoint,(t.scale>=$m&&t.scale<=Gm||isNaN(t.scale))&&(t.scale=1),(t.translate>=Hm&&t.translate<=Wm||isNaN(t.translate))&&(t.translate=0)}function $n(t,e,n,i){Qc(t.x,e.x,n.x,i?i.originX:void 0),Qc(t.y,e.y,n.y,i?i.originY:void 0)}function el(t,e,n){t.min=n.min+e.min,t.max=t.min+Le(e)}function qm(t,e,n){el(t.x,e.x,n.x),el(t.y,e.y,n.y)}function tl(t,e,n){t.min=e.min-n.min,t.max=t.min+Le(e)}function Gn(t,e,n){tl(t.x,e.x,n.x),tl(t.y,e.y,n.y)}const nl=()=>({translate:0,scale:1,origin:0,originPoint:0}),cn=()=>({x:nl(),y:nl()}),il=()=>({min:0,max:0}),_e=()=>({x:il(),y:il()});function ze(t){return[t("x"),t("y")]}function Sr(t){return t===void 0||t===1}function Cr({scale:t,scaleX:e,scaleY:n}){return!Sr(t)||!Sr(e)||!Sr(n)}function jt(t){return Cr(t)||sl(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function sl(t){return rl(t.x)||rl(t.y)}function rl(t){return t&&t!=="0%"}function Ai(t,e,n){const i=t-n,s=e*i;return n+s}function ol(t,e,n,i,s){return s!==void 0&&(t=Ai(t,s,i)),Ai(t,n,i)+e}function kr(t,e=0,n=1,i,s){t.min=ol(t.min,e,n,i,s),t.max=ol(t.max,e,n,i,s)}function al(t,{x:e,y:n}){kr(t.x,e.translate,e.scale,e.originPoint),kr(t.y,n.translate,n.scale,n.originPoint)}const cl=.999999999999,ll=1.0000000000001;function Km(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&dn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,al(t,r)),i&&jt(o.latestValues)&&dn(t,o.latestValues))}e.x<ll&&e.x>cl&&(e.x=1),e.y<ll&&e.y>cl&&(e.y=1)}function ln(t,e){t.min=t.min+e,t.max=t.max+e}function dl(t,e,n,i,s=.5){const o=me(t.min,t.max,s);kr(t,e,n,o,i)}function dn(t,e){dl(t.x,e.x,e.scaleX,e.scale,e.originX),dl(t.y,e.y,e.scaleY,e.scale,e.originY)}function ul(t,e){return Yc(Um(t.getBoundingClientRect(),e))}function Xm(t,e,n){const i=ul(t,n),{scroll:s}=e;return s&&(ln(i.x,s.offset.x),ln(i.y,s.offset.y)),i}const hl=({current:t})=>t?t.ownerDocument.defaultView:null,fl=(t,e)=>Math.abs(t-e);function Ym(t,e){const n=fl(t.x,e.x),i=fl(t.y,e.y);return Math.sqrt(n**2+i**2)}class pl{constructor(e,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 m=Er(this.lastMoveEventInfo,this.history),v=this.startEvent!==null,_=Ym(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!v&&!_)return;const{point:C}=m,{timestamp:S}=Te;this.history.push({...C,timestamp:S});const{onStart:w,onMove:T}=this.handlers;v||(w&&w(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,m)},this.handlePointerMove=(m,v)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Tr(v,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,v)=>{this.end();const{onEnd:_,onSessionEnd:C,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Er(m.type==="pointercancel"?this.lastMoveEventInfo:Tr(v,this.transformPagePoint),this.history);this.startEvent&&_&&_(m,w),C&&C(m,w)},!lr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=jn(e),c=Tr(a,this.transformPagePoint),{point:d}=c,{timestamp:f}=Te;this.history=[{...d,timestamp:f}];const{onSessionStart:p}=n;p&&p(e,Er(c,this.history)),this.removeListeners=Tn(Un(this.contextWindow,"pointermove",this.handlePointerMove),Un(this.contextWindow,"pointerup",this.handlePointerUp),Un(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Ct(this.updatePoint)}}function Tr(t,e){return e?{point:e(t.point)}:t}function ml(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Er({point:t},e){return{point:t,delta:ml(t,gl(e)),offset:ml(t,Zm(e)),velocity:Jm(e,.1)}}function Zm(t){return t[0]}function gl(t){return t[t.length-1]}function Jm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=gl(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>ot(e)));)n--;if(!i)return{x:0,y:0};const o=at(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 Qm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?me(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?me(n,t,i.max):Math.min(t,n)),t}function vl(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function eg(t,{top:e,left:n,bottom:i,right:s}){return{x:vl(t.x,n,s),y:vl(t.y,e,i)}}function yl(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function tg(t,e){return{x:yl(t.x,e.x),y:yl(t.y,e.y)}}function ng(t,e){let n=.5;const i=Le(t),s=Le(e);return s>i?n=En(e.min,e.max-i,t.min):i>s&&(n=En(t.min,t.max-s,e.min)),mt(0,1,n)}function ig(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Ir=.35;function sg(t=Ir){return t===!1?t=0:t===!0&&(t=Ir),{x:_l(t,"left","right"),y:_l(t,"top","bottom")}}function _l(t,e,n){return{min:bl(t,e),max:bl(t,n)}}function bl(t,e){return typeof t=="number"?t:t[e]||0}const rg=new WeakMap;class og{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=_e(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=p=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(jn(p).point)},r=(p,m)=>{const{drag:v,dragPropagation:_,onDragStart:C}=this.getProps();if(v&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=bp(v),!this.openDragLock))return;this.latestPointerEvent=p,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ze(w=>{let T=this.getAxisMotionValue(w).get()||0;if(ct.test(T)){const{projection:I}=this.visualElement;if(I&&I.layout){const R=I.layout.layoutBox[w];R&&(T=Le(R)*(parseFloat(T)/100))}}this.originPoint[w]=T}),C&&de.postRender(()=>C(p,m)),br(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(p,m)=>{this.latestPointerEvent=p,this.latestPanInfo=m;const{dragPropagation:v,dragDirectionLock:_,onDirectionLock:C,onDrag:S}=this.getProps();if(!v&&!this.openDragLock)return;const{offset:w}=m;if(_&&this.currentDirection===null){this.currentDirection=ag(w),this.currentDirection!==null&&C&&C(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),S&&S(p,m)},c=(p,m)=>{this.latestPointerEvent=p,this.latestPanInfo=m,this.stop(p,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>ze(p=>{var m;return this.getAnimationState(p)==="paused"&&((m=this.getAxisMotionValue(p).animation)==null?void 0:m.play())}),{dragSnapToOrigin:f}=this.getProps();this.panSession=new pl(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:f,distanceThreshold:i,contextWindow:hl(this.visualElement)})}stop(e,n){const i=e||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&&de.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.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(e,n,i){const{drag:s}=this.getProps();if(!i||!Ri(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Qm(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,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;e&&an(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=eg(i.layoutBox,e):this.constraints=!1,this.elastic=sg(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=ig(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!an(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Xm(i,s.root,this.visualElement.getTransformPagePoint());let r=tg(s.layout.layoutBox,o);if(n){const a=n(jm(r));this.hasMutatedConstraints=!!a,a&&(r=Yc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},d=ze(f=>{if(!Ri(f,n,this.currentDirection))return;let p=c&&c[f]||{};r&&(p={min:0,max:0});const m=s?200:1e6,v=s?40:1e7,_={type:"inertia",velocity:i?e[f]:0,bounceStiffness:m,bounceDamping:v,timeConstant:750,restDelta:1,restSpeed:10,...o,...p};return this.startAxisValueAnimation(f,_)});return Promise.all(d).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return br(this.visualElement,e),i.start(wr(e,i,0,n,this.visualElement,!1))}stopAnimation(){ze(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ze(e=>{var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.pause()})}getAnimationState(e){var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){ze(n=>{const{drag:i}=this.getProps();if(!Ri(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(e[n]-me(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!an(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};ze(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const c=a.get();s[r]=ng({min:c,max:c},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(),ze(r=>{if(!Ri(r,e,null))return;const a=this.getAxisMotionValue(r),{min:c,max:d}=this.constraints[r];a.set(me(c,d,s[r]))})}addListeners(){if(!this.visualElement.current)return;rg.set(this.visualElement,this);const e=this.visualElement.current,n=Un(e,"pointerdown",c=>{const{drag:d,dragListener:f=!0}=this.getProps();d&&f&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();an(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),de.read(i);const r=Bn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:c,hasLayoutChanged:d})=>{this.isDragging&&d&&(ze(f=>{const p=this.getAxisMotionValue(f);p&&(this.originPoint[f]+=c[f].translate,p.set(p.get()+c[f].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Ir,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Ri(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function ag(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class cg extends Et{constructor(e){super(e),this.removeGroupControls=We,this.removeListeners=We,this.controls=new og(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||We}unmount(){this.removeGroupControls(),this.removeListeners()}}const wl=t=>(e,n)=>{t&&de.postRender(()=>t(e,n))};class lg extends Et{constructor(){super(...arguments),this.removePointerDownListener=We}onPointerDown(e){this.session=new pl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:hl(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:wl(e),onStart:wl(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&de.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=Un(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Pi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function xl(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Hn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const n=xl(t,e.target.x),i=xl(t,e.target.y);return`${n}% ${i}%`}},dg={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Tt.parse(t);if(s.length>5)return i;const o=Tt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=c;const d=me(a,c,.5);return typeof s[2+r]=="number"&&(s[2+r]/=d),typeof s[3+r]=="number"&&(s[3+r]/=d),o(s)}};let Sl=!1;class ug extends Ze{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Xp(hg),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Sl&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Pi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Sl=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||de.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),cr.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Cl(t){const[e,n]=Tc(),i=xe(Ss);return M(ug,{...t,layoutGroup:i,switchLayoutGroup:xe(Oc),isPresent:e,safeToRemove:n})}const hg={borderRadius:{...Hn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Hn,borderTopRightRadius:Hn,borderBottomLeftRadius:Hn,borderBottomRightRadius:Hn,boxShadow:dg};function fg(t,e,n){const i=Ae(t)?t:rn(t);return i.start(wr("",i,e,n)),i.animation}const pg=(t,e)=>t.depth-e.depth;class mg{constructor(){this.children=[],this.isDirty=!1}add(e){ks(this.children,e),this.isDirty=!0}remove(e){Ts(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(pg),this.isDirty=!1,this.children.forEach(e)}}function gg(t,e){const n=Fe.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Ct(i),t(o-e))};return de.setup(i,!0),()=>Ct(i)}const kl=["TopLeft","TopRight","BottomLeft","BottomRight"],vg=kl.length,Tl=t=>typeof t=="string"?parseFloat(t):t,El=t=>typeof t=="number"||K.test(t);function yg(t,e,n,i,s,o){s?(t.opacity=me(0,n.opacity??1,_g(i)),t.opacityExit=me(e.opacity??1,0,bg(i))):o&&(t.opacity=me(e.opacity??1,n.opacity??1,i));for(let r=0;r<vg;r++){const a=`border${kl[r]}Radius`;let c=Il(e,a),d=Il(n,a);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||El(c)===El(d)?(t[a]=Math.max(me(Tl(c),Tl(d),i),0),(ct.test(d)||ct.test(c))&&(t[a]+="%")):t[a]=d}(e.rotate||n.rotate)&&(t.rotate=me(e.rotate||0,n.rotate||0,i))}function Il(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const _g=Al(0,.5,Ea),bg=Al(.5,.95,We);function Al(t,e,n){return i=>i<t?0:i>e?1:n(En(t,e,i))}function Rl(t,e){t.min=e.min,t.max=e.max}function qe(t,e){Rl(t.x,e.x),Rl(t.y,e.y)}function Pl(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Ml(t,e,n,i,s){return t-=e,t=Ai(t,1/n,i),s!==void 0&&(t=Ai(t,1/s,i)),t}function wg(t,e=0,n=1,i=.5,s,o=t,r=t){if(ct.test(e)&&(e=parseFloat(e),e=me(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=me(o.min,o.max,i);t===o&&(a-=e),t.min=Ml(t.min,e,n,a,s),t.max=Ml(t.max,e,n,a,s)}function Ll(t,e,[n,i,s],o,r){wg(t,e[n],e[i],e[s],e.scale,o,r)}const xg=["x","scaleX","originX"],Sg=["y","scaleY","originY"];function Dl(t,e,n,i){Ll(t.x,e,xg,n?n.x:void 0,i?i.x:void 0),Ll(t.y,e,Sg,n?n.y:void 0,i?i.y:void 0)}function Ol(t){return t.translate===0&&t.scale===1}function Nl(t){return Ol(t.x)&&Ol(t.y)}function Vl(t,e){return t.min===e.min&&t.max===e.max}function Cg(t,e){return Vl(t.x,e.x)&&Vl(t.y,e.y)}function Fl(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Bl(t,e){return Fl(t.x,e.x)&&Fl(t.y,e.y)}function jl(t){return Le(t.x)/Le(t.y)}function Ul(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class kg{constructor(){this.members=[]}add(e){ks(this.members,e),e.scheduleRender()}remove(e){if(Ts(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===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(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Tg(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:d,rotate:f,rotateX:p,rotateY:m,skewX:v,skewY:_}=n;d&&(i=`perspective(${d}px) ${i}`),f&&(i+=`rotate(${f}deg) `),p&&(i+=`rotateX(${p}deg) `),m&&(i+=`rotateY(${m}deg) `),v&&(i+=`skewX(${v}deg) `),_&&(i+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const Ar=["","X","Y","Z"],Eg=1e3;let Ig=0;function Rr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function $l(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Wc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&$l(i)}function Gl({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Ig++,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(Pg),this.nodes.forEach(Og),this.nodes.forEach(Ng),this.nodes.forEach(Mg)},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 c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new mg)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new As),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const c=this.eventHandlers.get(r);c&&c.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=kc(r)&&!Tp(r),this.instance=r;const{layoutId:a,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let f,p=0;const m=()=>this.root.updateBlockedByResize=!1;de.read(()=>{p=window.innerWidth}),t(r,()=>{const v=window.innerWidth;v!==p&&(p=v,this.root.updateBlockedByResize=!0,f&&f(),f=gg(m,250),Pi.hasAnimatedSinceResize&&(Pi.hasAnimatedSinceResize=!1,this.nodes.forEach(zl)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&d&&(a||c)&&this.addEventListener("didUpdate",({delta:f,hasLayoutChanged:p,hasRelativeLayoutChanged:m,layout:v})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||d.getDefaultTransition()||Ug,{onLayoutAnimationStart:C,onLayoutAnimationComplete:S}=d.getProps(),w=!this.targetLayout||!Bl(this.targetLayout,v),T=!p&&m;if(this.options.layoutRoot||this.resumeFrom||T||p&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const I={...rr(_,"layout"),onPlay:C,onComplete:S};(d.shouldReduceMotion||this.options.layoutRoot)&&(I.delay=0,I.type=!1),this.startAnimation(I),this.setAnimationOrigin(f,T)}else p||zl(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=v})}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(),Ct(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(Vg),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&&$l(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let f=0;f<this.path.length;f++){const p=this.path[f];p.shouldResetTransform=!0,p.updateScroll("snapshot"),p.options.layoutRoot&&p.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Hl);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Wl);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Dg),this.nodes.forEach(Ag),this.nodes.forEach(Rg)):this.nodes.forEach(Wl),this.clearAllSnapshots();const a=Fe.now();Te.delta=mt(0,1e3/60,a-Te.timestamp),Te.timestamp=a,Te.isProcessing=!0,Ms.update.process(Te),Ms.preRender.process(Te),Ms.render.process(Te),Te.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,cr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Lg),this.sharedNodes.forEach(Fg)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Le(this.snapshot.measuredBox.x)&&!Le(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 c=0;c<this.path.length;c++)this.path[c].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=_e(),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 c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Nl(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,f=d!==this.prevTransformTemplateValue;r&&this.instance&&(a||jt(this.latestValues)||f)&&(s(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return r&&(c=this.removeTransform(c)),$g(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var d;const{visualElement:r}=this.options;if(!r)return _e();const a=r.measureViewportBox();if(!(((d=this.scroll)==null?void 0:d.wasRoot)||this.path.some(Gg))){const{scroll:f}=this.root;f&&(ln(a.x,f.offset.x),ln(a.y,f.offset.y))}return a}removeElementScroll(r){var c;const a=_e();if(qe(a,r),(c=this.scroll)!=null&&c.wasRoot)return a;for(let d=0;d<this.path.length;d++){const f=this.path[d],{scroll:p,options:m}=f;f!==this.root&&p&&m.layoutScroll&&(p.wasRoot&&qe(a,r),ln(a.x,p.offset.x),ln(a.y,p.offset.y))}return a}applyTransform(r,a=!1){const c=_e();qe(c,r);for(let d=0;d<this.path.length;d++){const f=this.path[d];!a&&f.options.layoutScroll&&f.scroll&&f!==f.root&&dn(c,{x:-f.scroll.offset.x,y:-f.scroll.offset.y}),jt(f.latestValues)&&dn(c,f.latestValues)}return jt(this.latestValues)&&dn(c,this.latestValues),c}removeTransform(r){const a=_e();qe(a,r);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!d.instance||!jt(d.latestValues))continue;Cr(d.latestValues)&&d.updateSnapshot();const f=_e(),p=d.measurePageBox();qe(f,p),Dl(a,d.latestValues,d.snapshot?d.snapshot.layoutBox:void 0,f)}return jt(this.latestValues)&&Dl(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!==Te.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var m;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(r||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:f,layoutId:p}=this.options;if(!(!this.layout||!(f||p))){if(this.resolvedRelativeTargetAt=Te.timestamp,!this.targetDelta&&!this.relativeTarget){const v=this.getClosestProjectingParent();v&&v.layout&&this.animationProgress!==1?(this.relativeParent=v,this.forceRelativeParentToResolveTarget(),this.relativeTarget=_e(),this.relativeTargetOrigin=_e(),Gn(this.relativeTargetOrigin,this.layout.layoutBox,v.layout.layoutBox),qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=_e(),this.targetWithTransforms=_e()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),qm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):qe(this.target,this.layout.layoutBox),al(this.target,this.targetDelta)):qe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const v=this.getClosestProjectingParent();v&&!!v.resumingFrom==!!this.resumingFrom&&!v.options.layoutScroll&&v.target&&this.animationProgress!==1?(this.relativeParent=v,this.forceRelativeParentToResolveTarget(),this.relativeTarget=_e(),this.relativeTargetOrigin=_e(),Gn(this.relativeTargetOrigin,this.target,v.target),qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Cr(this.parent.latestValues)||sl(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 _;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let c=!0;if((this.isProjectionDirty||(_=this.parent)!=null&&_.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Te.timestamp&&(c=!1),c)return;const{layout:d,layoutId:f}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(d||f))return;qe(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,m=this.treeScale.y;Km(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=_e());const{target:v}=r;if(!v){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Pl(this.prevProjectionDelta.x,this.projectionDelta.x),Pl(this.prevProjectionDelta.y,this.projectionDelta.y)),$n(this.projectionDelta,this.layoutCorrected,v,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==m||!Ul(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ul(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",v))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=cn(),this.projectionDelta=cn(),this.projectionDeltaWithTransform=cn()}setAnimationOrigin(r,a=!1){const c=this.snapshot,d=c?c.latestValues:{},f={...this.latestValues},p=cn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=_e(),v=c?c.source:void 0,_=this.layout?this.layout.source:void 0,C=v!==_,S=this.getStack(),w=!S||S.members.length<=1,T=!!(C&&!w&&this.options.crossfade===!0&&!this.path.some(jg));this.animationProgress=0;let I;this.mixTargetDelta=R=>{const L=R/1e3;ql(p.x,r.x,L),ql(p.y,r.y,L),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Gn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Bg(this.relativeTarget,this.relativeTargetOrigin,m,L),I&&Cg(this.relativeTarget,I)&&(this.isProjectionDirty=!1),I||(I=_e()),qe(I,this.relativeTarget)),C&&(this.animationValues=f,yg(f,d,this.latestValues,L,T,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,c,d;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(Ct(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{Pi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=rn(0)),this.currentAnimation=fg(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:f=>{this.mixTargetDelta(f),r.onUpdate&&r.onUpdate(f)},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(Eg),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:c,layout:d,latestValues:f}=r;if(!(!a||!c||!d)){if(this!==r&&this.layout&&d&&Jl(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||_e();const p=Le(this.layout.layoutBox.x);c.x.min=r.target.x.min,c.x.max=c.x.min+p;const m=Le(this.layout.layoutBox.y);c.y.min=r.target.y.min,c.y.max=c.y.min+m}qe(a,c),dn(a,f),$n(this.projectionDeltaWithTransform,this.layoutCorrected,a,f)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new kg),this.sharedNodes.get(r).add(a);const d=a.options.initialPromotionConfig;a.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.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:c}={}){const d=this.getStack();d&&d.promote(this,c),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:c}=r;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const d={};c.z&&Rr("z",r,d,this.animationValues);for(let f=0;f<Ar.length;f++)Rr(`rotate${Ar[f]}`,r,d,this.animationValues),Rr(`skew${Ar[f]}`,r,d,this.animationValues);r.render();for(const f in d)r.setStaticValue(f,d[f]),this.animationValues&&(this.animationValues[f]=d[f]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Ii(a==null?void 0:a.pointerEvents)||"",r.transform=c?c(this.latestValues,""):"none";return}const d=this.getLead();if(!this.projectionDelta||!this.layout||!d.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Ii(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!jt(this.latestValues)&&(r.transform=c?c({},""):"none",this.hasProjected=!1);return}r.visibility="";const f=d.animationValues||d.latestValues;this.applyTransformsToTarget();let p=Tg(this.projectionDeltaWithTransform,this.treeScale,f);c&&(p=c(f,p)),r.transform=p;const{x:m,y:v}=this.projectionDelta;r.transformOrigin=`${m.origin*100}% ${v.origin*100}% 0`,d.animationValues?r.opacity=d===this?f.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:f.opacityExit:r.opacity=d===this?f.opacity!==void 0?f.opacity:"":f.opacityExit!==void 0?f.opacityExit:0;for(const _ in Vn){if(f[_]===void 0)continue;const{correct:C,applyTo:S,isCSSVariable:w}=Vn[_],T=p==="none"?f[_]:C(f[_],d);if(S){const I=S.length;for(let R=0;R<I;R++)r[S[R]]=T}else w?this.options.visualElement.renderState.vars[_]=T:r[_]=T}this.options.layoutId&&(r.pointerEvents=d===this?Ii(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(Hl),this.root.sharedNodes.clear()}}}function Ag(t){t.updateLayout()}function Rg(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?ze(p=>{const m=r?e.measuredBox[p]:e.layoutBox[p],v=Le(m);m.min=i[p].min,m.max=m.min+v}):Jl(o,e.layoutBox,i)&&ze(p=>{const m=r?e.measuredBox[p]:e.layoutBox[p],v=Le(i[p]);m.max=m.min+v,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[p].max=t.relativeTarget[p].min+v)});const a=cn();$n(a,i,e.layoutBox);const c=cn();r?$n(c,t.applyTransform(s,!0),e.measuredBox):$n(c,i,e.layoutBox);const d=!Nl(a);let f=!1;if(!t.resumeFrom){const p=t.getClosestProjectingParent();if(p&&!p.resumeFrom){const{snapshot:m,layout:v}=p;if(m&&v){const _=_e();Gn(_,e.layoutBox,m.layoutBox);const C=_e();Gn(C,i,v.layoutBox),Bl(_,C)||(f=!0),p.options.layoutRoot&&(t.relativeTarget=C,t.relativeTargetOrigin=_,t.relativeParent=p)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:c,layoutDelta:a,hasLayoutChanged:d,hasRelativeLayoutChanged:f})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function Pg(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Mg(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Lg(t){t.clearSnapshot()}function Hl(t){t.clearMeasurements()}function Wl(t){t.isLayoutDirty=!1}function Dg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function zl(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Og(t){t.resolveTargetDelta()}function Ng(t){t.calcProjection()}function Vg(t){t.resetSkewAndRotation()}function Fg(t){t.removeLeadSnapshot()}function ql(t,e,n){t.translate=me(e.translate,0,n),t.scale=me(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Kl(t,e,n,i){t.min=me(e.min,n.min,i),t.max=me(e.max,n.max,i)}function Bg(t,e,n,i){Kl(t.x,e.x,n.x,i),Kl(t.y,e.y,n.y,i)}function jg(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Ug={duration:.45,ease:[.4,0,.1,1]},Xl=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Yl=Xl("applewebkit/")&&!Xl("chrome/")?Math.round:We;function Zl(t){t.min=Yl(t.min),t.max=Yl(t.max)}function $g(t){Zl(t.x),Zl(t.y)}function Jl(t,e,n){return t==="position"||t==="preserve-aspect"&&!zm(jl(e),jl(n),.2)}function Gg(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Hg=Gl({attachResizeListener:(t,e)=>Bn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Pr={current:void 0},Ql=Gl({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Pr.current){const t=new Hg({});t.mount(window),t.setOptions({layoutScroll:!0}),Pr.current=t}return Pr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Wg={pan:{Feature:lg},drag:{Feature:cg,ProjectionNode:Ql,MeasureLayout:Cl}};function ed(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,o=i[s];o&&de.postRender(()=>o(e,jn(e)))}class zg extends Et{mount(){const{current:e}=this.node;e&&(this.unmount=wp(e,(n,i)=>(ed(this.node,i,"Start"),s=>ed(this.node,s,"End"))))}unmount(){}}class qg extends Et{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!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=Tn(Bn(this.node.current,"focus",()=>this.onFocus()),Bn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function td(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),o=i[s];o&&de.postRender(()=>o(e,jn(e)))}class Kg extends Et{mount(){const{current:e}=this.node;e&&(this.unmount=kp(e,(n,i)=>(td(this.node,i,"Start"),(s,{success:o})=>td(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Mr=new WeakMap,Lr=new WeakMap,Xg=t=>{const e=Mr.get(t.target);e&&e(t)},Yg=t=>{t.forEach(Xg)};function Zg({root:t,...e}){const n=t||document;Lr.has(n)||Lr.set(n,{});const i=Lr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Yg,{root:t,...e})),i[s]}function Jg(t,e,n){const i=Zg(e);return Mr.set(t,n),i.observe(t),()=>{Mr.delete(t),i.unobserve(t)}}const Qg={some:0,all:1};class ev extends Et{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:o}=e,r={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Qg[s]},a=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,o&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:f,onViewportLeave:p}=this.node.getProps(),m=d?f:p;m&&m(c)};return Jg(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(tv(e,n))&&this.startObserver()}unmount(){}}function tv({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const nv={inView:{Feature:ev},tap:{Feature:Kg},focus:{Feature:qg},hover:{Feature:zg}},iv={layout:{ProjectionNode:Ql,MeasureLayout:Cl}},Dr={current:null},nd={current:!1};function sv(){if(nd.current=!0,!!Cs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Dr.current=t.matches;t.addEventListener("change",e),e()}else Dr.current=!1}const rv=new WeakMap;function ov(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Ae(s))t.addValue(i,s);else if(Ae(o))t.addValue(i,rn(s,{owner:t}));else if(o!==s)if(t.hasValue(i)){const r=t.getValue(i);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(i);t.addValue(i,rn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const id=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class av{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,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=ir,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 m=Fe.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,de.render(this.render,!1,!0))};const{latestValues:c,renderState:d}=r;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=d,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Ei(n),this.isVariantNode=Mc(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:f,...p}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in p){const v=p[m];c[m]!==void 0&&Ae(v)&&v.set(c[m],!1)}}mount(e){this.current=e,rv.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),nd.current||sv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Dr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Ct(this.notifyUpdate),Ct(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=sn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&de.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in on){const n=on[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];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):_e()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<id.length;i++){const s=id[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=ov(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]: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(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=rn(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(va(i)||_a(i))?i=parseFloat(i):!Ip(i)&&Tt.test(n)&&(i=gc(e,n)),this.setBaseTarget(e,Ae(i)?i.get():i)),Ae(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var o;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const r=vr(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);r&&(i=r[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ae(s)?s:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new As),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class sd extends av{constructor(){super(...arguments),this.KeyframeResolver=gp}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ae(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function rd(t,{style:e,vars:n},i,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,i);for(r in n)o.setProperty(r,n[r])}function cv(t){return window.getComputedStyle(t)}class lv extends sd{constructor(){super(...arguments),this.type="html",this.renderInstance=rd}readValueFromInstance(e,n){var i;if(sn.has(n))return(i=this.projection)!=null&&i.isProjecting?Js(n):Nf(e,n);{const s=cv(e),o=(Ls(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return ul(e,n)}build(e,n,i){pr(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return yr(e,n,i)}}const od=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 dv(t,e,n,i){rd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(od.has(s)?s:fr(s),e.attrs[s])}class uv extends sd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=_e}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(sn.has(n)){const i=mc(n);return i&&i.default||0}return n=od.has(n)?n:fr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Hc(e,n,i)}build(e,n,i){Bc(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){dv(e,n,i,s)}mount(e){this.isSVGTag=Uc(e.tagName),super.mount(e)}}const hv=(t,e)=>gr(t)?new uv(e):new lv(e,{allowProjection:t!==it}),fv=hm({...Fm,...nv,...Wg,...iv},hv),Wn=Fp(fv),pv=["agent-id","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers"],Mi="widget-layout-id";function ad(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=ad(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function vt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=ad(t))&&(i&&(i+=" "),i+=e);return i}const mv=vs("listening"),Or=()=>ma(mv);function gv(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Li={theme:"dark",audio_visualizer_config:{color:"verdant",preset:"roundBars"},start_call_text:"Let's chat",default_state:"collapsed",position:"fixed",view_history_url:null,report_issue_url:null,give_feedback_url:null,agent_thinking_text:"Thinking...",speak_to_interrupt_text:"Speak to interrupt",logo_icon_url:null},cd=vs(Li),vv=()=>{const t=xs(cd);return St(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Li.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Li.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Li.speak_to_interrupt_text),n}),[t])},Ut=()=>pa(cd),ld=({size:t="large",className:e})=>{const n=Ut(),[i]=Or();return M("h1",{className:vt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},dd=({stream:t})=>{const e=ke(null);return Ve(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),M("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
9
+ `),()=>{y.removeChild(v),y.contains(v)&&y.removeChild(v)}},[e]),E(mp,{isPresent:e,childRef:o,sizeRef:r,children:mh(t,{ref:o})})}const vp=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:c})=>{const l=mi(_p),d=os();let u=!0,h=rt(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:g=>{l.set(g,!0);for(const v of l.values())if(!v)return;i&&i()},register:g=>(l.set(g,!1),()=>l.delete(g))}),[n,l,i]);return o&&u&&(h={...h}),rt(()=>{l.forEach((g,v)=>l.set(v,!1))},[n]),Ve(()=>{!n&&!l.size&&i&&i()},[n]),r==="popLayout"&&(t=E(gp,{isPresent:n,anchorX:a,root:c,children:t})),E(gi.Provider,{value:h,children:t})};function _p(){return new Map}function xc(t=!0){const e=Se(gi);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=os();Ve(()=>{if(t)return s(o)},[t]);const r=St(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Ci=t=>t.key||"";function Sc(t){const e=[];return sh.forEach(t,n=>{oa(n)&&e.push(n)}),e}const yp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:c})=>{const[l,d]=xc(r),u=rt(()=>Sc(t),[t]),h=r&&!l?[]:u.map(Ci),g=Te(!0),v=Te(u),y=mi(()=>new Map),[x,w]=ke(u),[S,k]=ke(u);ha(()=>{g.current=!1,v.current=u;for(let O=0;O<S.length;O++){const b=Ci(S[O]);h.includes(b)?y.delete(b):y.get(b)!==!0&&y.set(b,!1)}},[S,h.length,h.join("-")]);const A=[];if(u!==x){let O=[...u];for(let b=0;b<S.length;b++){const C=S[b],f=Ci(C);h.includes(f)||(O.splice(b,0,C),A.push(C))}return o==="wait"&&A.length&&(O=A),k(Sc(O)),w(u),null}const{forceRender:L}=Se(ys);return E(it,{children:S.map(O=>{const b=Ci(O),C=r&&!l?!1:u===S||h.includes(b),f=()=>{if(y.has(b))y.set(b,!0);else return;let m=!0;y.forEach(p=>{p||(m=!1)}),m&&(L==null||L(),k(v.current),r&&(d==null||d()),i&&i())};return E(vp,{isPresent:C,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:c,onExitComplete:C?void 0:f,anchorX:a,children:O},b)})})},Cc=mt({strict:!1}),kc={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"]},on={};for(const t in kc)on[t]={isEnabled:e=>kc[t].some(n=>!!e[n])};function bp(t){for(const e in t)on[e]={...on[e],...t[e]}}const wp=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 ki(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||wp.has(t)}let Tc=t=>!ki(t);function Ec(t){typeof t=="function"&&(Tc=e=>e.startsWith("on")?!ki(e):t(e))}try{Ec(require("@emotion/is-prop-valid").default)}catch{}function xp(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Tc(s)||n===!0&&ki(s)||!e&&!ki(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Sp({children:t,isValidProp:e,...n}){e&&Ec(e),n={...Se(Nn),...n},n.isStatic=mi(()=>n.isStatic);const i=rt(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return E(Nn.Provider,{value:i,children:t})}function Cp(t){if(typeof Proxy>"u")return t;const e=new Map,n=(...i)=>t(...i);return new Proxy(n,{get:(i,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const Ti=mt({});function Ei(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Vn(t){return typeof t=="string"||Array.isArray(t)}const ar=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],cr=["initial",...ar];function Ai(t){return Ei(t.animate)||cr.some(e=>Vn(t[e]))}function Ac(t){return!!(Ai(t)||t.variants)}function kp(t,e){if(Ai(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Vn(n)?n:void 0,animate:Vn(i)?i:void 0}}return t.inherit!==!1?e:{}}function Tp(t){const{initial:e,animate:n}=kp(t,Se(Ti));return rt(()=>({initial:e,animate:n}),[Ic(e),Ic(n)])}function Ic(t){return Array.isArray(t)?t.join(" "):t}const Ep=Symbol.for("motionComponentSymbol");function an(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Ap(t,e,n){return St(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):an(n)&&(n.current=i))},[e])}const lr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Rc="data-"+lr("framerAppearId"),Pc=mt({});function Ip(t,e,n,i,s){var y,x;const{visualElement:o}=Se(Ti),r=Se(Cc),a=Se(gi),c=Se(Nn).reducedMotion,l=Te(null);i=i||r.renderer,!l.current&&i&&(l.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const d=l.current,u=Se(Pc);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&Rp(l.current,n,s,u);const h=Te(!1);zo(()=>{d&&h.current&&d.update(n,a)});const g=n[Rc],v=Te(!!g&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,g))&&((x=window.MotionHasOptimisedAnimation)==null?void 0:x.call(window,g)));return ha(()=>{d&&(h.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),sr.render(d.render),v.current&&d.animationState&&d.animationState.animateChanges())}),Ve(()=>{d&&(!v.current&&d.animationState&&d.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,g)}),v.current=!1))}),d}function Rp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:d}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Mc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&an(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:d,layoutScroll:c,layoutRoot:l})}function Mc(t){if(t)return t.options.allowProjection!==!1?t.projection:Mc(t.parent)}function Pp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&bp(t);function o(a,c){let l;const d={...Se(Nn),...a,layoutId:Mp(a)},{isStatic:u}=d,h=Tp(a),g=i(a,u);if(!u&&bs){Lp();const v=Dp(d);l=v.MeasureLayout,h.visualElement=Ip(s,g,d,e,v.ProjectionNode)}return E(Ti.Provider,{value:h,children:[l&&h.visualElement?E(l,{visualElement:h.visualElement,...d}):null,n(s,a,Ap(g,h.visualElement,c),g,u,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=ih(o);return r[Ep]=s,r}function Mp({layoutId:t}){const e=Se(ys).id;return e&&t!==void 0?e+"-"+t:t}function Lp(t,e){Se(Cc).strict}function Dp(t){const{drag:e,layout:n}=on;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e!=null&&e.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const Fn={};function Op(t){for(const e in t)Fn[e]=t[e],Is(e)&&(Fn[e].isCSSVariable=!0)}function Lc(t,{layout:e,layoutId:n}){return sn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Fn[t]||t==="opacity")}const Np={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Vp=nn.length;function Fp(t,e,n){let i="",s=!0;for(let o=0;o<Vp;o++){const r=nn[o],a=t[r];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(r.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const l=fc(a,ir[r]);if(!c){s=!1;const d=Np[r]||r;i+=`${d}(${l}) `}n&&(e[r]=l)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function dr(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const c in e){const l=e[c];if(sn.has(c)){r=!0;continue}else if(Is(c)){s[c]=l;continue}else{const d=fc(l,ir[c]);c.startsWith("origin")?(a=!0,o[c]=d):i[c]=d}}if(e.transform||(r||n?i.transform=Fp(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:d=0}=o;i.transformOrigin=`${c} ${l} ${d}`}}const ur=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Dc(t,e,n){for(const i in e)!Re(e[i])&&!Lc(i,n)&&(t[i]=e[i])}function Bp({transformTemplate:t},e){return rt(()=>{const n=ur();return dr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function jp(t,e){const n=t.style||{},i={};return Dc(i,n,t),Object.assign(i,Bp(t,e)),i}function Up(t,e){const n={},i=jp(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const $p={offset:"stroke-dashoffset",array:"stroke-dasharray"},Hp={offset:"strokeDashoffset",array:"strokeDasharray"};function Gp(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?$p:Hp;t[o.offset]=G.transform(-i);const r=G.transform(e),a=G.transform(n);t[o.array]=`${r} ${a}`}function Oc(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},c,l,d){if(dr(t,a,l),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:h}=t;u.transform&&(h.transform=u.transform,delete u.transform),(h.transform||u.transformOrigin)&&(h.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),h.transform&&(h.transformBox=(d==null?void 0:d.transformBox)??"fill-box",delete u.transformBox),e!==void 0&&(u.x=e),n!==void 0&&(u.y=n),i!==void 0&&(u.scale=i),s!==void 0&&Gp(u,s,o,r,!1)}const Nc=()=>({...ur(),attrs:{}}),Vc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Wp(t,e,n,i){const s=rt(()=>{const o=Nc();return Oc(o,e,Vc(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Dc(o,t.style,t),s.style={...o,...s.style}}return s}const zp=["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 hr(t){return typeof t!="string"||t.includes("-")?!1:!!(zp.indexOf(t)>-1||/[A-Z]/u.test(t))}function qp(t=!1){return(n,i,s,{latestValues:o},r)=>{const c=(hr(n)?Wp:Up)(i,o,r,n),l=xp(i,typeof n=="string",t),d=n!==it?{...l,...c,ref:s}:{},{children:u}=i,h=rt(()=>Re(u)?u.get():u,[u]);return Ge(n,{...d,children:h})}}function Fc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function fr(t,e,n,i){if(typeof e=="function"){const[s,o]=Fc(i);e=e(n!==void 0?n:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=Fc(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function Ii(t){return Re(t)?t.get():t}function Kp({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Xp(n,i,s,t),renderState:e()}}const Bc=t=>(e,n)=>{const i=Se(Ti),s=Se(gi),o=()=>Kp(t,e,i,s);return n?o():mi(o)};function Xp(t,e,n,i){const s={},o=i(t,{});for(const h in o)s[h]=Ii(o[h]);let{initial:r,animate:a}=t;const c=Ai(t),l=Ac(t);e&&l&&!c&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let d=n?n.initial===!1:!1;d=d||r===!1;const u=d?a:r;if(u&&typeof u!="boolean"&&!Ei(u)){const h=Array.isArray(u)?u:[u];for(let g=0;g<h.length;g++){const v=fr(t,h[g]);if(v){const{transitionEnd:y,transition:x,...w}=v;for(const S in w){let k=w[S];if(Array.isArray(k)){const A=d?k.length-1:0;k=k[A]}k!==null&&(s[S]=k)}for(const S in y)s[S]=y[S]}}}return s}function pr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Re(i[r])||e.style&&Re(e.style[r])||Lc(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const Yp={useVisualState:Bc({scrapeMotionValuesFromProps:pr,createRenderState:ur})};function jc(t,e,n){const i=pr(t,e,n);for(const s in t)if(Re(t[s])||Re(e[s])){const o=nn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const Jp={useVisualState:Bc({scrapeMotionValuesFromProps:jc,createRenderState:Nc})};function Zp(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...hr(i)?Jp:Yp,preloadedFeatures:t,useRender:qp(s),createVisualElement:e,Component:i};return Pp(r)}}function Bn(t,e,n){const i=t.getProps();return fr(i,e,n!==void 0?n:i.custom,t)}const mr=t=>Array.isArray(t);function Qp(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,rn(n))}function em(t){return mr(t)?t[t.length-1]||0:t}function tm(t,e){const n=Bn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=em(o[r]);Qp(t,r,a)}}function nm(t){return!!(Re(t)&&t.add)}function gr(t,e){const n=t.getValue("willChange");if(nm(n))return n.add(e);if(!n&&vt.WillChange){const i=new vt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Uc(t){return t.props[Rc]}const im=t=>t!==null;function sm(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(im),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const rm={type:"spring",stiffness:500,damping:25,restSpeed:10},om=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),am={type:"keyframes",duration:.8},cm={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},lm=(t,{keyframes:e})=>e.length>2?am:sn.has(t)?t.startsWith("scale")?om(e[1]):rm:cm;function dm({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:c,elapsed:l,...d}){return!!Object.keys(d).length}const vr=(t,e,n,i={},s,o)=>r=>{const a=tr(i,t)||{},c=a.delay||i.delay||0;let{elapsed:l=0}=i;l=l-ot(c);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-l,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};dm(a)||Object.assign(d,lm(t,d)),d.duration&&(d.duration=ot(d.duration)),d.repeatDelay&&(d.repeatDelay=ot(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)),(vt.instantAnimations||vt.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const h=sm(d.keyframes,a);if(h!==void 0){de.update(()=>{d.onUpdate(h),d.onComplete()});return}}return a.isSync?new Ws(d):new Wf(d)};function um({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function $c(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const c=[],l=s&&t.animationState&&t.animationState.getState()[s];for(const d in a){const u=t.getValue(d,t.latestValues[d]??null),h=a[d];if(h===void 0||l&&um(l,d))continue;const g={delay:n,...tr(o||{},d)},v=u.get();if(v!==void 0&&!u.isAnimating&&!Array.isArray(h)&&h===v&&!g.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const w=Uc(t);if(w){const S=window.MotionHandoffAnimation(w,d,de);S!==null&&(g.startTime=S,y=!0)}}gr(t,d),u.start(vr(d,u,h,t.shouldReduceMotion&&oc.has(d)?{type:!1}:g,t,y));const x=u.animation;x&&c.push(x)}return r&&Promise.all(c).then(()=>{de.update(()=>{r&&tm(t,r)})}),c}function _r(t,e,n={}){var c;const i=Bn(t,e,n.type==="exit"?(c=t.presenceContext)==null?void 0:c.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all($c(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(l=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=s;return hm(t,e,l,d,u,h,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[l,d]=a==="beforeChildren"?[o,r]:[r,o];return l().then(()=>d())}else return Promise.all([o(),r(n.delay)])}function hm(t,e,n=0,i=0,s=0,o=1,r){const a=[],c=t.variantChildren.size,l=(c-1)*s,d=typeof i=="function",u=d?h=>i(h,c):o===1?(h=0)=>h*s:(h=0)=>l-h*s;return Array.from(t.variantChildren).sort(fm).forEach((h,g)=>{h.notify("AnimationStart",e),a.push(_r(h,e,{...r,delay:n+(d?0:i)+u(g)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function fm(t,e){return t.sortNodePosition(e)}function pm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>_r(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=_r(t,e,n);else{const s=typeof e=="function"?Bn(t,e,n.custom):e;i=Promise.all($c(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Hc(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const mm=cr.length;function Gc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Gc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<mm;n++){const i=cr[n],s=t.props[i];(Vn(s)||s===!1)&&(e[i]=s)}return e}const gm=[...ar].reverse(),vm=ar.length;function _m(t){return e=>Promise.all(e.map(({animation:n,options:i})=>pm(t,n,i)))}function ym(t){let e=_m(t),n=Wc(),i=!0;const s=c=>(l,d)=>{var h;const u=Bn(t,d,c==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(u){const{transition:g,transitionEnd:v,...y}=u;l={...l,...y,...v}}return l};function o(c){e=c(t)}function r(c){const{props:l}=t,d=Gc(t.parent)||{},u=[],h=new Set;let g={},v=1/0;for(let x=0;x<vm;x++){const w=gm[x],S=n[w],k=l[w]!==void 0?l[w]:d[w],A=Vn(k),L=w===c?S.isActive:null;L===!1&&(v=x);let O=k===d[w]&&k!==l[w]&&A;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),S.protectedKeys={...g},!S.isActive&&L===null||!k&&!S.prevProp||Ei(k)||typeof k=="boolean")continue;const b=bm(S.prevProp,k);let C=b||w===c&&S.isActive&&!O&&A||x>v&&A,f=!1;const m=Array.isArray(k)?k:[k];let p=m.reduce(s(w),{});L===!1&&(p={});const{prevResolvedValues:_={}}=S,T={..._,...p},P=M=>{C=!0,h.has(M)&&(f=!0,h.delete(M)),S.needsAnimating[M]=!0;const V=t.getValue(M);V&&(V.liveStyle=!1)};for(const M in T){const V=p[M],X=_[M];if(g.hasOwnProperty(M))continue;let B=!1;mr(V)&&mr(X)?B=!Hc(V,X):B=V!==X,B?V!=null?P(M):h.add(M):V!==void 0&&h.has(M)?P(M):S.protectedKeys[M]=!0}S.prevProp=k,S.prevResolvedValues=p,S.isActive&&(g={...g,...p}),i&&t.blockInitialAnimation&&(C=!1),C&&(!(O&&b)||f)&&u.push(...m.map(M=>({animation:M,options:{type:w}})))}if(h.size){const x={};if(typeof l.initial!="boolean"){const w=Bn(t,Array.isArray(l.initial)?l.initial[0]:l.initial);w&&w.transition&&(x.transition=w.transition)}h.forEach(w=>{const S=t.getBaseTarget(w),k=t.getValue(w);k&&(k.liveStyle=!0),x[w]=S??null}),u.push({animation:x})}let y=!!u.length;return i&&(l.initial===!1||l.initial===l.animate)&&!t.manuallyAnimateOnMount&&(y=!1),i=!1,y?e(u):Promise.resolve()}function a(c,l){var u;if(n[c].isActive===l)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(h=>{var g;return(g=h.animationState)==null?void 0:g.setActive(c,l)}),n[c].isActive=l;const d=r(c);for(const h in n)n[h].protectedKeys={};return d}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Wc(),i=!0}}}function bm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Hc(e,t):!1}function Bt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Wc(){return{animate:Bt(!0),whileInView:Bt(),whileHover:Bt(),whileTap:Bt(),whileDrag:Bt(),whileFocus:Bt(),exit:Bt()}}class Et{constructor(e){this.isMounted=!1,this.node=e}update(){}}class wm extends Et{constructor(e){super(e),e.animationState||(e.animationState=ym(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ei(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let xm=0;class Sm extends Et{constructor(){super(...arguments),this.id=xm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Cm={animation:{Feature:wm},exit:{Feature:Sm}};function jn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Un(t){return{point:{x:t.pageX,y:t.pageY}}}const km=t=>e=>rr(e)&&t(e,Un(e));function $n(t,e,n,i){return jn(t,e,km(n),i)}function zc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Tm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Em(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const qc=1e-4,Am=1-qc,Im=1+qc,Kc=.01,Rm=0-Kc,Pm=0+Kc;function Le(t){return t.max-t.min}function Mm(t,e,n){return Math.abs(t-e)<=n}function Xc(t,e,n,i=.5){t.origin=i,t.originPoint=me(e.min,e.max,t.origin),t.scale=Le(n)/Le(e),t.translate=me(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Am&&t.scale<=Im||isNaN(t.scale))&&(t.scale=1),(t.translate>=Rm&&t.translate<=Pm||isNaN(t.translate))&&(t.translate=0)}function Hn(t,e,n,i){Xc(t.x,e.x,n.x,i?i.originX:void 0),Xc(t.y,e.y,n.y,i?i.originY:void 0)}function Yc(t,e,n){t.min=n.min+e.min,t.max=t.min+Le(e)}function Lm(t,e,n){Yc(t.x,e.x,n.x),Yc(t.y,e.y,n.y)}function Jc(t,e,n){t.min=e.min-n.min,t.max=t.min+Le(e)}function Gn(t,e,n){Jc(t.x,e.x,n.x),Jc(t.y,e.y,n.y)}const Zc=()=>({translate:0,scale:1,origin:0,originPoint:0}),cn=()=>({x:Zc(),y:Zc()}),Qc=()=>({min:0,max:0}),ye=()=>({x:Qc(),y:Qc()});function ze(t){return[t("x"),t("y")]}function yr(t){return t===void 0||t===1}function br({scale:t,scaleX:e,scaleY:n}){return!yr(t)||!yr(e)||!yr(n)}function jt(t){return br(t)||el(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function el(t){return tl(t.x)||tl(t.y)}function tl(t){return t&&t!=="0%"}function Ri(t,e,n){const i=t-n,s=e*i;return n+s}function nl(t,e,n,i,s){return s!==void 0&&(t=Ri(t,s,i)),Ri(t,n,i)+e}function wr(t,e=0,n=1,i,s){t.min=nl(t.min,e,n,i,s),t.max=nl(t.max,e,n,i,s)}function il(t,{x:e,y:n}){wr(t.x,e.translate,e.scale,e.originPoint),wr(t.y,n.translate,n.scale,n.originPoint)}const sl=.999999999999,rl=1.0000000000001;function Dm(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&dn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,il(t,r)),i&&jt(o.latestValues)&&dn(t,o.latestValues))}e.x<rl&&e.x>sl&&(e.x=1),e.y<rl&&e.y>sl&&(e.y=1)}function ln(t,e){t.min=t.min+e,t.max=t.max+e}function ol(t,e,n,i,s=.5){const o=me(t.min,t.max,s);wr(t,e,n,o,i)}function dn(t,e){ol(t.x,e.x,e.scaleX,e.scale,e.originX),ol(t.y,e.y,e.scaleY,e.scale,e.originY)}function al(t,e){return zc(Em(t.getBoundingClientRect(),e))}function Om(t,e,n){const i=al(t,n),{scroll:s}=e;return s&&(ln(i.x,s.offset.x),ln(i.y,s.offset.y)),i}const cl=({current:t})=>t?t.ownerDocument.defaultView:null,ll=(t,e)=>Math.abs(t-e);function Nm(t,e){const n=ll(t.x,e.x),i=ll(t.y,e.y);return Math.sqrt(n**2+i**2)}class dl{constructor(e,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 h=Sr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=Nm(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:y}=h,{timestamp:x}=Ee;this.history.push({...y,timestamp:x});const{onStart:w,onMove:S}=this.handlers;g||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=xr(g,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:x}=this.handlers;if(this.dragSnapToOrigin&&x&&x(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Sr(h.type==="pointercancel"?this.lastMoveEventInfo:xr(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(h,w),y&&y(h,w)},!rr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Un(e),c=xr(a,this.transformPagePoint),{point:l}=c,{timestamp:d}=Ee;this.history=[{...l,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Sr(c,this.history)),this.removeListeners=En($n(this.contextWindow,"pointermove",this.handlePointerMove),$n(this.contextWindow,"pointerup",this.handlePointerUp),$n(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Ct(this.updatePoint)}}function xr(t,e){return e?{point:e(t.point)}:t}function ul(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Sr({point:t},e){return{point:t,delta:ul(t,hl(e)),offset:ul(t,Vm(e)),velocity:Fm(e,.1)}}function Vm(t){return t[0]}function hl(t){return t[t.length-1]}function Fm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=hl(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>ot(e)));)n--;if(!i)return{x:0,y:0};const o=at(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 Bm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?me(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?me(n,t,i.max):Math.min(t,n)),t}function fl(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function jm(t,{top:e,left:n,bottom:i,right:s}){return{x:fl(t.x,n,s),y:fl(t.y,e,i)}}function pl(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function Um(t,e){return{x:pl(t.x,e.x),y:pl(t.y,e.y)}}function $m(t,e){let n=.5;const i=Le(t),s=Le(e);return s>i?n=An(e.min,e.max-i,t.min):i>s&&(n=An(t.min,t.max-s,e.min)),gt(0,1,n)}function Hm(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Cr=.35;function Gm(t=Cr){return t===!1?t=0:t===!0&&(t=Cr),{x:ml(t,"left","right"),y:ml(t,"top","bottom")}}function ml(t,e,n){return{min:gl(t,e),max:gl(t,n)}}function gl(t,e){return typeof t=="number"?t:t[e]||0}const Wm=new WeakMap;class zm{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ye(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=u=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Un(u).point)},r=(u,h)=>{const{drag:g,dragPropagation:v,onDragStart:y}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=op(g),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ze(w=>{let S=this.getAxisMotionValue(w).get()||0;if(ct.test(S)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[w];A&&(S=Le(A)*(parseFloat(S)/100))}}this.originPoint[w]=S}),y&&de.postRender(()=>y(u,h)),gr(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},a=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:y,onDrag:x}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:w}=h;if(v&&this.currentDirection===null){this.currentDirection=qm(w),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),this.visualElement.render(),x&&x(u,h)},c=(u,h)=>{this.latestPointerEvent=u,this.latestPanInfo=h,this.stop(u,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>ze(u=>{var h;return this.getAnimationState(u)==="paused"&&((h=this.getAxisMotionValue(u).animation)==null?void 0:h.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new dl(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:i,contextWindow:cl(this.visualElement)})}stop(e,n){const i=e||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&&de.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.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(e,n,i){const{drag:s}=this.getProps();if(!i||!Pi(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Bm(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,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;e&&an(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=jm(i.layoutBox,e):this.constraints=!1,this.elastic=Gm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Hm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!an(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Om(i,s.root,this.visualElement.getTransformPagePoint());let r=Um(s.layout.layoutBox,o);if(n){const a=n(Tm(r));this.hasMutatedConstraints=!!a,a&&(r=zc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=ze(d=>{if(!Pi(d,n,this.currentDirection))return;let u=c&&c[d]||{};r&&(u={min:0,max:0});const h=s?200:1e6,g=s?40:1e7,v={type:"inertia",velocity:i?e[d]:0,bounceStiffness:h,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...u};return this.startAxisValueAnimation(d,v)});return Promise.all(l).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return gr(this.visualElement,e),i.start(vr(e,i,0,n,this.visualElement,!1))}stopAnimation(){ze(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ze(e=>{var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.pause()})}getAnimationState(e){var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){ze(n=>{const{drag:i}=this.getProps();if(!Pi(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(e[n]-me(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!an(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};ze(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const c=a.get();s[r]=$m({min:c,max:c},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(),ze(r=>{if(!Pi(r,e,null))return;const a=this.getAxisMotionValue(r),{min:c,max:l}=this.constraints[r];a.set(me(c,l,s[r]))})}addListeners(){if(!this.visualElement.current)return;Wm.set(this.visualElement,this);const e=this.visualElement.current,n=$n(e,"pointerdown",c=>{const{drag:l,dragListener:d=!0}=this.getProps();l&&d&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();an(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),de.read(i);const r=jn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(ze(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=c[d].translate,u.set(u.get()+c[d].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Cr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Pi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function qm(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Km extends Et{constructor(e){super(e),this.removeGroupControls=We,this.removeListeners=We,this.controls=new zm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||We}unmount(){this.removeGroupControls(),this.removeListeners()}}const vl=t=>(e,n)=>{t&&de.postRender(()=>t(e,n))};class Xm extends Et{constructor(){super(...arguments),this.removePointerDownListener=We}onPointerDown(e){this.session=new dl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:cl(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:vl(e),onStart:vl(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&de.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=$n(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Mi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function _l(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Wn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(G.test(t))t=parseFloat(t);else return t;const n=_l(t,e.target.x),i=_l(t,e.target.y);return`${n}% ${i}%`}},Ym={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Tt.parse(t);if(s.length>5)return i;const o=Tt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=c;const l=me(a,c,.5);return typeof s[2+r]=="number"&&(s[2+r]/=l),typeof s[3+r]=="number"&&(s[3+r]/=l),o(s)}};let yl=!1;class Jm extends Je{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Op(Zm),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),yl&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Mi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,yl=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||de.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),sr.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function bl(t){const[e,n]=xc(),i=Se(ys);return E(Jm,{...t,layoutGroup:i,switchLayoutGroup:Se(Pc),isPresent:e,safeToRemove:n})}const Zm={borderRadius:{...Wn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Wn,borderTopRightRadius:Wn,borderBottomLeftRadius:Wn,borderBottomRightRadius:Wn,boxShadow:Ym};function Qm(t,e,n){const i=Re(t)?t:rn(t);return i.start(vr("",i,e,n)),i.animation}const eg=(t,e)=>t.depth-e.depth;class tg{constructor(){this.children=[],this.isDirty=!1}add(e){ws(this.children,e),this.isDirty=!0}remove(e){xs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(eg),this.isDirty=!1,this.children.forEach(e)}}function ng(t,e){const n=Fe.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Ct(i),t(o-e))};return de.setup(i,!0),()=>Ct(i)}const wl=["TopLeft","TopRight","BottomLeft","BottomRight"],ig=wl.length,xl=t=>typeof t=="string"?parseFloat(t):t,Sl=t=>typeof t=="number"||G.test(t);function sg(t,e,n,i,s,o){s?(t.opacity=me(0,n.opacity??1,rg(i)),t.opacityExit=me(e.opacity??1,0,og(i))):o&&(t.opacity=me(e.opacity??1,n.opacity??1,i));for(let r=0;r<ig;r++){const a=`border${wl[r]}Radius`;let c=Cl(e,a),l=Cl(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||Sl(c)===Sl(l)?(t[a]=Math.max(me(xl(c),xl(l),i),0),(ct.test(l)||ct.test(c))&&(t[a]+="%")):t[a]=l}(e.rotate||n.rotate)&&(t.rotate=me(e.rotate||0,n.rotate||0,i))}function Cl(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const rg=kl(0,.5,Sa),og=kl(.5,.95,We);function kl(t,e,n){return i=>i<t?0:i>e?1:n(An(t,e,i))}function Tl(t,e){t.min=e.min,t.max=e.max}function qe(t,e){Tl(t.x,e.x),Tl(t.y,e.y)}function El(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Al(t,e,n,i,s){return t-=e,t=Ri(t,1/n,i),s!==void 0&&(t=Ri(t,1/s,i)),t}function ag(t,e=0,n=1,i=.5,s,o=t,r=t){if(ct.test(e)&&(e=parseFloat(e),e=me(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=me(o.min,o.max,i);t===o&&(a-=e),t.min=Al(t.min,e,n,a,s),t.max=Al(t.max,e,n,a,s)}function Il(t,e,[n,i,s],o,r){ag(t,e[n],e[i],e[s],e.scale,o,r)}const cg=["x","scaleX","originX"],lg=["y","scaleY","originY"];function Rl(t,e,n,i){Il(t.x,e,cg,n?n.x:void 0,i?i.x:void 0),Il(t.y,e,lg,n?n.y:void 0,i?i.y:void 0)}function Pl(t){return t.translate===0&&t.scale===1}function Ml(t){return Pl(t.x)&&Pl(t.y)}function Ll(t,e){return t.min===e.min&&t.max===e.max}function dg(t,e){return Ll(t.x,e.x)&&Ll(t.y,e.y)}function Dl(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ol(t,e){return Dl(t.x,e.x)&&Dl(t.y,e.y)}function Nl(t){return Le(t.x)/Le(t.y)}function Vl(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class ug{constructor(){this.members=[]}add(e){ws(this.members,e),e.scheduleRender()}remove(e){if(xs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===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(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function hg(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:l,rotate:d,rotateX:u,rotateY:h,skewX:g,skewY:v}=n;l&&(i=`perspective(${l}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),h&&(i+=`rotateY(${h}deg) `),g&&(i+=`skewX(${g}deg) `),v&&(i+=`skewY(${v}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const kr=["","X","Y","Z"],fg=1e3;let pg=0;function Tr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function Fl(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Uc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&Fl(i)}function Bl({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=pg++,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(vg),this.nodes.forEach(wg),this.nodes.forEach(xg),this.nodes.forEach(_g)},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 c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new tg)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new ks),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const c=this.eventHandlers.get(r);c&&c.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=wc(r)&&!hp(r),this.instance=r;const{layoutId:a,layout:c,visualElement:l}=this.options;if(l&&!l.current&&l.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let d,u=0;const h=()=>this.root.updateBlockedByResize=!1;de.read(()=>{u=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,d&&d(),d=ng(h,250),Mi.hasAnimatedSinceResize&&(Mi.hasAnimatedSinceResize=!1,this.nodes.forEach($l)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||l.getDefaultTransition()||Eg,{onLayoutAnimationStart:y,onLayoutAnimationComplete:x}=l.getProps(),w=!this.targetLayout||!Ol(this.targetLayout,g),S=!u&&h;if(this.options.layoutRoot||this.resumeFrom||S||u&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...tr(v,"layout"),onPlay:y,onComplete:x};(l.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,S)}else u||$l(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(),Ct(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(Sg),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&&Fl(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:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(jl);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ul);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(bg),this.nodes.forEach(mg),this.nodes.forEach(gg)):this.nodes.forEach(Ul),this.clearAllSnapshots();const a=Fe.now();Ee.delta=gt(0,1e3/60,a-Ee.timestamp),Ee.timestamp=a,Ee.isProcessing=!0,As.update.process(Ee),As.preRender.process(Ee),As.render.process(Ee),Ee.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,sr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(yg),this.sharedNodes.forEach(Cg)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Le(this.snapshot.measuredBox.x)&&!Le(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 c=0;c<this.path.length;c++)this.path[c].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ye(),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 c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Ml(this.projectionDelta),c=this.getTransformTemplate(),l=c?c(this.latestValues,""):void 0,d=l!==this.prevTransformTemplateValue;r&&this.instance&&(a||jt(this.latestValues)||d)&&(s(this.instance,l),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return r&&(c=this.removeTransform(c)),Ag(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var l;const{visualElement:r}=this.options;if(!r)return ye();const a=r.measureViewportBox();if(!(((l=this.scroll)==null?void 0:l.wasRoot)||this.path.some(Ig))){const{scroll:d}=this.root;d&&(ln(a.x,d.offset.x),ln(a.y,d.offset.y))}return a}removeElementScroll(r){var c;const a=ye();if(qe(a,r),(c=this.scroll)!=null&&c.wasRoot)return a;for(let l=0;l<this.path.length;l++){const d=this.path[l],{scroll:u,options:h}=d;d!==this.root&&u&&h.layoutScroll&&(u.wasRoot&&qe(a,r),ln(a.x,u.offset.x),ln(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const c=ye();qe(c,r);for(let l=0;l<this.path.length;l++){const d=this.path[l];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&dn(c,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),jt(d.latestValues)&&dn(c,d.latestValues)}return jt(this.latestValues)&&dn(c,this.latestValues),c}removeTransform(r){const a=ye();qe(a,r);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!jt(l.latestValues))continue;br(l.latestValues)&&l.updateSnapshot();const d=ye(),u=l.measurePageBox();qe(d,u),Rl(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,d)}return jt(this.latestValues)&&Rl(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!==Ee.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(r||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:u}=this.options;if(!(!this.layout||!(d||u))){if(this.resolvedRelativeTargetAt=Ee.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ye(),this.relativeTargetOrigin=ye(),Gn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ye(),this.targetWithTransforms=ye()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Lm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):qe(this.target,this.layout.layoutBox),il(this.target,this.targetDelta)):qe(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=ye(),this.relativeTargetOrigin=ye(),Gn(this.relativeTargetOrigin,this.target,g.target),qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||br(this.parent.latestValues)||el(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 c=!0;if((this.isProjectionDirty||(v=this.parent)!=null&&v.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Ee.timestamp&&(c=!1),c)return;const{layout:l,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||!(l||d))return;qe(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,h=this.treeScale.y;Dm(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=ye());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(El(this.prevProjectionDelta.x,this.projectionDelta.x),El(this.prevProjectionDelta.y,this.projectionDelta.y)),Hn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==h||!Vl(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vl(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 c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=cn(),this.projectionDelta=cn(),this.projectionDeltaWithTransform=cn()}setAnimationOrigin(r,a=!1){const c=this.snapshot,l=c?c.latestValues:{},d={...this.latestValues},u=cn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ye(),g=c?c.source:void 0,v=this.layout?this.layout.source:void 0,y=g!==v,x=this.getStack(),w=!x||x.members.length<=1,S=!!(y&&!w&&this.options.crossfade===!0&&!this.path.some(Tg));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const L=A/1e3;Hl(u.x,r.x,L),Hl(u.y,r.y,L),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Gn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),kg(this.relativeTarget,this.relativeTargetOrigin,h,L),k&&dg(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ye()),qe(k,this.relativeTarget)),y&&(this.animationValues=d,sg(d,l,this.latestValues,L,S,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,c,l;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(l=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||l.stop(),this.pendingAnimation&&(Ct(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{Mi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=rn(0)),this.currentAnimation=Qm(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(fg),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:c,layout:l,latestValues:d}=r;if(!(!a||!c||!l)){if(this!==r&&this.layout&&l&&Kl(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||ye();const u=Le(this.layout.layoutBox.x);c.x.min=r.target.x.min,c.x.max=c.x.min+u;const h=Le(this.layout.layoutBox.y);c.y.min=r.target.y.min,c.y.max=c.y.min+h}qe(a,c),dn(a,d),Hn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new ug),this.sharedNodes.get(r).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.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:c}={}){const l=this.getStack();l&&l.promote(this,c),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:c}=r;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const l={};c.z&&Tr("z",r,l,this.animationValues);for(let d=0;d<kr.length;d++)Tr(`rotate${kr[d]}`,r,l,this.animationValues),Tr(`skew${kr[d]}`,r,l,this.animationValues);r.render();for(const d in l)r.setStaticValue(d,l[d]),this.animationValues&&(this.animationValues[d]=l[d]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Ii(a==null?void 0:a.pointerEvents)||"",r.transform=c?c(this.latestValues,""):"none";return}const l=this.getLead();if(!this.projectionDelta||!this.layout||!l.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Ii(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!jt(this.latestValues)&&(r.transform=c?c({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=l.animationValues||l.latestValues;this.applyTransformsToTarget();let u=hg(this.projectionDeltaWithTransform,this.treeScale,d);c&&(u=c(d,u)),r.transform=u;const{x:h,y:g}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${g.origin*100}% 0`,l.animationValues?r.opacity=l===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=l===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const v in Fn){if(d[v]===void 0)continue;const{correct:y,applyTo:x,isCSSVariable:w}=Fn[v],S=u==="none"?d[v]:y(d[v],l);if(x){const k=x.length;for(let A=0;A<k;A++)r[x[A]]=S}else w?this.options.visualElement.renderState.vars[v]=S:r[v]=S}this.options.layoutId&&(r.pointerEvents=l===this?Ii(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(jl),this.root.sharedNodes.clear()}}}function mg(t){t.updateLayout()}function gg(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?ze(u=>{const h=r?e.measuredBox[u]:e.layoutBox[u],g=Le(h);h.min=i[u].min,h.max=h.min+g}):Kl(o,e.layoutBox,i)&&ze(u=>{const h=r?e.measuredBox[u]:e.layoutBox[u],g=Le(i[u]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+g)});const a=cn();Hn(a,i,e.layoutBox);const c=cn();r?Hn(c,t.applyTransform(s,!0),e.measuredBox):Hn(c,i,e.layoutBox);const l=!Ml(a);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:g}=u;if(h&&g){const v=ye();Gn(v,e.layoutBox,h.layoutBox);const y=ye();Gn(y,i,g.layoutBox),Ol(v,y)||(d=!0),u.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=v,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:c,layoutDelta:a,hasLayoutChanged:l,hasRelativeLayoutChanged:d})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function vg(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function _g(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function yg(t){t.clearSnapshot()}function jl(t){t.clearMeasurements()}function Ul(t){t.isLayoutDirty=!1}function bg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function $l(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function wg(t){t.resolveTargetDelta()}function xg(t){t.calcProjection()}function Sg(t){t.resetSkewAndRotation()}function Cg(t){t.removeLeadSnapshot()}function Hl(t,e,n){t.translate=me(e.translate,0,n),t.scale=me(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Gl(t,e,n,i){t.min=me(e.min,n.min,i),t.max=me(e.max,n.max,i)}function kg(t,e,n,i){Gl(t.x,e.x,n.x,i),Gl(t.y,e.y,n.y,i)}function Tg(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Eg={duration:.45,ease:[.4,0,.1,1]},Wl=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),zl=Wl("applewebkit/")&&!Wl("chrome/")?Math.round:We;function ql(t){t.min=zl(t.min),t.max=zl(t.max)}function Ag(t){ql(t.x),ql(t.y)}function Kl(t,e,n){return t==="position"||t==="preserve-aspect"&&!Mm(Nl(e),Nl(n),.2)}function Ig(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Rg=Bl({attachResizeListener:(t,e)=>jn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Er={current:void 0},Xl=Bl({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Er.current){const t=new Rg({});t.mount(window),t.setOptions({layoutScroll:!0}),Er.current=t}return Er.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Pg={pan:{Feature:Xm},drag:{Feature:Km,ProjectionNode:Xl,MeasureLayout:bl}};function Yl(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,o=i[s];o&&de.postRender(()=>o(e,Un(e)))}class Mg extends Et{mount(){const{current:e}=this.node;e&&(this.unmount=ap(e,(n,i)=>(Yl(this.node,i,"Start"),s=>Yl(this.node,s,"End"))))}unmount(){}}class Lg extends Et{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!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=En(jn(this.node.current,"focus",()=>this.onFocus()),jn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Jl(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),o=i[s];o&&de.postRender(()=>o(e,Un(e)))}class Dg extends Et{mount(){const{current:e}=this.node;e&&(this.unmount=up(e,(n,i)=>(Jl(this.node,i,"Start"),(s,{success:o})=>Jl(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ar=new WeakMap,Ir=new WeakMap,Og=t=>{const e=Ar.get(t.target);e&&e(t)},Ng=t=>{t.forEach(Og)};function Vg({root:t,...e}){const n=t||document;Ir.has(n)||Ir.set(n,{});const i=Ir.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Ng,{root:t,...e})),i[s]}function Fg(t,e,n){const i=Vg(e);return Ar.set(t,n),i.observe(t),()=>{Ar.delete(t),i.unobserve(t)}}const Bg={some:0,all:1};class jg extends Et{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:o}=e,r={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Bg[s]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,o&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),h=l?d:u;h&&h(c)};return Fg(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(Ug(e,n))&&this.startObserver()}unmount(){}}function Ug({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const $g={inView:{Feature:jg},tap:{Feature:Dg},focus:{Feature:Lg},hover:{Feature:Mg}},Hg={layout:{ProjectionNode:Xl,MeasureLayout:bl}},Rr={current:null},Zl={current:!1};function Gg(){if(Zl.current=!0,!!bs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Rr.current=t.matches;t.addEventListener("change",e),e()}else Rr.current=!1}const Wg=new WeakMap;function zg(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Re(s))t.addValue(i,s);else if(Re(o))t.addValue(i,rn(s,{owner:t}));else if(o!==s)if(t.hasValue(i)){const r=t.getValue(i);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(i);t.addValue(i,rn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const Ql=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class qg{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,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=Qs,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 h=Fe.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,de.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=r;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Ai(n),this.isVariantNode=Ac(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(n,{},this);for(const h in u){const g=u[h];c[h]!==void 0&&Re(g)&&g.set(c[h],!1)}}mount(e){this.current=e,Wg.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),Zl.current||Gg(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Rr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Ct(this.notifyUpdate),Ct(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=sn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&de.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in on){const n=on[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];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):ye()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<Ql.length;i++){const s=Ql[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=zg(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]: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(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=rn(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(fa(i)||ma(i))?i=parseFloat(i):!pp(i)&&Tt.test(n)&&(i=hc(e,n)),this.setBaseTarget(e,Re(i)?i.get():i)),Re(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var o;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const r=fr(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);r&&(i=r[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Re(s)?s:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new ks),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class ed extends qg{constructor(){super(...arguments),this.KeyframeResolver=np}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Re(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function td(t,{style:e,vars:n},i,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,i);for(r in n)o.setProperty(r,n[r])}function Kg(t){return window.getComputedStyle(t)}class Xg extends ed{constructor(){super(...arguments),this.type="html",this.renderInstance=td}readValueFromInstance(e,n){var i;if(sn.has(n))return(i=this.projection)!=null&&i.isProjecting?Ks(n):xf(e,n);{const s=Kg(e),o=(Is(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return al(e,n)}build(e,n,i){dr(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return pr(e,n,i)}}const nd=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 Yg(t,e,n,i){td(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(nd.has(s)?s:lr(s),e.attrs[s])}class Jg extends ed{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ye}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(sn.has(n)){const i=uc(n);return i&&i.default||0}return n=nd.has(n)?n:lr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return jc(e,n,i)}build(e,n,i){Oc(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){Yg(e,n,i,s)}mount(e){this.isSVGTag=Vc(e.tagName),super.mount(e)}}const Zg=(t,e)=>hr(t)?new Jg(e):new Xg(e,{allowProjection:t!==it}),Qg=Zp({...Cm,...$g,...Pg,...Hg},Zg),zn=Cp(Qg),ev=["agent-id","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers"],Li="widget-layout-id";function id(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=id(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function _t(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=id(t))&&(i&&(i+=" "),i+=e);return i}const tv=fs("listening"),Pr=()=>ua(tv);function nv(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Di={theme:"dark",audio_visualizer_config:{color:"verdant",preset:"roundBars"},start_call_text:"Let's chat",default_state:"collapsed",position:"fixed",view_history_url:null,report_issue_url:null,give_feedback_url:null,agent_thinking_text:"Thinking...",speak_to_interrupt_text:"Speak to interrupt",logo_icon_url:null},sd=fs(Di),iv=()=>{const t=_s(sd);return St(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Di.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Di.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Di.speak_to_interrupt_text),n}),[t])},Ut=()=>da(sd),rd=({size:t="large",className:e})=>{const n=Ut(),[i]=Pr();return E("h1",{className:_t({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},od=({stream:t})=>{const e=Te(null);return Ve(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),E("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const yv="4.5.1",Nr=Math.PI,un=2*Nr,Vr=Nr/2,ud=8.17579892,hd="dual-combined",Di="dual-horizontal",yt="single",lt="dual-vertical",fd="bar-index",pd="bar-level",Oi="gradient",md=60,gd="click",_v="fullscreenchange",vd="resize",bv="#111",yd="",_d="A",bd="B",wd="C",xd="D",Sd="468",Ni="sans-serif",wv="#0f0",xv="#7f7f7f22",hn=10,Cd="create",kd="fschange",Sv="lores",Cv=vd,Fr="user",kv="#000c",Td="#fff",Tv="#4f4",Ed="#888",Ev="#555",Br="bark",zn="linear",fn="log",jr="mel",Id=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Ad=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Id}],["rainbow",{dir:"h",colorStops:["#817",...Id,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],qn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:yt,colorMode:Oi,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:fn,gradient:Ad[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:yd,width:void 0},Iv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],Av=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Rv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Ur=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Pv=["ERR_INVALID_MODE","Invalid mode"],Mv=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Lv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Dv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Ov=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],Nv=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ke extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Rd=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Pd=t=>{for(const e in t)return!1;return!0},Vi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],Vv=(t,e,n,i,s)=>e+(i-e)*(s-t)/(n-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class Fv{constructor(e,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=[],e instanceof Element||(Pd(n)&&!Pd(e)&&(n=e),e=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[p,m]of Ad)this.registerGradient(p,m);this._container=e||!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 Ke(Iv)}}if(!s.createGain)throw new Ke(Av);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 p of[0,1])r.connect(o[p],p);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const p of["_scaleX","_scaleR"])this[p]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const c=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Cv),this._fsTimeout=0)},md))};window.ResizeObserver&&(this._observer=new ResizeObserver(c),this._observer.observe(this._container)),this._controller=new AbortController;const d=this._controller.signal;window.addEventListener(vd,c,{signal:d}),i.addEventListener(_v,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(kd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},md)},{signal:d});const f=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(gd,f))};window.addEventListener(gd,f),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:d}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Cd)}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=Vi(e,[yt,Di,lt,hd]),this._input.disconnect(),this._input.connect(this._chLayout!=yt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=yt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Vi(e,[Oi,fd,pd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const i of[0,1])this._analyzer[i].fftSize=e;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=Vi(e,[fn,Br,jr,zn]),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||qn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Fr)}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(Sv)}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 n of[0,1])this._analyzer[n].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 Ke(Ur);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const n of[0,1])this._analyzer[n].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new Ke(Ur);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 n=e|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new Ke(Pv,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||qn.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 Ke(Mv);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 n of[0,1])this._analyzer[n].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Vr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Rd("stereo","channelLayout"),this._chLayout!=yt}set stereo(e){Rd("stereo","channelLayout"),this.channelLayout=e?lt:yt}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=Vi(e,[yd,_d,bd,wd,xd,Sd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Fr)}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 yv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ke(Lv);const i=n?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==yt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:c,_splitter:d}=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(),d.disconnect(),o.disconnect(),c&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){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(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==yt?1:2;let r=0;for(let a=0;a<o;a++)for(let c=i;c<=s;c++)r+=this._normalizedB(this._fftData[a][c]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(qn))e.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(e,n){if(typeof e!="string"||e.trim().length==0)throw new Ke(Dv);if(typeof n!="object")throw new Ke(Ov);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ke(Nv);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const c=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:c,color:r}:o(r.pos)&&(r.pos=c),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[e]={bgColor:n.bgColor||bv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Fr)}setFreqRange(e,n){if(e<1||n<1)throw new Ke(Ur);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!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 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:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:c,_mode:d,_radial:f,_radialInvert:p,_reflexRatio:m}=this,v=s.width>>1,_=s.height>>1,C=o==lt&&!f,S=o==Di,w=d%10!=0,T=w&&this._frequencyScale==fn,I=this._showLeds&&w&&!f,R=this._lumiBars&&w&&!f,L=this._alphaBars&&!R&&d!=hn,D=this._outlineBars&&w&&!R&&!I,b=this._roundBars&&w&&!R&&!I,k=o!=lt||m>0&&!R,l=s.height-(C&&!I?.5:0)>>C,u=l*(R||f?1:1-m)|0,h=s.width-v*(S||c!=0),g=C?s.height-l*2:0,y=v*(c==-1&&!S&&!f);let E=Math.min(s.width,s.height)*.375*(o==lt?1:this._radius)|0,x=Math.min(v,_);p&&o!=lt&&([E,x]=[x,E]);const A=U=>e.push({...U,peak:[0,0],hold:[0],alpha:[0],value:[0]}),P=U=>{const W=this._freqToBin(U,"floor"),Y=this._binToFreq(W),Q=this._binToFreq(W+1),ue=Math.log2(U/Y)/Math.log2(Q/Y);return[W,ue]};let V,H,N;if(T){const U=(oe,fe,re)=>+oe.toPrecision(re?Math.max(fe,1+Math.log10(oe)|0):fe),W=oe=>{const fe=[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],re=Math.log10(oe)|0,dt=oe/10**re;let et=1;for(;et<fe.length&&dt>fe[et];)et++;return dt-fe[et-1]<fe[et]-dt&&et--,(fe[et]*10**(re+5)|0)/1e5},Y=[0,24,12,8,6,4,3,2,1][d],Q=n?10**(3/(Y*10)):2**(1/Y),ue=Q**.5;let Oe=n?7.94328235/(Y%2?1:ue):ud;do{let oe=Oe;const fe=U(oe/ue,4,!0),re=U(oe*ue,4,!0),[dt,et]=P(fe),[ni,ut]=P(re);n?oe=Y<4?W(oe):U(oe,oe.toString()[0]<5?3:2):oe=U(oe,4,!0),oe>=a&&A({posX:0,freq:oe,freqLo:fe,freqHi:re,binLo:dt,binHi:ni,ratioLo:et,ratioHi:ut}),Oe*=Q}while(Oe<=r);V=h/e.length,e.forEach((oe,fe)=>oe.posX=y+fe*V);const he=e[0],Me=e[e.length-1];H=this._freqScaling(he.freqLo),N=h/(this._freqScaling(Me.freqHi)-H),he.freqLo<a&&(he.freqLo=a,[he.binLo,he.ratioLo]=P(a)),Me.freqHi>r&&(Me.freqHi=r,[Me.binHi,Me.ratioHi]=P(r))}else if(w){const U=[0,24,12,8,6,4,3,2,1][d]*10,W=Y=>{switch(this._frequencyScale){case Br:return 1960/(26.81/(Y+.53)-1);case jr:return 700*(2**Y-1);case zn:return Y}};V=h/U,H=this._freqScaling(a),N=h/(this._freqScaling(r)-H);for(let Y=0,Q=0;Y<U;Y++,Q+=V){const ue=W(H+Q/N),Oe=W(H+(Q+V/2)/N),he=W(H+(Q+V)/N),[Me,oe]=P(ue),[fe,re]=P(he);A({posX:y+Q,freq:Oe,freqLo:ue,freqHi:he,binLo:Me,binHi:fe,ratioLo:oe,ratioHi:re})}}else{V=1,H=this._freqScaling(a),N=h/(this._freqScaling(r)-H);const U=this._freqToBin(a,"floor"),W=this._freqToBin(r);let Y=-999;for(let Q=U;Q<=W;Q++){const ue=this._binToFreq(Q),Oe=y+Math.round(N*(this._freqScaling(ue)-H));if(Oe>Y)A({posX:Oe,freq:ue,freqLo:ue,freqHi:ue,binLo:Q,binHi:Q,ratioLo:0,ratioHi:0}),Y=Oe;else if(e.length){const he=e[e.length-1];he.binHi=Q,he.freqHi=ue,he.freq=(he.freqLo*ue)**.5}}}let ne=0,G=0;if(I){const U=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),W=[[],[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,[Q,ue,Oe]=Y||W[d];let he,Me=u;if(Y){const oe=2*U;let fe;he=Q+1;do he--,fe=Me/he/(1+ue),G=fe*ue;while((fe<oe||G<oe)&&he>1)}else{const oe=540/ue;G=Math.min(ue*U,Math.max(2,Me/oe+.1|0))}k&&(Me+=G),Y||(he=Math.min(Q,Me/(G*2)|0)),ne=Oe>=1?Oe:V*Oe,this._leds=[he,ne,G,Me/he-G]}const F=Math.min(V-1,i*(i>0&&i<1?V:1));w&&(V-=Math.max(I?ne:0,F)),e.forEach((U,W)=>{let Y=U.posX,Q=V;w&&(i==0&&!I?(Y|=0,Q|=0,W>0&&Y>e[W-1].posX+e[W-1].width&&(Y--,Q++)):Y+=Math.max(I?ne:0,F)/2,U.posX=Y),U.barCenter=Y+(V==1?0:Q/2),U.width=Q});const te=[];for(const U of[0,1]){const W=o==lt?(l+g)*U:0,Y=W+l,Q=W+u-(!I||k?0:G);te.push({channelTop:W,channelBottom:Y,analyzerBottom:Q})}this._aux={analyzerHeight:u,analyzerWidth:h,centerX:v,centerY:_,channelCoords:te,channelHeight:l,channelGap:g,initialX:y,innerRadius:E,outerRadius:x,scaleMin:H,unitWidth:N},this._flg={isAlpha:L,isBands:w,isLeds:I,isLumi:R,isOctaves:T,isOutline:D,isRound:b,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:c,_noteLabels:d,_radial:f,_scaleX:p,_scaleR:m}=this,v=p.canvas,_=m.canvas,C=[],S=this._chLayout==Di,w=this._chLayout==lt,T=Math.min(r.width,r.height),I=["C",,"D",,"E","F",,"G",,"A",,"B"],R=T/34|0,L=v.height>>1,D=R>>1,b=L*(d?.7:1.5),k=D*(d?1:2),l=2**(1/12);if(!d&&(this._ansiBands||a!=fn))C.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==zn?C.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):C.push(8e3,16e3);else{let x=ud;for(let A=-1;A<11;A++)for(let P=0;P<12;P++){if(x>=this._minFreq&&x<=this._maxFreq){const V=I[P],H=V=="C";(V&&d&&!c&&!S||H)&&C.push(d?[x,V+(H?A:"")]:x)}x*=l}}_.width=_.height=Math.max(T*.15,(i<<1)+w*R);const u=_.width>>1,h=u-R*.7,g=(x,A)=>{const P=un*(x/r.width),V=P-Vr,H=h*Math.cos(V),N=h*Math.sin(V);m.save(),m.translate(u+H,u+N),m.rotate(P),m.fillText(A,0,0),m.restore()};v.width|=0,p.fillStyle=m.strokeStyle=kv,p.fillRect(0,0,v.width,v.height),m.arc(u,u,u-R/2,0,un),m.lineWidth=R,m.stroke(),p.fillStyle=m.fillStyle=Td,p.font=`${L}px ${Ni}`,m.font=`${D}px ${Ni}`,p.textAlign=m.textAlign="center";let y=-b/4,E=-k;for(const x of C){const[A,P]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],V=o*(this._freqScaling(A)-s),H=v.height*.75,N=P[0]=="C",ne=L*(d&&!c&&!S?N?1.2:.6:3);if(p.fillStyle=m.fillStyle=N&&!c&&!S?Tv:Td,d){const G=a==fn,F=a==zn;let te=["C"];if((G||A>2e3||!F&&A>250||(!f||w)&&(!F&&A>125||A>1e3))&&te.push("G"),(G||A>4e3||!F&&A>500||(!f||w)&&(!F&&A>250||A>2e3))&&te.push("E"),(F&&A>4e3||(!f||w)&&(G||A>2e3||!F&&A>500))&&te.push("D","F","A","B"),!te.includes(P[0]))continue}V>=y+b/2&&V<=e&&(p.fillText(P,S&&c==-1?e-V:n+V,H,ne),(S||c&&(V>b||c==1))&&p.fillText(P,S&&c!=1?e+V:(n||r.width)-V,H,ne),y=V+Math.min(ne,p.measureText(P).width)/2),V>=E+k&&V<e-k&&(g(S&&c==1?e-V:V,P),(S||c&&(V>k||c==1))&&g(S&&c!=-1?e+V:-V,P),E=V)}}_draw(e){this._runId=requestAnimationFrame(B=>this._draw(B));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:c,isOctaves:d,isOutline:f,isRound:p,noLedGap:m}=this._flg,{analyzerHeight:v,centerX:_,centerY:C,channelCoords:S,channelHeight:w,channelGap:T,initialX:I,innerRadius:R,outerRadius:L}=this._aux,{_bars:D,canvas:b,_canvasGradients:k,_chLayout:l,_colorMode:u,_ctx:h,_energy:g,_fadePeaks:y,fillAlpha:E,_fps:x,_linearAmplitude:A,_lineWidth:P,maxDecibels:V,minDecibels:H,_mirror:N,_mode:ne,overlay:G,_radial:F,showBgColor:te,showPeaks:U,useCanvas:W,_weightingFilter:Y}=this,Q=this._scaleX.canvas,ue=this._scaleR.canvas,Oe=x*this._peakFadeTime/1e3,he=x**2,Me=this._gravity*1e3,oe=x*this._peakHoldTime/1e3,fe=l==hd,re=l==Di,dt=l==lt,et=l==yt,ni=a&&this._trueLeds&&u==Oi,ut=F?b.width:this._aux.analyzerWidth,to=I+ut,ii=U&&this._peakLine&&ne==hn,At=F?L-R:v,R_=At/this._pixelRatio,[P_,U_,si,no]=this._leds||[];g.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*un/60/x);const M_=B=>{if(this._reflexRatio>0&&!c&&!F){let se,ht;this.reflexFit||dt?(se=dt&&B==0?w+T:0,ht=w-v):(se=b.height-v*2,ht=v),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,b.height),h.drawImage(b,0,S[B].channelTop,b.width,v,0,se,b.width,ht),h.restore()}},L_=()=>{this.showScaleX&&(F?(h.save(),h.translate(_,C),this._spinSpeed&&h.rotate(this._spinAngle+Vr),h.drawImage(ue,-ue.width>>1,-ue.width>>1),h.restore()):h.drawImage(Q,0,b.height-Q.height))},D_=B=>{const se=B**2,ht=424.36,Ie=11599.29,Zi=25122.25,Rt=544496.41,wt=148693636,qt=Kt=>20*Math.log10(Kt);switch(Y){case _d:const Kt=wt*se**2/((se+ht)*Math.sqrt((se+Ie)*(se+Rt))*(se+wt));return 2+qt(Kt);case bd:const Xt=wt*se*B/((se+ht)*Math.sqrt(se+Zi)*(se+wt));return .17+qt(Xt);case wd:const ro=wt*se/((se+ht)*(se+wt));return .06+qt(ro);case xd:const Ji=((103791848e-2-se)**2+108076816e-2*se)/((9837328-se)**2+11723776*se),oo=B/68966888496476e-18*Math.sqrt(Ji/((se+79919.29)*(se+1345600)));return qt(oo);case Sd:const Qi=-4737338981378384e-39*B**6+2043828333606125e-30*B**4-1363894795463638e-22*se+1,Yt=1306612257412824e-34*B**5-2118150887518656e-26*B**3+.0005559488023498642*B,Ge=.0001246332637532143*B/Math.hypot(Qi,Yt);return 18.2+qt(Ge)}return 0},io=(B,se,ht)=>{h.beginPath(),h.moveTo(B,se),h.lineTo(B,ht),h.stroke()},so=B=>{if(B&&P){const se=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=se}},zt=B=>Math.max(0,(B*P_|0)*(no+si)-si),O_=B=>{g.val=B,g.peak>0&&(g.hold--,g.hold<0&&(g.peak+=g.hold*Me/he/b.height*this._pixelRatio)),B>=g.peak&&(g.peak=B,g.hold=oe)};G&&h.clearRect(0,0,b.width,b.height);let Bu=0;const ju=D.length,Uu=et?1:2;for(let B=0;B<Uu;B++){const{channelTop:se,channelBottom:ht,analyzerBottom:Ie}=S[B],Zi=this._gradients[this._selectedGrads[B]],Rt=Zi.colorStops,wt=Rt.length,qt=!te||a&&!G?"#000":Zi.bgColor,Kt=dt&&F&&B?-1:1,Xt=!B&&N==-1||B&&N==1,ro=!re||B&&N!=1?0:ut>>(B||!Xt),Ji=re&&Xt?-1:1,oo=()=>{const z=Q.height,X=z>>1,J=A?100:V,le=A?0:H,we=A?20:5,Ue=v/(J-le),ft=N!=-1&&(!re||B==0||N==1),Pt=N!=1&&(!re||B!=N);h.save(),h.fillStyle=Ed,h.font=`${X}px ${Ni}`,h.textAlign="right",h.lineWidth=1;for(let Mt=J;Mt>le;Mt-=we){const yn=se+(J-Mt)*Ue,Se=Mt%2==0|0;if(Se){const Ne=yn+X*(yn==se?.8:.35);ft&&h.fillText(Mt,z*.85,Ne),Pt&&h.fillText(Mt,(re?ut:b.width)-z*.1,Ne),h.strokeStyle=Ed,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=Ev,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(I+z*Se*ft,~~yn+.5),h.lineTo(to-z*Se*Pt,~~yn+.5),h.stroke()}h.restore()},Qi=(z,X)=>{const J=tt[z]+(z<tt.length-1?(tt[z+1]-tt[z])*X:0);return isNaN(J)?-1/0:J},Yt=(z,X=Ji)=>X*un*((z+ro)/b.width)+this._spinAngle,Ge=(z,X,J)=>{const le=R+X*Kt,we=Yt(z,J);return[_+le*Math.cos(we),C+le*Math.sin(we)]},ao=(z,X,J,le,we)=>{h.beginPath();for(const Ue of N&&!re?[1,-1]:[Ji]){const[ft,Pt]=p?[Yt(z,Ue),Yt(z+J,Ue)]:[];h.moveTo(...Ge(z,X,Ue)),h.lineTo(...Ge(z,X+le,Ue)),p?h.arc(_,C,R+(X+le)*Kt,ft,Pt,Ue!=1):h.lineTo(...Ge(z+J,X+le,Ue)),h.lineTo(...Ge(z+J,X,Ue)),p&&!we&&h.arc(_,C,R+X*Kt,Pt,ft,Ue==1)}so(we),h.fill()},co=(z=0,X=0)=>{let J;if(u==Oi&&!ni||ne==hn)J=k[B];else{const le=u==fd?X%wt:Rt.findLastIndex(we=>a?zt(z)<=zt(we.level):z<=we.level);J=Rt[le].color}h.fillStyle=h.strokeStyle=J};if(W){if(re&&!F){const z=ut*(B+Xt),X=Xt?-1:1;h.setTransform(X,0,0,1,z,0)}if((!G||te)&&(G&&(h.globalAlpha=this.bgAlpha),h.fillStyle=qt,(B==0||!F&&!fe)&&h.fillRect(I,se-T,ut,(G&&this.reflexAlpha==1?v:w)+T),h.globalAlpha=1),this.showScaleY&&!c&&!F&&(B==0||!fe)&&oo(),a?(h.setLineDash([no,si]),h.lineWidth=D[0].width):h.lineWidth=f?Math.min(P,D[0].width/2):P,h.save(),!F){const z=new Path2D;z.rect(0,se,b.width,v),h.clip(z)}}let tt=this._fftData[B];this._analyzer[B].getFloatFrequencyData(tt),Y&&(tt=tt.map((z,X)=>z+D_(this._binToFreq(X)))),h.beginPath();let ri=[];for(let z=0;z<ju;z++){const X=D[z],{posX:J,barCenter:le,width:we,freq:Ue,binLo:ft,binHi:Pt,ratioLo:Mt,ratioHi:yn}=X;let Se=Math.max(Qi(ft,Mt),Qi(Pt,yn));for(let ae=ft+1;ae<Pt;ae++)tt[ae]>Se&&(Se=tt[ae]);if(Se=this._normalizedB(Se),X.value[B]=Se,Bu+=Se,X.peak[B]>0&&X.alpha[B]>0&&(X.hold[B]--,X.hold[B]<0)){if(y&&!ii){const ae=!o||f&&P>0?1:o?X.peak[B]:E;X.alpha[B]=ae*(1+X.hold[B]/Oe)}else X.peak[B]+=X.hold[B]*Me/he/R_;X.alpha[B]<=0&&(X.peak[B]=0)}if(Se>=X.peak[B]&&(X.peak[B]=Se,X.hold[B]=oe,X.alpha[B]=!o||f&&P>0?1:o?Se:E),!W)continue;h.globalAlpha=c||o?Se:f?E:1,co(Se,z);const Ne=c?At:a?zt(Se):Se*At|0;if(ne==hn){const ae=z?0:(this._normalizedB(tt[D[1].binLo])*At+Ne)/2;if(F){if(z==0&&(re&&h.moveTo(...Ge(0,0)),h.lineTo(...Ge(0,J<0?ae:Ne))),J>=0){const Xe=[J,Ne];h.lineTo(...Ge(...Xe)),ri.push(Xe)}}else{if(z==0)if(N==-1&&!re)h.moveTo(I,Ie-(J<I?ae:Ne));else{const Xe=ft?this._normalizedB(tt[ft-1])*At:Ne;h.moveTo(I-P,Ie-Xe)}(re||N!=-1||J>=I)&&h.lineTo(J,Ie-Ne)}}else if(a){if(te&&!G&&(B==0||!fe)){const ae=h.globalAlpha;h.strokeStyle=xv,h.globalAlpha=1,io(le,se,Ie),h.strokeStyle=h.fillStyle,h.globalAlpha=ae}if(ni){const ae=c?0:Rt.findLastIndex(Zt=>zt(Se)<=zt(Zt.level));let Xe=Ie;for(let Zt=wt-1;Zt>=ae;Zt--){h.strokeStyle=Rt[Zt].color;let Gu=Ie-(Zt==ae?Ne:zt(Rt[Zt].level));io(le,Xe,Gu),Xe=Gu-si}}else io(le,Ie,Ie-Ne)}else if(J>=I)if(F)ao(J,0,we,Ne,f);else if(p){const ae=we/2,Xe=Ie+ae;h.beginPath(),h.moveTo(J,Xe),h.lineTo(J,Xe-Ne),h.arc(le,Xe-Ne,ae,Nr,un),h.lineTo(J+we,Xe),so(f),h.fill()}else{const ae=f?h.lineWidth:0;h.beginPath(),h.rect(J,Ie+ae,we,-Ne-ae),so(f),h.fill()}const _n=X.peak[B],$u=X.alpha[B];if(_n>0&&$u>0&&U&&!ii&&!c&&J>=I&&J<to){if(y?h.globalAlpha=$u:f&&P>0?h.globalAlpha=1:o&&(h.globalAlpha=_n),(u==pd||ni)&&co(_n),a){const ae=zt(_n);ae>=si&&h.fillRect(J,Ie-ae,we,no)}else if(!F)h.fillRect(J,Ie-_n*At,we,2);else if(ne!=hn){const ae=_n*At;ao(J,ae,we,!this._radialInvert||dt||ae+R>=2?-2:2)}}}if(W){if(h.globalAlpha=1,ne==hn){if(co(),F&&!re){if(N){let z;for(;z=ri.pop();)h.lineTo(...Ge(...z,-1))}h.closePath()}if(P>0&&h.stroke(),E>0){if(F){const z=re?Yt(ut>>1):0,X=re?Yt(ut):un;h.moveTo(...Ge(re?ut>>1:0,0)),h.arc(_,C,R,z,X,re?!Xt:!0)}else h.lineTo(to,Ie),h.lineTo(I,Ie);h.globalAlpha=E,h.fill(),h.globalAlpha=1}if((ii||F&&U)&&(ri=[],h.beginPath(),D.forEach((z,X)=>{let J=z.posX,le=z.peak[B],we=X?"lineTo":"moveTo";if(F&&J<0){const Ue=D[X+1];le=Vv(J,le,Ue.posX,Ue.peak[B],0),J=0}le*=At,ii?(h[we](...F?Ge(J,le):[J,Ie-le]),F&&N&&!re&&ri.push([J,le])):le>0&&ao(J,le,1,-2)}),ii)){let z;for(;z=ri.pop();)h.lineTo(...Ge(...z,-1));h.lineWidth=1,h.stroke()}}h.restore(),re&&!F&&h.setTransform(1,0,0,1,0,0),(!re&&!fe||B)&&M_(B)}}if(O_(Bu/(ju<<Uu-1)),W&&(N&&!F&&!re&&(h.setTransform(-1,0,0,1,b.width-I,0),h.drawImage(b,I,0,_,b.height,0,0,_,b.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),L_()),this.showFPS){const B=Q.height;h.font=`bold ${B}px ${Ni}`,h.fillStyle=wv,h.textAlign="right",h.fillText(Math.round(x),b.width-B,B*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case fn:return Math.log2(e);case Br:return 26.81*e/(1960+e)-.53;case jr:return Math.log2(1+e/700);case zn:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:c,innerRadius:d,outerRadius:f}=this._aux,{isLumi:p}=this._flg,m=this._chLayout==lt,v=1-s,_=p?e.height:e.height*(1-s*!m)|0;for(const C of[0,1]){const S=this._gradients[this._selectedGrads[C]],w=S.colorStops,T=S.dir=="h";let I;if(i?I=n.createRadialGradient(r,a,f,r,a,d-(f-d)*m):I=n.createLinearGradient(...T?[c,0,c+o,0]:[0,0,0,_]),w){const R=m&&!this._splitGradient&&(!T||i);for(let L=0;L<1+R;L++){const D=w.length-1;w.forEach((b,k)=>{let l=b.pos;if(R&&(l/=2),m&&!p&&!i&&!T&&(l*=v,!R&&l>.5*v&&(l+=.5*s)),L==1)if(i||p){const u=D-k;b=w[u],l=1-b.pos/2}else k==0&&l>0&&I.addColorStop(.5,b.color),l+=.5;I.addColorStop(l,b.color),m&&k==D&&l<.5&&I.addColorStop(.5,b.color)})}}this._canvasGradients[C]=I}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(c,d,f)=>c<=d?d:c>=f?f:c,o=c=>10**(c/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){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 c=this.isFullscreen,d=c&&this._fsEl==n,f=d?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,p=d?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Cd&&n.width==f&&n.height==p)&&(n.width=f,n.height=p,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,f,p)),i.lineJoin="bevel",s.width=f,s.height=Math.max(20*o,Math.min(f,p)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==c&&(e=kd),this._fsStatus=c,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Ke(Rv,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(qn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...qn,...e});for(const r of Object.keys(e))i.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 Bv={verdant:{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]},twilight:{colorStops:[{color:"#81B9FF",pos:0},{color:"#371A5E",pos:.5},{color:"#81B9FF",pos:1}]},bloom:{colorStops:[{color:"#FFD4FE",pos:0},{color:"#FD05F9",pos:.5},{color:"#FFD4FE",pos:1}]},mystic:{colorStops:[{color:"#1F023A",pos:0},{color:"#CA76FF",pos:.5},{color:"#1F023A",pos:1}]},flare:{colorStops:[{color:"#FFFFFF",pos:0},{color:"#FC5F00",pos:.5},{color:"#FFFFFF",pos:1}]},glacier:{colorStops:[{color:"#4CE5F2",pos:0},{color:"#005A98",pos:.5},{color:"#4CE5F2",pos:1}]}},Md=({stream:t,className:e,onClick:n})=>{var o;const i=ke(null),s=Ut();return Ve(()=>{var d;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),c=new Fv(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",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:!0,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 c.registerGradient("gradient",Bv[((d=s.audio_visualizer_config)==null?void 0:d.color)||"verdant"]),c.gradient="gradient",()=>{c.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),M("div",{onClick:n,className:vt("w-full",e),ref:i})};/**
16
+ */const sv="4.5.1",Mr=Math.PI,un=2*Mr,Lr=Mr/2,ad=8.17579892,cd="dual-combined",Oi="dual-horizontal",yt="single",lt="dual-vertical",ld="bar-index",dd="bar-level",Ni="gradient",ud=60,hd="click",rv="fullscreenchange",fd="resize",ov="#111",pd="",md="A",gd="B",vd="C",_d="D",yd="468",Vi="sans-serif",av="#0f0",cv="#7f7f7f22",hn=10,bd="create",wd="fschange",lv="lores",dv=fd,Dr="user",uv="#000c",xd="#fff",hv="#4f4",Sd="#888",fv="#555",Or="bark",qn="linear",fn="log",Nr="mel",Cd=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],kd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Cd}],["rainbow",{dir:"h",colorStops:["#817",...Cd,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Kn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:yt,colorMode:Ni,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:fn,gradient:kd[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:pd,width:void 0},pv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],mv=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],gv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Vr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],vv=["ERR_INVALID_MODE","Invalid mode"],_v=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],yv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],bv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],wv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],xv=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ke extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Td=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Ed=t=>{for(const e in t)return!1;return!0},Fi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],Sv=(t,e,n,i,s)=>e+(i-e)*(s-t)/(n-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class Cv{constructor(e,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=[],e instanceof Element||(Ed(n)&&!Ed(e)&&(n=e),e=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,h]of kd)this.registerGradient(u,h);this._container=e||!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 Ke(pv)}}if(!s.createGain)throw new Ke(mv);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 c=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(dv),this._fsTimeout=0)},ud))};window.ResizeObserver&&(this._observer=new ResizeObserver(c),this._observer.observe(this._container)),this._controller=new AbortController;const l=this._controller.signal;window.addEventListener(fd,c,{signal:l}),i.addEventListener(rv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(wd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},ud)},{signal:l});const d=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(hd,d))};window.addEventListener(hd,d),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:l}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(bd)}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=Fi(e,[yt,Oi,lt,cd]),this._input.disconnect(),this._input.connect(this._chLayout!=yt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=yt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Fi(e,[Ni,ld,dd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const i of[0,1])this._analyzer[i].fftSize=e;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=Fi(e,[fn,Or,Nr,qn]),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||Kn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Dr)}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(lv)}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 n of[0,1])this._analyzer[n].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 Ke(Vr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const n of[0,1])this._analyzer[n].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new Ke(Vr);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 n=e|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new Ke(vv,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||Kn.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 Ke(_v);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 n of[0,1])this._analyzer[n].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Lr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Td("stereo","channelLayout"),this._chLayout!=yt}set stereo(e){Td("stereo","channelLayout"),this.channelLayout=e?lt:yt}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=Fi(e,[pd,md,gd,vd,_d,yd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,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 sv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ke(yv);const i=n?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==yt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:c,_splitter:l}=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(),l.disconnect(),o.disconnect(),c&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){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(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==yt?1:2;let r=0;for(let a=0;a<o;a++)for(let c=i;c<=s;c++)r+=this._normalizedB(this._fftData[a][c]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Kn))e.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(e,n){if(typeof e!="string"||e.trim().length==0)throw new Ke(bv);if(typeof n!="object")throw new Ke(wv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ke(xv);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const c=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:c,color:r}:o(r.pos)&&(r.pos=c),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[e]={bgColor:n.bgColor||ov,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Dr)}setFreqRange(e,n){if(e<1||n<1)throw new Ke(Vr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!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 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:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:c,_mode:l,_radial:d,_radialInvert:u,_reflexRatio:h}=this,g=s.width>>1,v=s.height>>1,y=o==lt&&!d,x=o==Oi,w=l%10!=0,S=w&&this._frequencyScale==fn,k=this._showLeds&&w&&!d,A=this._lumiBars&&w&&!d,L=this._alphaBars&&!A&&l!=hn,O=this._outlineBars&&w&&!A&&!k,b=this._roundBars&&w&&!A&&!k,C=o!=lt||h>0&&!A,f=s.height-(y&&!k?.5:0)>>y,m=f*(A||d?1:1-h)|0,p=s.width-g*(x||c!=0),_=y?s.height-f*2:0,T=g*(c==-1&&!x&&!d);let P=Math.min(s.width,s.height)*.375*(o==lt?1:this._radius)|0,I=Math.min(g,v);u&&o!=lt&&([P,I]=[I,P]);const D=q=>e.push({...q,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=q=>{const J=this._freqToBin(q,"floor"),Z=this._binToFreq(J),ee=this._binToFreq(J+1),ue=Math.log2(q/Z)/Math.log2(ee/Z);return[J,ue]};let V,X,B;if(S){const q=(se,fe,ie)=>+se.toPrecision(ie?Math.max(fe,1+Math.log10(se)|0):fe),J=se=>{const fe=[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],ie=Math.log10(se)|0,ut=se/10**ie;let et=1;for(;et<fe.length&&ut>fe[et];)et++;return ut-fe[et-1]<fe[et]-ut&&et--,(fe[et]*10**(ie+5)|0)/1e5},Z=[0,24,12,8,6,4,3,2,1][l],ee=n?10**(3/(Z*10)):2**(1/Z),ue=ee**.5;let Oe=n?7.94328235/(Z%2?1:ue):ad;do{let se=Oe;const fe=q(se/ue,4,!0),ie=q(se*ue,4,!0),[ut,et]=M(fe),[ii,ht]=M(ie);n?se=Z<4?J(se):q(se,se.toString()[0]<5?3:2):se=q(se,4,!0),se>=a&&D({posX:0,freq:se,freqLo:fe,freqHi:ie,binLo:ut,binHi:ii,ratioLo:et,ratioHi:ht}),Oe*=ee}while(Oe<=r);V=p/e.length,e.forEach((se,fe)=>se.posX=T+fe*V);const he=e[0],Me=e[e.length-1];X=this._freqScaling(he.freqLo),B=p/(this._freqScaling(Me.freqHi)-X),he.freqLo<a&&(he.freqLo=a,[he.binLo,he.ratioLo]=M(a)),Me.freqHi>r&&(Me.freqHi=r,[Me.binHi,Me.ratioHi]=M(r))}else if(w){const q=[0,24,12,8,6,4,3,2,1][l]*10,J=Z=>{switch(this._frequencyScale){case Or:return 1960/(26.81/(Z+.53)-1);case Nr:return 700*(2**Z-1);case qn:return Z}};V=p/q,X=this._freqScaling(a),B=p/(this._freqScaling(r)-X);for(let Z=0,ee=0;Z<q;Z++,ee+=V){const ue=J(X+ee/B),Oe=J(X+(ee+V/2)/B),he=J(X+(ee+V)/B),[Me,se]=M(ue),[fe,ie]=M(he);D({posX:T+ee,freq:Oe,freqLo:ue,freqHi:he,binLo:Me,binHi:fe,ratioLo:se,ratioHi:ie})}}else{V=1,X=this._freqScaling(a),B=p/(this._freqScaling(r)-X);const q=this._freqToBin(a,"floor"),J=this._freqToBin(r);let Z=-999;for(let ee=q;ee<=J;ee++){const ue=this._binToFreq(ee),Oe=T+Math.round(B*(this._freqScaling(ue)-X));if(Oe>Z)D({posX:Oe,freq:ue,freqLo:ue,freqHi:ue,binLo:ee,binHi:ee,ratioLo:0,ratioHi:0}),Z=Oe;else if(e.length){const he=e[e.length-1];he.binHi=ee,he.freqHi=ue,he.freq=(he.freqLo*ue)**.5}}}let re=0,Q=0;if(k){const q=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),J=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Z=this._ledParams,[ee,ue,Oe]=Z||J[l];let he,Me=m;if(Z){const se=2*q;let fe;he=ee+1;do he--,fe=Me/he/(1+ue),Q=fe*ue;while((fe<se||Q<se)&&he>1)}else{const se=540/ue;Q=Math.min(ue*q,Math.max(2,Me/se+.1|0))}C&&(Me+=Q),Z||(he=Math.min(ee,Me/(Q*2)|0)),re=Oe>=1?Oe:V*Oe,this._leds=[he,re,Q,Me/he-Q]}const U=Math.min(V-1,i*(i>0&&i<1?V:1));w&&(V-=Math.max(k?re:0,U)),e.forEach((q,J)=>{let Z=q.posX,ee=V;w&&(i==0&&!k?(Z|=0,ee|=0,J>0&&Z>e[J-1].posX+e[J-1].width&&(Z--,ee++)):Z+=Math.max(k?re:0,U)/2,q.posX=Z),q.barCenter=Z+(V==1?0:ee/2),q.width=ee});const ce=[];for(const q of[0,1]){const J=o==lt?(f+_)*q:0,Z=J+f,ee=J+m-(!k||C?0:Q);ce.push({channelTop:J,channelBottom:Z,analyzerBottom:ee})}this._aux={analyzerHeight:m,analyzerWidth:p,centerX:g,centerY:v,channelCoords:ce,channelHeight:f,channelGap:_,initialX:T,innerRadius:P,outerRadius:I,scaleMin:X,unitWidth:B},this._flg={isAlpha:L,isBands:w,isLeds:k,isLumi:A,isOctaves:S,isOutline:O,isRound:b,noLedGap:C},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:c,_noteLabels:l,_radial:d,_scaleX:u,_scaleR:h}=this,g=u.canvas,v=h.canvas,y=[],x=this._chLayout==Oi,w=this._chLayout==lt,S=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=S/34|0,L=g.height>>1,O=A>>1,b=L*(l?.7:1.5),C=O*(l?1:2),f=2**(1/12);if(!l&&(this._ansiBands||a!=fn))y.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==qn?y.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):y.push(8e3,16e3);else{let I=ad;for(let D=-1;D<11;D++)for(let M=0;M<12;M++){if(I>=this._minFreq&&I<=this._maxFreq){const V=k[M],X=V=="C";(V&&l&&!c&&!x||X)&&y.push(l?[I,V+(X?D:"")]:I)}I*=f}}v.width=v.height=Math.max(S*.15,(i<<1)+w*A);const m=v.width>>1,p=m-A*.7,_=(I,D)=>{const M=un*(I/r.width),V=M-Lr,X=p*Math.cos(V),B=p*Math.sin(V);h.save(),h.translate(m+X,m+B),h.rotate(M),h.fillText(D,0,0),h.restore()};g.width|=0,u.fillStyle=h.strokeStyle=uv,u.fillRect(0,0,g.width,g.height),h.arc(m,m,m-A/2,0,un),h.lineWidth=A,h.stroke(),u.fillStyle=h.fillStyle=xd,u.font=`${L}px ${Vi}`,h.font=`${O}px ${Vi}`,u.textAlign=h.textAlign="center";let T=-b/4,P=-C;for(const I of y){const[D,M]=Array.isArray(I)?I:[I,I<1e3?I|0:`${(I/100|0)/10}k`],V=o*(this._freqScaling(D)-s),X=g.height*.75,B=M[0]=="C",re=L*(l&&!c&&!x?B?1.2:.6:3);if(u.fillStyle=h.fillStyle=B&&!c&&!x?hv:xd,l){const Q=a==fn,U=a==qn;let ce=["C"];if((Q||D>2e3||!U&&D>250||(!d||w)&&(!U&&D>125||D>1e3))&&ce.push("G"),(Q||D>4e3||!U&&D>500||(!d||w)&&(!U&&D>250||D>2e3))&&ce.push("E"),(U&&D>4e3||(!d||w)&&(Q||D>2e3||!U&&D>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}V>=T+b/2&&V<=e&&(u.fillText(M,x&&c==-1?e-V:n+V,X,re),(x||c&&(V>b||c==1))&&u.fillText(M,x&&c!=1?e+V:(n||r.width)-V,X,re),T=V+Math.min(re,u.measureText(M).width)/2),V>=P+C&&V<e-C&&(_(x&&c==1?e-V:V,M),(x||c&&(V>C||c==1))&&_(x&&c!=-1?e+V:-V,M),P=V)}}_draw(e){this._runId=requestAnimationFrame(N=>this._draw(N));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:c,isOctaves:l,isOutline:d,isRound:u,noLedGap:h}=this._flg,{analyzerHeight:g,centerX:v,centerY:y,channelCoords:x,channelHeight:w,channelGap:S,initialX:k,innerRadius:A,outerRadius:L}=this._aux,{_bars:O,canvas:b,_canvasGradients:C,_chLayout:f,_colorMode:m,_ctx:p,_energy:_,_fadePeaks:T,fillAlpha:P,_fps:I,_linearAmplitude:D,_lineWidth:M,maxDecibels:V,minDecibels:X,_mirror:B,_mode:re,overlay:Q,_radial:U,showBgColor:ce,showPeaks:q,useCanvas:J,_weightingFilter:Z}=this,ee=this._scaleX.canvas,ue=this._scaleR.canvas,Oe=I*this._peakFadeTime/1e3,he=I**2,Me=this._gravity*1e3,se=I*this._peakHoldTime/1e3,fe=f==cd,ie=f==Oi,ut=f==lt,et=f==yt,ii=a&&this._trueLeds&&m==Ni,ht=U?b.width:this._aux.analyzerWidth,Jr=k+ht,si=q&&this._peakLine&&re==hn,It=U?L-A:g,hy=It/this._pixelRatio,[fy,Sy,ri,Zr]=this._leds||[];_.val>0&&I>0&&(this._spinAngle+=this._spinSpeed*un/60/I);const py=N=>{if(this._reflexRatio>0&&!c&&!U){let ne,ft;this.reflexFit||ut?(ne=ut&&N==0?w+S:0,ft=w-g):(ne=b.height-g*2,ft=g),p.save(),p.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(p.filter=`brightness(${this.reflexBright})`),p.setTransform(1,0,0,-1,0,b.height),p.drawImage(b,0,x[N].channelTop,b.width,g,0,ne,b.width,ft),p.restore()}},my=()=>{this.showScaleX&&(U?(p.save(),p.translate(v,y),this._spinSpeed&&p.rotate(this._spinAngle+Lr),p.drawImage(ue,-ue.width>>1,-ue.width>>1),p.restore()):p.drawImage(ee,0,b.height-ee.height))},gy=N=>{const ne=N**2,ft=424.36,Ie=11599.29,qi=25122.25,Rt=544496.41,wt=148693636,qt=Kt=>20*Math.log10(Kt);switch(Z){case md:const Kt=wt*ne**2/((ne+ft)*Math.sqrt((ne+Ie)*(ne+Rt))*(ne+wt));return 2+qt(Kt);case gd:const Xt=wt*ne*N/((ne+ft)*Math.sqrt(ne+qi)*(ne+wt));return .17+qt(Xt);case vd:const to=wt*ne/((ne+ft)*(ne+wt));return .06+qt(to);case _d:const Ki=((103791848e-2-ne)**2+108076816e-2*ne)/((9837328-ne)**2+11723776*ne),no=N/68966888496476e-18*Math.sqrt(Ki/((ne+79919.29)*(ne+1345600)));return qt(no);case yd:const Xi=-4737338981378384e-39*N**6+2043828333606125e-30*N**4-1363894795463638e-22*ne+1,Yt=1306612257412824e-34*N**5-2118150887518656e-26*N**3+.0005559488023498642*N,He=.0001246332637532143*N/Math.hypot(Xi,Yt);return 18.2+qt(He)}return 0},Qr=(N,ne,ft)=>{p.beginPath(),p.moveTo(N,ne),p.lineTo(N,ft),p.stroke()},eo=N=>{if(N&&M){const ne=p.globalAlpha;p.globalAlpha=1,p.stroke(),p.globalAlpha=ne}},zt=N=>Math.max(0,(N*fy|0)*(Zr+ri)-ri),vy=N=>{_.val=N,_.peak>0&&(_.hold--,_.hold<0&&(_.peak+=_.hold*Me/he/b.height*this._pixelRatio)),N>=_.peak&&(_.peak=N,_.hold=se)};Q&&p.clearRect(0,0,b.width,b.height);let ku=0;const Tu=O.length,Eu=et?1:2;for(let N=0;N<Eu;N++){const{channelTop:ne,channelBottom:ft,analyzerBottom:Ie}=x[N],qi=this._gradients[this._selectedGrads[N]],Rt=qi.colorStops,wt=Rt.length,qt=!ce||a&&!Q?"#000":qi.bgColor,Kt=ut&&U&&N?-1:1,Xt=!N&&B==-1||N&&B==1,to=!ie||N&&B!=1?0:ht>>(N||!Xt),Ki=ie&&Xt?-1:1,no=()=>{const $=ee.height,W=$>>1,K=D?100:V,le=D?0:X,we=D?20:5,Ue=g/(K-le),pt=B!=-1&&(!ie||N==0||B==1),Pt=B!=1&&(!ie||N!=B);p.save(),p.fillStyle=Sd,p.font=`${W}px ${Vi}`,p.textAlign="right",p.lineWidth=1;for(let Mt=K;Mt>le;Mt-=we){const yn=ne+(K-Mt)*Ue,Ce=Mt%2==0|0;if(Ce){const Ne=yn+W*(yn==ne?.8:.35);pt&&p.fillText(Mt,$*.85,Ne),Pt&&p.fillText(Mt,(ie?ht:b.width)-$*.1,Ne),p.strokeStyle=Sd,p.setLineDash([2,4]),p.lineDashOffset=0}else p.strokeStyle=fv,p.setLineDash([2,8]),p.lineDashOffset=1;p.beginPath(),p.moveTo(k+$*Ce*pt,~~yn+.5),p.lineTo(Jr-$*Ce*Pt,~~yn+.5),p.stroke()}p.restore()},Xi=($,W)=>{const K=tt[$]+($<tt.length-1?(tt[$+1]-tt[$])*W:0);return isNaN(K)?-1/0:K},Yt=($,W=Ki)=>W*un*(($+to)/b.width)+this._spinAngle,He=($,W,K)=>{const le=A+W*Kt,we=Yt($,K);return[v+le*Math.cos(we),y+le*Math.sin(we)]},io=($,W,K,le,we)=>{p.beginPath();for(const Ue of B&&!ie?[1,-1]:[Ki]){const[pt,Pt]=u?[Yt($,Ue),Yt($+K,Ue)]:[];p.moveTo(...He($,W,Ue)),p.lineTo(...He($,W+le,Ue)),u?p.arc(v,y,A+(W+le)*Kt,pt,Pt,Ue!=1):p.lineTo(...He($+K,W+le,Ue)),p.lineTo(...He($+K,W,Ue)),u&&!we&&p.arc(v,y,A+W*Kt,Pt,pt,Ue==1)}eo(we),p.fill()},so=($=0,W=0)=>{let K;if(m==Ni&&!ii||re==hn)K=C[N];else{const le=m==ld?W%wt:Rt.findLastIndex(we=>a?zt($)<=zt(we.level):$<=we.level);K=Rt[le].color}p.fillStyle=p.strokeStyle=K};if(J){if(ie&&!U){const $=ht*(N+Xt),W=Xt?-1:1;p.setTransform(W,0,0,1,$,0)}if((!Q||ce)&&(Q&&(p.globalAlpha=this.bgAlpha),p.fillStyle=qt,(N==0||!U&&!fe)&&p.fillRect(k,ne-S,ht,(Q&&this.reflexAlpha==1?g:w)+S),p.globalAlpha=1),this.showScaleY&&!c&&!U&&(N==0||!fe)&&no(),a?(p.setLineDash([Zr,ri]),p.lineWidth=O[0].width):p.lineWidth=d?Math.min(M,O[0].width/2):M,p.save(),!U){const $=new Path2D;$.rect(0,ne,b.width,g),p.clip($)}}let tt=this._fftData[N];this._analyzer[N].getFloatFrequencyData(tt),Z&&(tt=tt.map(($,W)=>$+gy(this._binToFreq(W)))),p.beginPath();let oi=[];for(let $=0;$<Tu;$++){const W=O[$],{posX:K,barCenter:le,width:we,freq:Ue,binLo:pt,binHi:Pt,ratioLo:Mt,ratioHi:yn}=W;let Ce=Math.max(Xi(pt,Mt),Xi(Pt,yn));for(let oe=pt+1;oe<Pt;oe++)tt[oe]>Ce&&(Ce=tt[oe]);if(Ce=this._normalizedB(Ce),W.value[N]=Ce,ku+=Ce,W.peak[N]>0&&W.alpha[N]>0&&(W.hold[N]--,W.hold[N]<0)){if(T&&!si){const oe=!o||d&&M>0?1:o?W.peak[N]:P;W.alpha[N]=oe*(1+W.hold[N]/Oe)}else W.peak[N]+=W.hold[N]*Me/he/hy;W.alpha[N]<=0&&(W.peak[N]=0)}if(Ce>=W.peak[N]&&(W.peak[N]=Ce,W.hold[N]=se,W.alpha[N]=!o||d&&M>0?1:o?Ce:P),!J)continue;p.globalAlpha=c||o?Ce:d?P:1,so(Ce,$);const Ne=c?It:a?zt(Ce):Ce*It|0;if(re==hn){const oe=$?0:(this._normalizedB(tt[O[1].binLo])*It+Ne)/2;if(U){if($==0&&(ie&&p.moveTo(...He(0,0)),p.lineTo(...He(0,K<0?oe:Ne))),K>=0){const Xe=[K,Ne];p.lineTo(...He(...Xe)),oi.push(Xe)}}else{if($==0)if(B==-1&&!ie)p.moveTo(k,Ie-(K<k?oe:Ne));else{const Xe=pt?this._normalizedB(tt[pt-1])*It:Ne;p.moveTo(k-M,Ie-Xe)}(ie||B!=-1||K>=k)&&p.lineTo(K,Ie-Ne)}}else if(a){if(ce&&!Q&&(N==0||!fe)){const oe=p.globalAlpha;p.strokeStyle=cv,p.globalAlpha=1,Qr(le,ne,Ie),p.strokeStyle=p.fillStyle,p.globalAlpha=oe}if(ii){const oe=c?0:Rt.findLastIndex(Jt=>zt(Ce)<=zt(Jt.level));let Xe=Ie;for(let Jt=wt-1;Jt>=oe;Jt--){p.strokeStyle=Rt[Jt].color;let Iu=Ie-(Jt==oe?Ne:zt(Rt[Jt].level));Qr(le,Xe,Iu),Xe=Iu-ri}}else Qr(le,Ie,Ie-Ne)}else if(K>=k)if(U)io(K,0,we,Ne,d);else if(u){const oe=we/2,Xe=Ie+oe;p.beginPath(),p.moveTo(K,Xe),p.lineTo(K,Xe-Ne),p.arc(le,Xe-Ne,oe,Mr,un),p.lineTo(K+we,Xe),eo(d),p.fill()}else{const oe=d?p.lineWidth:0;p.beginPath(),p.rect(K,Ie+oe,we,-Ne-oe),eo(d),p.fill()}const bn=W.peak[N],Au=W.alpha[N];if(bn>0&&Au>0&&q&&!si&&!c&&K>=k&&K<Jr){if(T?p.globalAlpha=Au:d&&M>0?p.globalAlpha=1:o&&(p.globalAlpha=bn),(m==dd||ii)&&so(bn),a){const oe=zt(bn);oe>=ri&&p.fillRect(K,Ie-oe,we,Zr)}else if(!U)p.fillRect(K,Ie-bn*It,we,2);else if(re!=hn){const oe=bn*It;io(K,oe,we,!this._radialInvert||ut||oe+A>=2?-2:2)}}}if(J){if(p.globalAlpha=1,re==hn){if(so(),U&&!ie){if(B){let $;for(;$=oi.pop();)p.lineTo(...He(...$,-1))}p.closePath()}if(M>0&&p.stroke(),P>0){if(U){const $=ie?Yt(ht>>1):0,W=ie?Yt(ht):un;p.moveTo(...He(ie?ht>>1:0,0)),p.arc(v,y,A,$,W,ie?!Xt:!0)}else p.lineTo(Jr,Ie),p.lineTo(k,Ie);p.globalAlpha=P,p.fill(),p.globalAlpha=1}if((si||U&&q)&&(oi=[],p.beginPath(),O.forEach(($,W)=>{let K=$.posX,le=$.peak[N],we=W?"lineTo":"moveTo";if(U&&K<0){const Ue=O[W+1];le=Sv(K,le,Ue.posX,Ue.peak[N],0),K=0}le*=It,si?(p[we](...U?He(K,le):[K,Ie-le]),U&&B&&!ie&&oi.push([K,le])):le>0&&io(K,le,1,-2)}),si)){let $;for(;$=oi.pop();)p.lineTo(...He(...$,-1));p.lineWidth=1,p.stroke()}}p.restore(),ie&&!U&&p.setTransform(1,0,0,1,0,0),(!ie&&!fe||N)&&py(N)}}if(vy(ku/(Tu<<Eu-1)),J&&(B&&!U&&!ie&&(p.setTransform(-1,0,0,1,b.width-k,0),p.drawImage(b,k,0,v,b.height,0,0,v,b.height),p.setTransform(1,0,0,1,0,0)),p.setLineDash([]),my()),this.showFPS){const N=ee.height;p.font=`bold ${N}px ${Vi}`,p.fillStyle=av,p.textAlign="right",p.fillText(Math.round(I),b.width-N,N*2)}this.onCanvasDraw&&(p.save(),p.fillStyle=p.strokeStyle=C[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:C}),p.restore())}_freqScaling(e){switch(this._frequencyScale){case fn:return Math.log2(e);case Or:return 26.81*e/(1960+e)-.53;case Nr:return Math.log2(1+e/700);case qn:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:c,innerRadius:l,outerRadius:d}=this._aux,{isLumi:u}=this._flg,h=this._chLayout==lt,g=1-s,v=u?e.height:e.height*(1-s*!h)|0;for(const y of[0,1]){const x=this._gradients[this._selectedGrads[y]],w=x.colorStops,S=x.dir=="h";let k;if(i?k=n.createRadialGradient(r,a,d,r,a,l-(d-l)*h):k=n.createLinearGradient(...S?[c,0,c+o,0]:[0,0,0,v]),w){const A=h&&!this._splitGradient&&(!S||i);for(let L=0;L<1+A;L++){const O=w.length-1;w.forEach((b,C)=>{let f=b.pos;if(A&&(f/=2),h&&!u&&!i&&!S&&(f*=g,!A&&f>.5*g&&(f+=.5*s)),L==1)if(i||u){const m=O-C;b=w[m],f=1-b.pos/2}else C==0&&f>0&&k.addColorStop(.5,b.color),f+=.5;k.addColorStop(f,b.color),h&&C==O&&f<.5&&k.addColorStop(.5,b.color)})}}this._canvasGradients[y]=k}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(c,l,d)=>c<=l?l:c>=d?d:c,o=c=>10**(c/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){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 c=this.isFullscreen,l=c&&this._fsEl==n,d=l?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,u=l?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=bd&&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!==c&&(e=wd),this._fsStatus=c,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Ke(gv,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(Kn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Kn,...e});for(const r of Object.keys(e))i.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 kv={verdant:{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]},twilight:{colorStops:[{color:"#81B9FF",pos:0},{color:"#371A5E",pos:.5},{color:"#81B9FF",pos:1}]},bloom:{colorStops:[{color:"#FFD4FE",pos:0},{color:"#FD05F9",pos:.5},{color:"#FFD4FE",pos:1}]},mystic:{colorStops:[{color:"#1F023A",pos:0},{color:"#CA76FF",pos:.5},{color:"#1F023A",pos:1}]},flare:{colorStops:[{color:"#FFFFFF",pos:0},{color:"#FC5F00",pos:.5},{color:"#FFFFFF",pos:1}]},glacier:{colorStops:[{color:"#4CE5F2",pos:0},{color:"#005A98",pos:.5},{color:"#4CE5F2",pos:1}]}},Ad=({stream:t,className:e,onClick:n})=>{var o;const i=Te(null),s=Ut();return Ve(()=>{var l;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),c=new Cv(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",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:!0,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 c.registerGradient("gradient",kv[((l=s.audio_visualizer_config)==null?void 0:l.color)||"verdant"]),c.gradient="gradient",()=>{c.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),E("div",{onClick:n,className:_t("w-full",e),ref:i})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Ld=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),jv=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Dd=t=>{const e=jv(t);return e.charAt(0).toUpperCase()+e.slice(1)},Uv=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
21
+ */const Id=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Tv=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Rd=t=>{const e=Tv(t);return e.charAt(0).toUpperCase()+e.slice(1)},Ev=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var $v={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"};/**
26
+ */var Av={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"};/**
27
27
  * @license lucide-preact v0.515.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Gv=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>He("svg",{...$v,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([c,d])=>He(c,d)),...st(s)]);/**
31
+ */const Iv=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>Ge("svg",{...Av,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([c,l])=>Ge(c,l)),...st(s)]);/**
32
32
  * @license lucide-preact v0.515.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const Be=(t,e)=>{const n=({class:i="",children:s,...o})=>He(Gv,{...o,iconNode:e,class:Uv(`lucide-${Ld(Dd(t))}`,`lucide-${Ld(t)}`,i)},s);return n.displayName=Dd(t),n};/**
36
+ */const Be=(t,e)=>{const n=({class:i="",children:s,...o})=>Ge(Iv,{...o,iconNode:e,class:Ev(`lucide-${Id(Rd(t))}`,`lucide-${Id(t)}`,i)},s);return n.displayName=Rd(t),n};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const Od=Be("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
41
+ */const Pd=Be("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Hv=Be("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"}]]);/**
46
+ */const Rv=Be("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"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const Nd=Be("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
51
+ */const Md=Be("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
52
52
  * @license lucide-preact v0.515.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const Wv=Be("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
56
+ */const Pv=Be("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
57
57
  * @license lucide-preact v0.515.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const zv=Be("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const Mv=Be("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
62
62
  * @license lucide-preact v0.515.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const qv=Be("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"}]]);/**
66
+ */const Lv=Be("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"}]]);/**
67
67
  * @license lucide-preact v0.515.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const Kv=Be("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"}]]);/**
71
+ */const Dv=Be("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"}]]);/**
72
72
  * @license lucide-preact v0.515.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const Xv=Be("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
76
+ */const Ov=Be("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
77
77
  * @license lucide-preact v0.515.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const Yv=Be("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"}]]);/**
81
+ */const Nv=Be("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"}]]);/**
82
82
  * @license lucide-preact v0.515.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
85
85
  * See the LICENSE file in the root directory of this source tree.
86
- */const Zv=Be("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"}]]);/**
86
+ */const Vv=Be("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"}]]);/**
87
87
  * @license lucide-preact v0.515.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const Jv=Be("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
91
+ */const Fv=Be("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
92
92
  * @license lucide-preact v0.515.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const Qv=Be("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
96
+ */const Bv=Be("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const ey=Be("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
101
+ */const jv=Be("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const $r=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Vd=vs(!1),ty=()=>ma(Vd),_t=({children:t,className:e,onClick:n,tooltip:i})=>M("button",{title:i,onClick:n,className:vt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Fd=({call:t})=>{const[e,n]=ty(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return M("div",{className:"flex items-center justify-center gap-2",children:[M(_t,{tooltip:e?"Unmute":"Mute",onClick:i,className:vt(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?M(qv,{className:"w-5 h-5 text-black dark:text-white"}):M(Kv,{className:"w-5 h-5 text-black dark:text-white"})}),M(_t,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:M(Yv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Bd=({call:t,onExpand:e})=>M(Wn.div,{layoutId:Mi,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[M(Md,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),M(dd,{stream:t.remoteStream}),M(ld,{size:"small"}),M(Fd,{call:t})]});function ny(){const[t,e]=Ce(!1),n=Ut();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},o=()=>{i(n.report_issue_url)},r=()=>{i(n.view_history_url)};return M("div",{children:[M(_t,{tooltip:"More",onClick:()=>e(!t),children:M(Nd,{className:"text-black dark:text-white"})}),t&&M("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[M(_t,{tooltip:"More",onClick:()=>e(!t),children:M(Nd,{className:"text-black dark:text-white"})}),M("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&M("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",M(Qv,{className:"w-4 h-4"})]}),n.report_issue_url&&M("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",M(ey,{className:"w-4 h-4"})]}),n.view_history_url&&M("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",M(Wv,{className:"w-4 h-4"})]})]})]})]})}function iy({onCapture:t,onClose:e}){const n=ke(null),i=ke(null),s=ke(null),[o,r]=Ce(null),[a,c]=Ce(!0);Ve(()=>((async()=>{try{const m=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=m,n.current&&(n.current.srcObject=m,c(!1))}catch(m){console.error("Error accessing camera:",m),m instanceof Error?m.name==="NotAllowedError"||m.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):m.name==="NotFoundError"||m.name==="DevicesNotFoundError"?r("No camera found on this device."):m.name==="NotReadableError"||m.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),c(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(m=>m.stop())}),[]);const d=()=>{if(!n.current||!i.current)return;const p=n.current,m=i.current,v=m.getContext("2d");if(!v)return;m.width=p.videoWidth,m.height=p.videoHeight,v.drawImage(p,0,0,m.width,m.height);const _=m.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(C=>C.stop()),t(_),e()},f=()=>{s.current&&s.current.getTracks().forEach(p=>p.stop()),e()};return M("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[M("div",{className:"absolute top-2 right-2 z-10",children:M(_t,{tooltip:"Close",onClick:f,children:M($r,{className:"text-white w-5 h-5"})})}),M("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&M("div",{className:"absolute text-white text-center",children:M("p",{className:"text-sm",children:"Loading camera..."})}),o&&M("div",{className:"text-white text-center max-w-xs",children:[M("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),M("p",{className:"text-xs",children:o}),M("button",{onClick:f,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&M(it,{children:[M("video",{ref:n,autoPlay:!0,playsInline:!0,className:vt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),M("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&M("div",{className:"p-3 flex justify-center",children:M("button",{onClick:d,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[M(Od,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function sy({item:t,containerRef:e}){const n=ke(null);return Ve(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),M("li",{className:vt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[M("span",{className:"text-xs text-[#969696]",children:t.timestamp.toLocaleTimeString()}),M("div",{className:vt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&M("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&M("img",{src:i.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},s))}),t.content&&M("p",{className:vt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const ry=({transcript:t,call:e})=>{const n=ke(null),i=ke(null),s=ke(null),[o,r]=Ce([]),[a,c]=Ce(!1),[d,f]=Ce([]),[,p]=Or();Ve(()=>()=>{o.forEach(b=>URL.revokeObjectURL(b.preview))},[o]),Ve(()=>{if(d.length===0)return;const b=t.filter(k=>k.role==="user"&&!k.id.startsWith("optimistic-"));if(b.length>0){const k=b[b.length-1];f(l=>l.filter(u=>u.timestamp>k.timestamp))}},[t,d]);const m=b=>new Promise((k,l)=>{const u=new FileReader;u.onload=()=>k(u.result),u.onerror=l,u.readAsDataURL(b)}),v=async b=>{if(b.type.startsWith("image/"))try{const k=await m(b),l=URL.createObjectURL(b),u={id:Date.now().toString(),file:b,base64:k,preview:l};r(h=>[...h,u])}catch(k){console.error("Error processing image:",k)}},_=b=>{r(k=>{const l=k.find(u=>u.id===b);return l&&URL.revokeObjectURL(l.preview),k.filter(u=>u.id!==b)})},C=b=>{const k=b.target,l=k.files;l&&l.length>0&&(Array.from(l).forEach(v),k.value="")},S=b=>{var l;const k=(l=b.clipboardData)==null?void 0:l.items;k&&Array.from(k).forEach(u=>{if(u.type.startsWith("image/")){const h=u.getAsFile();h&&v(h)}})},w=()=>{var b;(b=i.current)==null||b.click()},T=()=>{c(!0)},I=b=>{fetch(b).then(k=>k.blob()).then(k=>{const l=new File([k],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});v(l)}).catch(k=>{console.error("Error processing camera capture:",k)})},R=async()=>{var l;const b=n.current&&n.current.value.trim()!=="",k=o.length>0;if(b||k){const u=((l=n.current)==null?void 0:l.value)||"",h=new Date,g={id:`optimistic-${h.getTime()}`,role:"user",content:u,timestamp:h,attachments:o.map(y=>({type:"image",url:y.base64}))};f(y=>[...y,g]),k&&p("processing_image"),e.sendConversationMessage(u,o.map(y=>y.base64)),n.current&&(n.current.value=""),o.forEach(y=>URL.revokeObjectURL(y.preview)),r([])}},L=b=>{b.key==="Enter"&&(b.preventDefault(),R())},D=[...t,...d];return M("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[M("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((b,k)=>M(sy,{item:b,containerRef:s},b.id+k))}),o.length>0&&M("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(b=>M("div",{className:"relative",children:[M("img",{src:b.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),M("button",{onClick:()=>_(b.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:M($r,{className:"w-3 h-3"})})]},b.id))}),M("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[M("input",{ref:n,type:"text",onKeyDown:L,onPaste:S,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),M("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:C,className:"hidden"}),M(_t,{tooltip:"Attach image",onClick:w,children:M(Xv,{className:"text-[#969696] w-4 h-4"})}),M(_t,{tooltip:"Take photo",onClick:T,children:M(Od,{className:"text-[#969696] w-4 h-4"})}),M(_t,{tooltip:"Send",children:M(Zv,{onClick:R,className:"text-[#969696] w-4 h-4"})})]}),a&&M(iy,{onCapture:I,onClose:()=>c(!1)})]})};function oy({onCollapse:t}){return M("div",{className:"flex items-center justify-between w-full",children:[M(ny,{}),M(_t,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:M($r,{className:"text-black dark:text-white"})})]})}const ay=({call:t,onCollapse:e,transcript:n})=>M(Lp,{children:M(Wn.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[M("div",{className:"p-4 text-center",children:[M(oy,{onCollapse:e}),M(Md,{className:"h-[144px]",stream:t.remoteStream}),M(ld,{size:"large",className:"mb-4"}),M(Fd,{call:t})]}),M(dd,{stream:t.remoteStream}),M(ry,{call:t,transcript:n})]})});function jd(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function $(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(d){try{c(i.next(d))}catch(f){o(f)}}function a(d){try{c(i.throw(d))}catch(f){o(f)}}function c(d){var f;d.done?s(d.value):(f=d.value,f instanceof n?f:new n(function(p){p(f)})).then(r,a)}c((i=i.apply(t,[])).next())})}var Ud=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),cy=new Uint8Array(16);function ly(){if(!Ud)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ud(cy)}for(var $d=[],Fi=0;Fi<256;++Fi)$d[Fi]=(Fi+256).toString(16).substr(1);function pn(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||ly)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var c=0,d=$d;return[d[r[c++]],d[r[c++]],d[r[c++]],d[r[c++]],"-",d[r[c++]],d[r[c++]],"-",d[r[c++]],d[r[c++]],"-",d[r[c++]],d[r[c++]],"-",d[r[c++]],d[r[c++]],d[r[c++]],d[r[c++]],d[r[c++]],d[r[c++]]].join("")}(s)}const Gd="wss://rtc.telnyx.com",dy={urls:"stun:stun.l.google.com:19302"},uy={urls:"stun:stun.telnyx.com:3478"},Hd={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var j;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError"})(j||(j={}));var hy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wd(t,e){return t(e={exports:{}},e.exports),e.exports}var fy=Wd(function(t){var e,n;e=hy,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(S,w){var T=S[w];if(typeof T.bind=="function")return T.bind(S);try{return Function.prototype.bind.call(T,S)}catch{return function(){return Function.prototype.apply.apply(T,[S,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(S,w){for(var T=0;T<r.length;T++){var I=r[T];this[I]=T<S?i:this.methodFactory(I,S,w)}this.log=this.debug}function f(S,w,T){return function(){typeof console!==s&&(d.call(this,w,T),this[S].apply(this,arguments))}}function p(S,w,T){return function(I){return I==="debug"&&(I="log"),typeof console!==s&&(I==="trace"&&o?c:console[I]!==void 0?a(console,I):console.log!==void 0?a(console,"log"):i)}(S)||f.apply(this,arguments)}function m(S,w,T){var I,R=this;w=w??"WARN";var L="loglevel";function D(){var k;if(typeof window!==s&&L){try{k=window.localStorage[L]}catch{}if(typeof k===s)try{var l=window.document.cookie,u=l.indexOf(encodeURIComponent(L)+"=");u!==-1&&(k=/^([^;]+)/.exec(l.slice(u))[1])}catch{}return R.levels[k]===void 0&&(k=void 0),k}}typeof S=="string"?L+=":"+S:typeof S=="symbol"&&(L=void 0),R.name=S,R.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},R.methodFactory=T||p,R.getLevel=function(){return I},R.setLevel=function(k,l){if(typeof k=="string"&&R.levels[k.toUpperCase()]!==void 0&&(k=R.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=R.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(I=k,l!==!1&&function(u){var h=(r[u]||"silent").toUpperCase();if(typeof window!==s&&L){try{return void(window.localStorage[L]=h)}catch{}try{window.document.cookie=encodeURIComponent(L)+"="+h+";"}catch{}}}(k),d.call(R,k,S),typeof console===s&&k<R.levels.SILENT)return"No console available for logging"},R.setDefaultLevel=function(k){w=k,D()||R.setLevel(k,!1)},R.resetLevel=function(){R.setLevel(w,!1),function(){if(typeof window!==s&&L){try{return void window.localStorage.removeItem(L)}catch{}try{window.document.cookie=encodeURIComponent(L)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},R.enableAll=function(k){R.setLevel(R.levels.TRACE,k)},R.disableAll=function(k){R.setLevel(R.levels.SILENT,k)};var b=D();b==null&&(b=w),R.setLevel(b,!1)}var v=new m,_={};v.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[S];return w||(w=_[S]=new m(S,v.getLevel(),v.methodFactory)),w};var C=typeof window!==s?window.log:void 0;return v.noConflict=function(){return typeof window!==s&&window.log===v&&(window.log=C),v},v.getLoggers=function(){return _},v.default=v,v},t.exports?t.exports=n():e.log=n()});const O=fy.getLogger("telnyx"),py=O.methodFactory;O.methodFactory=(t,e,n)=>{const i=py(t,e,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)}},O.setLevel(O.getLevel());const Bi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{O.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},zd=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},mn=t=>t instanceof Function||typeof t=="function",ji=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,my=/^(ws|wss):\/\//,qd=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?qd(a,r):{result:s}},Kd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Ui=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Kn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Gr=t=>{var e,n,i,s,o,r;let a="",c="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(c=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||c};function Xd({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?gy(i,t):i,n=s}),resolve:e,reject:n}}const gy=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Hr="telnyx-voice-sdk-id";function $t(){return sessionStorage.getItem(Hr)}var Ee,It,ie;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Hr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ee||(Ee={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(It||(It={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ie||(ie={}));const Qe={generic:"event",[ie.Display]:"participantData",[ie.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError"},vy={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var Z,Wr,$e,bt,De;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(Z||(Z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Wr||(Wr={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}($e||($e={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(bt||(bt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(De||(De={}));const gn="GLOBAL",je={},Xn=(t,e)=>`${t}|${e}`,Yd=(t,e=gn)=>Xn(t,e)in je,Gt=(t,e,n=gn)=>{const i=Xn(t,n);i in je||(je[i]=[]),je[i].push(e)},Zd=(t,e,n=gn)=>{const i=function(s){Ht(t,i,n),e(s)};return i.prototype.targetRef=e,Gt(t,i,n)},Ht=(t,e,n=gn)=>{if(!Yd(t,n))return!1;const i=Xn(t,n);if(mn(e))for(let s=je[i].length-1;s>=0;s--){const o=je[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&je[i].splice(s,1)}else je[i]=[];return je[i].length===0&&delete je[i],!0},ee=(t,e,n=gn,i=!0)=>{const s=i&&n!==gn;if(!Yd(t,n))return s&&ee(t,e),!1;const o=Xn(t,n),r=je[o].length;if(!r)return s&&ee(t,e),!1;for(let a=r-1;a>=0;a--)je[o][a](e);return s&&ee(t,e),!0},zr=t=>{const e=Xn(t,"");Object.keys(je).filter(n=>n.indexOf(e)===0).forEach(n=>delete je[n])};let yy=typeof WebSocket<"u"?WebSocket:null;const _y=0,by=1,wy=2,xy=3;class Jd{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Gd,this._timers={},this._hasTrickleIceCanaryBeenUsed=!1,this._trickleIceCanaryEnabled=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Gd),n&&(this._host=(r=>`${my.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._trickleIceCanaryEnabled=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===by}get connecting(){return this._wsClient&&this._wsClient.readyState===_y}get closing(){return this._wsClient&&this._wsClient.readyState===wy}get closed(){return this._wsClient&&this._wsClient.readyState===xy}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=$t();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._trickleIceCanaryEnabled=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._trickleIceCanaryEnabled&&(e.searchParams.set("canary","true"),n&&!this._hasTrickleIceCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),O.debug("first trickle ice canary connection. Refreshing voice_sdk_id")),this.session.options.trickleIce=!0,this._hasTrickleIceCanaryBeenUsed=!0),this._wsClient=new yy(e.toString()),this._wsClient.onopen=i=>ee(j.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>ee(j.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>ee(j.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=zd(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(Hr,a)),this._unsetTimer(r.id),O.debug(`RECV:
106
+ */const Fr=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ld=fs(!1),Uv=()=>ua(Ld),bt=({children:t,className:e,onClick:n,tooltip:i})=>E("button",{title:i,onClick:n,className:_t("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Dd=({call:t})=>{const[e,n]=Uv(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return E("div",{className:"flex items-center justify-center gap-2",children:[E(bt,{tooltip:e?"Unmute":"Mute",onClick:i,className:_t(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?E(Lv,{className:"w-5 h-5 text-black dark:text-white"}):E(Dv,{className:"w-5 h-5 text-black dark:text-white"})}),E(bt,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:E(Nv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Od=({call:t,onExpand:e})=>E(zn.div,{layoutId:Li,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[E(Ad,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),E(od,{stream:t.remoteStream}),E(rd,{size:"small"}),E(Dd,{call:t})]});function $v(){const[t,e]=ke(!1),n=Ut();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},o=()=>{i(n.report_issue_url)},r=()=>{i(n.view_history_url)};return E("div",{children:[E(bt,{tooltip:"More",onClick:()=>e(!t),children:E(Md,{className:"text-black dark:text-white"})}),t&&E("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[E(bt,{tooltip:"More",onClick:()=>e(!t),children:E(Md,{className:"text-black dark:text-white"})}),E("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&E("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",E(Bv,{className:"w-4 h-4"})]}),n.report_issue_url&&E("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",E(jv,{className:"w-4 h-4"})]}),n.view_history_url&&E("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",E(Pv,{className:"w-4 h-4"})]})]})]})]})}function Hv({onCapture:t,onClose:e}){const n=Te(null),i=Te(null),s=Te(null),[o,r]=ke(null),[a,c]=ke(!0);Ve(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,n.current&&(n.current.srcObject=h,c(!1))}catch(h){console.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),c(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const l=()=>{if(!n.current||!i.current)return;const u=n.current,h=i.current,g=h.getContext("2d");if(!g)return;h.width=u.videoWidth,h.height=u.videoHeight,g.drawImage(u,0,0,h.width,h.height);const v=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(y=>y.stop()),t(v),e()},d=()=>{s.current&&s.current.getTracks().forEach(u=>u.stop()),e()};return E("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[E("div",{className:"absolute top-2 right-2 z-10",children:E(bt,{tooltip:"Close",onClick:d,children:E(Fr,{className:"text-white w-5 h-5"})})}),E("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&E("div",{className:"absolute text-white text-center",children:E("p",{className:"text-sm",children:"Loading camera..."})}),o&&E("div",{className:"text-white text-center max-w-xs",children:[E("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),E("p",{className:"text-xs",children:o}),E("button",{onClick:d,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&E(it,{children:[E("video",{ref:n,autoPlay:!0,playsInline:!0,className:_t("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),E("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&E("div",{className:"p-3 flex justify-center",children:E("button",{onClick:l,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[E(Pd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function Gv({item:t,containerRef:e}){const n=Te(null);return Ve(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),E("li",{className:_t("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[E("span",{className:"text-xs text-[#969696]",children:t.timestamp.toLocaleTimeString()}),E("div",{className:_t("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&E("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&E("img",{src:i.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},s))}),t.content&&E("p",{className:_t("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const Wv=({transcript:t,call:e})=>{const n=Te(null),i=Te(null),s=Te(null),[o,r]=ke([]),[a,c]=ke(!1),[l,d]=ke([]),[,u]=Pr();Ve(()=>()=>{o.forEach(b=>URL.revokeObjectURL(b.preview))},[o]),Ve(()=>{if(l.length===0)return;const b=t.filter(C=>C.role==="user"&&!C.id.startsWith("optimistic-"));if(b.length>0){const C=b[b.length-1];d(f=>f.filter(m=>m.timestamp>C.timestamp))}},[t,l]);const h=b=>new Promise((C,f)=>{const m=new FileReader;m.onload=()=>C(m.result),m.onerror=f,m.readAsDataURL(b)}),g=async b=>{if(b.type.startsWith("image/"))try{const C=await h(b),f=URL.createObjectURL(b),m={id:Date.now().toString(),file:b,base64:C,preview:f};r(p=>[...p,m])}catch(C){console.error("Error processing image:",C)}},v=b=>{r(C=>{const f=C.find(m=>m.id===b);return f&&URL.revokeObjectURL(f.preview),C.filter(m=>m.id!==b)})},y=b=>{const C=b.target,f=C.files;f&&f.length>0&&(Array.from(f).forEach(g),C.value="")},x=b=>{var f;const C=(f=b.clipboardData)==null?void 0:f.items;C&&Array.from(C).forEach(m=>{if(m.type.startsWith("image/")){const p=m.getAsFile();p&&g(p)}})},w=()=>{var b;(b=i.current)==null||b.click()},S=()=>{c(!0)},k=b=>{fetch(b).then(C=>C.blob()).then(C=>{const f=new File([C],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(f)}).catch(C=>{console.error("Error processing camera capture:",C)})},A=async()=>{var f;const b=n.current&&n.current.value.trim()!=="",C=o.length>0;if(b||C){const m=((f=n.current)==null?void 0:f.value)||"",p=new Date,_={id:`optimistic-${p.getTime()}`,role:"user",content:m,timestamp:p,attachments:o.map(T=>({type:"image",url:T.base64}))};d(T=>[...T,_]),C&&u("processing_image"),e.sendConversationMessage(m,o.map(T=>T.base64)),n.current&&(n.current.value=""),o.forEach(T=>URL.revokeObjectURL(T.preview)),r([])}},L=b=>{b.key==="Enter"&&(b.preventDefault(),A())},O=[...t,...l];return E("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[E("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((b,C)=>E(Gv,{item:b,containerRef:s},b.id+C))}),o.length>0&&E("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(b=>E("div",{className:"relative",children:[E("img",{src:b.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),E("button",{onClick:()=>v(b.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:E(Fr,{className:"w-3 h-3"})})]},b.id))}),E("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[E("input",{ref:n,type:"text",onKeyDown:L,onPaste:x,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),E("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:y,className:"hidden"}),E(bt,{tooltip:"Attach image",onClick:w,children:E(Ov,{className:"text-[#969696] w-4 h-4"})}),E(bt,{tooltip:"Take photo",onClick:S,children:E(Pd,{className:"text-[#969696] w-4 h-4"})}),E(bt,{tooltip:"Send",children:E(Vv,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&E(Hv,{onCapture:k,onClose:()=>c(!1)})]})};function zv({onCollapse:t}){return E("div",{className:"flex items-center justify-between w-full",children:[E($v,{}),E(bt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:E(Fr,{className:"text-black dark:text-white"})})]})}const qv=({call:t,onCollapse:e,transcript:n})=>E(yp,{children:E(zn.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[E("div",{className:"p-4 text-center",children:[E(zv,{onCollapse:e}),E(Ad,{className:"h-[144px]",stream:t.remoteStream}),E(rd,{size:"large",className:"mb-4"}),E(Dd,{call:t})]}),E(od,{stream:t.remoteStream}),E(Wv,{call:t,transcript:n})]})});function Nd(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function j(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(l){try{c(i.next(l))}catch(d){o(d)}}function a(l){try{c(i.throw(l))}catch(d){o(d)}}function c(l){var d;l.done?s(l.value):(d=l.value,d instanceof n?d:new n(function(u){u(d)})).then(r,a)}c((i=i.apply(t,[])).next())})}var Vd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Kv=new Uint8Array(16);function Xv(){if(!Vd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Vd(Kv)}for(var Fd=[],Bi=0;Bi<256;++Bi)Fd[Bi]=(Bi+256).toString(16).substr(1);function pn(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||Xv)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var c=0,l=Fd;return[l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]]].join("")}(s)}const Bd="wss://rtc.telnyx.com",jd={urls:"stun:stun.l.google.com:19302"},Yv=[{urls:"stun:stun.telnyx.com:3478"},jd,{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Jv=[{urls:"stun:stundev.telnyx.com:3478"},jd,{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError"})(F||(F={}));var Zv=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ud(t,e){return t(e={exports:{}},e.exports),e.exports}var Qv=Ud(function(t){var e,n;e=Zv,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(x,w){var S=x[w];if(typeof S.bind=="function")return S.bind(x);try{return Function.prototype.bind.call(S,x)}catch{return function(){return Function.prototype.apply.apply(S,[x,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(x,w){for(var S=0;S<r.length;S++){var k=r[S];this[k]=S<x?i:this.methodFactory(k,x,w)}this.log=this.debug}function d(x,w,S){return function(){typeof console!==s&&(l.call(this,w,S),this[x].apply(this,arguments))}}function u(x,w,S){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?c:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):i)}(x)||d.apply(this,arguments)}function h(x,w,S){var k,A=this;w=w??"WARN";var L="loglevel";function O(){var C;if(typeof window!==s&&L){try{C=window.localStorage[L]}catch{}if(typeof C===s)try{var f=window.document.cookie,m=f.indexOf(encodeURIComponent(L)+"=");m!==-1&&(C=/^([^;]+)/.exec(f.slice(m))[1])}catch{}return A.levels[C]===void 0&&(C=void 0),C}}typeof x=="string"?L+=":"+x:typeof x=="symbol"&&(L=void 0),A.name=x,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=S||u,A.getLevel=function(){return k},A.setLevel=function(C,f){if(typeof C=="string"&&A.levels[C.toUpperCase()]!==void 0&&(C=A.levels[C.toUpperCase()]),!(typeof C=="number"&&C>=0&&C<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+C;if(k=C,f!==!1&&function(m){var p=(r[m]||"silent").toUpperCase();if(typeof window!==s&&L){try{return void(window.localStorage[L]=p)}catch{}try{window.document.cookie=encodeURIComponent(L)+"="+p+";"}catch{}}}(C),l.call(A,C,x),typeof console===s&&C<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(C){w=C,O()||A.setLevel(C,!1)},A.resetLevel=function(){A.setLevel(w,!1),function(){if(typeof window!==s&&L){try{return void window.localStorage.removeItem(L)}catch{}try{window.document.cookie=encodeURIComponent(L)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(C){A.setLevel(A.levels.TRACE,C)},A.disableAll=function(C){A.setLevel(A.levels.SILENT,C)};var b=O();b==null&&(b=w),A.setLevel(b,!1)}var g=new h,v={};g.getLogger=function(x){if(typeof x!="symbol"&&typeof x!="string"||x==="")throw new TypeError("You must supply a name when creating a logger.");var w=v[x];return w||(w=v[x]=new h(x,g.getLevel(),g.methodFactory)),w};var y=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=y),g},g.getLoggers=function(){return v},g.default=g,g},t.exports?t.exports=n():e.log=n()});const R=Qv.getLogger("telnyx"),e_=R.methodFactory;R.methodFactory=(t,e,n)=>{const i=e_(t,e,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)}},R.setLevel("info");const ji=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{R.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},$d=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},mn=t=>t instanceof Function||typeof t=="function",Ui=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,t_=/^(ws|wss):\/\//,Hd=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Hd(a,r):{result:s}},Gd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),$i=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Xn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Br=t=>{var e,n,i,s,o,r;let a="",c="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(c=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||c};function Wd({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?n_(i,t):i,n=s}),resolve:e,reject:n}}const n_=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},jr="telnyx-voice-sdk-id";function $t(){return sessionStorage.getItem(jr)}var Ae,At,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(jr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ae||(Ae={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(At||(At={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(te||(te={}));const Qe={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError"},i_={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1};var z,Ur,$e,dt,De;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Ur||(Ur={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}($e||($e={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(dt||(dt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(De||(De={}));const gn="GLOBAL",je={},Yn=(t,e)=>`${t}|${e}`,zd=(t,e=gn)=>Yn(t,e)in je,Ht=(t,e,n=gn)=>{const i=Yn(t,n);i in je||(je[i]=[]),je[i].push(e)},qd=(t,e,n=gn)=>{const i=function(s){Gt(t,i,n),e(s)};return i.prototype.targetRef=e,Ht(t,i,n)},Gt=(t,e,n=gn)=>{if(!zd(t,n))return!1;const i=Yn(t,n);if(mn(e))for(let s=je[i].length-1;s>=0;s--){const o=je[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&je[i].splice(s,1)}else je[i]=[];return je[i].length===0&&delete je[i],!0},Y=(t,e,n=gn,i=!0)=>{const s=i&&n!==gn;if(!zd(t,n))return s&&Y(t,e),!1;const o=Yn(t,n),r=je[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)je[o][a](e);return s&&Y(t,e),!0},$r=t=>{const e=Yn(t,"");Object.keys(je).filter(n=>n.indexOf(e)===0).forEach(n=>delete je[n])};let s_=typeof WebSocket<"u"?WebSocket:null;const r_=0,o_=1,a_=2,c_=3;class Kd{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Bd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Bd),n&&(this._host=(a=>`${t_.test(a)?"":"wss://"}${a}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),(o||r)&&(this._useCanaryRtcServer=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===o_}get connecting(){return this._wsClient&&this._wsClient.readyState===r_}get closing(){return this._wsClient&&this._wsClient.readyState===a_}get closed(){return this._wsClient&&this._wsClient.readyState===c_}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=$t();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),R.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this._wsClient=new s_(e.toString()),this._wsClient.onopen=i=>Y(F.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Y(F.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Y(F.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=$d(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(jr,a)),this._unsetTimer(r.id),R.debug(`RECV:
107
107
  `,JSON.stringify(r,null,2),`
108
- `),De[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!ee(r.id,r)){const c=Gr(r);ee(j.SocketMessage,r,this.session.uuid),c&&(this.previousGatewayState=c)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();Zd(n.id,r=>{const{result:a,error:c}=qd(r);return c?o(c):s(a)})});return O.debug(`SEND:
108
+ `),De[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!Y(r.id,r)){const c=Br(r);Y(F.SocketMessage,r,this.session.uuid),c&&(this.previousGatewayState=c)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();qd(n.id,r=>{const{result:a,error:c}=Hd(r);return c?o(c):s(a)})});return R.debug(`SEND:
109
109
  `,JSON.stringify(n,null,2),`
110
- `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(mn(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)),ee(j.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else O.warn("Unknown message from socket",e)}}let Yn=class{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:pn()},e)}};const Qd={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 Re extends Yn{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=jd(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Qd)i&&n.hasOwnProperty(i)&&(n[Qd[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class eu extends Re{constructor(e){super(),this.method=ie.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Sy{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>$(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Gr(n))}),this.getIsRegistered=()=>$(this,void 0,void 0,function*(){const n=new eu($t());this.pendingRequestId=n.request.id,this.gatewayStateTask=Xd({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[De.REGISTER,De.REGED].includes(i)}),this.session=e,this.gatewayStateTask=Xd({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class tu extends Re{constructor(e){super(),this.method=ie.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Cy{constructor(e){if(this.options=e,this.uuid=pn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!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 Jd(this),this.registerAgent=new Sy(this)}get __logger(){return O}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return $(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Kd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Ui(this.options)||Kn(this.options)}broadcast(e){}disconnect(){return $(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners()})}on(e,n){return Gt(e,n,this.uuid),this}off(e,n){return Ht(e,n,this.uuid),this}connect(){return $(this,void 0,void 0,function*(){this.connection||(this.connection=new Jd(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){ee(j.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return $(this,void 0,void 0,function*(){this.options.keepConnectionAliveOnSocketClose&&this._emptyExecuteQueues()})}onNetworkClose(){this.relayProtocol&&zr(this.relayProtocol);for(const e in this.subscriptions)zr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Ht(e,null,n)):(delete this.subscriptions[e],zr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},mn(n)&&Gt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(j.SocketOpen,this._onSocketOpen),this.on(j.SocketClose,this.onNetworkClose),this.on(j.SocketError,this.onNetworkClose),this.on(j.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(j.SocketOpen,this._onSocketOpen),this.off(j.SocketClose,this.onNetworkClose),this.off(j.SocketError,this.onNetworkClose),this.off(j.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(O.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new tu($t()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){O.debug("Ping received"),this._pong=!0}static on(e,n){Gt(e,n)}static off(e){Ht(e)}static uuid(){return pn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const qr=t=>navigator.mediaDevices.getUserMedia(t),$i=t=>t&&t instanceof MediaStream,Zn=(t,e)=>{const n=ji(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},nu=(t,e)=>$(void 0,void 0,void 0,function*(){const n=ji(t);if(n===null)return O.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return O.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),ky=t=>{t&&t.readyState==="live"&&t.stop()},Jn=t=>{$i(t)&&t.getTracks().forEach(ky),t=null},Gi=t=>$(void 0,void 0,void 0,function*(){O.info("RTCService.getUserMedia",t);const{audio:e}=t;if(!e)return null;try{return yield qr(t)}catch(n){throw O.error("getUserMedia error: ",n),n}}),Qn=(t=null,e=!1)=>$(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===bt.AudioIn||s===bt.AudioOut,video:!s||s===bt.Video}))(t)).catch(s=>(console.error(s),null));if(i){if(Jn(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(o=>o.kind===t)),e===!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}),iu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Kr=(t,e,n)=>$(void 0,void 0,void 0,function*(){const i=yield Qn(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(t===o||e===r)return o}return null}),Ty=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Xr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=Yr(t);return n.includes(e)||i.includes(e)},Yr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},vn=(t,e=null,n=null)=>{if(!$i(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},su=t=>{vn(t,"audio",!0)},ru=t=>{vn(t,"audio",!1)},ou=t=>{vn(t,"audio",null)};function Ey(){try{const{browserInfo:t,name:e,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 f=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),p=f[0],m=parseInt(f[1],10);return{browserInfo:navigator.userAgent,name:p,version:m,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const f=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),p=f[0],m=parseInt(f[1],10);return{browserInfo:navigator.userAgent,name:p,version:m,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const f=navigator.userAgent.match(/safari/gim)[0],p=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),m=parseInt(p[1],10);return{browserInfo:navigator.userAgent,name:f,version:m,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const f=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),p=f[0],m=parseInt(f[1],10);return{browserInfo:navigator.userAgent,name:p,version:m,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!Gi}}catch(t){return t.message}}var ve;function au(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function cu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),t._playFulfilled=!0}))}function lu(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(ve||(ve={}));var du="2.25.2",Hi=du;class uu extends Re{constructor(e,n,i,s,o={},r){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Hi,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Iy extends Re{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class hu extends Re{toString(){return ie.Invite}}class fu extends Re{toString(){return ie.Answer}}class Zr extends Re{toString(){return ie.Attach}}class Ay extends Re{toString(){return ie.Bye}}class pu extends Re{toString(){return ie.Candidate}}class Ry extends Re{toString(){return ie.EndOfCandidates}}class Jr extends Re{toString(){return ie.Modify}}class mu extends Re{toString(){return ie.Info}}class Py extends Re{toString(){return ie.Broadcast}}class My extends Re{toString(){return ie.Subscribe}}class Ly extends Re{toString(){return ie.Unsubscribe}}class Dy extends Yn{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:pn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}const gu=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:Qe.conferenceUpdate,call:t.calls[s],canvasInfo:Oy(o),currentLayerIdx:r};switch(n){case"layer-info":{const c=Object.assign({action:$e.LayerInfo},a);ee(j.Notification,c,t.uuid);break}case"layout-info":{const c=Object.assign({action:$e.LayoutInfo},a);ee(j.Notification,c,t.uuid);break}}},Oy=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return zd(e)};var Wi,vu=Wd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(l){return l._maxListeners===void 0?s.defaultMaxListeners:l._maxListeners}function r(l,u,h,g){var y,E,x;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((E=l._events)?(E.newListener&&(l.emit("newListener",u,h.listener?h.listener:h),E=l._events),x=E[u]):(E=l._events=new i,l._eventsCount=0),x){if(typeof x=="function"?x=E[u]=g?[h,x]:[x,h]:g?x.unshift(h):x.push(h),!x.warned&&(y=o(l))&&0<y&&x.length>y){x.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+u+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=l,A.type=u,A.count=x.length,function(P){typeof console.warn=="function"?console.warn(P):console.log(P)}(A)}}else x=E[u]=h,++l._eventsCount;return l}function a(l,u,h){function g(){l.removeListener(u,g),y||(y=!0,h.apply(l,arguments))}var y=!1;return g.listener=h,g}function c(l){var u=this._events;if(u){var h=u[l];if(typeof h=="function")return 1;if(h)return h.length}return 0}function d(l,u){for(var h=Array(u);u--;)h[u]=l[u];return h}Object.defineProperty(e,"__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(l){if(typeof l!="number"||0>l||isNaN(l))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=l,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(l){var u,h,g,y,E,x,A,P=l==="error";if(x=this._events)P=P&&x.error==null;else if(!P)return!1;if(A=this.domain,P){if(u=arguments[1],!A){if(u instanceof Error)throw u;var V=new Error('Uncaught, unspecified "error" event. ('+u+")");throw V.context=u,V}return u||(u=new Error('Uncaught, unspecified "error" event')),u.domainEmitter=this,u.domain=A,u.domainThrown=!1,A.emit("error",u),!1}if(!(h=x[l]))return!1;var H=typeof h=="function";switch(g=arguments.length){case 1:(function(N,ne,G){if(ne)N.call(G);else for(var F=N.length,te=d(N,F),U=0;U<F;++U)te[U].call(G)})(h,H,this);break;case 2:(function(N,ne,G,F){if(ne)N.call(G,F);else for(var te=N.length,U=d(N,te),W=0;W<te;++W)U[W].call(G,F)})(h,H,this,arguments[1]);break;case 3:(function(N,ne,G,F,te){if(ne)N.call(G,F,te);else for(var U=N.length,W=d(N,U),Y=0;Y<U;++Y)W[Y].call(G,F,te)})(h,H,this,arguments[1],arguments[2]);break;case 4:(function(N,ne,G,F,te,U){if(ne)N.call(G,F,te,U);else for(var W=N.length,Y=d(N,W),Q=0;Q<W;++Q)Y[Q].call(G,F,te,U)})(h,H,this,arguments[1],arguments[2],arguments[3]);break;default:for(y=Array(g-1),E=1;E<g;E++)y[E-1]=arguments[E];(function(N,ne,G,F){if(ne)N.apply(G,F);else for(var te=N.length,U=d(N,te),W=0;W<te;++W)U[W].apply(G,F)})(h,H,this,y)}return!0},s.prototype.addListener=function(l,u){return r(this,l,u,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(l,u){return r(this,l,u,!0)},s.prototype.once=function(l,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.on(l,a(this,l,u)),this},s.prototype.prependOnceListener=function(l,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(l,a(this,l,u)),this},s.prototype.removeListener=function(l,u){var h,g,y,E,x;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if(!(g=this._events))return this;if(!(h=g[l]))return this;if(h===u||h.listener&&h.listener===u)--this._eventsCount==0?this._events=new i:(delete g[l],g.removeListener&&this.emit("removeListener",l,h.listener||u));else if(typeof h!="function"){for(y=-1,E=h.length;0<E--;)if(h[E]===u||h[E].listener&&h[E].listener===u){x=h[E].listener,y=E;break}if(0>y)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete g[l]}else(function(A,P){for(var V=P,H=V+1,N=A.length;H<N;V+=1,H+=1)A[V]=A[H];A.pop()})(h,y);g.removeListener&&this.emit("removeListener",l,x||u)}return this},s.prototype.removeAllListeners=function(l){var u,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[l]&&(--this._eventsCount==0?this._events=new i:delete h[l]),this;if(arguments.length===0){for(var g,y=Object.keys(h),E=0;E<y.length;++E)(g=y[E])!=="removeListener"&&this.removeAllListeners(g);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(u=h[l])=="function")this.removeListener(l,u);else if(u)do this.removeListener(l,u[u.length-1]);while(u[0]);return this},s.prototype.listeners=function(l){var u,h,g=this._events;return g?h=(u=g[l])?typeof u=="function"?[u.listener||u]:function(y){for(var E=Array(y.length),x=0;x<E.length;++x)E[x]=y[x].listener||y[x];return E}(u):[]:h=[],h},s.listenerCount=function(l,u){return typeof l.listenerCount=="function"?l.listenerCount(u):c.call(l,u)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var f,p=new Uint8Array(16);function m(){if(!f&&!(f=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 f(p)}for(var v=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],C=0;256>C;++C)_.push((C+256).toString(16).substr(1));function S(l){var u=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[l[u+0]]+_[l[u+1]]+_[l[u+2]]+_[l[u+3]]+"-"+_[l[u+4]]+_[l[u+5]]+"-"+_[l[u+6]]+_[l[u+7]]+"-"+_[l[u+8]]+_[l[u+9]]+"-"+_[l[u+10]]+_[l[u+11]]+_[l[u+12]]+_[l[u+13]]+_[l[u+14]]+_[l[u+15]]).toLowerCase();if(!function(g){return typeof g=="string"&&v.test(g)}(h))throw TypeError("Stringified UUID is invalid");return h}function w(l,u,h){var g=(l=l||{}).random||(l.rng||m)();return g[6]=64|15&g[6],g[8]=128|63&g[8],S(g)}function T(l,u){if(!l||!u)return{};const h={...l};if(h.localCandidateId){const g=u.get(h.localCandidateId);h.local={...g}}if(h.remoteCandidateId){const g=u.get(h.remoteCandidateId);h.remote={...g}}return h}function I(l,u,h){return 8*function(g,y,E){const x=g[E],A=y?y[E]:null;return x===null||A===null?null:(x-A)/(g.timestamp-y.timestamp)*1e3}(l,u,h)}function R(l){if(!l.entries)return l;const u={};return l.forEach(function(h,g){u[g]=h}),u}function L(l,u,h={}){if(!l)return null;let g={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(g.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const y of l.values())switch(y.type){case"outbound-rtp":{const E=y.mediaType||y.kind,x={};let A={};if(!["audio","video"].includes(E))continue;if(y.codecId){const P=l.get(y.codecId);P&&(x.clockRate=P.clockRate,x.mimeType=P.mimeType,x.payloadType=P.payloadType)}A=l.get(y.mediaSourceId)||l.get(y.trackId)||{},g[E].outbound.push({...y,...x,track:{...A}});break}case"inbound-rtp":{let E=y.mediaType||y.kind,x={};const A={};if(!["audio","video"].includes(E))if(y.id.includes("Video"))E="video";else{if(!y.id.includes("Audio"))continue;E="audio"}if(y.codecId){const P=l.get(y.codecId);P&&(A.clockRate=P.clockRate,A.mimeType=P.mimeType,A.payloadType=P.payloadType)}if(!g.connection.id&&y.transportId){const P=l.get(y.transportId);if(P&&P.selectedCandidatePairId){const V=l.get(P.selectedCandidatePairId);g.connection=T(V,l)}}x=l.get(y.mediaSourceId)||l.get(y.trackId)||{},g[E].inbound.push({...y,...A,track:{...x}});break}case"peer-connection":g.connection.dataChannelsClosed=y.dataChannelsClosed,g.connection.dataChannelsOpened=y.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let E=y.mediaType||y.kind;const x={};if(!["audio","video"].includes(E))if(y.id.includes("Video"))E="video";else{if(!y.id.includes("Audio"))continue;E="audio"}if(y.codecId){const A=l.get(y.codecId);A&&(x.clockRate=A.clockRate,x.mimeType=A.mimeType,x.payloadType=A.payloadType)}if(!g.connection.id&&y.transportId){const A=l.get(y.transportId);if(A&&A.selectedCandidatePairId){const P=l.get(A.selectedCandidatePairId);g.connection=T(P,l)}}g.remote[E].inbound.push({...y,...x});break}case"remote-outbound-rtp":{if(!h.remote)break;const E=y.mediaType||y.kind,x={};if(!["audio","video"].includes(E))continue;if(y.codecId){const A=l.get(y.codecId);A&&(x.clockRate=A.clockRate,x.mimeType=A.mimeType,x.payloadType=A.payloadType)}g.remote[E].outbound.push({...y,...x});break}}if(!g.connection.id)for(const y of l.values())y.type==="candidate-pair"&&y.nominated&&y.state==="succeeded"&&(g.connection=T(y,l));return g=function(y,E){return E&&(y.audio.inbound.map(x=>{let A=E.audio.inbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesReceived"),x.packetRate=I(x,A,"packetsReceived")}),y.audio.outbound.map(x=>{let A=E.audio.outbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesSent"),x.packetRate=I(x,A,"packetsSent")}),y.video.inbound.map(x=>{let A=E.video.inbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesReceived"),x.packetRate=I(x,A,"packetsReceived")}),y.video.outbound.map(x=>{let A=E.video.outbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesSent"),x.packetRate=I(x,A,"packetsSent")})),y}(g,u),g}let D,b={},k=[];e.WebRTCStats=class extends s{constructor(l){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 u={...l};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=u.getStatsInterval||1e3,this.rawStats=!!u.rawStats,this.statsObject=!!u.statsObject,this.filteredStats=!!u.filteredStats,this.shouldWrapGetUserMedia=!!u.wrapGetUserMedia,typeof u.remote=="boolean"&&(this.remote=u.remote),this.debug=!!u.debug,this.logLevel=u.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(l,u){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:l,pc:u})}async addConnection(l){const{pc:u,peerId:h}=l;let{connectionId:g,remote:y}=l;if(y=typeof y=="boolean"?y:this.remote,!(u&&u 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(g&&g in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${g}.`);for(let x in this.peersToMonitor[h]){const A=this.peersToMonitor[h][x];if(A.pc===u)throw new Error(`We are already monitoring peer with id ${h}.`);A.pc.connectionState==="closed"&&this.removeConnection({pc:A.pc})}}const E=u.getConfiguration();return E.iceServers&&E.iceServers.forEach(function(x){delete x.credential}),g||(g=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:g,data:{options:l,peerConfiguration:E}}),this.monitorPeer({peerId:h,connectionId:g,pc:u,remote:y}),{connectionId:g}}getTimeline(l){return this.timeline=this.timeline.sort((u,h)=>u.timestamp.getTime()-h.timestamp.getTime()),l?this.timeline.filter(u=>u.tag===l):this.timeline}get logger(){const l=u=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(u)>-1};return{error(...u){this.debug&&l("error")&&console.error("[webrtc-stats][error] ",...u)},warn(...u){this.debug&&l("warn")&&console.warn("[webrtc-stats][warn] ",...u)},info(...u){this.debug&&l("info")&&console.log("[webrtc-stats][info] ",...u)},debug(...u){this.debug&&l("debug")&&console.debug("[webrtc-stats][debug] ",...u)}}}removeConnection(l){let u,{connectionId:h,pc:g}=l;if(!g&&!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 y in this.peersToMonitor)h in this.peersToMonitor[y]&&(g=this.peersToMonitor[y][h].pc,u=y)}else if(g){if(!(g instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let y in this.peersToMonitor)for(let E in this.peersToMonitor[y])this.peersToMonitor[y][E].pc===g&&(h=E,u=y)}if(!g||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,g),delete this.peersToMonitor[u][h],Object.values(this.peersToMonitor[u]).length===0&&delete this.peersToMonitor[u],{connectionId:h}}removeAllPeers(){for(let l in this.peersToMonitor)this.removePeer(l)}removePeer(l){if(this.logger.info(`Removing PeerConnection with id ${l}.`),this.peersToMonitor[l]){for(let u in this.peersToMonitor[l]){let h=this.peersToMonitor[l][u].pc;this.removePeerConnectionEventListeners(u,h)}delete this.peersToMonitor[l]}}destroy(){this.removeAllPeers(),k.forEach(l=>{this.removeTrackEventListeners(l)}),k=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(l){let{peerId:u,connectionId:h,pc:g,remote:y}=l;if(!g)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const E={pc:g,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:y}};if(this.peersToMonitor[u]){if(h in this.peersToMonitor[u])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[u][h]=E}else this.peersToMonitor[u]={[h]:E};this.addPeerConnectionEventListeners(u,h,g),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(l=>{l.forEach(u=>{this.emitEvent(u)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(l=null){this.logger.info(l?`Getting stats from peer ${l}`:"Getting stats from all peers");let u={};if(l){if(!this.peersToMonitor[l])throw new Error(`Cannot get stats. Peer with id ${l} does not exist`);u[l]=this.peersToMonitor[l]}else u=this.peersToMonitor;let h=[];for(const g in u)for(const y in u[g]){const E=u[g][y],x=E.pc;if(x&&!this.checkIfConnectionIsClosed(g,y,x))try{const A=this.getTimestamp(),P=x.getStats(null);if(P){const V=await P,H=this.getTimestamp(),N=R(V),ne={remote:E.options.remote},G=L(V,E.stats.parsed,ne),F={event:"stats",tag:"stats",peerId:g,connectionId:y,timeTaken:H-A,data:G};this.rawStats===!0&&(F.rawStats=V),this.statsObject===!0&&(F.statsObject=N),this.filteredStats===!0&&(F.filteredStats=this.filteroutStats(N)),h.push(F),E.stats.parsed=G}else this.logger.error(`PeerConnection from peer ${g} did not return any stats data`)}catch(A){this.logger.error(A)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const l in this.peersToMonitor)for(const u in this.peersToMonitor[l]){const h=this.peersToMonitor[l][u].pc;this.checkIfConnectionIsClosed(l,u,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(l,u,h){const g=this.isConnectionClosed(h);if(g){this.removeConnection({pc:h});let y=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:y,peerId:l,connectionId:u,tag:"connection",data:"closed"})}return g}isConnectionClosed(l){return l.connectionState==="closed"||l.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."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const l=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return l({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(u=>(l({stream:u}),u),u=>(l({error:u}),Promise.reject(u)))}).bind(navigator.mediaDevices)}filteroutStats(l={}){const u={...l};for(const g in u){var h=u[g];this.statsToMonitor.includes(h.type)||delete u[g]}return u}get peerConnectionListeners(){return{icecandidate:(l,u,h,g)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",g),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:l,connectionId:u,data:g.candidate})},track:(l,u,h,g)=>{this.logger.debug(`[pc-event] track | peerId: ${l}`,g);const y=g.track,E=g.streams[0];l in this.peersToMonitor&&u in this.peersToMonitor[l]&&(this.peersToMonitor[l][u].stream=E),this.addTrackEventListeners(y,u),this.emitEvent({event:"ontrack",tag:"track",peerId:l,connectionId:u,data:{stream:E?this.getStreamDetails(E):null,track:y?this.getMediaTrackDetails(y):null,title:g.track.kind+":"+g.track.id+" "+g.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${l}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:l,connectionId:u,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${l}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:l,connectionId:u,data:h.iceConnectionState})},icegatheringstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${l}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:l,connectionId:u,data:h.iceGatheringState})},icecandidateerror:(l,u,h,g)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${l}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:l,connectionId:u,error:{errorCode:g.errorCode}})},connectionstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${l}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:l,connectionId:u,data:h.connectionState})},negotiationneeded:(l,u,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${l}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:l,connectionId:u})},datachannel:(l,u,h,g)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${l}`,g),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:l,connectionId:u,data:g.channel})}}}addPeerConnectionEventListeners(l,u,h){this.logger.debug(`Adding event listeners for peer ${l} and connection ${u}.`),b[u]={},Object.keys(this.peerConnectionListeners).forEach(g=>{b[u][g]=this.peerConnectionListeners[g].bind(this,l,u,h),h.addEventListener(g,b[u][g],!1)})}parseGetUserMedia(l){try{const u={event:"getUserMedia",tag:"getUserMedia",data:{...l}};l.stream&&(u.data.details=this.parseStream(l.stream),l.stream.getTracks().map(h=>{this.addTrackEventListeners(h),k.push(h)})),this.emitEvent(u)}catch{}}parseStream(l){const u={audio:[],video:[]};return l.getTracks().forEach(h=>{u[h.kind].push(this.getMediaTrackDetails(h))}),u}getMediaTrackDetails(l){return{enabled:l.enabled,id:l.id,contentHint:l.contentHint,kind:l.kind,label:l.label,muted:l.muted,readyState:l.readyState,constructorName:l.constructor.name,capabilities:l.getCapabilities?l.getCapabilities():{},constraints:l.getConstraints?l.getConstraints():{},settings:l.getSettings?l.getSettings():{},_track:l}}getStreamDetails(l){return{active:l.active,id:l.id,_stream:l}}getTrackEventObject(l){return{mute:u=>{this.emitEvent({event:"mute",tag:"track",connectionId:l,data:{event:u}})},unmute:u=>{this.emitEvent({event:"unmute",tag:"track",connectionId:l,data:{event:u}})},overconstrained:u=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:l,data:{event:u}})},ended:u=>{this.emitEvent({event:"ended",tag:"track",connectionId:l,data:{event:u}}),this.removeTrackEventListeners(u.target)}}}addTrackEventListeners(l,u){b[l.id]={};const h=this.getTrackEventObject(u);Object.keys(h).forEach(g=>{b[l.id][g]=h[g].bind(this),l.addEventListener(g,b[l.id][g])}),b[l.id].readyState=setInterval(()=>{if(l.readyState==="ended"){let g=new CustomEvent("ended",{detail:{check:"readyState"}});l.dispatchEvent(g)}},1e3)}removeTrackEventListeners(l){if(l.id in b){const u=this.getTrackEventObject();Object.keys(u).forEach(h=>{l.removeEventListener(h,b[l.id][h])}),clearInterval(b[l.id].readyState),delete b[l.id]}}addToTimeline(l){this.timeline.push(l),this.emit("timeline",l)}emitEvent(l){const u={...l,timestamp:new Date};this.addToTimeline(u),u.tag&&this.emit(u.tag,u)}set getStatsInterval(l){if(!Number.isInteger(l))throw new Error(`getStatsInterval should be an integer, got: ${l}`);this._getStatsInterval=l,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(l,u){l in b&&(Object.keys(this.peerConnectionListeners).forEach(h=>{u.removeEventListener(h,b[l][h],!1)}),delete b[l]),u.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),u.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const l=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const u=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return l.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),u.apply(navigator.mediaDevices,arguments).then(function(g){return g},function(g){return l.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,g.name),Promise.reject(g)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(Wi=vu)&&Wi.__esModule&&Object.prototype.hasOwnProperty.call(Wi,"default")&&Wi.default;var Ny=vu.WebRTCStats;function Vy(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(d){const{jitter:f,rtt:p}=d,m=f+p/2;return .024*m+.11*(m-177.3)*(m>177.3?1:0)}({rtt:s,jitter:i}),r=function(d){const{packetsLost:f,packetsReceived:p}=d,m=f/(p+f)*100;return 20*Math.log(1+m)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function Fy(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class By extends Yn{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class jy extends Yn{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class Uy extends Yn{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function $y(t){const e=pn(),n=new Ny({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>$(this,void 0,void 0,function*(){s.event==="stats"&&ee(j.StatsFrame,function({data:o}){var r,a,c,d,f,p,m,v;const{audio:_,remote:C}=o,{audio:S}=C,w=(a=(r=S.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,T=(d=(c=S.inbound[0])===null||c===void 0?void 0:c.roundTripTime)!==null&&d!==void 0?d:1/0,I=(p=(f=_.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&p!==void 0?p:-1,R=(v=(m=_.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,L=Vy({jitter:1e3*w,rtt:1e3*T,packetsLost:R,packetsReceived:I});return{jitter:w,rtt:T,mos:L,quality:Fy(L),inboundAudio:_.inbound[0],outboundAudio:_.outbound[0],remoteInboundAudio:S.inbound[0],remoteOutboundAudio:S.outbound[0]}}(s),t.uuid),yield t.execute(new Uy(e,s))});return{start:(s,o,r)=>$(this,void 0,void 0,function*(){yield t.execute(new By(e)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>$(this,void 0,void 0,function*(){const o=n.getTimeline();ee(j.StatsReport,o,t.uuid),s==="file"&&function(r,a){const c=new Blob([JSON.stringify(r)],{type:"application/json"}),d=URL.createObjectURL(c),f=document.createElement("a");f.href=d,f.download=`${a}.json`,f.click(),URL.revokeObjectURL(d)}(o,`webrtc-stats-${e}-${Date.now()}`),yield t.execute(new jy(e)),n.removeAllPeers(),n.destroy()})}}class yu{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this.handleConnectionStateChange=r=>$(this,void 0,void 0,function*(){const{connectionState:a}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${a}`),a==="failed"||a==="disconnected"){const c=()=>$(this,void 0,void 0,function*(){this._isOffer()&&!this._restartedIceOnConnectionStateFailed?(this.instance.restartIce(),O.debug(`Peer Connection ${a}. Restarting ICE gathering.`),a==="failed"&&(this._restartedIceOnConnectionStateFailed=!0,O.debug("ICE has been restarted on connection state failed.")),this._isTrickleIce()?yield this.startTrickleIceNegotiation():this.startNegotiation()):this._restartedIceOnConnectionStateFailed&&(O.debug("Peer Connection failed again after ICE restart. Closing unrecoverable call."),ee(j.PeerConnectionFailureError,{error:new Error(`Peer Connection failed twice. previous state: ${this._prevConnectionState}, current state: ${a}`),sessionId:this._session.sessionid},this.options.id)),window.removeEventListener("online",c)});navigator.onLine?c():window.addEventListener("online",c)}this._prevConnectionState==="connected"&&a==="disconnected"&&(yield this._resetJitterBuffer()),this._prevConnectionState==="disconnected"&&a==="connected"&&(yield this._resetJitterBuffer()),this._prevConnectionState=a,this._isTrickleIce()&&(a==="connecting"&&performance.mark("peer-connection-connecting"),a==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=r=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return r.setCodecPreferences?r.setCodecPreferences(this.options.preferred_codecs):void 0},O.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!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._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Ee.Offer}get isAnswer(){return this.type===Ee.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get keepConnectionAliveOnSocketClose(){return this.options.keepConnectionAliveOnSocketClose||this._session.options.keepConnectionAliveOnSocketClose}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return $(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){O.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{O.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),O.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=c=>`${c.toFixed(2)}ms`;return{"New Call":{duration:a(e.duration)},"Peer Creation":{duration:a(n.duration)},"ICE Gathering":{duration:a(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:a(o.duration)},"SDP Send":{duration:a(s.duration)},"Total Duration":{duration:a(r.duration)}}}handleSignalingStateChangeEvent(e){switch(O.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(){O.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?O.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Zn(i,o)}createPeerConnection(){return $(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ee.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(ee(j.MediaError,n,this.options.id),null)),performance.mark("peer-creation-end")})}init(){var e;return $(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if($i(i)){const o=i.getAudioTracks();if(O.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(r=>{O.info("Local audio tracks constraints: ",r.getConstraints())}),this.isOffer&&typeof this.instance.addTransceiver=="function"){const r={direction:"sendrecv",streams:[i]};o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label;const c=this.instance.addTransceiver(a,r);this._setAudioCodec(c)})}else typeof this.instance.addTrack=="function"?(o.forEach(r=>{this.options.userVariables.microphoneLabel=r.label,this.instance.addTrack(r,i)}),this.instance.getTransceivers().forEach(r=>this._setAudioCodec(r))):this.instance.addStream(i);s===!1&&Zn(n,i)}this.isOffer?this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers(),this.isDebugEnabled&&(this.statsReporter=$y(this._session))})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);O.info("Add transceiver",e,n)}}_createOffer(){return $(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!!this.options.audio,O.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){O.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return $(this,void 0,void 0,function*(){O.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return $(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return O.debug("Skipping negotiation, state:",this.instance.signalingState),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:Ee.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){O.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return $(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){mn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return $(this,void 0,void 0,function*(){if($i(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,$(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s}=n;const{micLabel:o=""}=n;return s&&(s=yield Kr(s,o,bt.AudioIn).catch(r=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),{audio:i}}));var n;return Gi(e)})}_resetJitterBuffer(){return $(this,void 0,void 0,function*(){try{const e=this.instance.getReceivers().find(n=>n.track&&n.track.kind==="audio");e&&"jitterBufferTarget"in e&&(e.jitterBufferTarget=20,O.debug("[jitter] target set to",e.jitterBufferTarget,"ms"))}catch(e){O.error("Peer _resetJitterBuffer error:",e)}})}_isOffer(){return this.type===Ee.Offer}_isAnswer(){return this.type===Ee.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n}=this.options,i={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:[dy,Hd],iceTransportPolicy:n?"relay":"all"};return O.info("RTC config",i),i}close(){var e;return $(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 _u=Hi;class bu{constructor(e,n){this.session=e,this.id="",this.state=Z[Z.New],this.prevState="",this.channels=[],this.role=Wr.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._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._checkConferenceSerno=C=>{const S=C<0||!this._lastSerno||this._lastSerno&&C===this._lastSerno+1;return S&&C>=0&&(this._lastSerno=C),S},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(C=>{C.forEach(S=>{this._statsBindings.forEach(w=>{if(w.callback){if(w.constraints){for(var T in w.constraints)if(w.constraints.hasOwnProperty(T)&&w.constraints[T]!==S[T])return}w.callback(S)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:d,remoteElement:f,options:p,mediaConstraints:{audio:m},ringtoneFile:v,ringbackFile:_}=e;this.options=Object.assign({},vy,{audio:m,iceServers:i,localElement:d,remoteElement:f,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:v,ringbackFile:_,debug:p.debug,debugOutput:p.debugOutput,trickleIce:p.trickleIce,prefetchIceCandidates:p.prefetchIceCandidates,keepConnectionAliveOnSocketClose:p.keepConnectionAliveOnSocketClose},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=au(this.options.ringtoneFile,"_ringtone"),this._ringback=au(this.options.ringbackFile,"_ringback"))}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),n=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("total-duration","peer-creation-start","sdp-send-end"),o=r=>`${r.toFixed(2)}ms`;return{"Peer Creation":{duration:o(e.duration)},"ICE Gathering":{duration:o(n.duration)},"SDP Send":{duration:o(i.duration)},"Total Duration":{duration:o(s.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}invite(){return $(this,void 0,void 0,function*(){this.direction=It.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new yu(Ee.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init()})}answer(e={}){var n;return $(this,void 0,void 0,function*(){performance.mark("new-call-start"),this.stopRingtone(),this.direction=It.Inbound,((n=e==null?void 0:e.customHeaders)===null||n===void 0?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new yu(Ee.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end")})}playRingtone(){cu(this._ringtone)}stopRingtone(){lu(this._ringtone)}playRingback(){cu(this._ringback)}stopRingback(){lu(this._ringback)}hangup(e,n){var i,s,o;let r=e||{},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(Z.Hangup);const c=()=>{var d;return(d=this.peer)===null||d===void 0||d.close(),this.setState(Z.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const d=new Ay({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(d).catch(f=>{O.error("telnyx_rtc.bye failed!",f),ee(j.Error,{error:f,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new Jr({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 Jr({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 Jr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new mu({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},s=new mu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){ru(this.options.localStream)}unmuteAudio(){su(this.options.localStream)}toggleAudioMute(){ou(this.options.localStream)}setAudioInDevice(e){return $(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 qr({audio:{deviceId:{exact:e}}}),o=s.getAudioTracks()[0];i.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach(a=>a.stop()),r.getVideoTracks().forEach(a=>s.addTrack(a)),this.options.localStream=s}})}muteVideo(){var e;e=this.options.localStream,vn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,vn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,vn(e,"video",null)}setVideoDevice(e){return $(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 qr({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Zn(r,s),this.options.camId=e,a.getAudioTracks().forEach(c=>s.addTrack(c)),a.getVideoTracks().forEach(c=>c.stop()),this.options.localStream=s}})}deaf(){ru(this.options.remoteStream)}undeaf(){su(this.options.remoteStream)}toggleDeaf(){ou(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return $(this,void 0,void 0,function*(){if(!this||!this.peer)return void O.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 O.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"}]),O.info("Parameters: ",r),O.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{O.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>console.error(a))}else O.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=Z[this._state].toLowerCase(),this.prevState=Z[this._prevState].toLowerCase(),O.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Qe.callUpdate,call:this}),e){case Z.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case Z.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&nu(n,i)},0);break;case Z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case ie.Answer:if(this.gotAnswer=!0,this._state>=Z.Active)return;this._state>=Z.Early&&this.setState(Z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case ie.Media:if(this._state>=Z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case ie.Display:case ie.Attach:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const c=a===It.Inbound?It.Outbound:It.Inbound,d={type:Qe[n],call:this,displayName:o,displayNumber:r,displayDirection:c};ee(j.Notification,d,this.id)||ee(j.Notification,d,this.session.uuid);break}case ie.Candidate:this._addIceCandidate(i);break;case ie.Info:case ie.Event:{const o=Object.assign(Object.assign({},i),{type:Qe.generic,call:this});ee(j.Notification,o,this.id)||ee(j.Notification,o,this.session.uuid);break}case ie.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 ie.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,n){return $(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return O.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:c,modChannel:d,laName:f,conferenceMemberID:p,role:m}=n;this._dispatchConferenceUpdate({action:$e.Join,conferenceName:f,participantId:Number(p),role:m}),a&&(yield this._subscribeConferenceChat(a)),c&&(yield this._subscribeConferenceInfo(c));const v=[];for(const _ in s)v.push(Object.assign({callId:s[_][0],index:Number(_)},Bi(s[_][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:v});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:o,index:r},Bi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:o,index:r},Bi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:o,index:r},Bi(s)));break;case"clear":this._dispatchConferenceUpdate({action:$e.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return $(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:c,type:d}=s.data;this._dispatchConferenceUpdate({action:$e.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:c,messageType:d,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{O.error("ConfChat subscription error:",s)});Xr(i,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 $(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,gu(this.session,o)):O.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{O.error("ConfInfo subscription error:",s)});Xr(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(Z.Active):this.setState(Z.Held),!0}_handleChangeHoldStateError(e){return O.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return $(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ee.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(Z.Early),this.gotAnswer&&this.setState(Z.Active)}).catch(i=>{O.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){mn(this.peer.onSdpReadyTwice)?ee(j.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return O.info(`No candidate - retry
111
- `),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${_u}`};switch(o){case Ee.Offer:this.setState(Z.Requesting),r=new hu(a);break;case Ee.Answer:this.setState(Z.Answering),r=this.options.attach===!0?new Zr(a):new fu(a);break;default:return O.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(c=>{const{node_id:d=null}=c;this._targetNodeId=d,o===Ee.Offer?this.setState(Z.Trying):this.setState(Z.Active)}).catch(c=>{O.error(`${this.id} - Sending ${o} error:`,c),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return O.error("No SDP data provided"),this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const o={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${_u}`};switch(i){case Ee.Offer:this.setState(Z.Requesting),s=new hu(o);break;case Ee.Answer:this.setState(Z.Answering),s=this.options.attach===!0?new Zr(o):new fu(o);break;default:return O.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Ee.Offer?this.setState(Z.Trying):this.setState(Z.Active)}).catch(r=>{O.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?O.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(O.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new pu({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return O.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{O.debug("Successfully added ICE candidate:",e)}).catch(i=>{O.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Ry({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Zn(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{O.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&O.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{O.debug("ICE candidate error:",n)},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Zn(i,s)})}_onMediaError(e){this._dispatchNotification({type:Qe.userMediaError,error:e}),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Qe.peerConnectionFailureError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Qe.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(ee(j.Notification,e,this.id,!1)||ee(j.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;var o;this.options.id=e?e.toString():pn(),this.id=this.options.id,n&&(o=n,Object.keys(o).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Gt(j.MediaError,this._onMediaError,this.id),Gt(j.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),mn(s)&&Gt(j.Notification,s.bind(this),this.id),this.setState(Z.New),O.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:n}=this.options;Jn(e),Jn(n),Ht(j.MediaError,null,this.id),Ht(j.PeerConnectionFailureError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),O.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),O.info("Stats stopped")}}bu.setStateTelnyx=t=>{if(t){switch(t._state){case Z.Requesting:case Z.Recovering:case Z.Trying:case Z.Early:t.state="connecting";break;case Z.Active:t.state="active";break;case Z.Held:t.state="held";break;case Z.Hangup:case Z.Destroy:t.state="done";break;case Z.Answering:t.state="ringing";break;case Z.New:t.state="new"}return t}};class Wt extends bu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new Dy(e,n))}hangup(e={},n=!0){this.screenShare instanceof Wt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return $(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(d=>{d.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,c=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Wt(this.session,c),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Wt&&this.screenShare.hangup()}setAudioOutDevice(e){return $(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&nu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);O.setLevel(2),this._statsInterval=window.setInterval(()=>$(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+=`
110
+ `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(mn(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)),Y(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else R.warn("Unknown message from socket",e)}}class Jn{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:pn()},e)}}const Xd={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Pe extends Jn{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Nd(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Xd)i&&n.hasOwnProperty(i)&&(n[Xd[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class Yd extends Pe{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class l_{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>j(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Br(n))}),this.getIsRegistered=()=>j(this,void 0,void 0,function*(){const n=new Yd($t());this.pendingRequestId=n.request.id,this.gatewayStateTask=Wd({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[De.REGISTER,De.REGED].includes(i)}),this.session=e,this.gatewayStateTask=Wd({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Jd extends Pe{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class d_{constructor(e){if(this.options=e,this.uuid=pn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");e.debug&&R.setLevel("debug"),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 Kd(this),this.registerAgent=new l_(this)}get __logger(){return R}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return j(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Gd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return $i(this.options)||Xn(this.options)}broadcast(e){}disconnect(){return j(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners()})}on(e,n){return Ht(e,n,this.uuid),this}off(e,n){return Gt(e,n,this.uuid),this}connect(){return j(this,void 0,void 0,function*(){this.connection||(this.connection=new Kd(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){Y(F.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return j(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&$r(this.relayProtocol);for(const e in this.subscriptions)$r(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Gt(e,null,n)):(delete this.subscriptions[e],$r(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},mn(n)&&Ht(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].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:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(R.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Jd($t()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){R.debug("Ping received"),this._pong=!0}static on(e,n){Ht(e,n)}static off(e){Gt(e)}static uuid(){return pn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Hr=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,Zn=(t,e)=>{const n=Ui(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},Zd=(t,e)=>j(void 0,void 0,void 0,function*(){const n=Ui(t);if(n===null)return R.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return R.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),u_=t=>{t&&t.readyState==="live"&&t.stop()},Qn=t=>{vn(t)&&t.getTracks().forEach(u_),t=null},Hi=t=>j(void 0,void 0,void 0,function*(){R.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Hr(t)}catch(i){throw R.error("getUserMedia error: ",i),i}}),ei=(t=null,e=!1)=>j(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===dt.AudioIn||s===dt.AudioOut,video:!s||s===dt.Video}))(t)).catch(s=>(R.error(s),null));if(i){if(Qn(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(o=>o.kind===t)),e===!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}),Qd=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Gi=(t,e,n)=>j(void 0,void 0,void 0,function*(){const i=yield ei(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(t===o||e===r)return o}return null}),h_=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Gr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=Wr(t);return n.includes(e)||i.includes(e)},Wr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},_n=(t,e=null,n=null)=>{if(!vn(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},eu=t=>{_n(t,"audio",!0)},zr=t=>{_n(t,"audio",!1)},tu=t=>{_n(t,"audio",null)},f_=t=>((e,n=null)=>{if(!vn(e))return null;let i=[];switch(n){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some(s=>s.enabled)})(t,"audio");function p_(){try{const{browserInfo:t,name:e,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],h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,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],h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,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("/"),h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,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],h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,l=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&l),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!Hi}}catch(t){return t.message}}var ve;function nu(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function iu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{R.error("playAudio",e),t._playFulfilled=!0}))}function su(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(ve||(ve={}));var ru="2.25.12",Wi=ru;class ou extends Pe{constructor(e,n,i,s,o={},r){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Wi,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class m_ extends Pe{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class au extends Pe{toString(){return te.Invite}}class cu extends Pe{toString(){return te.Answer}}class qr extends Pe{toString(){return te.Attach}}class g_ extends Pe{toString(){return te.Bye}}class lu extends Pe{toString(){return te.Candidate}}class v_ extends Pe{toString(){return te.EndOfCandidates}}class Kr extends Pe{toString(){return te.Modify}}class du extends Pe{toString(){return te.Info}}class __ extends Pe{toString(){return te.Broadcast}}class y_ extends Pe{toString(){return te.Subscribe}}class b_ extends Pe{toString(){return te.Unsubscribe}}class w_ extends Jn{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:pn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}var zi,uu=Ud(function(t,e){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,p,_){var T,P,I;if(typeof p!="function")throw new TypeError('"listener" argument must be a function');if((P=f._events)?(P.newListener&&(f.emit("newListener",m,p.listener?p.listener:p),P=f._events),I=P[m]):(P=f._events=new i,f._eventsCount=0),I){if(typeof I=="function"?I=P[m]=_?[p,I]:[I,p]:_?I.unshift(p):I.push(p),!I.warned&&(T=o(f))&&0<T&&I.length>T){I.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+I.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");D.name="MaxListenersExceededWarning",D.emitter=f,D.type=m,D.count=I.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(D)}}else I=P[m]=p,++f._eventsCount;return f}function a(f,m,p){function _(){f.removeListener(m,_),T||(T=!0,p.apply(f,arguments))}var T=!1;return _.listener=p,_}function c(f){var m=this._events;if(m){var p=m[f];if(typeof p=="function")return 1;if(p)return p.length}return 0}function l(f,m){for(var p=Array(m);m--;)p[m]=f[m];return p}Object.defineProperty(e,"__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,p,_,T,P,I,D,M=f==="error";if(I=this._events)M=M&&I.error==null;else if(!M)return!1;if(D=this.domain,M){if(m=arguments[1],!D){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=D,m.domainThrown=!1,D.emit("error",m),!1}if(!(p=I[f]))return!1;var X=typeof p=="function";switch(_=arguments.length){case 1:(function(B,re,Q){if(re)B.call(Q);else for(var U=B.length,ce=l(B,U),q=0;q<U;++q)ce[q].call(Q)})(p,X,this);break;case 2:(function(B,re,Q,U){if(re)B.call(Q,U);else for(var ce=B.length,q=l(B,ce),J=0;J<ce;++J)q[J].call(Q,U)})(p,X,this,arguments[1]);break;case 3:(function(B,re,Q,U,ce){if(re)B.call(Q,U,ce);else for(var q=B.length,J=l(B,q),Z=0;Z<q;++Z)J[Z].call(Q,U,ce)})(p,X,this,arguments[1],arguments[2]);break;case 4:(function(B,re,Q,U,ce,q){if(re)B.call(Q,U,ce,q);else for(var J=B.length,Z=l(B,J),ee=0;ee<J;++ee)Z[ee].call(Q,U,ce,q)})(p,X,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(_-1),P=1;P<_;P++)T[P-1]=arguments[P];(function(B,re,Q,U){if(re)B.apply(Q,U);else for(var ce=B.length,q=l(B,ce),J=0;J<ce;++J)q[J].apply(Q,U)})(p,X,this,T)}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 p,_,T,P,I;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(_=this._events))return this;if(!(p=_[f]))return this;if(p===m||p.listener&&p.listener===m)--this._eventsCount==0?this._events=new i:(delete _[f],_.removeListener&&this.emit("removeListener",f,p.listener||m));else if(typeof p!="function"){for(T=-1,P=p.length;0<P--;)if(p[P]===m||p[P].listener&&p[P].listener===m){I=p[P].listener,T=P;break}if(0>T)return this;if(p.length===1){if(p[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete _[f]}else(function(D,M){for(var V=M,X=V+1,B=D.length;X<B;V+=1,X+=1)D[V]=D[X];D.pop()})(p,T);_.removeListener&&this.emit("removeListener",f,I||m)}return this},s.prototype.removeAllListeners=function(f){var m,p;if(!(p=this._events))return this;if(!p.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):p[f]&&(--this._eventsCount==0?this._events=new i:delete p[f]),this;if(arguments.length===0){for(var _,T=Object.keys(p),P=0;P<T.length;++P)(_=T[P])!=="removeListener"&&this.removeAllListeners(_);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=p[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,p,_=this._events;return _?p=(m=_[f])?typeof m=="function"?[m.listener||m]:function(T){for(var P=Array(T.length),I=0;I<P.length;++I)P[I]=T[I].listener||T[I];return P}(m):[]:p=[],p},s.listenerCount=function(f,m){return typeof f.listenerCount=="function"?f.listenerCount(m):c.call(f,m)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function h(){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=[],y=0;256>y;++y)v.push((y+256).toString(16).substr(1));function x(f){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,p=(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(_){return typeof _=="string"&&g.test(_)}(p))throw TypeError("Stringified UUID is invalid");return p}function w(f,m,p){var _=(f=f||{}).random||(f.rng||h)();return _[6]=64|15&_[6],_[8]=128|63&_[8],x(_)}function S(f,m){if(!f||!m)return{};const p={...f};if(p.localCandidateId){const _=m.get(p.localCandidateId);p.local={..._}}if(p.remoteCandidateId){const _=m.get(p.remoteCandidateId);p.remote={..._}}return p}function k(f,m,p){return 8*function(_,T,P){const I=_[P],D=T?T[P]:null;return I===null||D===null?null:(I-D)/(_.timestamp-T.timestamp)*1e3}(f,m,p)}function A(f){if(!f.entries)return f;const m={};return f.forEach(function(p,_){m[_]=p}),m}function L(f,m,p={}){if(!f)return null;let _={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};p.remote&&(_.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const T of f.values())switch(T.type){case"outbound-rtp":{const P=T.mediaType||T.kind,I={};let D={};if(!["audio","video"].includes(P))continue;if(T.codecId){const M=f.get(T.codecId);M&&(I.clockRate=M.clockRate,I.mimeType=M.mimeType,I.payloadType=M.payloadType)}D=f.get(T.mediaSourceId)||f.get(T.trackId)||{},_[P].outbound.push({...T,...I,track:{...D}});break}case"inbound-rtp":{let P=T.mediaType||T.kind,I={};const D={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const M=f.get(T.codecId);M&&(D.clockRate=M.clockRate,D.mimeType=M.mimeType,D.payloadType=M.payloadType)}if(!_.connection.id&&T.transportId){const M=f.get(T.transportId);if(M&&M.selectedCandidatePairId){const V=f.get(M.selectedCandidatePairId);_.connection=S(V,f)}}I=f.get(T.mediaSourceId)||f.get(T.trackId)||{},_[P].inbound.push({...T,...D,track:{...I}});break}case"peer-connection":_.connection.dataChannelsClosed=T.dataChannelsClosed,_.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!p.remote)break;let P=T.mediaType||T.kind;const I={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const D=f.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}if(!_.connection.id&&T.transportId){const D=f.get(T.transportId);if(D&&D.selectedCandidatePairId){const M=f.get(D.selectedCandidatePairId);_.connection=S(M,f)}}_.remote[P].inbound.push({...T,...I});break}case"remote-outbound-rtp":{if(!p.remote)break;const P=T.mediaType||T.kind,I={};if(!["audio","video"].includes(P))continue;if(T.codecId){const D=f.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}_.remote[P].outbound.push({...T,...I});break}}if(!_.connection.id)for(const T of f.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(_.connection=S(T,f));return _=function(T,P){return P&&(T.audio.inbound.map(I=>{let D=P.audio.inbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesReceived"),I.packetRate=k(I,D,"packetsReceived")}),T.audio.outbound.map(I=>{let D=P.audio.outbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesSent"),I.packetRate=k(I,D,"packetsSent")}),T.video.inbound.map(I=>{let D=P.video.inbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesReceived"),I.packetRate=k(I,D,"packetsReceived")}),T.video.outbound.map(I=>{let D=P.video.outbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesSent"),I.packetRate=k(I,D,"packetsSent")})),T}(_,m),_}let O,b={},C=[];e.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:p}=f;let{connectionId:_,remote:T}=f;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!p)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[p]){if(_&&_ in this.peersToMonitor[p])throw new Error(`We are already monitoring connection with id ${_}.`);for(let I in this.peersToMonitor[p]){const D=this.peersToMonitor[p][I];if(D.pc===m)throw new Error(`We are already monitoring peer with id ${p}.`);D.pc.connectionState==="closed"&&this.removeConnection({pc:D.pc})}}const P=m.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(I){delete I.credential}),_||(_=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:p,connectionId:_,data:{options:f,peerConfiguration:P}}),this.monitorPeer({peerId:p,connectionId:_,pc:m,remote:T}),{connectionId:_}}getTimeline(f){return this.timeline=this.timeline.sort((m,p)=>m.timestamp.getTime()-p.timestamp.getTime()),f?this.timeline.filter(m=>m.tag===f):this.timeline}get logger(){const f=m=>{const p=["none","error","warn","info","debug"];return p.slice(0,p.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:p,pc:_}=f;if(!_&&!p)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(p){if(typeof p!="string")throw new Error("connectionId must be a string.");for(let T in this.peersToMonitor)p in this.peersToMonitor[T]&&(_=this.peersToMonitor[T][p].pc,m=T)}else if(_){if(!(_ instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let P in this.peersToMonitor[T])this.peersToMonitor[T][P].pc===_&&(p=P,m=T)}if(!_||!p)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(p,_),delete this.peersToMonitor[m][p],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:p}}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 p=this.peersToMonitor[f][m].pc;this.removePeerConnectionEventListeners(m,p)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),C.forEach(f=>{this.removeTrackEventListeners(f)}),C=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(f){let{peerId:m,connectionId:p,pc:_,remote:T}=f;if(!_)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:_,connectionId:p,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};if(this.peersToMonitor[m]){if(p in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${p}`);this.peersToMonitor[m][p]=P}else this.peersToMonitor[m]={[p]:P};this.addPeerConnectionEventListeners(m,p,_),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 p=[];for(const _ in m)for(const T in m[_]){const P=m[_][T],I=P.pc;if(I&&!this.checkIfConnectionIsClosed(_,T,I))try{const D=this.getTimestamp(),M=I.getStats(null);if(M){const V=await M,X=this.getTimestamp(),B=A(V),re={remote:P.options.remote},Q=L(V,P.stats.parsed,re),U={event:"stats",tag:"stats",peerId:_,connectionId:T,timeTaken:X-D,data:Q};this.rawStats===!0&&(U.rawStats=V),this.statsObject===!0&&(U.statsObject=B),this.filteredStats===!0&&(U.filteredStats=this.filteroutStats(B)),p.push(U),P.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${_} did not return any stats data`)}catch(D){this.logger.error(D)}}return p}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const m in this.peersToMonitor[f]){const p=this.peersToMonitor[f][m].pc;this.checkIfConnectionIsClosed(f,m,p)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,m,p){const _=this.isConnectionClosed(p);if(_){this.removeConnection({pc:p});let T=p.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,peerId:f,connectionId:m,tag:"connection",data:"closed"})}return _}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 _ in m){var p=m[_];this.statsToMonitor.includes(p.type)||delete m[_]}return m}get peerConnectionListeners(){return{icecandidate:(f,m,p,_)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",_),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:m,data:_.candidate})},track:(f,m,p,_)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,_);const T=_.track,P=_.streams[0];f in this.peersToMonitor&&m in this.peersToMonitor[f]&&(this.peersToMonitor[f][m].stream=P),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:m,data:{stream:P?this.getStreamDetails(P):null,track:T?this.getMediaTrackDetails(T):null,title:_.track.kind+":"+_.track.id+" "+_.streams.map(function(I){return"stream:"+I.id})}})},signalingstatechange:(f,m,p)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:m,data:{signalingState:p.signalingState,localDescription:p.localDescription,remoteDescription:p.remoteDescription}})},iceconnectionstatechange:(f,m,p)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:p.iceConnectionState})},icegatheringstatechange:(f,m,p)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:m,data:p.iceGatheringState})},icecandidateerror:(f,m,p,_)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:m,error:{errorCode:_.errorCode}})},connectionstatechange:(f,m,p)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:p.connectionState})},negotiationneeded:(f,m,p)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:m})},datachannel:(f,m,p,_)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,_),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:m,data:_.channel})}}}addPeerConnectionEventListeners(f,m,p){this.logger.debug(`Adding event listeners for peer ${f} and connection ${m}.`),b[m]={},Object.keys(this.peerConnectionListeners).forEach(_=>{b[m][_]=this.peerConnectionListeners[_].bind(this,f,m,p),p.addEventListener(_,b[m][_],!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(p=>{this.addTrackEventListeners(p),C.push(p)})),this.emitEvent(m)}catch{}}parseStream(f){const m={audio:[],video:[]};return f.getTracks().forEach(p=>{m[p.kind].push(this.getMediaTrackDetails(p))}),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){b[f.id]={};const p=this.getTrackEventObject(m);Object.keys(p).forEach(_=>{b[f.id][_]=p[_].bind(this),f.addEventListener(_,b[f.id][_])}),b[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let _=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(_)}},1e3)}removeTrackEventListeners(f){if(f.id in b){const m=this.getTrackEventObject();Object.keys(m).forEach(p=>{f.removeEventListener(p,b[f.id][p])}),clearInterval(b[f.id].readyState),delete b[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 b&&(Object.keys(this.peerConnectionListeners).forEach(p=>{m.removeEventListener(p,b[f][p],!1)}),delete b[f]),m.getSenders().forEach(p=>{p.track&&this.removeTrackEventListeners(p.track)}),m.getReceivers().forEach(p=>{p.track&&this.removeTrackEventListeners(p.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),p=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(_){return _},function(_){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,_.name),Promise.reject(_)})};navigator.mediaDevices.getDisplayMedia=p.bind(navigator.mediaDevices)}}}});(zi=uu)&&zi.__esModule&&Object.prototype.hasOwnProperty.call(zi,"default")&&zi.default;var x_=uu.WebRTCStats;function S_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(l){const{jitter:d,rtt:u}=l,h=d+u/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:i}),r=function(l){const{packetsLost:d,packetsReceived:u}=l,h=d/(u+d)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function C_(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class k_ extends Jn{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class T_ extends Jn{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class E_ extends Jn{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function hu(t,e){var n,i;return{errorCode:t.errorCode,errorText:t.errorText,url:t.url,address:t.address,port:t.port,connectionState:e.connectionState,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState,localDescriptionType:(n=e.localDescription)===null||n===void 0?void 0:n.type,remoteDescriptionType:(i=e.remoteDescription)===null||i===void 0?void 0:i.type}}function A_(t,e){const n=pn(),i=new x_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),s=o=>j(this,void 0,void 0,function*(){o.event==="stats"&&Y(F.StatsFrame,function({data:r}){var a,c,l,d,u,h,g,v;const{audio:y,remote:x}=r,{audio:w}=x,S=(c=(a=w.inbound[0])===null||a===void 0?void 0:a.jitter)!==null&&c!==void 0?c:1/0,k=(d=(l=w.inbound[0])===null||l===void 0?void 0:l.roundTripTime)!==null&&d!==void 0?d:1/0,A=(h=(u=y.inbound[0])===null||u===void 0?void 0:u.packetsReceived)!==null&&h!==void 0?h:-1,L=(v=(g=y.inbound[0])===null||g===void 0?void 0:g.packetsLost)!==null&&v!==void 0?v:-1,O=S_({jitter:1e3*S,rtt:1e3*k,packetsLost:L,packetsReceived:A});return{jitter:S,rtt:k,mos:O,quality:C_(O),inboundAudio:y.inbound[0],outboundAudio:y.outbound[0],remoteInboundAudio:w.inbound[0],remoteOutboundAudio:w.outbound[0]}}(o),t.uuid),yield t.execute(new E_(n,o))});return{start:(o,r,a)=>j(this,void 0,void 0,function*(){yield t.execute(new k_(n,e)),i.on("timeline",s),yield new Promise(c=>setTimeout(c,500)),i.addConnection({pc:o,peerId:r,connectionId:a})}),stop:o=>j(this,void 0,void 0,function*(){const r=i.getTimeline();Y(F.StatsReport,r,t.uuid),o==="file"&&function(a,c){const l=new Blob([JSON.stringify(a)],{type:"application/json"}),d=URL.createObjectURL(l),u=document.createElement("a");u.href=d,u.download=`${c}.json`,u.click(),URL.revokeObjectURL(d)}(r,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new T_(n,e)),i.removeAllPeers(),i.destroy()}),reportConnectionStateChange:o=>{const r={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};s(r)},reportIceCandidateError:o=>{const r={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};s(r)}}}const fu=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:Qe.conferenceUpdate,call:t.calls[s],canvasInfo:I_(o),currentLayerIdx:r};switch(n){case"layer-info":{const c=Object.assign({action:$e.LayerInfo},a);Y(F.Notification,c,t.uuid);break}case"layout-info":{const c=Object.assign({action:$e.LayoutInfo},a);Y(F.Notification,c,t.uuid);break}}},I_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return $d(e)};class pu{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=r=>j(this,void 0,void 0,function*(){const{connectionState:a}=this.instance;if(R.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${a}`),a==="failed"||a==="disconnected"){const c=()=>j(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(d,u){return j(this,void 0,void 0,function*(){const h={connectionState:d.connectionState,previousConnectionState:u,iceConnectionState:d.iceConnectionState,iceGatheringState:d.iceGatheringState,signalingState:d.signalingState},g=d.getTransceivers();if(g.length>0){const v=g[0].sender,y=v==null?void 0:v.transport;y&&(h.dtlsState=y.state)}d.sctp&&(h.sctpState=d.sctp.state);try{const v=yield d.getStats();v.forEach(y=>{y.type==="candidate-pair"&&y.state==="succeeded"&&(h.candidatePairState=y.state,v.forEach(x=>{x.type==="local-candidate"&&x.id===y.localCandidateId&&(h.localCandidateType=x.candidateType,h.selectedCandidatePair=h.selectedCandidatePair||{local:{},remote:{}},h.selectedCandidatePair.local={address:x.address,port:x.port,protocol:x.protocol,candidateType:x.candidateType}),x.type==="remote-candidate"&&x.id===y.remoteCandidateId&&(h.remoteCandidateType=x.candidateType,h.selectedCandidatePair=h.selectedCandidatePair||{local:{},remote:{}},h.selectedCandidatePair.remote={address:x.address,port:x.port,protocol:x.protocol,candidateType:x.candidateType})})),y.type==="transport"&&(h.dtlsCipher=y.dtlsCipher,h.srtpCipher=y.srtpCipher,h.tlsVersion=y.tlsVersion,y.dtlsState&&(h.dtlsState=y.dtlsState))})}catch(v){R.error("Error gathering connection state details:",v)}return h})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}this._restartedIceOnConnectionStateFailed?(R.debug("Peer Connection failed again after ICE restart. Recovering call via peer reconnection through error handling."),Y(F.PeerConnectionFailureError,{error:new Error(`Peer Connection failed twice. previous state: ${this._prevConnectionState}, current state: ${a}`),sessionId:this._session.sessionid},this.options.id)):(this.instance.restartIce(),a==="failed"&&(this._restartedIceOnConnectionStateFailed=!0,R.debug("ICE has been restarted on connection state failed.")),this._isTrickleIce()?yield this.startTrickleIceNegotiation():this.startNegotiation()),window.removeEventListener("online",c)});navigator.onLine?c():window.addEventListener("online",c)}this._prevConnectionState==="connected"&&a==="disconnected"&&(yield this._resetJitterBuffer()),this._prevConnectionState==="disconnected"&&a==="connected"&&(yield this._resetJitterBuffer()),this._prevConnectionState=a,this._isTrickleIce()&&(a==="connecting"&&performance.mark("peer-connection-connecting"),a==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks())),this._restartNegotiationOnDeviceSleepWakeup()}),this._handleIceConnectionStateChange=r=>{R.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=r=>{R.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},R.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},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._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Ae.Offer}get isAnswer(){return this.type===Ae.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get keepConnectionAliveOnSocketClose(){return this.options.keepConnectionAliveOnSocketClose||this._session.options.keepConnectionAliveOnSocketClose}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return j(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){R.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{R.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),R.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=c=>`${c.toFixed(2)}ms`;return{"New Call":{duration:a(e.duration)},"Peer Creation":{duration:a(n.duration)},"ICE Gathering":{duration:a(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:a(o.duration)},"SDP Send":{duration:a(s.duration)},"Total Duration":{duration:a(r.duration)}}}handleSignalingStateChangeEvent(e){switch(R.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":if(this.keepConnectionAliveOnSocketClose)return void R.debug("Keeping peer connection alive due to keepConnectionAliveOnSocketClose option");this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){R.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?R.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Zn(i,o)}createPeerConnection(){return j(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ae.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(F.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(R.info("Muting local audio tracks on start"),zr(this.options.localStream)),performance.mark("peer-creation-end")})}init(){var e;return j(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=A_(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(vn(i)){const o=i.getAudioTracks();let r=[...o];if(R.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(l=>{R.info("Local audio tracks constraints: ",l.getConstraints())}),this.options.video){const l=i.getVideoTracks();r=[...o,...l],R.info("Local video tracks: ",l),typeof this.options.video=="object"&&l.forEach(d=>{R.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:c}=(l=>{const d=[],u=[];return l&&l.length!==0?(l.forEach(h=>{const g=h.mimeType.toLocaleLowerCase();g.startsWith("audio/")?d.push(h):g.startsWith("video/")&&u.push(h)}),{audioCodecs:d,videoCodecs:u}):{audioCodecs:d,videoCodecs:u}})(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const l={direction:"sendrecv",streams:[i]};r.forEach(d=>{d.kind==="audio"&&(this.options.userVariables.microphoneLabel=d.label),d.kind==="video"&&(this.options.userVariables.cameraLabel=d.label);const u=this.instance.addTransceiver(d,l);d.kind==="audio"&&a.length>0&&this._setCodecs(u,a),d.kind==="video"&&c.length>0&&this._setCodecs(u,c)})}else typeof this.instance.addTrack=="function"?(r.forEach(l=>{l.kind==="audio"&&(this.options.userVariables.microphoneLabel=l.label),l.kind==="video"&&(this.options.userVariables.cameraLabel=l.label),this.instance.addTrack(l,i)}),this.instance.getTransceivers().forEach(l=>{l.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(l,a),l.receiver.track.kind==="video"&&c.length>0&&this._setCodecs(l,c)})):this.instance.addStream(i);s===!1&&Zn(n,i)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);R.info("Add transceiver",e,n)}}_createOffer(){return j(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,R.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){R.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return j(this,void 0,void 0,function*(){R.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return j(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return R.debug("Skipping negotiation, state:",this.instance.signalingState),R.debug(" - 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:Ae.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){R.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return j(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){mn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return j(this,void 0,void 0,function*(){if(vn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,j(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:c=""}=n;return s&&(s=yield Gi(s,a,dt.AudioIn).catch(l=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield Gi(r,c,dt.Video).catch(l=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Hi(e)})}_resetJitterBuffer(){return j(this,void 0,void 0,function*(){try{const e=this.instance.getReceivers().find(i=>i.track&&i.track.kind==="audio"),n=this.instance.getReceivers().find(i=>i.track&&i.track.kind==="video");e&&"jitterBufferTarget"in e&&(e.jitterBufferTarget=20,R.debug("audio [jitter] target set to",e.jitterBufferTarget,"ms")),n&&"jitterBufferTarget"in n&&(n.jitterBufferTarget=20,R.debug("video [jitter] target set to",n.jitterBufferTarget,"ms"))}catch(e){R.error("Peer _resetJitterBuffer error:",e)}})}_restartNegotiationOnDeviceSleepWakeup(){return j(this,void 0,void 0,function*(){this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null);let e=Date.now();this._sleepWakeupIntervalId=setInterval(()=>j(this,void 0,void 0,function*(){var n;const i=Date.now();if(i-e>5e3){if(R.warn(`Device sleep/wake detected. Time jump: ${i-e}ms, connectionState: ${(n=this.instance)===null||n===void 0?void 0:n.connectionState}`),!this.instance)return void R.debug("Peer connection closed, skipping ICE restart");R.info("Restarting ICE and renegotiating due to device wakeup"),this.instance.restartIce(),this._isTrickleIce()?yield this.startTrickleIceNegotiation():this.startNegotiation()}e=i}),1e3)})}_isOffer(){return this.type===Ae.Offer}_isAnswer(){return this.type===Ae.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return R.info("RTC config",s),s}close(){var e;return j(this,void 0,void 0,function*(){this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),yield(e=this.statsReporter)===null||e===void 0?void 0:e.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const mu=Wi;class gu{constructor(e,n){this.session=e,this.id="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Ur.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._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._checkConferenceSerno=x=>{const w=x<0||!this._lastSerno||this._lastSerno&&x===this._lastSerno+1;return w&&x>=0&&(this._lastSerno=x),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(x=>{x.forEach(w=>{this._statsBindings.forEach(S=>{if(S.callback){if(S.constraints){for(var k in S.constraints)if(S.constraints.hasOwnProperty(k)&&S.constraints[k]!==w[k])return}S.callback(w)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:l,remoteElement:d,options:u,mediaConstraints:{audio:h,video:g},ringtoneFile:v,ringbackFile:y}=e;this.options=Object.assign({},i_,{audio:h,video:g,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:i,localElement:l,remoteElement:d,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:v,ringbackFile:y,debug:u.debug,debugOutput:u.debugOutput,trickleIce:u.trickleIce,prefetchIceCandidates:u.prefetchIceCandidates,keepConnectionAliveOnSocketClose:u.keepConnectionAliveOnSocketClose,mutedMicOnStart:u.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=nu(this.options.ringtoneFile,"_ringtone"),this._ringback=nu(this.options.ringbackFile,"_ringback"))}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),n=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("total-duration","peer-creation-start","sdp-send-end"),o=r=>`${r.toFixed(2)}ms`;return{"Peer Creation":{duration:o(e.duration)},"ICE Gathering":{duration:o(n.duration)},"SDP Send":{duration:o(i.duration)},"Total Duration":{duration:o(s.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}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}`}get isAudioMuted(){return!f_(this.options.localStream)}invite(){return j(this,void 0,void 0,function*(){this.direction=At.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new pu(Ae.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init()})}answer(e={}){var n;return j(this,void 0,void 0,function*(){performance.mark("new-call-start"),this.stopRingtone(),this.direction=At.Inbound,((n=e==null?void 0:e.customHeaders)===null||n===void 0?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new pu(Ae.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end")})}playRingtone(){iu(this._ringtone)}stopRingtone(){su(this._ringtone)}playRingback(){iu(this._ringback)}stopRingback(){su(this._ringback)}hangup(e,n){var i,s,o;let r=e||{},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(z.Hangup);const c=()=>{var l;return(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const l=new g_({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(l).catch(d=>{R.error("telnyx_rtc.bye failed!",d),Y(F.Error,{error:d,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new Kr({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 Kr({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 Kr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new du({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},s=new du({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){zr(this.options.localStream)}unmuteAudio(){eu(this.options.localStream)}toggleAudioMute(){tu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return j(this,void 0,void 0,function*(){const{instance:i}=this.peer,s=i.getSenders().find(({track:{kind:o}})=>o==="audio");if(s){const o=yield Hr({audio:{deviceId:{exact:e}}}),r=o.getAudioTracks()[0];r.enabled=!n,s.replaceTrack(r),this.options.micId=e;const{localStream:a}=this.options;a.getAudioTracks().forEach(c=>c.stop()),a.getVideoTracks().forEach(c=>o.addTrack(c)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,_n(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,_n(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,_n(e,"video",null)}setVideoDevice(e){return j(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 Hr({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Zn(r,s),this.options.camId=e,a.getAudioTracks().forEach(c=>s.addTrack(c)),a.getVideoTracks().forEach(c=>c.stop()),this.options.localStream=s}})}deaf(){zr(this.options.remoteStream)}undeaf(){eu(this.options.remoteStream)}toggleDeaf(){tu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return j(this,void 0,void 0,function*(){if(!this||!this.peer)return void R.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 R.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"}]),R.info("Parameters: ",r),R.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{R.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>R.error(a))}else R.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),R.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Qe.callUpdate,call:this}),e){case z.Purge:R.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case z.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&Zd(n,i)},0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(this.gotAnswer=!0,this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:case te.Attach:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const c=a===At.Inbound?At.Outbound:At.Inbound,l={type:Qe[n],call:this,displayName:o,displayNumber:r,displayDirection:c};Y(F.Notification,l,this.id)||Y(F.Notification,l,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const o=Object.assign(Object.assign({},i),{type:Qe.generic,call:this});Y(F.Notification,o,this.id)||Y(F.Notification,o,this.session.uuid);break}case te.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 te.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,n){return j(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return R.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:c,modChannel:l,laName:d,conferenceMemberID:u,role:h}=n;this._dispatchConferenceUpdate({action:$e.Join,conferenceName:d,participantId:Number(u),role:h}),a&&(yield this._subscribeConferenceChat(a)),c&&(yield this._subscribeConferenceInfo(c));const g=[];for(const v in s)g.push(Object.assign({callId:s[v][0],index:Number(v)},ji(s[v][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:o,index:r},ji(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:o,index:r},ji(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:o,index:r},ji(s)));break;case"clear":this._dispatchConferenceUpdate({action:$e.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:c,type:l}=s.data;this._dispatchConferenceUpdate({action:$e.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:c,messageType:l,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{R.error("ConfChat subscription error:",s)});Gr(i,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 j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,fu(this.session,o)):R.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{R.error("ConfInfo subscription error:",s)});Gr(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){return R.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return j(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ae.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(i=>{R.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){mn(this.peer.onSdpReadyTwice)?Y(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(e){var n,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return R.info(`No candidate - retry
111
+ `),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${mu}`};switch(o){case Ae.Offer:this.setState(z.Requesting),r=new au(a);break;case Ae.Answer:this.setState(z.Answering),r=this.options.attach===!0?new qr(a):new cu(a);break;default:return R.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(c=>{const{node_id:l=null}=c;this._targetNodeId=l,o===Ae.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(c=>{R.error(`${this.id} - Sending ${o} error:`,c),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return R.error("No SDP data provided"),this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const o={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${mu}`};switch(i){case Ae.Offer:this.setState(z.Requesting),s=new au(o);break;case Ae.Answer:this.setState(z.Answering),s=this.options.attach===!0?new qr(o):new cu(o);break;default:return R.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Ae.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(r=>{R.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?R.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(R.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new lu({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return R.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{R.debug("Successfully added ICE candidate:",e)}).catch(i=>{R.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new v_({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.onicecandidateerror=n=>{var i;if(R.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=hu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Zn(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{R.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&R.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(R.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=hu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Zn(i,s)})}_onMediaError(e){this._dispatchNotification({type:Qe.userMediaError,error:e}),R.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Qe.peerConnectionFailureError,error:e}),R.error("Peer connection failure error, hanging up call",e),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Qe.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(Y(F.Notification,e,this.id,!1)||Y(F.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;var o;this.options.id=e?e.toString():pn(),this.id=this.options.id,n&&(o=n,Object.keys(o).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ht(F.MediaError,this._onMediaError,this.id),Ht(F.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),mn(s)&&Ht(F.Notification,s.bind(this),this.id),this.setState(z.New),R.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;Qn(n),Qn(i),Gt(F.MediaError,null,this.id),Gt(F.PeerConnectionFailureError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),R.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),R.info("Stats stopped")}}gu.setStateTelnyx=t=>{if(t){switch(t._state){case z.Requesting:case z.Recovering:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class Wt extends gu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new w_(e,n))}hangup(e={},n=!0){this.screenShare instanceof Wt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return j(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(l=>{l.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,c=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Wt(this.session,c),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Wt&&this.screenShare.hangup()}setAudioOutDevice(e){return j(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Zd(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);R.setLevel(2),this._statsInterval=window.setInterval(()=>j(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+=`
112
112
  ${r.type}
113
113
  `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
114
- `)}))}),O.info(i)}),2e3)}}class Gy extends Cy{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return $(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return $(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return $(this,void 0,void 0,function*(){try{const i=yield Gi({audio:e,video:n});return Jn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return $(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(Z.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Zd(j.SpeedTest,r=>{const{upDur:a,downDur:c}=r,d=c?8*e/(c/1e3)/1024:0;n({upDur:a,downDur:c,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:d.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Qn().catch(e=>(ee(j.MediaError,e,this.uuid),[]))}getVideoDevices(){return Qn(bt.Video).catch(e=>(ee(j.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Qn(bt.AudioIn).catch(e=>(ee(j.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Qn(bt.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),ee(j.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Kr(e,n,i)}getDeviceResolutions(e){return $(this,void 0,void 0,function*(){try{return yield(n=>$(void 0,void 0,void 0,function*(){const i=[],s=yield Gi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<iu.length;r++){const[a,c]=iu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:c}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${c}`,width:a,height:c})}return Jn(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints}}setAudioSettings(e){return $(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=jd(e,["micId","micLabel"]);return Ty(s),this._audioConstraints=yield((o,r,a,c)=>$(void 0,void 0,void 0,function*(){const{deviceId:d}=c;if(d===void 0&&(o||r)){const f=yield Kr(o,r,a).catch(p=>null);f&&(c.deviceId={exact:f})}return c}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}set iceServers(e){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[n]:[]:e||[Hd,uy,n]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ji(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ji(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new Py({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return $(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&!this._existsSubscription(this.relayProtocol,c))).length)return{};const s=new My({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Yr(o);return r.length&&r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),a.forEach(c=>this._addSubscription(this.relayProtocol,i,c)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return $(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new Ly({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Yr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&this.connected&&(this._closeConnection(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return Wt.setStateTelnyx(e)}}class wu{constructor(e,n){this.code=n,this.message=e}}class xu extends Re{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Hi,data:navigator.userAgent}};r&&(c.sessid=r),s&&(c.target_version_id=s),this.buildRequest({method:this.method,params:c})}}const Hy=Hi;class Pe{constructor(e){this.session=e,this.handleLogin=()=>$(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new uu(n,i||s,o,this.session.sessionid,r,!!$t()),c=yield this.session.execute(a).catch(this.session.handleLoginError);c&&(this.session.sessionid=c.sessid)}),this.handleAnonymousLogin=()=>$(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new xu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!$t()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new Iy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Kd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,c=r==null?void 0:r.callID,d=r==null?void 0:r.eventChannel,f=r==null?void 0:r.eventType,p=o===ie.Attach;let m=!1;if(f==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(c&&i.calls.hasOwnProperty(c)){if(!p)return i.calls[c].handleMessage(e),void this._ack(s,o);m=(i.calls[c].options.keepConnectionAliveOnSocketClose||i.options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[c].peer)===null||n===void 0)&&n.instance),m?O.info(`[${new Date().toISOString()}][${c}] re-attaching call due to ATTACH`):(O.debug(`Session Options: ${i.options}`),O.debug(`Call: ${i.calls[c]}`),O.info(`[${new Date().toISOString()}][${c}] Hanging up the call due to ATTACH`),i.calls[c].hangup({},!1))}const v=()=>{var S,w,T,I,R,L;const D={id:c,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:p,mediaSettings:r.mediaSettings,debug:(S=i.options.debug)!==null&&S!==void 0&&S,debugOutput:(w=i.options.debugOutput)!==null&&w!==void 0?w:"socket",trickleIce:(T=i.options.trickleIce)!==null&&T!==void 0&&T,prefetchIceCandidates:(I=i.options.prefetchIceCandidates)!==null&&I!==void 0&&I,forceRelayCandidate:(R=i.options.forceRelayCandidate)!==null&&R!==void 0&&R,keepConnectionAliveOnSocketClose:(L=i.options.keepConnectionAliveOnSocketClose)!==null&&L!==void 0&&L};r.telnyx_call_control_id&&(D.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(D.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(D.telnyxLegId=r.telnyx_leg_id),r.client_state&&(D.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(D.customHeaders=r.dialogParams.custom_headers);const b=new Wt(i,D);return b.nodeId=this.nodeId,b},_=new eu(a),C=new tu(a);switch(o){case ie.Ping:this.session.setPingReceived(),this.session.execute(C).then(()=>{Pe.receivedAuthenticationRequired=0}).catch(T=>$(this,void 0,void 0,function*(){T.code===this.session.authenticationRequiredErrorCode&&(Pe.receivedAuthenticationRequired+=1,Pe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(O.warn("Ping failed twice with Authentication Required. Re-logging in..."),Ui(this.session.options)?this.handleLogin():Kn(this.session.options)&&this.handleAnonymousLogin()))}));break;case ie.Punt:if(m)return void O.info(`[${new Date().toISOString()}][${c}] Ignoring PUNT due to keepConnectionAliveOnSocketClose`);i.disconnect();break;case ie.Invite:{const T=v();T.playRingtone(),T.setState(Z.Ringing),T.direction=It.Inbound,this._ack(s,o);break}case ie.Attach:{if(m)return void this.session.execute(new Zr({sessid:this.session.sessionid,sdp:this.session.calls[c].peer.instance.localDescription.sdp,dialogParams:this.session.calls[c].options,"User-Agent":`Web-${Hy}`}));O.info(`[${new Date().toISOString()}][${c}] Re-creating call instance.`);const T=v();this.session.autoRecoverCalls?T.answer():T.setState(Z.Recovering),T.handleMessage(e);break}case ie.Event:case"webrtc.event":if(!d)return void O.error("Verto received an unknown event:",r);const S=i.relayProtocol,w=d.split(".")[0];i._existsSubscription(S,d)?ee(S,r,d):d===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(S,w)?ee(S,r,w):i.calls.hasOwnProperty(d)?i.calls[d].handleMessage(e):ee(j.Notification,r,i.uuid);break;case ie.Info:r.type=Qe.generic,ee(j.Notification,r,i.uuid);break;case ie.ClientReady:this.session.execute(_);break;default:{const T=Gr(e);if(T){switch(T){case De.REGISTER:case De.REGED:i.connection.previousGatewayState!==De.REGED&&i.connection.previousGatewayState!==De.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),Pe.retriedRegister=0,r.type=Qe.vertoClientReady,ee(j.Ready,r,i.uuid),i.options.trickleIce&&(O.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new pu({candidate:""})).catch(I=>{I.code===this.session.invalidMethodErrorCode?(console.warn("Trickle ICE is not supported by the server, disabling it."),O.debug("Trickle ICE check error:",JSON.stringify(I,null,2)),i.options.trickleIce=!1):O.debug("Trickle ICE check:",JSON.stringify(I,null,2))})));break;case De.UNREGED:case De.NOREG:if(Pe.retriedRegister+=1,Pe.retriedRegister===5){Pe.retriedRegister=0,ee(j.Error,{error:new wu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(_)},this.reconnectDelay());break;case De.FAILED:case De.FAIL_WAIT:if(i.connection.previousGatewayState!==De.FAILED&&i.connection.previousGatewayState!==De.FAIL_WAIT){if(!this.session.hasAutoReconnect()){Pe.retriedConnect=0,ee(j.Error,{error:new wu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(Pe.retriedConnect+=1,Pe.retriedConnect===5){Pe.retriedConnect=0,ee(j.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:O.warn("GatewayState message unknown method:",e)}break}O.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return $(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:d,conferenceMemberID:f,role:p,callID:m}=e;switch(s){case"conference-liveArray-join":{const v=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:S})=>{const w=m||this._retrieveCallId(S,o);if(w&&n.calls.hasOwnProperty(w)){const T=n.calls[w];T._addChannel(o),T.extension=r,T.handleConferenceUpdate(S,e).then(I=>{I==="INVALID_PACKET"&&v()})}}},C=yield n.vertoSubscribe(_).catch(S=>{O.error("liveArray subscription error:",S)});Xr(C,o)&&v();break}case"conference-liveArray-part":{let v=null;if(o&&n._existsSubscription(i,o)){const{callId:C=null}=n.subscriptions[i][o];if(v=n.calls[C]||null,C!==null){const S={type:Qe.conferenceUpdate,action:$e.Leave,conferenceName:r,participantId:Number(f),role:p};ee(j.Notification,S,C,!1)||ee(j.Notification,S,n.uuid),v===null&&Ht(j.Notification,null,C)}}const _=[o,a,c,d];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:C=[]})=>{v&&(v.channels=v.channels.filter(S=>!C.includes(S)))}).catch(C=>{O.error("liveArray unsubscribe error:",C)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":gu(this.session,e);break;case"logo-info":{const n={type:Qe.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};ee(j.Notification,n,this.session.uuid);break}}}}Pe.retriedConnect=0,Pe.retriedRegister=0,Pe.receivedAuthenticationRequired=0;class Wy extends Gy{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>$(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,c=new uu(n,i||s,o,this.sessionid,r,!!$t()),d=yield this.execute(c).catch(this._handleLoginError);d&&(this._autoReconnect=a,this.sessionid=d.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>$(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new xu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!$t()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(O.info(`Hanging up call due to page unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Ui(this.options)||Kn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new Wt(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Kn(this.options)||!!e.destinationNumber}_onSocketOpen(){return $(this,void 0,void 0,function*(){return Ui(this.options)?this.handleLoginOnSocketOpen():Kn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new Pe(this).handleMessage(e)}}class zy extends Wy{constructor(e){super(e),console.log(`SDK version: ${du}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ey()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ve.not_supported},{browserName:"Firefox",supported:ve.not_supported},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",features:["audio"],supported:ve.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",features:["audio"],supported:ve.partial}]}]}}function qy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Su={exports:{}},Cu;function Ky(){return Cu||(Cu=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(c,d,f){this.fn=c,this.context=d,this.once=f||!1}function o(c,d,f,p,m){if(typeof f!="function")throw new TypeError("The listener must be a function");var v=new s(f,p||c,m),_=n?n+d:d;return c._events[_]?c._events[_].fn?c._events[_]=[c._events[_],v]:c._events[_].push(v):(c._events[_]=v,c._eventsCount++),c}function r(c,d){--c._eventsCount===0?c._events=new i:delete c._events[d]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],d,f;if(this._eventsCount===0)return c;for(f in d=this._events)e.call(d,f)&&c.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},a.prototype.listeners=function(c){var d=n?n+c:c,f=this._events[d];if(!f)return[];if(f.fn)return[f.fn];for(var p=0,m=f.length,v=new Array(m);p<m;p++)v[p]=f[p].fn;return v},a.prototype.listenerCount=function(c){var d=n?n+c:c,f=this._events[d];return f?f.fn?1:f.length:0},a.prototype.emit=function(c,d,f,p,m,v){var _=n?n+c:c;if(!this._events[_])return!1;var C=this._events[_],S=arguments.length,w,T;if(C.fn){switch(C.once&&this.removeListener(c,C.fn,void 0,!0),S){case 1:return C.fn.call(C.context),!0;case 2:return C.fn.call(C.context,d),!0;case 3:return C.fn.call(C.context,d,f),!0;case 4:return C.fn.call(C.context,d,f,p),!0;case 5:return C.fn.call(C.context,d,f,p,m),!0;case 6:return C.fn.call(C.context,d,f,p,m,v),!0}for(T=1,w=new Array(S-1);T<S;T++)w[T-1]=arguments[T];C.fn.apply(C.context,w)}else{var I=C.length,R;for(T=0;T<I;T++)switch(C[T].once&&this.removeListener(c,C[T].fn,void 0,!0),S){case 1:C[T].fn.call(C[T].context);break;case 2:C[T].fn.call(C[T].context,d);break;case 3:C[T].fn.call(C[T].context,d,f);break;case 4:C[T].fn.call(C[T].context,d,f,p);break;default:if(!w)for(R=1,w=new Array(S-1);R<S;R++)w[R-1]=arguments[R];C[T].fn.apply(C[T].context,w)}}return!0},a.prototype.on=function(c,d,f){return o(this,c,d,f,!1)},a.prototype.once=function(c,d,f){return o(this,c,d,f,!0)},a.prototype.removeListener=function(c,d,f,p){var m=n?n+c:c;if(!this._events[m])return this;if(!d)return r(this,m),this;var v=this._events[m];if(v.fn)v.fn===d&&(!p||v.once)&&(!f||v.context===f)&&r(this,m);else{for(var _=0,C=[],S=v.length;_<S;_++)(v[_].fn!==d||p&&!v[_].once||f&&v[_].context!==f)&&C.push(v[_]);C.length?this._events[m]=C.length===1?C[0]:C:r(this,m)}return this},a.prototype.removeAllListeners=function(c){var d;return c?(d=n?n+c:c,this._events[d]&&r(this,d)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Su)),Su.exports}var Xy=Ky();const Qr=qy(Xy),ei=new Qr;function Yy(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const Zy=10;class Jy{constructor(){ye(this,"animationFrameId",null);ye(this,"stream",null);ye(this,"audioContext",null);ye(this,"source",null);ye(this,"analyser",null);ye(this,"updateAgentState",Yy(e=>{ei.emit("conversation.agent.state",e)},100))}setMonitoredAudioStream(e){this.stream&&this.stopAudioStreamMonitor(),this.stream=e,this.startAudioStreamMonitor()}stopAudioStreamMonitor(){var e;this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),(e=this.source)==null||e.disconnect()}startAudioStreamMonitor(){if(!this.stream)return;this.audioContext=new AudioContext,this.source=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.source.connect(this.analyser),this.analyser.fftSize=512;const e=new Uint8Array(this.analyser.frequencyBinCount),n=()=>{var s;const i=e.reduce((o,r)=>o+r,0)/e.length;(s=this.analyser)==null||s.getByteFrequencyData(e),i>=Zy?this.updateAgentState("speaking"):this.updateAgentState("listening"),this.animationFrameId=requestAnimationFrame(n)};this.animationFrameId=requestAnimationFrame(n)}}function Qy(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function e_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function t_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function n_(t){return e_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function i_(t){if(!t_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class s_ extends Qr{constructor(n){super();ye(this,"telnyxRTC");ye(this,"transcript",[]);ye(this,"onSocketMessage",n=>{if(Qy(n))switch(n.params.type){case"response.text.delta":{const i=n_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ei.emit("conversation.agent.state","listening"));return}case"conversation.item.created":{const i=i_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ei.emit("conversation.agent.state","thinking"));return}}});this.telnyxRTC=n,this.telnyxRTC.on(j.SocketMessage,this.onSocketMessage)}}class r_ extends Qr{constructor(n){super();ye(this,"telnyxRTC");ye(this,"transcription");ye(this,"agentId");ye(this,"versionId");ye(this,"debug");ye(this,"audioStreamMonitor");ye(this,"activeCall");ye(this,"onClientReady",()=>{this.emit("agent.connected")});ye(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});ye(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,this.audioStreamMonitor.setMonitoredAudioStream(n.call.remoteStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});ye(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});ye(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.debug=n.debug||!1,this.activeCall=null,this.telnyxRTC=new zy({environment:n.environment||"production",anonymous_login:{target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},debug:n.debug||!1}),this.telnyxRTC.on(j.Ready,this.onClientReady),this.telnyxRTC.on(j.Error,this.onClientOrSocketError),this.telnyxRTC.on(j.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(j.Notification,this.onNotification),this.transcription=new s_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ei.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Jy}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.stopAudioStreamMonitor(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(j.Ready,this.onClientReady),this.telnyxRTC.off(j.Error,this.onClientOrSocketError),this.telnyxRTC.off(j.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(j.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ei.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){console.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,d;if(!this.telnyxRTC){console.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:d.find(f=>f.mimeType.toLowerCase().includes("opus")),{customHeaders:s,...o}=n||{},r=s?[...s]:[];this.versionId&&r.push({name:"X-AI-Assistant-Version-ID",value:this.versionId});const a=this.telnyxRTC.newCall({destinationNumber:"xxx",...o,preferred_codecs:[i],customHeaders:r.length>0?r:void 0});this.emit("conversation.update",{call:a,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}}var ku={exports:{}},ti={};/**
115
- * @license React
116
- * react-jsx-runtime.production.js
117
- *
118
- * Copyright (c) Meta Platforms, Inc. and affiliates.
119
- *
120
- * This source code is licensed under the MIT license found in the
121
- * LICENSE file in the root directory of this source tree.
122
- */var Tu;function o_(){if(Tu)return ti;Tu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return ti.Fragment=e,ti.jsx=n,ti.jsxs=n,ti}var Eu;function a_(){return Eu||(Eu=1,ku.exports=o_()),ku.exports}a_(),pt(void 0),pt(null);const c_=(t,e,n,i,s)=>new r_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s}),l_=(t,e,n,i,s)=>{const[o,r]=Ce(null),[a,c]=Ce(!1),[d,f]=Ce(null);return Ve(()=>{if(!t)return;const p=c_(t,e,n,i,s),m=()=>{c(!0),f(null)},v=()=>{c(!1)},_=C=>{f(C),console.error("AI Agent error:",C)};return p.on("agent.connected",m),p.on("agent.disconnected",v),p.on("agent.error",_),p.connect(),r(p),()=>{p.off("agent.connected",m),p.off("agent.disconnected",v),p.off("agent.error",_),p.disconnect()}},[t,e,n,i,s]),{client:o,isConnected:a,error:d}};typeof SuppressedError=="function"&&SuppressedError,typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto);for(var d_=[],zi=0;zi<256;++zi)d_[zi]=(zi+256).toString(16).substr(1);var qi;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError"})(qi||(qi={}));var u_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Iu(t,e){return t(e={exports:{}},e.exports),e.exports}var h_=Iu(function(t){var e,n;e=u_,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(S,w){var T=S[w];if(typeof T.bind=="function")return T.bind(S);try{return Function.prototype.bind.call(T,S)}catch{return function(){return Function.prototype.apply.apply(T,[S,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(S,w){for(var T=0;T<r.length;T++){var I=r[T];this[I]=T<S?i:this.methodFactory(I,S,w)}this.log=this.debug}function f(S,w,T){return function(){typeof console!==s&&(d.call(this,w,T),this[S].apply(this,arguments))}}function p(S,w,T){return function(I){return I==="debug"&&(I="log"),typeof console!==s&&(I==="trace"&&o?c:console[I]!==void 0?a(console,I):console.log!==void 0?a(console,"log"):i)}(S)||f.apply(this,arguments)}function m(S,w,T){var I,R=this;w=w??"WARN";var L="loglevel";function D(){var k;if(typeof window!==s&&L){try{k=window.localStorage[L]}catch{}if(typeof k===s)try{var l=window.document.cookie,u=l.indexOf(encodeURIComponent(L)+"=");u!==-1&&(k=/^([^;]+)/.exec(l.slice(u))[1])}catch{}return R.levels[k]===void 0&&(k=void 0),k}}typeof S=="string"?L+=":"+S:typeof S=="symbol"&&(L=void 0),R.name=S,R.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},R.methodFactory=T||p,R.getLevel=function(){return I},R.setLevel=function(k,l){if(typeof k=="string"&&R.levels[k.toUpperCase()]!==void 0&&(k=R.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=R.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(I=k,l!==!1&&function(u){var h=(r[u]||"silent").toUpperCase();if(typeof window!==s&&L){try{return void(window.localStorage[L]=h)}catch{}try{window.document.cookie=encodeURIComponent(L)+"="+h+";"}catch{}}}(k),d.call(R,k,S),typeof console===s&&k<R.levels.SILENT)return"No console available for logging"},R.setDefaultLevel=function(k){w=k,D()||R.setLevel(k,!1)},R.resetLevel=function(){R.setLevel(w,!1),function(){if(typeof window!==s&&L){try{return void window.localStorage.removeItem(L)}catch{}try{window.document.cookie=encodeURIComponent(L)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},R.enableAll=function(k){R.setLevel(R.levels.TRACE,k)},R.disableAll=function(k){R.setLevel(R.levels.SILENT,k)};var b=D();b==null&&(b=w),R.setLevel(b,!1)}var v=new m,_={};v.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[S];return w||(w=_[S]=new m(S,v.getLevel(),v.methodFactory)),w};var C=typeof window!==s?window.log:void 0;return v.noConflict=function(){return typeof window!==s&&window.log===v&&(window.log=C),v},v.getLoggers=function(){return _},v.default=v,v},t.exports?t.exports=n():e.log=n()});const Ki=h_.getLogger("telnyx"),f_=Ki.methodFactory;Ki.methodFactory=(t,e,n)=>{const i=f_(t,e,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)}},Ki.setLevel(Ki.getLevel());const p_="telnyx-voice-sdk-id";var Au,Ru,Xi;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(p_)}),function(t){t.Offer="offer",t.Answer="answer"}(Au||(Au={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(Ru||(Ru={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(Xi||(Xi={})),Xi.Display+"",Xi.Attach+"";var Pu,Mu,Lu,Du,Ou;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(Pu||(Pu={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Mu||(Mu={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(Lu||(Lu={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Du||(Du={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Ou||(Ou={}));var Nu;(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Nu||(Nu={}));var Yi,Vu=Iu(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(l){return l._maxListeners===void 0?s.defaultMaxListeners:l._maxListeners}function r(l,u,h,g){var y,E,x;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((E=l._events)?(E.newListener&&(l.emit("newListener",u,h.listener?h.listener:h),E=l._events),x=E[u]):(E=l._events=new i,l._eventsCount=0),x){if(typeof x=="function"?x=E[u]=g?[h,x]:[x,h]:g?x.unshift(h):x.push(h),!x.warned&&(y=o(l))&&0<y&&x.length>y){x.warned=!0;var A=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+u+" listeners added. Use emitter.setMaxListeners() to increase limit");A.name="MaxListenersExceededWarning",A.emitter=l,A.type=u,A.count=x.length,function(P){typeof console.warn=="function"?console.warn(P):console.log(P)}(A)}}else x=E[u]=h,++l._eventsCount;return l}function a(l,u,h){function g(){l.removeListener(u,g),y||(y=!0,h.apply(l,arguments))}var y=!1;return g.listener=h,g}function c(l){var u=this._events;if(u){var h=u[l];if(typeof h=="function")return 1;if(h)return h.length}return 0}function d(l,u){for(var h=Array(u);u--;)h[u]=l[u];return h}Object.defineProperty(e,"__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(l){if(typeof l!="number"||0>l||isNaN(l))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=l,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(l){var u,h,g,y,E,x,A,P=l==="error";if(x=this._events)P=P&&x.error==null;else if(!P)return!1;if(A=this.domain,P){if(u=arguments[1],!A){if(u instanceof Error)throw u;var V=new Error('Uncaught, unspecified "error" event. ('+u+")");throw V.context=u,V}return u||(u=new Error('Uncaught, unspecified "error" event')),u.domainEmitter=this,u.domain=A,u.domainThrown=!1,A.emit("error",u),!1}if(!(h=x[l]))return!1;var H=typeof h=="function";switch(g=arguments.length){case 1:(function(N,ne,G){if(ne)N.call(G);else for(var F=N.length,te=d(N,F),U=0;U<F;++U)te[U].call(G)})(h,H,this);break;case 2:(function(N,ne,G,F){if(ne)N.call(G,F);else for(var te=N.length,U=d(N,te),W=0;W<te;++W)U[W].call(G,F)})(h,H,this,arguments[1]);break;case 3:(function(N,ne,G,F,te){if(ne)N.call(G,F,te);else for(var U=N.length,W=d(N,U),Y=0;Y<U;++Y)W[Y].call(G,F,te)})(h,H,this,arguments[1],arguments[2]);break;case 4:(function(N,ne,G,F,te,U){if(ne)N.call(G,F,te,U);else for(var W=N.length,Y=d(N,W),Q=0;Q<W;++Q)Y[Q].call(G,F,te,U)})(h,H,this,arguments[1],arguments[2],arguments[3]);break;default:for(y=Array(g-1),E=1;E<g;E++)y[E-1]=arguments[E];(function(N,ne,G,F){if(ne)N.apply(G,F);else for(var te=N.length,U=d(N,te),W=0;W<te;++W)U[W].apply(G,F)})(h,H,this,y)}return!0},s.prototype.addListener=function(l,u){return r(this,l,u,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(l,u){return r(this,l,u,!0)},s.prototype.once=function(l,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.on(l,a(this,l,u)),this},s.prototype.prependOnceListener=function(l,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(l,a(this,l,u)),this},s.prototype.removeListener=function(l,u){var h,g,y,E,x;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if(!(g=this._events))return this;if(!(h=g[l]))return this;if(h===u||h.listener&&h.listener===u)--this._eventsCount==0?this._events=new i:(delete g[l],g.removeListener&&this.emit("removeListener",l,h.listener||u));else if(typeof h!="function"){for(y=-1,E=h.length;0<E--;)if(h[E]===u||h[E].listener&&h[E].listener===u){x=h[E].listener,y=E;break}if(0>y)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete g[l]}else(function(A,P){for(var V=P,H=V+1,N=A.length;H<N;V+=1,H+=1)A[V]=A[H];A.pop()})(h,y);g.removeListener&&this.emit("removeListener",l,x||u)}return this},s.prototype.removeAllListeners=function(l){var u,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[l]&&(--this._eventsCount==0?this._events=new i:delete h[l]),this;if(arguments.length===0){for(var g,y=Object.keys(h),E=0;E<y.length;++E)(g=y[E])!=="removeListener"&&this.removeAllListeners(g);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(u=h[l])=="function")this.removeListener(l,u);else if(u)do this.removeListener(l,u[u.length-1]);while(u[0]);return this},s.prototype.listeners=function(l){var u,h,g=this._events;return g?h=(u=g[l])?typeof u=="function"?[u.listener||u]:function(y){for(var E=Array(y.length),x=0;x<E.length;++x)E[x]=y[x].listener||y[x];return E}(u):[]:h=[],h},s.listenerCount=function(l,u){return typeof l.listenerCount=="function"?l.listenerCount(u):c.call(l,u)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var f,p=new Uint8Array(16);function m(){if(!f&&!(f=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 f(p)}for(var v=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],C=0;256>C;++C)_.push((C+256).toString(16).substr(1));function S(l){var u=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[l[u+0]]+_[l[u+1]]+_[l[u+2]]+_[l[u+3]]+"-"+_[l[u+4]]+_[l[u+5]]+"-"+_[l[u+6]]+_[l[u+7]]+"-"+_[l[u+8]]+_[l[u+9]]+"-"+_[l[u+10]]+_[l[u+11]]+_[l[u+12]]+_[l[u+13]]+_[l[u+14]]+_[l[u+15]]).toLowerCase();if(!function(g){return typeof g=="string"&&v.test(g)}(h))throw TypeError("Stringified UUID is invalid");return h}function w(l,u,h){var g=(l=l||{}).random||(l.rng||m)();return g[6]=64|15&g[6],g[8]=128|63&g[8],S(g)}function T(l,u){if(!l||!u)return{};const h={...l};if(h.localCandidateId){const g=u.get(h.localCandidateId);h.local={...g}}if(h.remoteCandidateId){const g=u.get(h.remoteCandidateId);h.remote={...g}}return h}function I(l,u,h){return 8*function(g,y,E){const x=g[E],A=y?y[E]:null;return x===null||A===null?null:(x-A)/(g.timestamp-y.timestamp)*1e3}(l,u,h)}function R(l){if(!l.entries)return l;const u={};return l.forEach(function(h,g){u[g]=h}),u}function L(l,u,h={}){if(!l)return null;let g={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(g.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const y of l.values())switch(y.type){case"outbound-rtp":{const E=y.mediaType||y.kind,x={};let A={};if(!["audio","video"].includes(E))continue;if(y.codecId){const P=l.get(y.codecId);P&&(x.clockRate=P.clockRate,x.mimeType=P.mimeType,x.payloadType=P.payloadType)}A=l.get(y.mediaSourceId)||l.get(y.trackId)||{},g[E].outbound.push({...y,...x,track:{...A}});break}case"inbound-rtp":{let E=y.mediaType||y.kind,x={};const A={};if(!["audio","video"].includes(E))if(y.id.includes("Video"))E="video";else{if(!y.id.includes("Audio"))continue;E="audio"}if(y.codecId){const P=l.get(y.codecId);P&&(A.clockRate=P.clockRate,A.mimeType=P.mimeType,A.payloadType=P.payloadType)}if(!g.connection.id&&y.transportId){const P=l.get(y.transportId);if(P&&P.selectedCandidatePairId){const V=l.get(P.selectedCandidatePairId);g.connection=T(V,l)}}x=l.get(y.mediaSourceId)||l.get(y.trackId)||{},g[E].inbound.push({...y,...A,track:{...x}});break}case"peer-connection":g.connection.dataChannelsClosed=y.dataChannelsClosed,g.connection.dataChannelsOpened=y.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let E=y.mediaType||y.kind;const x={};if(!["audio","video"].includes(E))if(y.id.includes("Video"))E="video";else{if(!y.id.includes("Audio"))continue;E="audio"}if(y.codecId){const A=l.get(y.codecId);A&&(x.clockRate=A.clockRate,x.mimeType=A.mimeType,x.payloadType=A.payloadType)}if(!g.connection.id&&y.transportId){const A=l.get(y.transportId);if(A&&A.selectedCandidatePairId){const P=l.get(A.selectedCandidatePairId);g.connection=T(P,l)}}g.remote[E].inbound.push({...y,...x});break}case"remote-outbound-rtp":{if(!h.remote)break;const E=y.mediaType||y.kind,x={};if(!["audio","video"].includes(E))continue;if(y.codecId){const A=l.get(y.codecId);A&&(x.clockRate=A.clockRate,x.mimeType=A.mimeType,x.payloadType=A.payloadType)}g.remote[E].outbound.push({...y,...x});break}}if(!g.connection.id)for(const y of l.values())y.type==="candidate-pair"&&y.nominated&&y.state==="succeeded"&&(g.connection=T(y,l));return g=function(y,E){return E&&(y.audio.inbound.map(x=>{let A=E.audio.inbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesReceived"),x.packetRate=I(x,A,"packetsReceived")}),y.audio.outbound.map(x=>{let A=E.audio.outbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesSent"),x.packetRate=I(x,A,"packetsSent")}),y.video.inbound.map(x=>{let A=E.video.inbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesReceived"),x.packetRate=I(x,A,"packetsReceived")}),y.video.outbound.map(x=>{let A=E.video.outbound.find(P=>P.id===x.id);x.bitrate=I(x,A,"bytesSent"),x.packetRate=I(x,A,"packetsSent")})),y}(g,u),g}let D,b={},k=[];e.WebRTCStats=class extends s{constructor(l){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 u={...l};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=u.getStatsInterval||1e3,this.rawStats=!!u.rawStats,this.statsObject=!!u.statsObject,this.filteredStats=!!u.filteredStats,this.shouldWrapGetUserMedia=!!u.wrapGetUserMedia,typeof u.remote=="boolean"&&(this.remote=u.remote),this.debug=!!u.debug,this.logLevel=u.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(l,u){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:l,pc:u})}async addConnection(l){const{pc:u,peerId:h}=l;let{connectionId:g,remote:y}=l;if(y=typeof y=="boolean"?y:this.remote,!(u&&u 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(g&&g in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${g}.`);for(let x in this.peersToMonitor[h]){const A=this.peersToMonitor[h][x];if(A.pc===u)throw new Error(`We are already monitoring peer with id ${h}.`);A.pc.connectionState==="closed"&&this.removeConnection({pc:A.pc})}}const E=u.getConfiguration();return E.iceServers&&E.iceServers.forEach(function(x){delete x.credential}),g||(g=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:g,data:{options:l,peerConfiguration:E}}),this.monitorPeer({peerId:h,connectionId:g,pc:u,remote:y}),{connectionId:g}}getTimeline(l){return this.timeline=this.timeline.sort((u,h)=>u.timestamp.getTime()-h.timestamp.getTime()),l?this.timeline.filter(u=>u.tag===l):this.timeline}get logger(){const l=u=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(u)>-1};return{error(...u){this.debug&&l("error")&&console.error("[webrtc-stats][error] ",...u)},warn(...u){this.debug&&l("warn")&&console.warn("[webrtc-stats][warn] ",...u)},info(...u){this.debug&&l("info")&&console.log("[webrtc-stats][info] ",...u)},debug(...u){this.debug&&l("debug")&&console.debug("[webrtc-stats][debug] ",...u)}}}removeConnection(l){let u,{connectionId:h,pc:g}=l;if(!g&&!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 y in this.peersToMonitor)h in this.peersToMonitor[y]&&(g=this.peersToMonitor[y][h].pc,u=y)}else if(g){if(!(g instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let y in this.peersToMonitor)for(let E in this.peersToMonitor[y])this.peersToMonitor[y][E].pc===g&&(h=E,u=y)}if(!g||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,g),delete this.peersToMonitor[u][h],Object.values(this.peersToMonitor[u]).length===0&&delete this.peersToMonitor[u],{connectionId:h}}removeAllPeers(){for(let l in this.peersToMonitor)this.removePeer(l)}removePeer(l){if(this.logger.info(`Removing PeerConnection with id ${l}.`),this.peersToMonitor[l]){for(let u in this.peersToMonitor[l]){let h=this.peersToMonitor[l][u].pc;this.removePeerConnectionEventListeners(u,h)}delete this.peersToMonitor[l]}}destroy(){this.removeAllPeers(),k.forEach(l=>{this.removeTrackEventListeners(l)}),k=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(l){let{peerId:u,connectionId:h,pc:g,remote:y}=l;if(!g)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const E={pc:g,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:y}};if(this.peersToMonitor[u]){if(h in this.peersToMonitor[u])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[u][h]=E}else this.peersToMonitor[u]={[h]:E};this.addPeerConnectionEventListeners(u,h,g),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(l=>{l.forEach(u=>{this.emitEvent(u)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(l=null){this.logger.info(l?`Getting stats from peer ${l}`:"Getting stats from all peers");let u={};if(l){if(!this.peersToMonitor[l])throw new Error(`Cannot get stats. Peer with id ${l} does not exist`);u[l]=this.peersToMonitor[l]}else u=this.peersToMonitor;let h=[];for(const g in u)for(const y in u[g]){const E=u[g][y],x=E.pc;if(x&&!this.checkIfConnectionIsClosed(g,y,x))try{const A=this.getTimestamp(),P=x.getStats(null);if(P){const V=await P,H=this.getTimestamp(),N=R(V),ne={remote:E.options.remote},G=L(V,E.stats.parsed,ne),F={event:"stats",tag:"stats",peerId:g,connectionId:y,timeTaken:H-A,data:G};this.rawStats===!0&&(F.rawStats=V),this.statsObject===!0&&(F.statsObject=N),this.filteredStats===!0&&(F.filteredStats=this.filteroutStats(N)),h.push(F),E.stats.parsed=G}else this.logger.error(`PeerConnection from peer ${g} did not return any stats data`)}catch(A){this.logger.error(A)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const l in this.peersToMonitor)for(const u in this.peersToMonitor[l]){const h=this.peersToMonitor[l][u].pc;this.checkIfConnectionIsClosed(l,u,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(l,u,h){const g=this.isConnectionClosed(h);if(g){this.removeConnection({pc:h});let y=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:y,peerId:l,connectionId:u,tag:"connection",data:"closed"})}return g}isConnectionClosed(l){return l.connectionState==="closed"||l.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."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const l=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return l({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(u=>(l({stream:u}),u),u=>(l({error:u}),Promise.reject(u)))}).bind(navigator.mediaDevices)}filteroutStats(l={}){const u={...l};for(const g in u){var h=u[g];this.statsToMonitor.includes(h.type)||delete u[g]}return u}get peerConnectionListeners(){return{icecandidate:(l,u,h,g)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",g),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:l,connectionId:u,data:g.candidate})},track:(l,u,h,g)=>{this.logger.debug(`[pc-event] track | peerId: ${l}`,g);const y=g.track,E=g.streams[0];l in this.peersToMonitor&&u in this.peersToMonitor[l]&&(this.peersToMonitor[l][u].stream=E),this.addTrackEventListeners(y,u),this.emitEvent({event:"ontrack",tag:"track",peerId:l,connectionId:u,data:{stream:E?this.getStreamDetails(E):null,track:y?this.getMediaTrackDetails(y):null,title:g.track.kind+":"+g.track.id+" "+g.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${l}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:l,connectionId:u,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${l}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:l,connectionId:u,data:h.iceConnectionState})},icegatheringstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${l}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:l,connectionId:u,data:h.iceGatheringState})},icecandidateerror:(l,u,h,g)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${l}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:l,connectionId:u,error:{errorCode:g.errorCode}})},connectionstatechange:(l,u,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${l}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:l,connectionId:u,data:h.connectionState})},negotiationneeded:(l,u,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${l}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:l,connectionId:u})},datachannel:(l,u,h,g)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${l}`,g),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:l,connectionId:u,data:g.channel})}}}addPeerConnectionEventListeners(l,u,h){this.logger.debug(`Adding event listeners for peer ${l} and connection ${u}.`),b[u]={},Object.keys(this.peerConnectionListeners).forEach(g=>{b[u][g]=this.peerConnectionListeners[g].bind(this,l,u,h),h.addEventListener(g,b[u][g],!1)})}parseGetUserMedia(l){try{const u={event:"getUserMedia",tag:"getUserMedia",data:{...l}};l.stream&&(u.data.details=this.parseStream(l.stream),l.stream.getTracks().map(h=>{this.addTrackEventListeners(h),k.push(h)})),this.emitEvent(u)}catch{}}parseStream(l){const u={audio:[],video:[]};return l.getTracks().forEach(h=>{u[h.kind].push(this.getMediaTrackDetails(h))}),u}getMediaTrackDetails(l){return{enabled:l.enabled,id:l.id,contentHint:l.contentHint,kind:l.kind,label:l.label,muted:l.muted,readyState:l.readyState,constructorName:l.constructor.name,capabilities:l.getCapabilities?l.getCapabilities():{},constraints:l.getConstraints?l.getConstraints():{},settings:l.getSettings?l.getSettings():{},_track:l}}getStreamDetails(l){return{active:l.active,id:l.id,_stream:l}}getTrackEventObject(l){return{mute:u=>{this.emitEvent({event:"mute",tag:"track",connectionId:l,data:{event:u}})},unmute:u=>{this.emitEvent({event:"unmute",tag:"track",connectionId:l,data:{event:u}})},overconstrained:u=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:l,data:{event:u}})},ended:u=>{this.emitEvent({event:"ended",tag:"track",connectionId:l,data:{event:u}}),this.removeTrackEventListeners(u.target)}}}addTrackEventListeners(l,u){b[l.id]={};const h=this.getTrackEventObject(u);Object.keys(h).forEach(g=>{b[l.id][g]=h[g].bind(this),l.addEventListener(g,b[l.id][g])}),b[l.id].readyState=setInterval(()=>{if(l.readyState==="ended"){let g=new CustomEvent("ended",{detail:{check:"readyState"}});l.dispatchEvent(g)}},1e3)}removeTrackEventListeners(l){if(l.id in b){const u=this.getTrackEventObject();Object.keys(u).forEach(h=>{l.removeEventListener(h,b[l.id][h])}),clearInterval(b[l.id].readyState),delete b[l.id]}}addToTimeline(l){this.timeline.push(l),this.emit("timeline",l)}emitEvent(l){const u={...l,timestamp:new Date};this.addToTimeline(u),u.tag&&this.emit(u.tag,u)}set getStatsInterval(l){if(!Number.isInteger(l))throw new Error(`getStatsInterval should be an integer, got: ${l}`);this._getStatsInterval=l,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(l,u){l in b&&(Object.keys(this.peerConnectionListeners).forEach(h=>{u.removeEventListener(h,b[l][h],!1)}),delete b[l]),u.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),u.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const l=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const u=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return l.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),u.apply(navigator.mediaDevices,arguments).then(function(g){return g},function(g){return l.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,g.name),Promise.reject(g)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(Yi=Vu)&&Yi.__esModule&&Object.prototype.hasOwnProperty.call(Yi,"default")&&Yi.default,Vu.WebRTCStats;const m_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e;Ve(()=>{if(!t)return;const r=()=>{n()},a=f=>{s(f)},c=f=>{i(f)},d=t.telnyxRTC;if(d&&typeof d=="object"){const f=d,p=m=>{o(m)};return f.on(qi.SocketMessage,p),t.on("agent.connected",r),t.on("agent.error",a),t.on("conversation.update",c),()=>{t.off("agent.connected",r),t.off("agent.error",a),t.off("conversation.update",c),f.off(qi.SocketMessage,p)}}else return t.on("agent.connected",r),t.on("agent.error",a),t.on("conversation.update",c),()=>{t.off("agent.connected",r),t.off("agent.error",a),t.off("conversation.update",c)}},[t,n,i,s,o])},g_=2e3;async function v_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Fu(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const y_=t=>{const[e,n]=Ce([]),[,i]=Or();return Ve(()=>{if(!t)return;const o=c=>{n(d=>{const f=d[d.length-1];if(c.role==="assistant"&&f&&Fu(f.id)===Fu(c.id)&&f.role==="assistant"){const p={...f,content:f.content+c.content,timestamp:c.timestamp};return[...d.slice(0,-1),p]}if(c.role==="user"&&f&&f.role==="user"&&c.timestamp.getTime()-f.timestamp.getTime()<g_){const m={...f,id:c.id,content:f.content+" "+c.content,timestamp:c.timestamp,attachments:[...f.attachments||[],...c.attachments||[]]};return[...d.slice(0,-1),m]}if(c.role==="user"){const p=c.attachments&&c.attachments.length>0;i(p?"processing_image":"thinking")}return[...d,c]})},r=c=>{c==="speaking"?i("speaking"):c==="listening"&&i(d=>d==="processing_image"||d==="thinking"?d:"listening")},a=c=>{var f;const d=(f=c.call)==null?void 0:f.state;(d==="destroy"||d==="done")&&n([])};return t.on("transcript.item",o),t.on("conversation.agent.state",r),t.on("conversation.update",a),()=>{t.off("transcript.item",o),t.off("conversation.agent.state",r),t.off("conversation.update",a)}},[t,i]),{transcript:e,sendMessage:async(o,r)=>{if(!t)return;const a=[];if(r&&r.length>0)for(const c of r)try{const d=await v_(c);a.push(d)}catch(d){throw console.error("Failed to convert file to base64:",d),d}t.sendConversationMessage(o,a)}}},__=({call:t,client:e})=>{const n=Ut(),[i,s]=Ce(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),{transcript:a}=y_(e);switch(i){case"collapsed":return M(Bd,{onExpand:o,call:t,client:e});case"expanded":return M(ay,{transcript:a,onCollapse:r,call:t});default:return M(Bd,{onExpand:o,call:t,client:e})}},eo=()=>M(Wn.div,{layoutId:Mi,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:M("div",{className:"rounded-full animate-spin",children:M(zv,{})})}),b_=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return M(eo,{});case"done":case"purged":case"destroy":return null;case"active":return M(__,{client:e,call:t});default:return M(eo,{})}},w_=({className:t})=>M("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[M("g",{clipPath:"url(#:R5lfm:)",children:[M("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"}),M("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"}),M("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"}),M("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"}),M("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"})]}),M("defs",{children:M("clipPath",{id:":R5lfm:",children:M("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function x_(){const t=Ut();return t.logo_icon_url?M("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:M("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):M(w_,{className:"w-8 h-8 mr-2"})}const S_=({client:t,callProps:e})=>{const n=Ut(),i=()=>{if(!t){console.error("Client is not initialized.");return}t.startConversation({...e})};return M(Wn.button,{layoutId:Mi,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[M(x_,{}),n.start_call_text]})},C_='@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-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--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-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom: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-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.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-lg{border-radius:var(--radius-lg)}.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{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.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-black{color:var(--color-black)}.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}.opacity-0{opacity:0}.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-lg{--tw-backdrop-blur:blur(var(--blur-lg));-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,)}.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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;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 (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width: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)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@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)}}',k_=({children:t})=>M("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:M("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),T_={duration:.1,ease:"circOut"},E_=({children:t,position:e="fixed"})=>{const n=Ut(),s=(e??n.position??"fixed")==="fixed"?M(k_,{children:t}):t;return M("div",{className:vt(n.theme==="dark"&&"dark"),children:M(Vp,{transition:T_,children:[M("style",{children:C_}),s]})})},I_=t=>M(Wn.div,{layoutId:Mi,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[M(Hv,{className:"w-8 h-8 text-red-400"}),M("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),M("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[M("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),M("li",{children:["Make sure that the"," ",M("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",M(Jv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function A_({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,environment:c,position:d="fixed","version-id":f}){const{client:p}=l_(t,c,f,e,n),[m,v]=Ce(null),[_,C]=Ce(!1),[S,w]=Ce(!1),[T,I]=Ce(!1),R=xs(Vd),L=vv(),D={};if(i&&(D.destinationNumber=i),s&&(D.callerNumber=s),o&&(D.callerName=o),r)try{D.customHeaders=JSON.parse(r)}catch(g){console.error("Invalid JSON for call-custom-headers attribute:",r,g)}if(a)try{D.audio=JSON.parse(a);const g=D.audio;if(typeof g=="object"){const y=navigator.mediaDevices.getSupportedConstraints();Object.keys(g).forEach(E=>{y[E]||console.warn(`Audio constraint not supported by browser: ${E}`)})}}catch(g){console.error("Invalid JSON for call-audio attribute:",a,g)}const b=St(()=>{C(!1)},[]),k=St(g=>{var y;if(((y=g.call)==null?void 0:y.state)==="destroy")return R(!1),v(null);v(g)},[R]),l=St(()=>{C(!1),w(!0)},[]),u=St(g=>{if(gv(g)){const y=g.params.widget_settings;y&&Object.keys(y).length>0&&(L(y),I(!0))}},[L]);return m_(p,{onReady:b,onConversationUpdate:k,onError:l,onConfigMessage:u}),M(E_,{position:d,children:t?S?M(I_,{agentId:t}):_?M(eo,{}):m!=null&&m.call?M(b_,{call:m.call,client:p}):T?M(S_,{client:p,callProps:D}):null:M("div",{children:"Please provide an assistant ID."})})}th(A_,"telnyx-ai-agent",pv,{shadow:!0})})();
114
+ `)}))}),R.info(i)}),2e3)}}class R_ extends d_{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._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield Hi({audio:e,video:n});return Qn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(z.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(qd(F.SpeedTest,r=>{const{upDur:a,downDur:c}=r,l=c?8*e/(c/1e3)/1024:0;n({upDur:a,downDur:c,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:l.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return ei().catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getVideoDevices(){return ei(dt.Video).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ei(dt.AudioIn).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ei(dt.AudioOut).catch(e=>(R.error("getAudioOutDevices",e),Y(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Gi(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield Hi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<Qd.length;r++){const[a,c]=Qd[r];(yield o.applyConstraints({width:{exact:a},height:{exact:c}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${c}`,width:a,height:c})}return Qn(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return j(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Nd(e,["micId","micLabel"]);return h_(s),this._audioConstraints=yield((o,r,a,c)=>j(void 0,void 0,void 0,function*(){const{deviceId:l}=c;if(l===void 0&&(o||r)){const d=yield Gi(o,r,a).catch(u=>null);d&&(c.deviceId={exact:d})}return c}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?Jv:Yv}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ui(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ui(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new __({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&!this._existsSubscription(this.relayProtocol,c))).length)return{};const s=new y_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Wr(o);return r.length&&r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),a.forEach(c=>this._addSubscription(this.relayProtocol,i,c)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new b_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Wr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(R.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,R.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return Wt.setStateTelnyx(e)}}class vu{constructor(e,n){this.code=n,this.message=e}}class _u extends Pe{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Wi,data:navigator.userAgent}};r&&(c.sessid=r),s&&(c.target_version_id=s),this.buildRequest({method:this.method,params:c})}}const P_=Wi;class xe{constructor(e){this.session=e,this.handleLogin=()=>j(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new ou(n,i||s,o,this.session.sessionid,r,!!$t()),c=yield this.session.execute(a).catch(this.session.handleLoginError);c&&(this.session.sessionid=c.sessid)}),this.handleAnonymousLogin=()=>j(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new _u({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!$t()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new m_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Gd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,c=r==null?void 0:r.callID,l=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,u=o===te.Attach,h=o===te.Punt;let g=!1;if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(c&&i.calls.hasOwnProperty(c)){if(!u)return i.calls[c].handleMessage(e),void this._ack(s,o);g=(i.options.keepConnectionAliveOnSocketClose||i.calls[c].options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[c].peer)===null||n===void 0)&&n.instance),g?R.info(`[${new Date().toISOString()}][${c}] re-attaching call due to ATTACH and keepConnectionAliveOnSocketClose`):(R.info(`[${new Date().toISOString()}][${c}] Hanging up the call due to ATTACH`),i.calls[c].hangup({},!1))}if(h&&i.options.keepConnectionAliveOnSocketClose)return R.info(`[${new Date().toISOString()}][${c}] keeping call alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),this.session.socketDisconnect(),void this._ack(s,o);const v=()=>{var w,S,k,A,L,O;const b={id:c,audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:u,mediaSettings:r.mediaSettings,debug:(w=i.options.debug)!==null&&w!==void 0&&w,debugOutput:(S=i.options.debugOutput)!==null&&S!==void 0?S:"socket",trickleIce:(k=i.options.trickleIce)!==null&&k!==void 0&&k,prefetchIceCandidates:(A=i.options.prefetchIceCandidates)!==null&&A!==void 0&&A,forceRelayCandidate:(L=i.options.forceRelayCandidate)!==null&&L!==void 0&&L,keepConnectionAliveOnSocketClose:(O=i.options.keepConnectionAliveOnSocketClose)!==null&&O!==void 0&&O};r.telnyx_call_control_id&&(b.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(b.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(b.telnyxLegId=r.telnyx_leg_id),r.client_state&&(b.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(b.customHeaders=r.dialogParams.custom_headers);const C=new Wt(i,b);return C.nodeId=this.nodeId,C},y=new Yd(a),x=new Jd(a);switch(o){case te.Ping:this.session.setPingReceived(),this.session.execute(x).then(()=>{xe.receivedAuthenticationRequired=0}).catch(k=>j(this,void 0,void 0,function*(){k.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(R.warn("Ping failed twice with Authentication Required. Re-logging in..."),$i(this.session.options)?this.handleLogin():Xn(this.session.options)&&this.handleAnonymousLogin(),xe.receivedAuthenticationRequired=-1))}));break;case te.Punt:i.disconnect();break;case te.Invite:{const k=v();k.playRingtone(),k.setState(z.Ringing),k.direction=At.Inbound,this._ack(s,o);break}case te.Attach:{if(g)return void this.session.execute(new qr({sessid:this.session.sessionid,sdp:this.session.calls[c].peer.instance.localDescription.sdp,dialogParams:this.session.calls[c].options,"User-Agent":`Web-${P_}`}));R.info(`[${new Date().toISOString()}][${c}] Re-creating call instance.`);const k=v();this.session.autoRecoverCalls?k.answer():k.setState(z.Recovering),k.handleMessage(e);break}case te.Event:case"webrtc.event":if(!l)return void R.error("Verto received an unknown event:",r);const w=i.relayProtocol,S=l.split(".")[0];i._existsSubscription(w,l)?Y(w,r,l):l===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(w,S)?Y(w,r,S):i.calls.hasOwnProperty(l)?i.calls[l].handleMessage(e):Y(F.Notification,r,i.uuid);break;case te.Info:r.type=Qe.generic,Y(F.Notification,r,i.uuid);break;case te.ClientReady:this.session.execute(y);break;default:{const k=Br(e);if(k){switch(k){case De.REGISTER:case De.REGED:i.connection.previousGatewayState!==De.REGED&&i.connection.previousGatewayState!==De.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=Qe.vertoClientReady,Y(F.Ready,r,i.uuid),i.options.trickleIce&&(R.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new lu({candidate:""})).catch(A=>{A.code===this.session.invalidMethodErrorCode?(R.warn("Trickle ICE is not supported by the server, disabling it."),R.debug("Trickle ICE check error:",JSON.stringify(A,null,2)),i.options.trickleIce=!1):R.debug("Trickle ICE check:",JSON.stringify(A,null,2))})));break;case De.UNREGED:case De.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(F.Error,{error:new vu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(y)},this.reconnectDelay());break;case De.FAILED:case De.FAIL_WAIT:if(i.connection.previousGatewayState!==De.FAILED&&i.connection.previousGatewayState!==De.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(F.Error,{error:new vu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(F.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{if(R.debug(`Reconnecting... Retry ${xe.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose)return R.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:R.warn("GatewayState message unknown method:",e)}break}R.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:l,conferenceMemberID:d,role:u,callID:h}=e;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:x})=>{const w=h||this._retrieveCallId(x,o);if(w&&n.calls.hasOwnProperty(w)){const S=n.calls[w];S._addChannel(o),S.extension=r,S.handleConferenceUpdate(x,e).then(k=>{k==="INVALID_PACKET"&&g()})}}},y=yield n.vertoSubscribe(v).catch(x=>{R.error("liveArray subscription error:",x)});Gr(y,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:y=null}=n.subscriptions[i][o];if(g=n.calls[y]||null,y!==null){const x={type:Qe.conferenceUpdate,action:$e.Leave,conferenceName:r,participantId:Number(d),role:u};Y(F.Notification,x,y,!1)||Y(F.Notification,x,n.uuid),g===null&&Gt(F.Notification,null,y)}}const v=[o,a,c,l];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:y=[]})=>{g&&(g.channels=g.channels.filter(x=>!y.includes(x)))}).catch(y=>{R.error("liveArray unsubscribe error:",y)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":fu(this.session,e);break;case"logo-info":{const n={type:Qe.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};Y(F.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class M_ extends R_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(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,c=new ou(n,i||s,o,this.sessionid,r,!!$t()),l=yield this.execute(c).catch(this._handleLoginError);l&&(this._autoReconnect=a,this.sessionid=l.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new _u({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!$t()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(R.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return $i(this.options)||Xn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new Wt(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Xn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return $i(this.options)?this.handleLoginOnSocketOpen():Xn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class L_ extends M_{constructor(e){super(e),R.info(`SDK version: ${ru}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return p_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ve.not_supported},{browserName:"Firefox",supported:ve.not_supported},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",features:["audio"],supported:ve.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",features:["audio"],supported:ve.partial}]}]}}function D_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var yu={exports:{}},bu;function O_(){return bu||(bu=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(c,l,d){this.fn=c,this.context=l,this.once=d||!1}function o(c,l,d,u,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new s(d,u||c,h),v=n?n+l:l;return c._events[v]?c._events[v].fn?c._events[v]=[c._events[v],g]:c._events[v].push(g):(c._events[v]=g,c._eventsCount++),c}function r(c,l){--c._eventsCount===0?c._events=new i:delete c._events[l]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],l,d;if(this._eventsCount===0)return c;for(d in l=this._events)e.call(l,d)&&c.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},a.prototype.listeners=function(c){var l=n?n+c:c,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,h=d.length,g=new Array(h);u<h;u++)g[u]=d[u].fn;return g},a.prototype.listenerCount=function(c){var l=n?n+c:c,d=this._events[l];return d?d.fn?1:d.length:0},a.prototype.emit=function(c,l,d,u,h,g){var v=n?n+c:c;if(!this._events[v])return!1;var y=this._events[v],x=arguments.length,w,S;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),x){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,l),!0;case 3:return y.fn.call(y.context,l,d),!0;case 4:return y.fn.call(y.context,l,d,u),!0;case 5:return y.fn.call(y.context,l,d,u,h),!0;case 6:return y.fn.call(y.context,l,d,u,h,g),!0}for(S=1,w=new Array(x-1);S<x;S++)w[S-1]=arguments[S];y.fn.apply(y.context,w)}else{var k=y.length,A;for(S=0;S<k;S++)switch(y[S].once&&this.removeListener(c,y[S].fn,void 0,!0),x){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,l);break;case 3:y[S].fn.call(y[S].context,l,d);break;case 4:y[S].fn.call(y[S].context,l,d,u);break;default:if(!w)for(A=1,w=new Array(x-1);A<x;A++)w[A-1]=arguments[A];y[S].fn.apply(y[S].context,w)}}return!0},a.prototype.on=function(c,l,d){return o(this,c,l,d,!1)},a.prototype.once=function(c,l,d){return o(this,c,l,d,!0)},a.prototype.removeListener=function(c,l,d,u){var h=n?n+c:c;if(!this._events[h])return this;if(!l)return r(this,h),this;var g=this._events[h];if(g.fn)g.fn===l&&(!u||g.once)&&(!d||g.context===d)&&r(this,h);else{for(var v=0,y=[],x=g.length;v<x;v++)(g[v].fn!==l||u&&!g[v].once||d&&g[v].context!==d)&&y.push(g[v]);y.length?this._events[h]=y.length===1?y[0]:y:r(this,h)}return this},a.prototype.removeAllListeners=function(c){var l;return c?(l=n?n+c:c,this._events[l]&&r(this,l)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(yu)),yu.exports}var N_=O_();const Xr=D_(N_),ti=new Xr;function V_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const F_=10;class B_{constructor(){_e(this,"animationFrameId",null);_e(this,"stream",null);_e(this,"audioContext",null);_e(this,"source",null);_e(this,"analyser",null);_e(this,"updateAgentState",V_(e=>{ti.emit("conversation.agent.state",e)},100))}setMonitoredAudioStream(e){this.stream&&this.stopAudioStreamMonitor(),this.stream=e,this.startAudioStreamMonitor()}stopAudioStreamMonitor(){var e;this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),(e=this.source)==null||e.disconnect()}startAudioStreamMonitor(){if(!this.stream)return;this.audioContext=new AudioContext,this.source=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.source.connect(this.analyser),this.analyser.fftSize=512;const e=new Uint8Array(this.analyser.frequencyBinCount),n=()=>{var s;const i=e.reduce((o,r)=>o+r,0)/e.length;(s=this.analyser)==null||s.getByteFrequencyData(e),i>=F_?this.updateAgentState("speaking"):this.updateAgentState("listening"),this.animationFrameId=requestAnimationFrame(n)};this.animationFrameId=requestAnimationFrame(n)}}function j_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function U_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function $_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function H_(t){return U_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function G_(t){if(!$_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class W_ extends Xr{constructor(n){super();_e(this,"telnyxRTC");_e(this,"transcript",[]);_e(this,"onSocketMessage",n=>{if(j_(n))switch(n.params.type){case"response.text.delta":{const i=H_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ti.emit("conversation.agent.state","listening"));return}case"conversation.item.created":{const i=G_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ti.emit("conversation.agent.state","thinking"));return}}});this.telnyxRTC=n,this.telnyxRTC.on(F.SocketMessage,this.onSocketMessage)}}class z_ extends Xr{constructor(n){super();_e(this,"telnyxRTC");_e(this,"transcription");_e(this,"agentId");_e(this,"versionId");_e(this,"debug");_e(this,"audioStreamMonitor");_e(this,"activeCall");_e(this,"onClientReady",()=>{this.emit("agent.connected")});_e(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});_e(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,this.audioStreamMonitor.setMonitoredAudioStream(n.call.remoteStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});_e(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});_e(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.debug=n.debug||!1,this.activeCall=null,this.telnyxRTC=new L_({environment:n.environment||"production",anonymous_login:{target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},debug:n.debug||!1,trickleIce:n.trickleIce}),this.telnyxRTC.on(F.Ready,this.onClientReady),this.telnyxRTC.on(F.Error,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(F.Notification,this.onNotification),this.transcription=new W_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ti.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new B_}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.stopAudioStreamMonitor(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(F.Ready,this.onClientReady),this.telnyxRTC.off(F.Error,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(F.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ti.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){console.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var l,d;if(!this.telnyxRTC){console.error("Client is not initialized.");return}const i=(d=(l=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:l.codecs)==null?void 0:d.find(u=>u.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId});const c=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:o,preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:c,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}}var wu={exports:{}},ni={},xu;function q_(){if(xu)return ni;xu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return ni.Fragment=e,ni.jsx=n,ni.jsxs=n,ni}var Su;function K_(){return Su||(Su=1,wu.exports=q_()),wu.exports}K_(),mt(void 0),mt(null);const X_=(t,e,n,i,s)=>new z_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s}),Y_=(t,e,n,i,s)=>{const[o,r]=ke(null),[a,c]=ke(!1),[l,d]=ke(null);return Ve(()=>{if(!t)return;const u=X_(t,e,n,i,s),h=()=>{c(!0),d(null)},g=()=>{c(!1)},v=y=>{d(y),console.error("AI Agent error:",y)};return u.on("agent.connected",h),u.on("agent.disconnected",g),u.on("agent.error",v),u.connect(),r(u),()=>{u.off("agent.connected",h),u.off("agent.disconnected",g),u.off("agent.error",v),u.disconnect()}},[t,e,n,i,s]),{client:o,isConnected:a,error:l}},J_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e;Ve(()=>{if(!t)return;const r=()=>{n()},a=d=>{s(d)},c=d=>{i(d)},l=t.telnyxRTC;if(l&&typeof l=="object"){const d=l,u=h=>{o(h)};return d.on(F.SocketMessage,u),t.on("agent.connected",r),t.on("agent.error",a),t.on("conversation.update",c),()=>{t.off("agent.connected",r),t.off("agent.error",a),t.off("conversation.update",c),d.off(F.SocketMessage,u)}}else return t.on("agent.connected",r),t.on("agent.error",a),t.on("conversation.update",c),()=>{t.off("agent.connected",r),t.off("agent.error",a),t.off("conversation.update",c)}},[t,n,i,s,o])},Z_=2e3;async function Q_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Cu(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const ey=t=>{const[e,n]=ke([]),[,i]=Pr();return Ve(()=>{if(!t)return;const o=c=>{n(l=>{const d=l[l.length-1];if(c.role==="assistant"&&d&&Cu(d.id)===Cu(c.id)&&d.role==="assistant"){const u={...d,content:d.content+c.content,timestamp:c.timestamp};return[...l.slice(0,-1),u]}if(c.role==="user"&&d&&d.role==="user"&&c.timestamp.getTime()-d.timestamp.getTime()<Z_){const h={...d,id:c.id,content:d.content+" "+c.content,timestamp:c.timestamp,attachments:[...d.attachments||[],...c.attachments||[]]};return[...l.slice(0,-1),h]}if(c.role==="user"){const u=c.attachments&&c.attachments.length>0;i(u?"processing_image":"thinking")}return[...l,c]})},r=c=>{c==="speaking"?i("speaking"):c==="listening"&&i(l=>l==="processing_image"||l==="thinking"?l:"listening")},a=c=>{var d;const l=(d=c.call)==null?void 0:d.state;(l==="destroy"||l==="done")&&n([])};return t.on("transcript.item",o),t.on("conversation.agent.state",r),t.on("conversation.update",a),()=>{t.off("transcript.item",o),t.off("conversation.agent.state",r),t.off("conversation.update",a)}},[t,i]),{transcript:e,sendMessage:async(o,r)=>{if(!t)return;const a=[];if(r&&r.length>0)for(const c of r)try{const l=await Q_(c);a.push(l)}catch(l){throw console.error("Failed to convert file to base64:",l),l}t.sendConversationMessage(o,a)}}},ty=({call:t,client:e})=>{const n=Ut(),[i,s]=ke(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),{transcript:a}=ey(e);switch(i){case"collapsed":return E(Od,{onExpand:o,call:t,client:e});case"expanded":return E(qv,{transcript:a,onCollapse:r,call:t});default:return E(Od,{onExpand:o,call:t,client:e})}},Yr=()=>E(zn.div,{layoutId:Li,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:E("div",{className:"rounded-full animate-spin",children:E(Mv,{})})}),ny=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return E(Yr,{});case"done":case"purged":case"destroy":return null;case"active":return E(ty,{client:e,call:t});default:return E(Yr,{})}},iy=({className:t})=>E("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[E("g",{clipPath:"url(#:R5lfm:)",children:[E("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"}),E("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"}),E("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"}),E("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"}),E("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"})]}),E("defs",{children:E("clipPath",{id:":R5lfm:",children:E("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function sy(){const t=Ut();return t.logo_icon_url?E("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:E("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):E(iy,{className:"w-8 h-8 mr-2"})}const ry=({client:t,callProps:e})=>{const n=Ut(),i=()=>{if(!t){console.error("Client is not initialized.");return}t.startConversation({...e})};return E(zn.button,{layoutId:Li,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[E(sy,{}),n.start_call_text]})},oy='@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-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--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-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom: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-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.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-lg{border-radius:var(--radius-lg)}.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{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.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-black{color:var(--color-black)}.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}.opacity-0{opacity:0}.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-lg{--tw-backdrop-blur:blur(var(--blur-lg));-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,)}.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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;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 (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width: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)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@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)}}',ay=({children:t})=>E("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:E("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),cy={duration:.1,ease:"circOut"},ly=({children:t,position:e="fixed"})=>{const n=Ut(),s=(e??n.position??"fixed")==="fixed"?E(ay,{children:t}):t;return E("div",{className:_t(n.theme==="dark"&&"dark"),children:E(Sp,{transition:cy,children:[E("style",{children:oy}),s]})})},dy=t=>E(zn.div,{layoutId:Li,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[E(Rv,{className:"w-8 h-8 text-red-400"}),E("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),E("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[E("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),E("li",{children:["Make sure that the"," ",E("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",E(Fv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function uy({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,environment:c,position:l="fixed","version-id":d}){const{client:u}=Y_(t,c,d,e,n),[h,g]=ke(null),[v,y]=ke(!1),[x,w]=ke(!1),[S,k]=ke(!1),A=_s(Ld),L=iv(),O={};if(i&&(O.destinationNumber=i),s&&(O.callerNumber=s),o&&(O.callerName=o),r)try{O.customHeaders=JSON.parse(r)}catch(_){console.error("Invalid JSON for call-custom-headers attribute:",r,_)}if(a)try{O.audio=JSON.parse(a);const _=O.audio;if(typeof _=="object"){const T=navigator.mediaDevices.getSupportedConstraints();Object.keys(_).forEach(P=>{T[P]||console.warn(`Audio constraint not supported by browser: ${P}`)})}}catch(_){console.error("Invalid JSON for call-audio attribute:",a,_)}const b=St(()=>{y(!1)},[]),C=St(_=>{var T;if(((T=_.call)==null?void 0:T.state)==="destroy")return A(!1),g(null);g(_)},[A]),f=St(()=>{y(!1),w(!0)},[]),m=St(_=>{if(nv(_)){const T=_.params.widget_settings;T&&Object.keys(T).length>0&&(L(T),k(!0))}},[L]);return J_(u,{onReady:b,onConversationUpdate:C,onError:f,onConfigMessage:m}),E(ly,{position:l,children:t?x?E(dy,{agentId:t}):v?E(Yr,{}):h!=null&&h.call?E(ny,{call:h.call,client:u}):S?E(ry,{client:u,callProps:O}):null:E("div",{children:"Please provide an assistant ID."})})}Uu(uy,"telnyx-ai-agent",ev,{shadow:!0})})();