@telnyx/ai-agent-widget 0.32.2-beta.0 → 0.32.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.min.js +35 -30
- package/package.json +2 -2
package/dist/bundle.min.js
CHANGED
|
@@ -1,114 +1,119 @@
|
|
|
1
|
-
var o0=Object.defineProperty;var a0=(Qe,G,Bt)=>G in Qe?o0(Qe,G,{enumerable:!0,configurable:!0,writable:!0,value:Bt}):Qe[G]=Bt;var Y=(Qe,G,Bt)=>a0(Qe,typeof G!="symbol"?G+"":G,Bt);(function(){"use strict";var Qe,G,Bt,jt,mo,vo,yo,_o,as,ls,cs,bo,Tn={},wo=[],Yu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,An=Array.isArray;function st(t,e){for(var n in e)t[n]=e[n];return t}function ds(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function We(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?Qe.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 En(t,r,i,s,null)}function En(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??++Bt,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(o),o}function rt(t){return t.children}function et(t,e){this.props=t,this.context=e}function nn(t,e){if(e==null)return t.__?nn(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"?nn(t):null}function So(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 So(t)}}function us(t){(!t.__d&&(t.__d=!0)&&jt.push(t)&&!hi.__r++||mo!=G.debounceRendering)&&((mo=G.debounceRendering)||vo)(hi)}function hi(){for(var t,e,n,i,s,o,r,a=1;jt.length;)jt.length>a&&jt.sort(yo),t=jt.shift(),a=jt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=st({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),hs(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??nn(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,Ao(o,n,r),n.__e!=s&&So(n)));hi.__r=0}function Co(t,e,n,i,s,o,r,a,l,c,d){var u,f,m,_,v,w,y=i&&i.__k||wo,C=e.length;for(l=Ju(n,e,y,l,C),u=0;u<C;u++)(m=n.__k[u])!=null&&(f=m.__i==-1?Tn:y[m.__i]||Tn,m.__i=u,w=hs(t,m,f,s,o,r,a,l,c,d),_=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&fs(f.ref,null,m),d.push(m.ref,m.__c||_,m)),v==null&&_!=null&&(v=_),4&m.__u||f.__k===m.__k?l=xo(m,l,t):typeof m.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),m.__u&=-7);return n.__e=v,l}function Ju(t,e,n,i,s){var o,r,a,l,c,d=n.length,u=d,f=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+f,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?En(null,r,null,null,null):An(r)?En(rt,{children:r},null,null,null):r.constructor==null&&r.__b>0?En(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=Zu(r,n,l,u))!=-1&&(u--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>d?f--:s<d&&f++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,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=nn(a)),Io(a,a));return i}function xo(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=xo(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=nn(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ot(t,e){return e=e||[],t==null||typeof t=="boolean"||(An(t)?t.some(function(n){ot(n,e)}):e.push(t)),e}function Zu(t,e,n,i){var s,o,r=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function ko(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Yu.test(e)?n:n+"px"}function fi(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||ko(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||ko(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(_o,"$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=as,t.addEventListener(e,o?cs:ls,o)):t.removeEventListener(e,o?cs:ls,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 To(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=as++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function hs(t,e,n,i,s,o,r,a,l,c){var d,u,f,m,_,v,w,y,C,k,T,E,D,S,x,p,g,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(d=G.__b)&&d(e);e:if(typeof h=="function")try{if(y=e.props,C="prototype"in h&&h.prototype.render,k=(d=h.contextType)&&i[d.__c],T=d?k?k.props.value:d.__:i,n.__c?w=(u=e.__c=n.__c).__=u.__E:(C?e.__c=u=new h(y,T):(e.__c=u=new et(y,T),u.constructor=h,u.render=eh),k&&k.sub(u),u.props=y,u.state||(u.state={}),u.context=T,u.__n=i,f=u.__d=!0,u.__h=[],u._sb=[]),C&&u.__s==null&&(u.__s=u.state),C&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=st({},u.__s)),st(u.__s,h.getDerivedStateFromProps(y,u.__s))),m=u.props,_=u.state,u.__v=e,f)C&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),C&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(C&&h.getDerivedStateFromProps==null&&y!==m&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,T),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,T)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=y,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),E=0;E<u._sb.length;E++)u.__h.push(u._sb[E]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,T),C&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(m,_,v)})}if(u.context=T,u.props=y,u.__P=t,u.__e=!1,D=G.__r,S=0,C){for(u.state=u.__s,u.__d=!1,D&&D(e),d=u.render(u.props,u.state,u.context),x=0;x<u._sb.length;x++)u.__h.push(u._sb[x]);u._sb=[]}else do u.__d=!1,D&&D(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(i=st(st({},i),u.getChildContext())),C&&!f&&u.getSnapshotBeforeUpdate!=null&&(v=u.getSnapshotBeforeUpdate(m,_)),p=d,d!=null&&d.type===rt&&d.key==null&&(p=Eo(d.props.children)),a=Co(t,An(p)?p:[p],e,n,i,s,o,r,a,l,c),u.base=e.__e,e.__u&=-161,u.__h.length&&r.push(u),w&&(u.__E=u.__=null)}catch(b){if(e.__v=null,l||o!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(g=o.length;g--;)ds(o[g]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,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,l,c);return(d=G.diffed)&&d(e),128&e.__u?void 0:a}function Ao(t,e,n){for(var i=0;i<n.length;i++)fs(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){G.__e(o,s.__v)}})}function Eo(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:An(t)?t.map(Eo):st({},t)}function Qu(t,e,n,i,s,o,r,a,l){var c,d,u,f,m,_,v,w=n.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((m=o[c])&&"setAttribute"in m==!!C&&(C?m.localName==C:m.nodeType==3)){t=m,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(G.__m&&G.__m(e,o),a=!1),o=null}if(C==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&Qe.call(t.childNodes),w=n.props||Tn,!a&&o!=null)for(w={},c=0;c<t.attributes.length;c++)w[(m=t.attributes[c]).name]=m.value;for(c in w)if(m=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=m;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;fi(t,c,null,m,s)}}for(c in y)m=y[c],c=="children"?f=m:c=="dangerouslySetInnerHTML"?d=m:c=="value"?_=m:c=="checked"?v=m:a&&typeof m!="function"||w[c]===m||fi(t,c,m,w[c],s);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),Co(e.type=="template"?t.content:t,An(f)?f:[f],e,n,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&nn(n,0),a,l),o!=null)for(c=o.length;c--;)ds(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=w[c])&&fi(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&fi(t,c,v,w[c],s))}return t}function fs(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){G.__e(s,n)}}function Io(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||fs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){G.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Io(i[s],e,n||typeof t.type!="function");n||ds(t.__e),t.__c=t.__=t.__e=void 0}function eh(t,e,n){return this.constructor(t,n)}function pi(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],hs(e,t=(!i&&n||e).__k=We(rt,null,[t]),s||Tn,Tn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?Qe.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),Ao(o,t,r)}function Ro(t,e){pi(t,e,Ro)}function ps(t,e,n){var i,s,o,r,a=st({},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?Qe.call(arguments,2):n),En(t.type,a,i||t.key,s||t.ref,null)}function vt(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,us(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"+bo++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}Qe=wo.slice,G={__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}},Bt=0,et.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=st({},this.state),typeof t=="function"&&(t=t(st({},n),this.props)),t&&st(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),us(this))},et.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),us(this))},et.prototype.render=rt,jt=[],vo=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,yo=function(t,e){return t.__v.__b-e.__v.__b},hi.__r=0,_o=/(PointerCapture)$|Capture$/i,as=0,ls=To(!1),cs=To(!0),bo=0;var th=0;function R(t,e,n,i,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--th,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return G.vnode&&G.vnode(c),c}function gs(){return(gs=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 nh=["context","children"];function ih(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(t,nh);return ps(e,n)}function sh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=We(ih,gs({},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,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Lo(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),d=l[r].slot;d?o[d]=We(Po,{name:d},c):s[r]=c}var u=i?We(Po,null,s):s;return We(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ro:pi)(this._vdom,this._root)}function Lo(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function rh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Lo(t)]=n,this._vdom=ps(this._vdom,i),pi(this._vdom,this._root)}}function oh(){pi(this._vdom=null,this._root)}function Po(t,e){var n=this;return We("slot",gs({},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 ah(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=sh,s.prototype.attributeChangedCallback=rh,s.prototype.disconnectedCallback=oh,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 Tt,ce,ms,Mo,In=0,Do=[],ge=G,Oo=ge.__b,No=ge.__r,Fo=ge.diffed,Vo=ge.__c,Bo=ge.unmount,jo=ge.__;function sn(t,e){ge.__h&&ge.__h(ce,t,In||e),In=0;var n=ce.__H||(ce.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function xe(t){return In=1,Uo(Go,t)}function Uo(t,e,n){var i=sn(Tt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Go(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=ce,!ce.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!o||o.call(this,a,l,c);var u=i.__c.props!==a;return d.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};ce.__f=!0;var o=ce.shouldComponentUpdate,r=ce.componentWillUpdate;ce.componentWillUpdate=function(a,l,c){if(this.__e){var d=o;o=void 0,s(a,l,c),o=d}r&&r.call(this,a,l,c)},ce.shouldComponentUpdate=s}return i.__N||i.__}function ke(t,e){var n=sn(Tt++,3);!ge.__s&&_s(n.__H,e)&&(n.__=t,n.u=e,ce.__H.__h.push(n))}function $o(t,e){var n=sn(Tt++,4);!ge.__s&&_s(n.__H,e)&&(n.__=t,n.u=e,ce.__h.push(n))}function me(t){return In=5,ze(function(){return{current:t}},[])}function ze(t,e){var n=sn(Tt++,7);return _s(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function yt(t,e){return In=8,ze(function(){return t},e)}function Te(t){var e=ce.context[t.__c],n=sn(Tt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ce)),e.props.value):t.__}function lh(t,e){ge.useDebugValue&&ge.useDebugValue(e?e(t):t)}function vs(){var t=sn(Tt++,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 ch(){for(var t;t=Do.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(gi),t.__H.__h.forEach(ys),t.__H.__h=[]}catch(e){t.__H.__h=[],ge.__e(e,t.__v)}}ge.__b=function(t){ce=null,Oo&&Oo(t)},ge.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),jo&&jo(t,e)},ge.__r=function(t){No&&No(t),Tt=0;var e=(ce=t.__c).__H;e&&(ms===ce?(e.__h=[],ce.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(gi),e.__h.forEach(ys),e.__h=[],Tt=0)),ms=ce},ge.diffed=function(t){Fo&&Fo(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Do.push(e)!==1&&Mo===ge.requestAnimationFrame||((Mo=ge.requestAnimationFrame)||dh)(ch)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ms=ce=null},ge.__c=function(t,e){e.some(function(n){try{n.__h.forEach(gi),n.__h=n.__h.filter(function(i){return!i.__||ys(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ge.__e(i,n.__v)}}),Vo&&Vo(t,e)},ge.unmount=function(t){Bo&&Bo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{gi(i)}catch(s){e=s}}),n.__H=void 0,e&&ge.__e(e,n.__v))};var Ho=typeof requestAnimationFrame=="function";function dh(t){var e,n=function(){clearTimeout(i),Ho&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ho&&(e=requestAnimationFrame(n))}function gi(t){var e=ce,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ce=e}function ys(t){var e=ce;t.__c=t.__(),ce=e}function _s(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Go(t,e){return typeof e=="function"?e(t):e}const Rn={},Wo=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,zo=t=>"init"in t,bs=t=>!!t.write,qo=t=>"v"in t||"e"in t,mi=t=>{if("e"in t)throw t.e;if((Rn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},vi=new WeakMap,Ko=t=>{var e;return yi(t)&&!!((e=vi.get(t))!=null&&e[0])},uh=t=>{const e=vi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Xo=(t,e)=>{let n=vi.get(t);if(!n){n=[!0,new Set],vi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},yi=t=>typeof(t==null?void 0:t.then)=="function",Yo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},ws=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(yi(e))for(const r of i.d.keys())Yo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,yi(o)&&uh(o))},Jo=(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},hh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},Ss=()=>{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},fh=t=>(t.c||(t.c=Ss()),t.m||(t.m=Ss()),t.u||(t.u=Ss()),t.f||(t.f=hh()),t),ph=Symbol(),Zo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...m)=>f.read(...m),l=(f,...m)=>f.write(...m),c=(f,m)=>{var _;return(_=f.unstable_onInit)==null?void 0:_.call(f,m)},d=(f,m)=>{var _;return(_=f.onMount)==null?void 0:_.call(f,m)},...u)=>{const f=u[0]||(S=>{if((Rn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let x=t.get(S);return x||(x={d:new Map,p:new Set,n:0},t.set(S,x),c==null||c(S,D)),x}),m=u[1]||(()=>{const S=[],x=p=>{try{p()}catch(g){S.push(g)}};do{r.f&&x(r.f);const p=new Set,g=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(g)}),i.clear(),o.forEach(g),o.clear(),s.forEach(g),s.clear(),p.forEach(x),i.size&&_()}while(i.size||o.size||s.size);if(S.length)throw new AggregateError(S)}),_=u[2]||(()=>{const S=[],x=new WeakSet,p=new WeakSet,g=Array.from(i);for(;g.length;){const h=g[g.length-1],b=f(h);if(p.has(h)){g.pop();continue}if(x.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Rn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),g.pop();continue}x.add(h);for(const I of Jo(h,b,e))x.has(I)||g.push(I)}for(let h=S.length-1;h>=0;--h){const[b,I]=S[h];let P=!1;for(const L of I.d.keys())if(L!==b&&i.has(L)){P=!0;break}P&&(v(b),C(b)),n.delete(b)}}),v=u[3]||(S=>{var x;const p=f(S);if(qo(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([M,N])=>v(M).n===N)))return p;p.d.clear();let g=!0;const h=()=>{e.has(S)&&(C(S),_(),m())},b=M=>{var N;if(Wo(S,M)){const j=f(M);if(!qo(j))if(zo(M))ws(M,M.init,f);else throw new Error("no atom init");return mi(j)}const W=v(M);try{return mi(W)}finally{p.d.set(M,W.n),Ko(p.v)&&Yo(S,p.v,W),(N=e.get(M))==null||N.t.add(S),g||h()}};let I,P;const L={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Rn?"production":void 0)!=="production"&&!bs(S)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&bs(S)&&(P=(...M)=>{if((Rn?"production":void 0)!=="production"&&g&&console.warn("setSelf function cannot be called in sync"),!g)try{return y(S,...M)}finally{_(),m()}}),P}},O=p.n;try{const M=a(S,b,L);return ws(S,M,f),yi(M)&&(Xo(M,()=>I==null?void 0:I.abort()),M.then(h,h)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{g=!1,O!==p.n&&n.get(S)===O&&(n.set(S,p.n),i.add(S),(x=r.c)==null||x.call(r,S))}}),w=u[4]||(S=>{const x=[S];for(;x.length;){const p=x.pop(),g=f(p);for(const h of Jo(p,g,e)){const b=f(h);n.set(h,b.n),x.push(h)}}}),y=u[5]||((S,...x)=>{let p=!0;const g=b=>mi(v(b)),h=(b,...I)=>{var P;const L=f(b);try{if(Wo(S,b)){if(!zo(b))throw new Error("atom not writable");const O=L.n,M=I[0];ws(b,M,f),C(b),O!==L.n&&(i.add(b),(P=r.c)==null||P.call(r,b),w(b));return}else return y(b,...I)}finally{p||(_(),m())}};try{return l(S,g,h,...x)}finally{p=!1}}),C=u[6]||(S=>{var x;const p=f(S),g=e.get(S);if(g&&!Ko(p.v)){for(const[h,b]of p.d)if(!g.d.has(h)){const I=f(h);k(h).t.add(S),g.d.add(h),b!==I.n&&(i.add(h),(x=r.c)==null||x.call(r,h),w(h))}for(const h of g.d||[])if(!p.d.has(h)){g.d.delete(h);const b=T(h);b==null||b.t.delete(S)}}}),k=u[7]||(S=>{var x;const p=f(S);let g=e.get(S);if(!g){v(S);for(const h of p.d.keys())k(h).t.add(S);if(g={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,g),(x=r.m)==null||x.call(r,S),bs(S)){const h=()=>{let b=!0;const I=(...P)=>{try{return y(S,...P)}finally{b||(_(),m())}};try{const P=d(S,I);P&&(g.u=()=>{b=!0;try{P()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return g}),T=u[8]||(S=>{var x;const p=f(S);let g=e.get(S);if(g&&!g.l.size&&!Array.from(g.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){g.u&&o.add(g.u),g=void 0,e.delete(S),(x=r.u)==null||x.call(r,S);for(const h of p.d.keys()){const b=T(h);b==null||b.t.delete(S)}return}return g}),E=[t,e,n,i,s,o,r,a,l,c,d,f,m,_,v,w,y,C,k,T],D={get:S=>mi(v(S)),set:(S,...x)=>{try{return y(S,...x)}finally{_(),m()}},sub:(S,x)=>{const g=k(S).l;return g.add(x),m(),()=>{g.delete(x),T(S),m()}}};return Object.defineProperty(D,ph,{value:E}),D},gh=fh,Qo=Xo,Cs={};let mh=0;function _i(t,e){const n=`atom${++mh}`,i={toString(){return(Cs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=vh,i.write=yh),i}function vh(t){return t(this)}function yh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const _h=()=>{let t=0;const e=gh({}),n=new WeakMap,i=new WeakMap,s=Zo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...d)=>t?c(a,...d):a.write(l,c,...d)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=n.get(a);delete l.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 l={read:()=>null,write:(c,d)=>{++t;try{for(const[u,f]of a)"init"in u&&d(u,f)}finally{--t}}};s.set(l)}})};function bh(){return(Cs?"production":void 0)!=="production"?_h():Zo()}let Ln;function wh(){return Ln||(Ln=bh(),(Cs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Ln),globalThis.__JOTAI_DEFAULT_STORE__!==Ln&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Ln}function ea(t,e){for(var n in e)t[n]=e[n];return t}function ta(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 na=$o;function ia(t,e){this.props=t,this.context=e}(ia.prototype=new et).isPureReactComponent=!0,ia.prototype.shouldComponentUpdate=function(t,e){return ta(this.props,t)||ta(this.state,e)};var sa=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),sa&&sa(t)};var Sh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Ch(t){function e(n){var i=ea({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Sh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var ra=function(t,e){return t==null?null:ot(ot(t).map(e))},xh={map:ra,forEach:ra,count:function(t){return t?ot(t).length:0},only:function(t){var e=ot(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ot},kh=G.__e;G.__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)}kh(t,e,n,i)};var oa=G.unmount;function aa(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=ea({},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 aa(i,e,n)})),t}function la(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return la(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 xs(){this.__u=0,this.o=null,this.__b=null}function ca(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function bi(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),oa&&oa(t)},(xs.prototype=new et).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=ca(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=la(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},xs.prototype.componentWillUnmount=function(){this.o=[]},xs.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]=aa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&We(rt,null,t.fallback);return s&&(s.__u&=-33),[We(rt,null,e.__a?null:t.children),s]};var da=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]}};(bi.prototype=new et).__a=function(t){var e=this,n=ca(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),da(e,t,i)):s()};n?n(o):o()}},bi.prototype.render=function(t){this.i=null,this.l=new Map;var e=ot(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},bi.prototype.componentDidUpdate=bi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){da(t,n,e)})};var ua=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Th=/^(?: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)/,Eh=/[A-Z0-9]/g,Ih=typeof document<"u",Rh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};et.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(et.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var ha=G.event;function Lh(){}function Ph(){return this.cancelBubble}function Mh(){return this.defaultPrevented}G.event=function(t){return ha&&(t=ha(t)),t.persist=Lh,t.isPropagationStopped=Ph,t.isDefaultPrevented=Mh,t.nativeEvent=t};var Dh={enumerable:!1,configurable:!0,get:function(){return this.class}},fa=G.vnode;G.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||Ih&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Rh(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Ah.test(r)&&(r=l):l=r="oninput":o&&Th.test(r)?r=r.replace(Eh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",Dh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ua,fa&&fa(t)};var pa=G.__r;G.__r=function(t){pa&&pa(t),t.__c};var ga=G.diffed;G.diffed=function(t){ga&&ga(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 ma(t){return!!t&&t.$$typeof===ua}function Oh(t){return ma(t)?ps.apply(null,arguments):t}var va={};const Nh={},Fh=vt(void 0);function ya(t){return Te(Fh)||wh()}const ks=t=>typeof(t==null?void 0:t.then)=="function",Ts=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Vh=va.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ts(t),t)}),As=new WeakMap,_a=(t,e)=>{let n=As.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=c=>d=>{o===c&&i(d)},a=c=>d=>{o===c&&s(d)},l=()=>{try{const c=e();ks(c)?(As.set(c,n),o=c,c.then(r(c),a(c)),Qo(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),Qo(t,l)}),As.set(t,n)),n};function Es(t,e){const{delay:n,unstable_promiseStatus:i=!va.use}={},s=ya(),[[o,r,a],l]=Uo(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 c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),ke(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);ks(u)&&Ts(_a(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),d},[s,t,n,i]),lh(c),ks(c)){const d=_a(c,()=>s.get(t));return i&&Ts(d),Vh(d)}return c}function wi(t,e){const n=ya();return yt((...s)=>{if((Nh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function ba(t,e){return[Es(t),wi(t)]}const Is=vt({});function Si(t){const e=me(null);return e.current===null&&(e.current=t()),e.current}const Rs=typeof window<"u",wa=Rs?$o:ke,Ci=vt(null);function Ls(t,e){t.indexOf(e)===-1&&t.push(e)}function Ps(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const _t=(t,e,n)=>n>e?e:n<t?t:n;let Ms=()=>{};const bt={},Sa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Ca(t){return typeof t=="object"&&t!==null}const xa=t=>/^0[^.\s]+$/u.test(t);function Ds(t){let e;return()=>(e===void 0&&(e=t()),e)}const qe=t=>t,Bh=(t,e)=>n=>e(t(n)),Pn=(...t)=>t.reduce(Bh),Mn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Os{constructor(){this.subscriptions=[]}add(e){return Ls(this.subscriptions,e),()=>Ps(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 at=t=>t*1e3,lt=t=>t/1e3;function ka(t,e){return e?t*(1e3/e):0}const Ta=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,jh=1e-7,Uh=12;function $h(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=Ta(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>jh&&++a<Uh);return r}function Dn(t,e,n,i){if(t===e&&n===i)return qe;const s=o=>$h(o,0,1,t,n);return o=>o===0||o===1?o:Ta(s(o),e,i)}const Aa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Ea=t=>e=>1-t(1-e),Ia=Dn(.33,1.53,.69,.99),Ns=Ea(Ia),Ra=Aa(Ns),La=t=>(t*=2)<1?.5*Ns(t):.5*(2-Math.pow(2,-10*(t-1))),Fs=t=>1-Math.sin(Math.acos(t)),Pa=Ea(Fs),Ma=Aa(Fs),Hh=Dn(.42,0,1,1),Gh=Dn(0,0,.58,1),Da=Dn(.42,0,.58,1),Wh=t=>Array.isArray(t)&&typeof t[0]!="number",Oa=t=>Array.isArray(t)&&typeof t[0]=="number",zh={linear:qe,easeIn:Hh,easeInOut:Da,easeOut:Gh,circIn:Fs,circInOut:Ma,circOut:Pa,backIn:Ns,backInOut:Ra,backOut:Ia,anticipate:La},qh=t=>typeof t=="string",Na=t=>{if(Oa(t)){Ms(t.length===4);const[e,n,i,s]=t;return Dn(e,n,i,s)}else if(qh(t))return zh[t];return t},xi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Fa={value:null};function Kh(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},l=0;function c(u){r.has(u)&&(d.schedule(u),t()),l++,u(a)}const d={schedule:(u,f=!1,m=!1)=>{const v=m&&s?n:i;return f&&r.add(u),v.has(u)||v.add(u),u},cancel:u=>{i.delete(u),r.delete(u)},process:u=>{if(a=u,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&Fa.value&&Fa.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,d.process(u))}};return d}const Xh=40;function Va(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=xi.reduce((k,T)=>(k[T]=Kh(o,e?T:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:f,render:m,postRender:_}=r,v=()=>{const k=bt.useManualTiming?s.timestamp:performance.now();n=!1,bt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(k-s.timestamp,Xh),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),d.process(s),u.process(s),f.process(s),m.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},w=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:xi.reduce((k,T)=>{const E=r[T];return k[T]=(D,S=!1,x=!1)=>(n||w(),E.schedule(D,S,x)),k},{}),cancel:k=>{for(let T=0;T<xi.length;T++)r[xi[T]].cancel(k)},state:s,steps:r}}const{schedule:ue,cancel:At,state:Ee,steps:Vs}=Va(typeof requestAnimationFrame<"u"?requestAnimationFrame:qe,!0);let ki;function Yh(){ki=void 0}const Be={now:()=>(ki===void 0&&Be.set(Ee.isProcessing||bt.useManualTiming?Ee.timestamp:performance.now()),ki),set:t=>{ki=t,queueMicrotask(Yh)}},Ba=t=>e=>typeof e=="string"&&e.startsWith(t),Bs=Ba("--"),Jh=Ba("var(--"),js=t=>Jh(t)?Zh.test(t.split("/*")[0].trim()):!1,Zh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},On={...rn,transform:t=>_t(0,1,t)},Ti={...rn,default:1},Nn=t=>Math.round(t*1e5)/1e5,Us=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Qh(t){return t==null}const ef=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,$s=(t,e)=>n=>!!(typeof n=="string"&&ef.test(n)&&n.startsWith(t)||e&&!Qh(n)&&Object.prototype.hasOwnProperty.call(n,e)),ja=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Us);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},tf=t=>_t(0,255,t),Hs={...rn,transform:t=>Math.round(tf(t))},Ut={test:$s("rgb","red"),parse:ja("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Hs.transform(t)+", "+Hs.transform(e)+", "+Hs.transform(n)+", "+Nn(On.transform(i))+")"};function nf(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 Gs={test:$s("#"),parse:nf,transform:Ut.transform},Fn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Et=Fn("deg"),ct=Fn("%"),z=Fn("px"),sf=Fn("vh"),rf=Fn("vw"),Ua={...ct,parse:t=>ct.parse(t)/100,transform:t=>ct.transform(t*100)},on={test:$s("hsl","hue"),parse:ja("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ct.transform(Nn(e))+", "+ct.transform(Nn(n))+", "+Nn(On.transform(i))+")"},we={test:t=>Ut.test(t)||Gs.test(t)||on.test(t),parse:t=>Ut.test(t)?Ut.parse(t):on.test(t)?on.parse(t):Gs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ut.transform(t):on.transform(t),getAnimatableNone:t=>{const e=we.parse(t);return e.alpha=0,we.transform(e)}},of=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function af(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Us))==null?void 0:e.length)||0)+(((n=t.match(of))==null?void 0:n.length)||0)>0}const $a="number",Ha="color",lf="var",cf="var(",Ga="${}",df=/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 Vn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(df,l=>(we.test(l)?(i.color.push(o),s.push(Ha),n.push(we.parse(l))):l.startsWith(cf)?(i.var.push(o),s.push(lf),n.push(l)):(i.number.push(o),s.push($a),n.push(parseFloat(l))),++o,Ga)).split(Ga);return{values:n,split:a,indexes:i,types:s}}function Wa(t){return Vn(t).values}function za(t){const{split:e,types:n}=Vn(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===$a?o+=Nn(s[r]):a===Ha?o+=we.transform(s[r]):o+=s[r]}return o}}const uf=t=>typeof t=="number"?0:we.test(t)?we.getAnimatableNone(t):t;function hf(t){const e=Wa(t);return za(t)(e.map(uf))}const It={test:af,parse:Wa,createTransformer:za,getAnimatableNone:hf};function Ws(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 ff({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,l=2*n-a;s=Ws(l,a,t+1/3),o=Ws(l,a,t),r=Ws(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function Ai(t,e){return n=>n>0?e:t}const ve=(t,e,n)=>t+(e-t)*n,zs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},pf=[Gs,Ut,on],gf=t=>pf.find(e=>e.test(t));function qa(t){const e=gf(t);if(!e)return!1;let n=e.parse(t);return e===on&&(n=ff(n)),n}const Ka=(t,e)=>{const n=qa(t),i=qa(e);if(!n||!i)return Ai(t,e);const s={...n};return o=>(s.red=zs(n.red,i.red,o),s.green=zs(n.green,i.green,o),s.blue=zs(n.blue,i.blue,o),s.alpha=ve(n.alpha,i.alpha,o),Ut.transform(s))},qs=new Set(["none","hidden"]);function mf(t,e){return qs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function vf(t,e){return n=>ve(t,e,n)}function Ks(t){return typeof t=="number"?vf:typeof t=="string"?js(t)?Ai:we.test(t)?Ka:bf:Array.isArray(t)?Xa:typeof t=="object"?we.test(t)?Ka:yf:Ai}function Xa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ks(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function yf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Ks(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function _f(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 bf=(t,e)=>{const n=It.createTransformer(e),i=Vn(t),s=Vn(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?qs.has(t)&&!s.values.length||qs.has(e)&&!i.values.length?mf(t,e):Pn(Xa(_f(i,s),s.values),n):Ai(t,e)};function Ya(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ve(t,e,n):Ks(t)(t,e)}const wf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ue.update(e,n),stop:()=>At(e),now:()=>Ee.isProcessing?Ee.timestamp:Be.now()}},Ja=(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)})`},Ei=2e4;function Xs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ei;)e+=n,i=t.next(e);return e>=Ei?1/0:e}function Sf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Xs(i),Ei);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:lt(s)}}const Cf=5;function Za(t,e,n){const i=Math.max(e-Cf,0);return ka(n-t(i),e-i)}const ye={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Ys=.001;function xf({duration:t=ye.duration,bounce:e=ye.bounce,velocity:n=ye.velocity,mass:i=ye.mass}){let s,o,r=1-e;r=_t(ye.minDamping,ye.maxDamping,r),t=_t(ye.minDuration,ye.maxDuration,lt(t)),r<1?(s=c=>{const d=c*r,u=d*t,f=d-n,m=Js(c,r),_=Math.exp(-u);return Ys-f/m*_},o=c=>{const u=c*r*t,f=u*n+n,m=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-u),v=Js(Math.pow(c,2),r);return(-s(c)+Ys>0?-1:1)*((f-m)*_)/v}):(s=c=>{const d=Math.exp(-c*t),u=(c-n)*t+1;return-Ys+d*u},o=c=>{const d=Math.exp(-c*t),u=(n-c)*(t*t);return d*u});const a=5/t,l=Tf(s,o,a);if(t=at(t),isNaN(l))return{stiffness:ye.stiffness,damping:ye.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const kf=12;function Tf(t,e,n){let i=n;for(let s=1;s<kf;s++)i=i-t(i)/e(i);return i}function Js(t,e){return t*Math.sqrt(1-e*e)}const Af=["duration","bounce"],Ef=["stiffness","damping","mass"];function Qa(t,e){return e.some(n=>t[n]!==void 0)}function If(t){let e={velocity:ye.velocity,stiffness:ye.stiffness,damping:ye.damping,mass:ye.mass,isResolvedFromDuration:!1,...t};if(!Qa(t,Ef)&&Qa(t,Af))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*_t(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ye.mass,stiffness:s,damping:o}}else{const n=xf(t);e={...e,...n,mass:ye.mass},e.isResolvedFromDuration=!0}return e}function Ii(t=ye.visualDuration,e=ye.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:l,damping:c,mass:d,duration:u,velocity:f,isResolvedFromDuration:m}=If({...n,velocity:-lt(n.velocity||0)}),_=f||0,v=c/(2*Math.sqrt(l*d)),w=r-o,y=lt(Math.sqrt(l/d)),C=Math.abs(w)<5;i||(i=C?ye.restSpeed.granular:ye.restSpeed.default),s||(s=C?ye.restDelta.granular:ye.restDelta.default);let k;if(v<1){const E=Js(y,v);k=D=>{const S=Math.exp(-v*y*D);return r-S*((_+v*y*w)/E*Math.sin(E*D)+w*Math.cos(E*D))}}else if(v===1)k=E=>r-Math.exp(-y*E)*(w+(_+y*w)*E);else{const E=y*Math.sqrt(v*v-1);k=D=>{const S=Math.exp(-v*y*D),x=Math.min(E*D,300);return r-S*((_+v*y*w)*Math.sinh(x)+E*w*Math.cosh(x))/E}}const T={calculatedDuration:m&&u||null,next:E=>{const D=k(E);if(m)a.done=E>=u;else{let S=E===0?_:0;v<1&&(S=E===0?at(_):Za(k,E,D));const x=Math.abs(S)<=i,p=Math.abs(r-D)<=s;a.done=x&&p}return a.value=a.done?r:D,a},toString:()=>{const E=Math.min(Xs(T),Ei),D=Ja(S=>T.next(E*S).value,E,30);return E+"ms "+D},toTransition:()=>{}};return T}Ii.applyToOptions=t=>{const e=Sf(t,100,Ii);return t.ease=e.ease,t.duration=at(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:l,restDelta:c=.5,restSpeed:d}){const u=t[0],f={done:!1,value:u},m=x=>a!==void 0&&x<a||l!==void 0&&x>l,_=x=>a===void 0?l:l===void 0||Math.abs(a-x)<Math.abs(l-x)?a:l;let v=n*e;const w=u+v,y=r===void 0?w:r(w);y!==w&&(v=y-u);const C=x=>-v*Math.exp(-x/i),k=x=>y+C(x),T=x=>{const p=C(x),g=k(x);f.done=Math.abs(p)<=c,f.value=f.done?y:g};let E,D;const S=x=>{m(f.value)&&(E=x,D=Ii({keyframes:[f.value,_(f.value)],velocity:Za(k,x,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return S(0),{calculatedDuration:null,next:x=>{let p=!1;return!D&&E===void 0&&(p=!0,T(x),S(x)),E!==void 0&&x>=E?D.next(x-E):(!p&&T(x),f)}}}function Rf(t,e,n){const i=[],s=n||bt.mix||Ya,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||qe:e;a=Pn(l,a)}i.push(a)}return i}function Lf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Ms(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=Rf(e,i,s),l=a.length,c=d=>{if(r&&d<t[0])return e[0];let u=0;if(l>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const f=Mn(t[u],t[u+1],d);return a[u](f)};return n?d=>c(_t(t[0],t[o-1],d)):c}function Pf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Mn(0,e,i);t.push(ve(n,1,s))}}function Mf(t){const e=[0];return Pf(e,t.length-1),e}function Df(t,e){return t.map(n=>n*e)}function Of(t,e){return t.map(()=>e||Da).splice(0,t.length-1)}function Bn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Wh(i)?i.map(Na):Na(i),o={done:!1,value:e[0]},r=Df(n&&n.length===e.length?n:Mf(e),t),a=Lf(r,e,{ease:Array.isArray(s)?s:Of(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Nf=t=>t!==null;function Qs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Nf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Ff={decay:Zs,inertia:Zs,tween:Bn,keyframes:Bn,spring:Ii};function el(t){typeof t.type=="string"&&(t.type=Ff[t.type])}class er{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 Vf=t=>t/100;class tr extends er{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!==Be.now()&&this.tick(Be.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;el(e);const{type:n=Bn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||Bn;l!==Bn&&typeof a[0]!="number"&&(this.mixKeyframes=Pn(Vf,Ya(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=Xs(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}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:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:d,repeat:u,repeatType:f,repeatDelay:m,type:_,onUpdate:v,finalKeyframe:w}=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 y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,T=i;if(u){const x=Math.min(this.currentTime,s)/a;let p=Math.floor(x),g=x%1;!g&&x>=1&&(g=1),g===1&&p--,p=Math.min(p,u+1),!!(p%2)&&(f==="reverse"?(g=1-g,m&&(g-=m/a)):f==="mirror"&&(T=r)),k=_t(0,1,g)*a}const E=C?{done:!1,value:d[0]}:T.next(k);o&&(E.value=o(E.value));let{done:D}=E;!C&&l!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return S&&_!==Zs&&(E.value=Qs(d,this.options,w,this.speed)),v&&v(E.value),S&&this.finish(),E}then(e,n){return this.finished.then(e,n)}get duration(){return lt(this.calculatedDuration)}get time(){return lt(this.currentTime)}set time(e){var n;e=at(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(Be.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=lt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=wf,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(Be.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 Bf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const $t=t=>t*180/Math.PI,nr=t=>{const e=$t(Math.atan2(t[1],t[0]));return ir(e)},jf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:nr,rotateZ:nr,skewX:t=>$t(Math.atan(t[1])),skewY:t=>$t(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},ir=t=>(t=t%360,t<0&&(t+=360),t),tl=nr,nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),il=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Uf={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:nl,scaleY:il,scale:t=>(nl(t)+il(t))/2,rotateX:t=>ir($t(Math.atan2(t[6],t[5]))),rotateY:t=>ir($t(Math.atan2(-t[2],t[0]))),rotateZ:tl,rotate:tl,skewX:t=>$t(Math.atan(t[4])),skewY:t=>$t(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function sr(t){return t.includes("scale")?1:0}function rr(t,e){if(!t||t==="none")return sr(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Uf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=jf,s=a}if(!s)return sr(e);const o=i[e],r=s[1].split(",").map(Hf);return typeof o=="function"?o(r):r[o]}const $f=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return rr(n,e)};function Hf(t){return parseFloat(t.trim())}const an=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ln=new Set(an),sl=t=>t===rn||t===z,Gf=new Set(["x","y","z"]),Wf=an.filter(t=>!Gf.has(t));function zf(t){const e=[];return Wf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ht={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})=>rr(e,"x"),y:(t,{transform:e})=>rr(e,"y")};Ht.translateX=Ht.x,Ht.translateY=Ht.y;const Gt=new Set;let or=!1,ar=!1,lr=!1;function rl(){if(ar){const t=Array.from(Gt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=zf(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)})}ar=!1,or=!1,Gt.forEach(t=>t.complete(lr)),Gt.clear()}function ol(){Gt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ar=!0)})}function qf(){lr=!0,ol(),rl(),lr=!1}class cr{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?(Gt.add(this),or||(or=!0,ue.read(ol),ue.resolveKeyframes(rl))):(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])}Bf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Gt.delete(this)}cancel(){this.state==="scheduled"&&(Gt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Kf=t=>t.startsWith("--");function Xf(t,e,n){Kf(e)?t.style.setProperty(e,n):t.style[e]=n}const Yf=Ds(()=>window.ScrollTimeline!==void 0),Jf={};function Zf(t,e){const n=Ds(t);return()=>Jf[e]??n()}const al=Zf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),jn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,ll={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:jn([0,.65,.55,1]),circOut:jn([.55,0,1,.45]),backIn:jn([.31,.01,.66,-.59]),backOut:jn([.33,1.53,.69,.99])};function cl(t,e){if(t)return typeof t=="function"?al()?Ja(t,e):"ease-out":Oa(t)?jn(t):Array.isArray(t)?t.map(n=>cl(n,e)||ll.easeOut):ll[t]}function Qf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[e]:n};l&&(d.offset=l);const u=cl(a,s);Array.isArray(u)&&(d.easing=u);const f={delay:i,duration:s,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(d,f)}function dl(t){return typeof t=="function"&&"applyToOptions"in t}function ep({type:t,...e}){return dl(t)&&al()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class tp extends er{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:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Ms(typeof e.type!="string");const c=ep(e);this.animation=Qf(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Qs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Xf(n,i,d),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var 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 lt(Number(e))}get time(){return lt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=at(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&&Yf()?(this.animation.timeline=e,qe):n(this)}}const ul={anticipate:La,backInOut:Ra,circInOut:Ma};function np(t){return t in ul}function ip(t){typeof t.ease=="string"&&np(t.ease)&&(t.ease=ul[t.ease])}const hl=10;class sp extends tp{constructor(e){ip(e),el(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 tr({...r,autoplay:!1}),l=at(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-hl).value,a.sample(l).value,hl),a.stop()}}const fl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(It.test(t)||t==="0")&&!t.startsWith("url("));function rp(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 op(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=fl(s,e),a=fl(o,e);return!r||!a?!1:rp(t)||(n==="spring"||dl(n))&&i}function dr(t){return Ca(t)&&"offsetHeight"in t}const ap=new Set(["opacity","clipPath","filter","transform"]),lp=Ds(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function cp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!dr((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return lp()&&n&&ap.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const dp=40;class up extends er{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:d,...u}){var _;super(),this.stop=()=>{var v,w;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=Be.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},m=(d==null?void 0:d.KeyframeResolver)||cr;this.keyframeResolver=new m(a,(v,w,y)=>this.onKeyframesResolved(v,w,f,!y),l,c,d),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:d}=i;this.resolvedAt=Be.now(),op(e,o,r,a)||((bt.instantAnimations||!l)&&(d==null||d(Qs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>dp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},m=!c&&cp(f)?new sp({...f,element:f.motionValue.owner.current}):new tr(f);m.finished.then(()=>this.notifyFinished()).catch(qe),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}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(),qf()),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 hp=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function fp(t){const e=hp.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function pl(t,e,n=1){const[i,s]=fp(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Sa(r)?parseFloat(r):r}return js(s)?pl(s,e,n+1):s}function ur(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const gl=new Set(["width","height","top","left","right","bottom",...an]),pp={test:t=>t==="auto",parse:t=>t},ml=t=>e=>e.test(t),vl=[rn,z,ct,Et,rf,sf,pp],yl=t=>vl.find(ml(t));function gp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xa(t):!0}const mp=new Set(["brightness","contrast","saturate","opacity"]);function vp(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Us)||[];if(!i)return t;const s=n.replace(i,"");let o=mp.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const yp=/\b([a-z-]*)\(.*?\)/gu,hr={...It,getAnimatableNone:t=>{const e=t.match(yp);return e?e.map(vp).join(" "):t}},_l={...rn,transform:Math.round},fr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...{rotate:Et,rotateX:Et,rotateY:Et,rotateZ:Et,scale:Ti,scaleX:Ti,scaleY:Ti,scaleZ:Ti,skew:Et,skewX:Et,skewY:Et,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:On,originX:Ua,originY:Ua,originZ:z},zIndex:_l,fillOpacity:On,strokeOpacity:On,numOctaves:_l},_p={...fr,color:we,backgroundColor:we,outlineColor:we,fill:we,stroke:we,borderColor:we,borderTopColor:we,borderRightColor:we,borderBottomColor:we,borderLeftColor:we,filter:hr,WebkitFilter:hr},bl=t=>_p[t];function wl(t,e){let n=bl(t);return n!==hr&&(n=It),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const bp=new Set(["auto","none","0"]);function wp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!bp.has(o)&&Vn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=wl(n,s)}class Sp extends cr{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 l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),js(c))){const d=pl(c,n.current);d!==void 0&&(e[l]=d),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!gl.has(i)||e.length!==2)return;const[s,o]=e,r=yl(s),a=yl(o);if(r!==a)if(sl(r)&&sl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Ht[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||gp(e[s]))&&i.push(s);i.length&&wp(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=Ht[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]=Ht[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(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function Cp(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 Sl=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Cl=30,xp=t=>!isNaN(parseFloat(t));class kp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Be.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Be.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=xp(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 Os);const i=this.events[e].add(n);return e==="change"?()=>{i(),ue.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=Be.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Cl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Cl);return ka(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 cn(t,e){return new kp(t,e)}const{schedule:pr}=Va(queueMicrotask,!1),tt={x:!1,y:!1};function xl(){return tt.x||tt.y}function Tp(t){return t==="x"||t==="y"?tt[t]?null:(tt[t]=!0,()=>{tt[t]=!1}):tt.x||tt.y?null:(tt.x=tt.y=!0,()=>{tt.x=tt.y=!1})}function kl(t,e){const n=Cp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Tl(t){return!(t.pointerType==="touch"||xl())}function Ap(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{if(!Tl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const d=u=>{Tl(u)&&(c(u),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Al=(t,e)=>e?t===e?!0:Al(t,e.parentElement):!1,gr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ep=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ip(t){return Ep.has(t.tagName)||t.tabIndex!==-1}const Ri=new WeakSet;function El(t){return e=>{e.key==="Enter"&&t(e)}}function mr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Rp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=El(()=>{if(Ri.has(n))return;mr(n,"down");const s=El(()=>{mr(n,"up")}),o=()=>mr(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 Il(t){return gr(t)&&!xl()}function Lp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{const l=a.currentTarget;if(!Il(a))return;Ri.add(l);const c=e(l,a),d=(m,_)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),Ri.has(l)&&Ri.delete(l),Il(m)&&typeof c=="function"&&c(m,{success:_})},u=m=>{d(m,l===window||l===document||n.useGlobalTarget||Al(l,m.target))},f=m=>{d(m,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),dr(a)&&(a.addEventListener("focus",c=>Rp(c,s)),!Ip(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Rl(t){return Ca(t)&&"ownerSVGElement"in t}function Pp(t){return Rl(t)&&t.tagName==="svg"}const Pe=t=>!!(t&&t.getVelocity),Mp=[...vl,we,It],Dp=t=>Mp.find(ml(t)),Un=vt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Op extends et{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=dr(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 Np({children:t,isPresent:e,anchorX:n,root:i}){const s=vs(),o=me(null),r=me({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Te(Un);return na(()=>{const{width:l,height:c,top:d,left:u,right:f}=r.current;if(e||!o.current||!l||!c)return;const m=n==="left"?`left: ${u}`:`right: ${f}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=i??document.head;return v.appendChild(_),_.sheet&&_.sheet.insertRule(`
|
|
1
|
+
var ib=Object.defineProperty;var sb=(nt,G,jt)=>G in nt?ib(nt,G,{enumerable:!0,configurable:!0,writable:!0,value:jt}):nt[G]=jt;var J=(nt,G,jt)=>sb(nt,typeof G!="symbol"?G+"":G,jt);(function(){"use strict";var nt,G,jt,$t,Cr,Tr,kr,xr,ps,ms,gs,Er,In={},Ir=[],ch=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,An=Array.isArray;function at(t,e){for(var n in e)t[n]=e[n];return t}function vs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ke(t,e,n){var i,s,r,o={};for(r in e)r=="key"?i=e[r]:r=="ref"?s=e[r]:o[r]=e[r];if(arguments.length>2&&(o.children=arguments.length>3?nt.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)o[r]===void 0&&(o[r]=t.defaultProps[r]);return Rn(t,o,i,s,null)}function Rn(t,e,n,i,s){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++jt,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(r),r}function lt(t){return t.children}function it(t,e){this.props=t,this.context=e}function on(t,e){if(e==null)return t.__?on(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"?on(t):null}function Ar(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 Ar(t)}}function ys(t){(!t.__d&&(t.__d=!0)&&$t.push(t)&&!yi.__r++||Cr!=G.debounceRendering)&&((Cr=G.debounceRendering)||Tr)(yi)}function yi(){for(var t,e,n,i,s,r,o,a=1;$t.length;)$t.length>a&&$t.sort(kr),t=$t.shift(),a=$t.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,r=[],o=[],e.__P&&((n=at({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),_s(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,r,s??on(i),!!(32&i.__u),o),n.__v=i.__v,n.__.__k[n.__i]=n,Mr(r,n,o),n.__e!=s&&Ar(n)));yi.__r=0}function Rr(t,e,n,i,s,r,o,a,l,c,u){var d,f,g,v,_,w,y=i&&i.__k||Ir,T=e.length;for(l=dh(n,e,y,l,T),d=0;d<T;d++)(g=n.__k[d])!=null&&(f=g.__i==-1?In:y[g.__i]||In,g.__i=d,w=_s(t,g,f,s,r,o,a,l,c,u),v=g.__e,g.ref&&f.ref!=g.ref&&(f.ref&&bs(f.ref,null,g),u.push(g.ref,g.__c||v,g)),_==null&&v!=null&&(_=v),4&g.__u||f.__k===g.__k?l=Lr(g,l,t):typeof g.type=="function"&&w!==void 0?l=w:v&&(l=v.nextSibling),g.__u&=-7);return n.__e=_,l}function dh(t,e,n,i,s){var r,o,a,l,c,u=n.length,d=u,f=0;for(t.__k=new Array(s),r=0;r<s;r++)(o=e[r])!=null&&typeof o!="boolean"&&typeof o!="function"?(l=r+f,(o=t.__k[r]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Rn(null,o,null,null,null):An(o)?Rn(lt,{children:o},null,null,null):o.constructor==null&&o.__b>0?Rn(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,a=null,(c=o.__i=uh(o,n,l,d))!=-1&&(d--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?f--:s<u&&f++),typeof o.type!="function"&&(o.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,o.__u|=4))):t.__k[r]=null;if(d)for(r=0;r<u;r++)(a=n[r])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=on(a)),Or(a,a));return i}function Lr(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=Lr(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=on(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ct(t,e){return e=e||[],t==null||typeof t=="boolean"||(An(t)?t.some(function(n){ct(n,e)}):e.push(t)),e}function uh(t,e,n,i){var s,r,o=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&o==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,r=n+1;s>=0||r<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&o==l.key&&a==l.type)return s;s--}if(r<e.length){if((l=e[r])&&(2&l.__u)==0&&o==l.key&&a==l.type)return r;r++}}return-1}function Dr(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||ch.test(e)?n:n+"px"}function _i(t,e,n,i,s){var r,o;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||Dr(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Dr(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(xr,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?i?n.u=i.u:(n.u=ps,t.addEventListener(e,r?gs:ms,r)):t.removeEventListener(e,r?gs:ms,r);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 Pr(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ps++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function _s(t,e,n,i,s,r,o,a,l,c){var u,d,f,g,v,_,w,y,T,x,I,A,M,S,C,p,m,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),r=[a=e.__e=n.__e]),(u=G.__b)&&u(e);e:if(typeof h=="function")try{if(y=e.props,T="prototype"in h&&h.prototype.render,x=(u=h.contextType)&&i[u.__c],I=u?x?x.props.value:u.__:i,n.__c?w=(d=e.__c=n.__c).__=d.__E:(T?e.__c=d=new h(y,I):(e.__c=d=new it(y,I),d.constructor=h,d.render=fh),x&&x.sub(d),d.props=y,d.state||(d.state={}),d.context=I,d.__n=i,f=d.__d=!0,d.__h=[],d._sb=[]),T&&d.__s==null&&(d.__s=d.state),T&&h.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=at({},d.__s)),at(d.__s,h.getDerivedStateFromProps(y,d.__s))),g=d.props,v=d.state,d.__v=e,f)T&&h.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),T&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(T&&h.getDerivedStateFromProps==null&&y!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,I),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,I)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),A=0;A<d._sb.length;A++)d.__h.push(d._sb[A]);d._sb=[],d.__h.length&&o.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,I),T&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,v,_)})}if(d.context=I,d.props=y,d.__P=t,d.__e=!1,M=G.__r,S=0,T){for(d.state=d.__s,d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),C=0;C<d._sb.length;C++)d.__h.push(d._sb[C]);d._sb=[]}else do d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++S<25);d.state=d.__s,d.getChildContext!=null&&(i=at(at({},i),d.getChildContext())),T&&!f&&d.getSnapshotBeforeUpdate!=null&&(_=d.getSnapshotBeforeUpdate(g,v)),p=u,u!=null&&u.type===lt&&u.key==null&&(p=Nr(u.props.children)),a=Rr(t,An(p)?p:[p],e,n,i,s,r,o,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),w&&(d.__E=d.__=null)}catch(b){if(e.__v=null,l||r!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;r[r.indexOf(a)]=null,e.__e=a}else for(m=r.length;m--;)vs(r[m]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=hh(n.__e,e,n,i,s,r,o,l,c);return(u=G.diffed)&&u(e),128&e.__u?void 0:a}function Mr(t,e,n){for(var i=0;i<n.length;i++)bs(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(r){r.call(s)})}catch(r){G.__e(r,s.__v)}})}function Nr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:An(t)?t.map(Nr):at({},t)}function hh(t,e,n,i,s,r,o,a,l){var c,u,d,f,g,v,_,w=n.props,y=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"),r!=null){for(c=0;c<r.length;c++)if((g=r[c])&&"setAttribute"in g==!!T&&(T?g.localName==T:g.nodeType==3)){t=g,r[c]=null;break}}if(t==null){if(T==null)return document.createTextNode(y);t=document.createElementNS(s,T,y.is&&y),a&&(G.__m&&G.__m(e,r),a=!1),r=null}if(T==null)w===y||a&&t.data==y||(t.data=y);else{if(r=r&&nt.call(t.childNodes),w=n.props||In,!a&&r!=null)for(w={},c=0;c<t.attributes.length;c++)w[(g=t.attributes[c]).name]=g.value;for(c in w)if(g=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;_i(t,c,null,g,s)}}for(c in y)g=y[c],c=="children"?f=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?v=g:c=="checked"?_=g:a&&typeof g!="function"||w[c]===g||_i(t,c,g,w[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Rr(e.type=="template"?t.content:t,An(f)?f:[f],e,n,i,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,r,o,r?r[0]:n.__k&&on(n,0),a,l),r!=null)for(c=r.length;c--;)vs(r[c]);a||(c="value",T=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[c]||T=="progress"&&!v||T=="option"&&v!=w[c])&&_i(t,c,v,w[c],s),c="checked",_!=null&&_!=t[c]&&_i(t,c,_,w[c],s))}return t}function bs(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){G.__e(s,n)}}function Or(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||bs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){G.__e(r,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Or(i[s],e,n||typeof t.type!="function");n||vs(t.__e),t.__c=t.__=t.__e=void 0}function fh(t,e,n){return this.constructor(t,n)}function bi(t,e,n){var i,s,r,o;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],o=[],_s(e,t=(!i&&n||e).__k=Ke(lt,null,[t]),s||In,In,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?nt.call(e.childNodes):null,r,!i&&n?n:s?s.__e:e.firstChild,i,o),Mr(r,t,o)}function Fr(t,e){bi(t,e,Fr)}function ws(t,e,n){var i,s,r,o,a=at({},t.props);for(r in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)r=="key"?i=e[r]:r=="ref"?s=e[r]:a[r]=e[r]===void 0&&o!=null?o[r]:e[r];return arguments.length>2&&(a.children=arguments.length>3?nt.call(arguments,2):n),Rn(t.type,a,i||t.key,s||t.ref,null)}function bt(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(r){this.props.value!=r.value&&i.forEach(function(o){o.__e=!0,ys(o)})},this.sub=function(r){i.add(r);var o=r.componentWillUnmount;r.componentWillUnmount=function(){i&&i.delete(r),o&&o.call(r)}}),n.children}return e.__c="__cC"+Er++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}nt=Ir.slice,G={__e:function(t,e,n,i){for(var s,r,o;e=e.__;)if((s=e.__c)&&!s.__)try{if((r=s.constructor)&&r.getDerivedStateFromError!=null&&(s.setState(r.getDerivedStateFromError(t)),o=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),o=s.__d),o)return s.__E=s}catch(a){t=a}throw t}},jt=0,it.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=at({},this.state),typeof t=="function"&&(t=t(at({},n),this.props)),t&&at(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),ys(this))},it.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ys(this))},it.prototype.render=lt,$t=[],Tr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,kr=function(t,e){return t.__v.__b-e.__v.__b},yi.__r=0,xr=/(PointerCapture)$|Capture$/i,ps=0,ms=Pr(!1),gs=Pr(!0),Er=0;var ph=0;function R(t,e,n,i,s,r){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?o=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ph,__i:-1,__u:0,__source:s,__self:r};if(typeof t=="function"&&(o=t.defaultProps))for(a in o)l[a]===void 0&&(l[a]=o[a]);return G.vnode&&G.vnode(c),c}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 mh=["context","children"];function gh(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var r,o,a={},l=Object.keys(i);for(o=0;o<l.length;o++)s.indexOf(r=l[o])>=0||(a[r]=i[r]);return a}(t,mh);return ws(e,n)}function vh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ke(gh,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=[],r={},o=0,a=n.attributes,l=n.childNodes;for(o=a.length;o--;)a[o].name!=="slot"&&(r[a[o].name]=a[o].value,r[Vr(a[o].name)]=a[o].value);for(o=l.length;o--;){var c=e(l[o],null),u=l[o].slot;u?r[u]=Ke(Br,{name:u},c):s[o]=c}var d=i?Ke(Br,null,s):s;return Ke(i||n.nodeName.toLowerCase(),r,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Fr:bi)(this._vdom,this._root)}function Vr(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function yh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Vr(t)]=n,this._vdom=ws(this._vdom,i),bi(this._vdom,this._root)}}function _h(){bi(this._vdom=null,this._root)}function Br(t,e){var n=this;return Ke("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 bh(t,e,n,i){function s(){var r=Reflect.construct(HTMLElement,[],s);return r._vdomComponent=t,r._root=i&&i.shadow?r.attachShadow({mode:i.mode||"open"}):r,r}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=vh,s.prototype.attributeChangedCallback=yh,s.prototype.disconnectedCallback=_h,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=n,n.forEach(function(r){Object.defineProperty(s.prototype,r,{get:function(){return this._vdom.props[r]},set:function(o){this._vdom?this.attributeChangedCallback(r,null,o):(this._props||(this._props={}),this._props[r]=o,this.connectedCallback());var a=typeof o;o!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(r,o)}})}),customElements.define(e,s)}var Et,fe,Cs,Ur,Ln=0,jr=[],ye=G,$r=ye.__b,Hr=ye.__r,Wr=ye.diffed,Gr=ye.__c,zr=ye.unmount,qr=ye.__;function rn(t,e){ye.__h&&ye.__h(fe,t,Ln||e),Ln=0;var n=fe.__H||(fe.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function xe(t){return Ln=1,Kr(Jr,t)}function Kr(t,e,n){var i=rn(Et++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Jr(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=fe,!fe.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(f){return!!f.__c});if(u.every(function(f){return!f.__N}))return!r||r.call(this,a,l,c);var d=i.__c.props!==a;return u.forEach(function(f){if(f.__N){var g=f.__[0];f.__=f.__N,f.__N=void 0,g!==f.__[0]&&(d=!0)}}),r&&r.call(this,a,l,c)||d};fe.__f=!0;var r=fe.shouldComponentUpdate,o=fe.componentWillUpdate;fe.componentWillUpdate=function(a,l,c){if(this.__e){var u=r;r=void 0,s(a,l,c),r=u}o&&o.call(this,a,l,c)},fe.shouldComponentUpdate=s}return i.__N||i.__}function Ee(t,e){var n=rn(Et++,3);!ye.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,fe.__H.__h.push(n))}function Xr(t,e){var n=rn(Et++,4);!ye.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,fe.__h.push(n))}function de(t){return Ln=5,Xe(function(){return{current:t}},[])}function Xe(t,e){var n=rn(Et++,7);return xs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ge(t,e){return Ln=8,Xe(function(){return t},e)}function Ie(t){var e=fe.context[t.__c],n=rn(Et++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(fe)),e.props.value):t.__}function wh(t,e){ye.useDebugValue&&ye.useDebugValue(e?e(t):t)}function Ts(){var t=rn(Et++,11);if(!t.__){for(var e=fe.__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 Sh(){for(var t;t=jr.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(wi),t.__H.__h.forEach(ks),t.__H.__h=[]}catch(e){t.__H.__h=[],ye.__e(e,t.__v)}}ye.__b=function(t){fe=null,$r&&$r(t)},ye.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),qr&&qr(t,e)},ye.__r=function(t){Hr&&Hr(t),Et=0;var e=(fe=t.__c).__H;e&&(Cs===fe?(e.__h=[],fe.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(wi),e.__h.forEach(ks),e.__h=[],Et=0)),Cs=fe},ye.diffed=function(t){Wr&&Wr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(jr.push(e)!==1&&Ur===ye.requestAnimationFrame||((Ur=ye.requestAnimationFrame)||Ch)(Sh)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Cs=fe=null},ye.__c=function(t,e){e.some(function(n){try{n.__h.forEach(wi),n.__h=n.__h.filter(function(i){return!i.__||ks(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ye.__e(i,n.__v)}}),Gr&&Gr(t,e)},ye.unmount=function(t){zr&&zr(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{wi(i)}catch(s){e=s}}),n.__H=void 0,e&&ye.__e(e,n.__v))};var Yr=typeof requestAnimationFrame=="function";function Ch(t){var e,n=function(){clearTimeout(i),Yr&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Yr&&(e=requestAnimationFrame(n))}function wi(t){var e=fe,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),fe=e}function ks(t){var e=fe;t.__c=t.__(),fe=e}function xs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Jr(t,e){return typeof e=="function"?e(t):e}const Dn={},Zr=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Qr=t=>"init"in t,Es=t=>!!t.write,ea=t=>"v"in t||"e"in t,Si=t=>{if("e"in t)throw t.e;if((Dn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Ci=new WeakMap,ta=t=>{var e;return Ti(t)&&!!((e=Ci.get(t))!=null&&e[0])},Th=t=>{const e=Ci.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},na=(t,e)=>{let n=Ci.get(t);if(!n){n=[!0,new Set],Ci.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},Ti=t=>typeof(t==null?void 0:t.then)=="function",ia=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Is=(t,e,n)=>{const i=n(t),s="v"in i,r=i.v;if(Ti(e))for(const o of i.d.keys())ia(t,e,n(o));i.v=e,delete i.e,(!s||!Object.is(r,i.v))&&(++i.n,Ti(r)&&Th(r))},sa=(t,e,n)=>{var i;const s=new Set;for(const r of((i=n.get(t))==null?void 0:i.t)||[])n.has(r)&&s.add(r);for(const r of e.p)s.add(r);return s},kh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},As=()=>{const t={},e=new WeakMap,n=i=>{var s,r;(s=e.get(t))==null||s.forEach(o=>o(i)),(r=e.get(i))==null||r.forEach(o=>o())};return n.add=(i,s)=>{const r=i||t,o=(e.has(r)?e:e.set(r,new Set)).get(r);return o.add(s),()=>{o==null||o.delete(s),o.size||e.delete(r)}},n},xh=t=>(t.c||(t.c=As()),t.m||(t.m=As()),t.u||(t.u=As()),t.f||(t.f=kh()),t),Eh=Symbol(),oa=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,r=new Set,o={},a=(f,...g)=>f.read(...g),l=(f,...g)=>f.write(...g),c=(f,g)=>{var v;return(v=f.unstable_onInit)==null?void 0:v.call(f,g)},u=(f,g)=>{var v;return(v=f.onMount)==null?void 0:v.call(f,g)},...d)=>{const f=d[0]||(S=>{if((Dn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let C=t.get(S);return C||(C={d:new Map,p:new Set,n:0},t.set(S,C),c==null||c(S,M)),C}),g=d[1]||(()=>{const S=[],C=p=>{try{p()}catch(m){S.push(m)}};do{o.f&&C(o.f);const p=new Set,m=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(m)}),i.clear(),r.forEach(m),r.clear(),s.forEach(m),s.clear(),p.forEach(C),i.size&&v()}while(i.size||r.size||s.size);if(S.length)throw new AggregateError(S)}),v=d[2]||(()=>{const S=[],C=new WeakSet,p=new WeakSet,m=Array.from(i);for(;m.length;){const h=m[m.length-1],b=f(h);if(p.has(h)){m.pop();continue}if(C.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Dn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),m.pop();continue}C.add(h);for(const E of sa(h,b,e))C.has(E)||m.push(E)}for(let h=S.length-1;h>=0;--h){const[b,E]=S[h];let D=!1;for(const L of E.d.keys())if(L!==b&&i.has(L)){D=!0;break}D&&(_(b),T(b)),n.delete(b)}}),_=d[3]||(S=>{var C;const p=f(S);if(ea(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([P,B])=>_(P).n===B)))return p;p.d.clear();let m=!0;const h=()=>{e.has(S)&&(T(S),v(),g())},b=P=>{var B;if(Zr(S,P)){const j=f(P);if(!ea(j))if(Qr(P))Is(P,P.init,f);else throw new Error("no atom init");return Si(j)}const X=_(P);try{return Si(X)}finally{p.d.set(P,X.n),ta(p.v)&&ia(S,p.v,X),(B=e.get(P))==null||B.t.add(S),m||h()}};let E,D;const L={get signal(){return E||(E=new AbortController),E.signal},get setSelf(){return(Dn?"production":void 0)!=="production"&&!Es(S)&&console.warn("setSelf function cannot be used with read-only atom"),!D&&Es(S)&&(D=(...P)=>{if((Dn?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return y(S,...P)}finally{v(),g()}}),D}},N=p.n;try{const P=a(S,b,L);return Is(S,P,f),Ti(P)&&(na(P,()=>E==null?void 0:E.abort()),P.then(h,h)),p}catch(P){return delete p.v,p.e=P,++p.n,p}finally{m=!1,N!==p.n&&n.get(S)===N&&(n.set(S,p.n),i.add(S),(C=o.c)==null||C.call(o,S))}}),w=d[4]||(S=>{const C=[S];for(;C.length;){const p=C.pop(),m=f(p);for(const h of sa(p,m,e)){const b=f(h);n.set(h,b.n),C.push(h)}}}),y=d[5]||((S,...C)=>{let p=!0;const m=b=>Si(_(b)),h=(b,...E)=>{var D;const L=f(b);try{if(Zr(S,b)){if(!Qr(b))throw new Error("atom not writable");const N=L.n,P=E[0];Is(b,P,f),T(b),N!==L.n&&(i.add(b),(D=o.c)==null||D.call(o,b),w(b));return}else return y(b,...E)}finally{p||(v(),g())}};try{return l(S,m,h,...C)}finally{p=!1}}),T=d[6]||(S=>{var C;const p=f(S),m=e.get(S);if(m&&!ta(p.v)){for(const[h,b]of p.d)if(!m.d.has(h)){const E=f(h);x(h).t.add(S),m.d.add(h),b!==E.n&&(i.add(h),(C=o.c)==null||C.call(o,h),w(h))}for(const h of m.d||[])if(!p.d.has(h)){m.d.delete(h);const b=I(h);b==null||b.t.delete(S)}}}),x=d[7]||(S=>{var C;const p=f(S);let m=e.get(S);if(!m){_(S);for(const h of p.d.keys())x(h).t.add(S);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,m),(C=o.m)==null||C.call(o,S),Es(S)){const h=()=>{let b=!0;const E=(...D)=>{try{return y(S,...D)}finally{b||(v(),g())}};try{const D=u(S,E);D&&(m.u=()=>{b=!0;try{D()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return m}),I=d[8]||(S=>{var C;const p=f(S);let m=e.get(S);if(m&&!m.l.size&&!Array.from(m.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){m.u&&r.add(m.u),m=void 0,e.delete(S),(C=o.u)==null||C.call(o,S);for(const h of p.d.keys()){const b=I(h);b==null||b.t.delete(S)}return}return m}),A=[t,e,n,i,s,r,o,a,l,c,u,f,g,v,_,w,y,T,x,I],M={get:S=>Si(_(S)),set:(S,...C)=>{try{return y(S,...C)}finally{v(),g()}},sub:(S,C)=>{const m=x(S).l;return m.add(C),g(),()=>{m.delete(C),I(S),g()}}};return Object.defineProperty(M,Eh,{value:A}),M},Ih=xh,ra=na,Rs={};let Ah=0;function ki(t,e){const n=`atom${++Ah}`,i={toString(){return(Rs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=Rh,i.write=Lh),i}function Rh(t){return t(this)}function Lh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const Dh=()=>{let t=0;const e=Ih({}),n=new WeakMap,i=new WeakMap,s=oa(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),r=new Set;return e.m.add(void 0,a=>{r.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{r.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>r,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,f]of a)"init"in d&&u(d,f)}finally{--t}}};s.set(l)}})};function Ph(){return(Rs?"production":void 0)!=="production"?Dh():oa()}let Pn;function Mh(){return Pn||(Pn=Ph(),(Rs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Pn),globalThis.__JOTAI_DEFAULT_STORE__!==Pn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Pn}function aa(t,e){for(var n in e)t[n]=e[n];return t}function la(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 ca=Xr;function da(t,e){this.props=t,this.context=e}(da.prototype=new it).isPureReactComponent=!0,da.prototype.shouldComponentUpdate=function(t,e){return la(this.props,t)||la(this.state,e)};var ua=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ua&&ua(t)};var Nh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Oh(t){function e(n){var i=aa({},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 ha=function(t,e){return t==null?null:ct(ct(t).map(e))},Fh={map:ha,forEach:ha,count:function(t){return t?ct(t).length:0},only:function(t){var e=ct(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ct},Vh=G.__e;G.__e=function(t,e,n,i){if(t.then){for(var s,r=e;r=r.__;)if((s=r.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}Vh(t,e,n,i)};var fa=G.unmount;function pa(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=aa({},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 pa(i,e,n)})),t}function ma(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return ma(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 Ls(){this.__u=0,this.o=null,this.__b=null}function ga(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function xi(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),fa&&fa(t)},(Ls.prototype=new it).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=ga(i.__v),r=!1,o=function(){r||(r=!0,n.__R=null,s?s(a):a())};n.__R=o;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=ma(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Ls.prototype.componentWillUnmount=function(){this.o=[]},Ls.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]=pa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&Ke(lt,null,t.fallback);return s&&(s.__u&=-33),[Ke(lt,null,e.__a?null:t.children),s]};var va=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]}};(xi.prototype=new it).__a=function(t){var e=this,n=ga(e.__v),i=e.l.get(t);return i[0]++,function(s){var r=function(){e.props.revealOrder?(i.push(s),va(e,t,i)):s()};n?n(r):r()}},xi.prototype.render=function(t){this.i=null,this.l=new Map;var e=ct(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},xi.prototype.componentDidUpdate=xi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){va(t,n,e)})};var ya=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]/,Uh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,jh=/[A-Z0-9]/g,$h=typeof document<"u",Hh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};it.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(it.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var _a=G.event;function Wh(){}function Gh(){return this.cancelBubble}function zh(){return this.defaultPrevented}G.event=function(t){return _a&&(t=_a(t)),t.persist=Wh,t.isPropagationStopped=Gh,t.isDefaultPrevented=zh,t.nativeEvent=t};var qh={enumerable:!1,configurable:!0,get:function(){return this.class}},ba=G.vnode;G.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},r=i.indexOf("-")===-1;for(var o in n){var a=n[o];if(!(o==="value"&&"defaultValue"in n&&a==null||$h&&o==="children"&&i==="noscript"||o==="class"||o==="className")){var l=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?o="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Hh(n.type)?l==="onfocus"?o="onfocusin":l==="onblur"?o="onfocusout":Uh.test(o)&&(o=l):l=o="oninput":r&&Bh.test(o)?o=o.replace(jh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[o=l]&&(o="oninputCapture"),s[o]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",qh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ya,ba&&ba(t)};var wa=G.__r;G.__r=function(t){wa&&wa(t),t.__c};var Sa=G.diffed;G.diffed=function(t){Sa&&Sa(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 Ca(t){return!!t&&t.$$typeof===ya}function Kh(t){return Ca(t)?ws.apply(null,arguments):t}var Ta={};const Xh={},Yh=bt(void 0);function ka(t){return Ie(Yh)||Mh()}const Ds=t=>typeof(t==null?void 0:t.then)=="function",Ps=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Jh=Ta.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ps(t),t)}),Ms=new WeakMap,xa=(t,e)=>{let n=Ms.get(t);return n||(n=new Promise((i,s)=>{let r=t;const o=c=>u=>{r===c&&i(u)},a=c=>u=>{r===c&&s(u)},l=()=>{try{const c=e();Ds(c)?(Ms.set(c,n),r=c,c.then(o(c),a(c)),ra(c,l)):i(c)}catch(c){s(c)}};t.then(o(t),a(t)),ra(t,l)}),Ms.set(t,n)),n};function Ns(t,e){const{delay:n,unstable_promiseStatus:i=!Ta.use}={},s=ka(),[[r,o,a],l]=Kr(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=r;if((o!==s||a!==t)&&(l(),c=s.get(t)),Ee(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);Ds(d)&&Ps(xa(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),u},[s,t,n,i]),wh(c),Ds(c)){const u=xa(c,()=>s.get(t));return i&&Ps(u),Jh(u)}return c}function Ei(t,e){const n=ka();return Ge((...s)=>{if((Xh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function Ea(t,e){return[Ns(t),Ei(t)]}const Os=bt({});function Ii(t){const e=de(null);return e.current===null&&(e.current=t()),e.current}const Fs=typeof window<"u",Ia=Fs?Xr:Ee,Ai=bt(null);function Vs(t,e){t.indexOf(e)===-1&&t.push(e)}function Bs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const wt=(t,e,n)=>n>e?e:n<t?t:n;let Us=()=>{};const St={},Aa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Ra(t){return typeof t=="object"&&t!==null}const La=t=>/^0[^.\s]+$/u.test(t);function js(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ye=t=>t,Zh=(t,e)=>n=>e(t(n)),Mn=(...t)=>t.reduce(Zh),Nn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class $s{constructor(){this.subscriptions=[]}add(e){return Vs(this.subscriptions,e),()=>Bs(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 r=0;r<s;r++){const o=this.subscriptions[r];o&&o(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const dt=t=>t*1e3,ut=t=>t/1e3;function Da(t,e){return e?t*(1e3/e):0}const Pa=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Qh=1e-7,ef=12;function tf(t,e,n,i,s){let r,o,a=0;do o=e+(n-e)/2,r=Pa(o,i,s)-t,r>0?n=o:e=o;while(Math.abs(r)>Qh&&++a<ef);return o}function On(t,e,n,i){if(t===e&&n===i)return Ye;const s=r=>tf(r,0,1,t,n);return r=>r===0||r===1?r:Pa(s(r),e,i)}const Ma=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Na=t=>e=>1-t(1-e),Oa=On(.33,1.53,.69,.99),Hs=Na(Oa),Fa=Ma(Hs),Va=t=>(t*=2)<1?.5*Hs(t):.5*(2-Math.pow(2,-10*(t-1))),Ws=t=>1-Math.sin(Math.acos(t)),Ba=Na(Ws),Ua=Ma(Ws),nf=On(.42,0,1,1),sf=On(0,0,.58,1),ja=On(.42,0,.58,1),of=t=>Array.isArray(t)&&typeof t[0]!="number",$a=t=>Array.isArray(t)&&typeof t[0]=="number",rf={linear:Ye,easeIn:nf,easeInOut:ja,easeOut:sf,circIn:Ws,circInOut:Ua,circOut:Ba,backIn:Hs,backInOut:Fa,backOut:Oa,anticipate:Va},af=t=>typeof t=="string",Ha=t=>{if($a(t)){Us(t.length===4);const[e,n,i,s]=t;return On(e,n,i,s)}else if(af(t))return rf[t];return t},Ri=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Wa={value:null};function lf(t,e){let n=new Set,i=new Set,s=!1,r=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){o.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,f=!1,g=!1)=>{const _=g&&s?n:i;return f&&o.add(d),_.has(d)||_.add(d),d},cancel:d=>{i.delete(d),o.delete(d)},process:d=>{if(a=d,s){r=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&Wa.value&&Wa.value.frameloop[e].push(l),l=0,n.clear(),s=!1,r&&(r=!1,u.process(d))}};return u}const cf=40;function Ga(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,o=Ri.reduce((x,I)=>(x[I]=lf(r,e?I:void 0),x),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:f,render:g,postRender:v}=o,_=()=>{const x=St.useManualTiming?s.timestamp:performance.now();n=!1,St.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(x-s.timestamp,cf),1)),s.timestamp=x,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),f.process(s),g.process(s),v.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(_))},w=()=>{n=!0,i=!0,s.isProcessing||t(_)};return{schedule:Ri.reduce((x,I)=>{const A=o[I];return x[I]=(M,S=!1,C=!1)=>(n||w(),A.schedule(M,S,C)),x},{}),cancel:x=>{for(let I=0;I<Ri.length;I++)o[Ri[I]].cancel(x)},state:s,steps:o}}const{schedule:me,cancel:It,state:Le,steps:Gs}=Ga(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ye,!0);let Li;function df(){Li=void 0}const $e={now:()=>(Li===void 0&&$e.set(Le.isProcessing||St.useManualTiming?Le.timestamp:performance.now()),Li),set:t=>{Li=t,queueMicrotask(df)}},za=t=>e=>typeof e=="string"&&e.startsWith(t),zs=za("--"),uf=za("var(--"),qs=t=>uf(t)?hf.test(t.split("/*")[0].trim()):!1,hf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,an={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Fn={...an,transform:t=>wt(0,1,t)},Di={...an,default:1},Vn=t=>Math.round(t*1e5)/1e5,Ks=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ff(t){return t==null}const pf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Xs=(t,e)=>n=>!!(typeof n=="string"&&pf.test(n)&&n.startsWith(t)||e&&!ff(n)&&Object.prototype.hasOwnProperty.call(n,e)),qa=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,r,o,a]=i.match(Ks);return{[t]:parseFloat(s),[e]:parseFloat(r),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},mf=t=>wt(0,255,t),Ys={...an,transform:t=>Math.round(mf(t))},Ht={test:Xs("rgb","red"),parse:qa("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ys.transform(t)+", "+Ys.transform(e)+", "+Ys.transform(n)+", "+Vn(Fn.transform(i))+")"};function gf(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 Js={test:Xs("#"),parse:gf,transform:Ht.transform},Bn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),At=Bn("deg"),ht=Bn("%"),z=Bn("px"),vf=Bn("vh"),yf=Bn("vw"),Ka={...ht,parse:t=>ht.parse(t)/100,transform:t=>ht.transform(t*100)},ln={test:Xs("hsl","hue"),parse:qa("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ht.transform(Vn(e))+", "+ht.transform(Vn(n))+", "+Vn(Fn.transform(i))+")"},Te={test:t=>Ht.test(t)||Js.test(t)||ln.test(t),parse:t=>Ht.test(t)?Ht.parse(t):ln.test(t)?ln.parse(t):Js.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ht.transform(t):ln.transform(t),getAnimatableNone:t=>{const e=Te.parse(t);return e.alpha=0,Te.transform(e)}},_f=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function bf(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Ks))==null?void 0:e.length)||0)+(((n=t.match(_f))==null?void 0:n.length)||0)>0}const Xa="number",Ya="color",wf="var",Sf="var(",Ja="${}",Cf=/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 Un(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let r=0;const a=e.replace(Cf,l=>(Te.test(l)?(i.color.push(r),s.push(Ya),n.push(Te.parse(l))):l.startsWith(Sf)?(i.var.push(r),s.push(wf),n.push(l)):(i.number.push(r),s.push(Xa),n.push(parseFloat(l))),++r,Ja)).split(Ja);return{values:n,split:a,indexes:i,types:s}}function Za(t){return Un(t).values}function Qa(t){const{split:e,types:n}=Un(t),i=e.length;return s=>{let r="";for(let o=0;o<i;o++)if(r+=e[o],s[o]!==void 0){const a=n[o];a===Xa?r+=Vn(s[o]):a===Ya?r+=Te.transform(s[o]):r+=s[o]}return r}}const Tf=t=>typeof t=="number"?0:Te.test(t)?Te.getAnimatableNone(t):t;function kf(t){const e=Za(t);return Qa(t)(e.map(Tf))}const Rt={test:bf,parse:Za,createTransformer:Qa,getAnimatableNone:kf};function Zs(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 xf({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,r=0,o=0;if(!e)s=r=o=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Zs(l,a,t+1/3),r=Zs(l,a,t),o=Zs(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(r*255),blue:Math.round(o*255),alpha:i}}function Pi(t,e){return n=>n>0?e:t}const _e=(t,e,n)=>t+(e-t)*n,Qs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Ef=[Js,Ht,ln],If=t=>Ef.find(e=>e.test(t));function el(t){const e=If(t);if(!e)return!1;let n=e.parse(t);return e===ln&&(n=xf(n)),n}const tl=(t,e)=>{const n=el(t),i=el(e);if(!n||!i)return Pi(t,e);const s={...n};return r=>(s.red=Qs(n.red,i.red,r),s.green=Qs(n.green,i.green,r),s.blue=Qs(n.blue,i.blue,r),s.alpha=_e(n.alpha,i.alpha,r),Ht.transform(s))},eo=new Set(["none","hidden"]);function Af(t,e){return eo.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Rf(t,e){return n=>_e(t,e,n)}function to(t){return typeof t=="number"?Rf:typeof t=="string"?qs(t)?Pi:Te.test(t)?tl:Pf:Array.isArray(t)?nl:typeof t=="object"?Te.test(t)?tl:Lf:Pi}function nl(t,e){const n=[...t],i=n.length,s=t.map((r,o)=>to(r)(r,e[o]));return r=>{for(let o=0;o<i;o++)n[o]=s[o](r);return n}}function Lf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=to(t[s])(t[s],e[s]));return s=>{for(const r in i)n[r]=i[r](s);return n}}function Df(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const r=e.types[s],o=t.indexes[r][i[r]],a=t.values[o]??0;n[s]=a,i[r]++}return n}const Pf=(t,e)=>{const n=Rt.createTransformer(e),i=Un(t),s=Un(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?eo.has(t)&&!s.values.length||eo.has(e)&&!i.values.length?Af(t,e):Mn(nl(Df(i,s),s.values),n):Pi(t,e)};function il(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?_e(t,e,n):to(t)(t,e)}const Mf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>me.update(e,n),stop:()=>It(e),now:()=>Le.isProcessing?Le.timestamp:$e.now()}},sl=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let r=0;r<s;r++)i+=Math.round(t(r/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Mi=2e4;function no(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Mi;)e+=n,i=t.next(e);return e>=Mi?1/0:e}function Nf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(no(i),Mi);return{type:"keyframes",ease:r=>i.next(s*r).value/e,duration:ut(s)}}const Of=5;function ol(t,e,n){const i=Math.max(e-Of,0);return Da(n-t(i),e-i)}const be={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},io=.001;function Ff({duration:t=be.duration,bounce:e=be.bounce,velocity:n=be.velocity,mass:i=be.mass}){let s,r,o=1-e;o=wt(be.minDamping,be.maxDamping,o),t=wt(be.minDuration,be.maxDuration,ut(t)),o<1?(s=c=>{const u=c*o,d=u*t,f=u-n,g=so(c,o),v=Math.exp(-d);return io-f/g*v},r=c=>{const d=c*o*t,f=d*n+n,g=Math.pow(o,2)*Math.pow(c,2)*t,v=Math.exp(-d),_=so(Math.pow(c,2),o);return(-s(c)+io>0?-1:1)*((f-g)*v)/_}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-io+u*d},r=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const a=5/t,l=Bf(s,r,a);if(t=dt(t),isNaN(l))return{stiffness:be.stiffness,damping:be.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:o*2*Math.sqrt(i*c),duration:t}}}const Vf=12;function Bf(t,e,n){let i=n;for(let s=1;s<Vf;s++)i=i-t(i)/e(i);return i}function so(t,e){return t*Math.sqrt(1-e*e)}const Uf=["duration","bounce"],jf=["stiffness","damping","mass"];function rl(t,e){return e.some(n=>t[n]!==void 0)}function $f(t){let e={velocity:be.velocity,stiffness:be.stiffness,damping:be.damping,mass:be.mass,isResolvedFromDuration:!1,...t};if(!rl(t,jf)&&rl(t,Uf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,r=2*wt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:be.mass,stiffness:s,damping:r}}else{const n=Ff(t);e={...e,...n,mass:be.mass},e.isResolvedFromDuration=!0}return e}function Ni(t=be.visualDuration,e=be.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const r=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:r},{stiffness:l,damping:c,mass:u,duration:d,velocity:f,isResolvedFromDuration:g}=$f({...n,velocity:-ut(n.velocity||0)}),v=f||0,_=c/(2*Math.sqrt(l*u)),w=o-r,y=ut(Math.sqrt(l/u)),T=Math.abs(w)<5;i||(i=T?be.restSpeed.granular:be.restSpeed.default),s||(s=T?be.restDelta.granular:be.restDelta.default);let x;if(_<1){const A=so(y,_);x=M=>{const S=Math.exp(-_*y*M);return o-S*((v+_*y*w)/A*Math.sin(A*M)+w*Math.cos(A*M))}}else if(_===1)x=A=>o-Math.exp(-y*A)*(w+(v+y*w)*A);else{const A=y*Math.sqrt(_*_-1);x=M=>{const S=Math.exp(-_*y*M),C=Math.min(A*M,300);return o-S*((v+_*y*w)*Math.sinh(C)+A*w*Math.cosh(C))/A}}const I={calculatedDuration:g&&d||null,next:A=>{const M=x(A);if(g)a.done=A>=d;else{let S=A===0?v:0;_<1&&(S=A===0?dt(v):ol(x,A,M));const C=Math.abs(S)<=i,p=Math.abs(o-M)<=s;a.done=C&&p}return a.value=a.done?o:M,a},toString:()=>{const A=Math.min(no(I),Mi),M=sl(S=>I.next(A*S).value,A,30);return A+"ms "+M},toTransition:()=>{}};return I}Ni.applyToOptions=t=>{const e=Nf(t,100,Ni);return t.ease=e.ease,t.duration=dt(e.duration),t.type="keyframes",t};function oo({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:r=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],f={done:!1,value:d},g=C=>a!==void 0&&C<a||l!==void 0&&C>l,v=C=>a===void 0?l:l===void 0||Math.abs(a-C)<Math.abs(l-C)?a:l;let _=n*e;const w=d+_,y=o===void 0?w:o(w);y!==w&&(_=y-d);const T=C=>-_*Math.exp(-C/i),x=C=>y+T(C),I=C=>{const p=T(C),m=x(C);f.done=Math.abs(p)<=c,f.value=f.done?y:m};let A,M;const S=C=>{g(f.value)&&(A=C,M=Ni({keyframes:[f.value,v(f.value)],velocity:ol(x,C,f.value),damping:s,stiffness:r,restDelta:c,restSpeed:u}))};return S(0),{calculatedDuration:null,next:C=>{let p=!1;return!M&&A===void 0&&(p=!0,I(C),S(C)),A!==void 0&&C>=A?M.next(C-A):(!p&&I(C),f)}}}function Hf(t,e,n){const i=[],s=n||St.mix||il,r=t.length-1;for(let o=0;o<r;o++){let a=s(t[o],t[o+1]);if(e){const l=Array.isArray(e)?e[o]||Ye:e;a=Mn(l,a)}i.push(a)}return i}function Wf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const r=t.length;if(Us(r===e.length),r===1)return()=>e[0];if(r===2&&e[0]===e[1])return()=>e[1];const o=t[0]===t[1];t[0]>t[r-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Hf(e,i,s),l=a.length,c=u=>{if(o&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const f=Nn(t[d],t[d+1],u);return a[d](f)};return n?u=>c(wt(t[0],t[r-1],u)):c}function Gf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Nn(0,e,i);t.push(_e(n,1,s))}}function zf(t){const e=[0];return Gf(e,t.length-1),e}function qf(t,e){return t.map(n=>n*e)}function Kf(t,e){return t.map(()=>e||ja).splice(0,t.length-1)}function jn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=of(i)?i.map(Ha):Ha(i),r={done:!1,value:e[0]},o=qf(n&&n.length===e.length?n:zf(e),t),a=Wf(o,e,{ease:Array.isArray(s)?s:Kf(e,s)});return{calculatedDuration:t,next:l=>(r.value=a(l),r.done=l>=t,r)}}const Xf=t=>t!==null;function ro(t,{repeat:e,repeatType:n="loop"},i,s=1){const r=t.filter(Xf),a=s<0||e&&n!=="loop"&&e%2===1?0:r.length-1;return!a||i===void 0?r[a]:i}const Yf={decay:oo,inertia:oo,tween:jn,keyframes:jn,spring:Ni};function al(t){typeof t.type=="string"&&(t.type=Yf[t.type])}class ao{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 Jf=t=>t/100;class lo extends ao{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!==$e.now()&&this.tick($e.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;al(e);const{type:n=jn,repeat:i=0,repeatDelay:s=0,repeatType:r,velocity:o=0}=e;let{keyframes:a}=e;const l=n||jn;l!==jn&&typeof a[0]!="number"&&(this.mixKeyframes=Mn(Jf,il(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});r==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-o})),c.calculatedDuration===null&&(c.calculatedDuration=no(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}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:r,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:f,repeatDelay:g,type:v,onUpdate:_,finalKeyframe:w}=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 y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),T=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let x=this.currentTime,I=i;if(d){const C=Math.min(this.currentTime,s)/a;let p=Math.floor(C),m=C%1;!m&&C>=1&&(m=1),m===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(f==="reverse"?(m=1-m,g&&(m-=g/a)):f==="mirror"&&(I=o)),x=wt(0,1,m)*a}const A=T?{done:!1,value:u[0]}:I.next(x);r&&(A.value=r(A.value));let{done:M}=A;!T&&l!==null&&(M=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return S&&v!==oo&&(A.value=ro(u,this.options,w,this.speed)),_&&_(A.value),S&&this.finish(),A}then(e,n){return this.finished.then(e,n)}get duration(){return ut(this.calculatedDuration)}get time(){return ut(this.currentTime)}set time(e){var n;e=dt(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($e.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=ut(this.currentTime))}play(){var s,r;if(this.isStopped)return;const{driver:e=Mf,startTime:n}=this.options;this.driver||(this.driver=e(o=>this.tick(o))),(r=(s=this.options).onPlay)==null||r.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($e.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 Zf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Wt=t=>t*180/Math.PI,co=t=>{const e=Wt(Math.atan2(t[1],t[0]));return uo(e)},Qf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:co,rotateZ:co,skewX:t=>Wt(Math.atan(t[1])),skewY:t=>Wt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},uo=t=>(t=t%360,t<0&&(t+=360),t),ll=co,cl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),dl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),ep={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:cl,scaleY:dl,scale:t=>(cl(t)+dl(t))/2,rotateX:t=>uo(Wt(Math.atan2(t[6],t[5]))),rotateY:t=>uo(Wt(Math.atan2(-t[2],t[0]))),rotateZ:ll,rotate:ll,skewX:t=>Wt(Math.atan(t[4])),skewY:t=>Wt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ho(t){return t.includes("scale")?1:0}function fo(t,e){if(!t||t==="none")return ho(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=ep,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Qf,s=a}if(!s)return ho(e);const r=i[e],o=s[1].split(",").map(np);return typeof r=="function"?r(o):o[r]}const tp=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return fo(n,e)};function np(t){return parseFloat(t.trim())}const cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dn=new Set(cn),ul=t=>t===an||t===z,ip=new Set(["x","y","z"]),sp=cn.filter(t=>!ip.has(t));function op(t){const e=[];return sp.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Gt={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})=>fo(e,"x"),y:(t,{transform:e})=>fo(e,"y")};Gt.translateX=Gt.x,Gt.translateY=Gt.y;const zt=new Set;let po=!1,mo=!1,go=!1;function hl(){if(mo){const t=Array.from(zt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=op(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(([r,o])=>{var a;(a=i.getValue(r))==null||a.set(o)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}mo=!1,po=!1,zt.forEach(t=>t.complete(go)),zt.clear()}function fl(){zt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(mo=!0)})}function rp(){go=!0,fl(),hl(),go=!1}class vo{constructor(e,n,i,s,r,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=r,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(zt.add(this),po||(po=!0,me.read(fl),me.resolveKeyframes(hl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const r=s==null?void 0:s.get(),o=e[e.length-1];if(r!==void 0)e[0]=r;else if(i&&n){const a=i.readValue(n,o);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=o),s&&r===void 0&&s.set(e[0])}Zf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),zt.delete(this)}cancel(){this.state==="scheduled"&&(zt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const ap=t=>t.startsWith("--");function lp(t,e,n){ap(e)?t.style.setProperty(e,n):t.style[e]=n}const cp=js(()=>window.ScrollTimeline!==void 0),dp={};function up(t,e){const n=js(t);return()=>dp[e]??n()}const pl=up(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),$n=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,ml={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:$n([0,.65,.55,1]),circOut:$n([.55,0,1,.45]),backIn:$n([.31,.01,.66,-.59]),backOut:$n([.33,1.53,.69,.99])};function gl(t,e){if(t)return typeof t=="function"?pl()?sl(t,e):"ease-out":$a(t)?$n(t):Array.isArray(t)?t.map(n=>gl(n,e)||ml.easeOut):ml[t]}function hp(t,e,n,{delay:i=0,duration:s=300,repeat:r=0,repeatType:o="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=gl(a,s);Array.isArray(d)&&(u.easing=d);const f={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:r+1,direction:o==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(u,f)}function vl(t){return typeof t=="function"&&"applyToOptions"in t}function fp({type:t,...e}){return vl(t)&&pl()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class pp extends ao{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:r,allowFlatten:o=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!r,this.allowFlatten=o,this.options=e,Us(typeof e.type!="string");const c=fp(e);this.animation=hp(n,i,s,c,r),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=ro(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):lp(n,i,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var 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 ut(Number(e))}get time(){return ut(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=dt(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&&cp()?(this.animation.timeline=e,Ye):n(this)}}const yl={anticipate:Va,backInOut:Fa,circInOut:Ua};function mp(t){return t in yl}function gp(t){typeof t.ease=="string"&&mp(t.ease)&&(t.ease=yl[t.ease])}const _l=10;class vp extends pp{constructor(e){gp(e),al(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:r,...o}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new lo({...o,autoplay:!1}),l=dt(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-_l).value,a.sample(l).value,_l),a.stop()}}const bl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Rt.test(t)||t==="0")&&!t.startsWith("url("));function yp(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 _p(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const r=t[t.length-1],o=bl(s,e),a=bl(r,e);return!o||!a?!1:yp(t)||(n==="spring"||vl(n))&&i}function yo(t){return Ra(t)&&"offsetHeight"in t}const bp=new Set(["opacity","clipPath","filter","transform"]),wp=js(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Sp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:r,type:o}=t;if(!yo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return wp()&&n&&bp.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&r!==0&&o!=="inertia"}const Cp=40;class Tp extends ao{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:r=0,repeatType:o="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var v;super(),this.stop=()=>{var _,w;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=$e.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:r,repeatType:o,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||vo;this.keyframeResolver=new g(a,(_,w,y)=>this.onKeyframesResolved(_,w,f,!y),l,c,u),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:r,type:o,velocity:a,delay:l,isHandoff:c,onUpdate:u}=i;this.resolvedAt=$e.now(),_p(e,r,o,a)||((St.instantAnimations||!l)&&(u==null||u(ro(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Cp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!c&&Sp(f)?new vp({...f,element:f.motionValue.owner.current}):new lo(f);g.finished.then(()=>this.notifyFinished()).catch(Ye),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(),rp()),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 kp=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function xp(t){const e=kp.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function wl(t,e,n=1){const[i,s]=xp(t);if(!i)return;const r=window.getComputedStyle(e).getPropertyValue(i);if(r){const o=r.trim();return Aa(o)?parseFloat(o):o}return qs(s)?wl(s,e,n+1):s}function _o(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Sl=new Set(["width","height","top","left","right","bottom",...cn]),Ep={test:t=>t==="auto",parse:t=>t},Cl=t=>e=>e.test(t),Tl=[an,z,ht,At,yf,vf,Ep],kl=t=>Tl.find(Cl(t));function Ip(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||La(t):!0}const Ap=new Set(["brightness","contrast","saturate","opacity"]);function Rp(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Ks)||[];if(!i)return t;const s=n.replace(i,"");let r=Ap.has(e)?1:0;return i!==n&&(r*=100),e+"("+r+s+")"}const Lp=/\b([a-z-]*)\(.*?\)/gu,bo={...Rt,getAnimatableNone:t=>{const e=t.match(Lp);return e?e.map(Rp).join(" "):t}},xl={...an,transform:Math.round},wo={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...{rotate:At,rotateX:At,rotateY:At,rotateZ:At,scale:Di,scaleX:Di,scaleY:Di,scaleZ:Di,skew:At,skewX:At,skewY:At,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:Fn,originX:Ka,originY:Ka,originZ:z},zIndex:xl,fillOpacity:Fn,strokeOpacity:Fn,numOctaves:xl},Dp={...wo,color:Te,backgroundColor:Te,outlineColor:Te,fill:Te,stroke:Te,borderColor:Te,borderTopColor:Te,borderRightColor:Te,borderBottomColor:Te,borderLeftColor:Te,filter:bo,WebkitFilter:bo},El=t=>Dp[t];function Il(t,e){let n=El(t);return n!==bo&&(n=Rt),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 r=t[i];typeof r=="string"&&!Pp.has(r)&&Un(r).values.length&&(s=t[i]),i++}if(s&&n)for(const r of e)t[r]=Il(n,s)}class Np extends vo{constructor(e,n,i,s,r){super(e,n,i,s,r,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),qs(c))){const u=wl(c,n.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Sl.has(i)||e.length!==2)return;const[s,r]=e,o=kl(s),a=kl(r);if(o!==a)if(ul(o)&&ul(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Gt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Ip(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=Gt[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 r=i.length-1,o=i[r];i[r]=Gt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function Op(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 Al=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Rl=30,Fp=t=>!isNaN(parseFloat(t));class Vp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var o,a;const r=$e.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((o=this.events.change)==null||o.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=$e.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Fp(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 $s);const i=this.events[e].add(n);return e==="change"?()=>{i(),me.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=$e.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Rl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Rl);return Da(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 un(t,e){return new Vp(t,e)}const{schedule:So}=Ga(queueMicrotask,!1),st={x:!1,y:!1};function Ll(){return st.x||st.y}function Bp(t){return t==="x"||t==="y"?st[t]?null:(st[t]=!0,()=>{st[t]=!1}):st.x||st.y?null:(st.x=st.y=!0,()=>{st.x=st.y=!1})}function Dl(t,e){const n=Op(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Pl(t){return!(t.pointerType==="touch"||Ll())}function Up(t,e,n={}){const[i,s,r]=Dl(t,n),o=a=>{if(!Pl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Pl(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",o,s)}),r}const Ml=(t,e)=>e?t===e?!0:Ml(t,e.parentElement):!1,Co=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,jp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function $p(t){return jp.has(t.tagName)||t.tabIndex!==-1}const Oi=new WeakSet;function Nl(t){return e=>{e.key==="Enter"&&t(e)}}function To(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Hp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Nl(()=>{if(Oi.has(n))return;To(n,"down");const s=Nl(()=>{To(n,"up")}),r=()=>To(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",r,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function Ol(t){return Co(t)&&!Ll()}function Wp(t,e,n={}){const[i,s,r]=Dl(t,n),o=a=>{const l=a.currentTarget;if(!Ol(a))return;Oi.add(l);const c=e(l,a),u=(g,v)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),Oi.has(l)&&Oi.delete(l),Ol(g)&&typeof c=="function"&&c(g,{success:v})},d=g=>{u(g,l===window||l===document||n.useGlobalTarget||Ml(l,g.target))},f=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,s),yo(a)&&(a.addEventListener("focus",c=>Hp(c,s)),!$p(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),r}function Fl(t){return Ra(t)&&"ownerSVGElement"in t}function Gp(t){return Fl(t)&&t.tagName==="svg"}const Ne=t=>!!(t&&t.getVelocity),zp=[...Tl,Te,Rt],qp=t=>zp.find(Cl(t)),Hn=bt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Kp extends it{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=yo(i)&&i.offsetWidth||0,r=this.props.sizeRef.current;r.height=n.offsetHeight||0,r.width=n.offsetWidth||0,r.top=n.offsetTop,r.left=n.offsetLeft,r.right=s-r.width-r.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Xp({children:t,isPresent:e,anchorX:n,root:i}){const s=Ts(),r=de(null),o=de({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Ie(Hn);return ca(()=>{const{width:l,height:c,top:u,left:d,right:f}=o.current;if(e||!r.current||!l||!c)return;const g=n==="left"?`left: ${d}`:`right: ${f}`;r.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const _=i??document.head;return _.appendChild(v),v.sheet&&v.sheet.insertRule(`
|
|
2
2
|
[data-motion-pop-id="${s}"] {
|
|
3
3
|
position: absolute !important;
|
|
4
4
|
width: ${l}px !important;
|
|
5
5
|
height: ${c}px !important;
|
|
6
|
-
${
|
|
7
|
-
top: ${
|
|
6
|
+
${g}px !important;
|
|
7
|
+
top: ${u}px !important;
|
|
8
8
|
}
|
|
9
|
-
`),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),R(Op,{isPresent:e,childRef:o,sizeRef:r,children:Oh(t,{ref:o})})}const Fp=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Si(Vp),d=vs();let u=!0,f=ze(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:m=>{c.set(m,!0);for(const _ of c.values())if(!_)return;i&&i()},register:m=>(c.set(m,!1),()=>c.delete(m))}),[n,c,i]);return o&&u&&(f={...f}),ze(()=>{c.forEach((m,_)=>c.set(_,!1))},[n]),ke(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=R(Np,{isPresent:n,anchorX:a,root:l,children:t})),R(Ci.Provider,{value:f,children:t})};function Vp(){return new Map}function Ll(t=!0){const e=Te(Ci);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=vs();ke(()=>{if(t)return s(o)},[t]);const r=yt(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Li=t=>t.key||"";function Pl(t){const e=[];return xh.forEach(t,n=>{ma(n)&&e.push(n)}),e}const Bp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,d]=Ll(r),u=ze(()=>Pl(t),[t]),f=r&&!c?[]:u.map(Li),m=me(!0),_=me(u),v=Si(()=>new Map),[w,y]=xe(u),[C,k]=xe(u);wa(()=>{m.current=!1,_.current=u;for(let D=0;D<C.length;D++){const S=Li(C[D]);f.includes(S)?v.delete(S):v.get(S)!==!0&&v.set(S,!1)}},[C,f.length,f.join("-")]);const T=[];if(u!==w){let D=[...u];for(let S=0;S<C.length;S++){const x=C[S],p=Li(x);f.includes(p)||(D.splice(S,0,x),T.push(x))}return o==="wait"&&T.length&&(D=T),k(Pl(D)),y(u),null}const{forceRender:E}=Te(Is);return R(rt,{children:C.map(D=>{const S=Li(D),x=r&&!c?!1:u===C||f.includes(S),p=()=>{if(v.has(S))v.set(S,!0);else return;let g=!0;v.forEach(h=>{h||(g=!1)}),g&&(E==null||E(),k(_.current),r&&(d==null||d()),i&&i())};return R(Fp,{isPresent:x,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:x?void 0:p,anchorX:a,children:D},S)})})},Ml=vt({strict:!1}),Dl={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"]},dn={};for(const t in Dl)dn[t]={isEnabled:e=>Dl[t].some(n=>!!e[n])};function jp(t){for(const e in t)dn[e]={...dn[e],...t[e]}}const Up=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 Pi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Up.has(t)}let Ol=t=>!Pi(t);function Nl(t){typeof t=="function"&&(Ol=e=>e.startsWith("on")?!Pi(e):t(e))}try{Nl(require("@emotion/is-prop-valid").default)}catch{}function $p(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Ol(s)||n===!0&&Pi(s)||!e&&!Pi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Hp({children:t,isValidProp:e,...n}){e&&Nl(e),n={...Te(Un),...n},n.isStatic=Si(()=>n.isStatic);const i=ze(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return R(Un.Provider,{value:i,children:t})}function Gp(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 Mi=vt({});function Di(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function $n(t){return typeof t=="string"||Array.isArray(t)}const vr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],yr=["initial",...vr];function Oi(t){return Di(t.animate)||yr.some(e=>$n(t[e]))}function Fl(t){return!!(Oi(t)||t.variants)}function Wp(t,e){if(Oi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||$n(n)?n:void 0,animate:$n(i)?i:void 0}}return t.inherit!==!1?e:{}}function zp(t){const{initial:e,animate:n}=Wp(t,Te(Mi));return ze(()=>({initial:e,animate:n}),[Vl(e),Vl(n)])}function Vl(t){return Array.isArray(t)?t.join(" "):t}const qp=Symbol.for("motionComponentSymbol");function un(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Kp(t,e,n){return yt(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):un(n)&&(n.current=i))},[e])}const _r=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bl="data-"+_r("framerAppearId"),jl=vt({});function Xp(t,e,n,i,s){var v,w;const{visualElement:o}=Te(Mi),r=Te(Ml),a=Te(Ci),l=Te(Un).reducedMotion,c=me(null);i=i||r.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,u=Te(jl);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&Yp(c.current,n,s,u);const f=me(!1);na(()=>{d&&f.current&&d.update(n,a)});const m=n[Bl],_=me(!!m&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,m))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,m)));return wa(()=>{d&&(f.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),pr.render(d.render),_.current&&d.animationState&&d.animationState.animateChanges())}),ke(()=>{d&&(!_.current&&d.animationState&&d.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,m)}),_.current=!1))}),d}function Yp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Ul(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&un(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:d,layoutScroll:l,layoutRoot:c})}function Ul(t){if(t)return t.options.allowProjection!==!1?t.projection:Ul(t.parent)}function Jp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&jp(t);function o(a,l){let c;const d={...Te(Un),...a,layoutId:Zp(a)},{isStatic:u}=d,f=zp(a),m=i(a,u);if(!u&&Rs){Qp();const _=eg(d);c=_.MeasureLayout,f.visualElement=Xp(s,m,d,e,_.ProjectionNode)}return R(Mi.Provider,{value:f,children:[c&&f.visualElement?R(c,{visualElement:f.visualElement,...d}):null,n(s,a,Kp(m,f.visualElement,l),m,u,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Ch(o);return r[qp]=s,r}function Zp({layoutId:t}){const e=Te(Is).id;return e&&t!==void 0?e+"-"+t:t}function Qp(t,e){Te(Ml).strict}function eg(t){const{drag:e,layout:n}=dn;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 Hn={};function tg(t){for(const e in t)Hn[e]=t[e],Bs(e)&&(Hn[e].isCSSVariable=!0)}function $l(t,{layout:e,layoutId:n}){return ln.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Hn[t]||t==="opacity")}const ng={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ig=an.length;function sg(t,e,n){let i="",s=!0;for(let o=0;o<ig;o++){const r=an[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Sl(a,fr[r]);if(!l){s=!1;const d=ng[r]||r;i+=`${d}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function br(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(ln.has(l)){r=!0;continue}else if(Bs(l)){s[l]=c;continue}else{const d=Sl(c,fr[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(e.transform||(r||n?i.transform=sg(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;i.transformOrigin=`${l} ${c} ${d}`}}const wr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Hl(t,e,n){for(const i in e)!Pe(e[i])&&!$l(i,n)&&(t[i]=e[i])}function rg({transformTemplate:t},e){return ze(()=>{const n=wr();return br(n,e,t),Object.assign({},n.vars,n.style)},[e])}function og(t,e){const n=t.style||{},i={};return Hl(i,n,t),Object.assign(i,rg(t,e)),i}function ag(t,e){const n={},i=og(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 lg={offset:"stroke-dashoffset",array:"stroke-dasharray"},cg={offset:"strokeDashoffset",array:"strokeDasharray"};function dg(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?lg:cg;t[o.offset]=z.transform(-i);const r=z.transform(e),a=z.transform(n);t[o.array]=`${r} ${a}`}function Gl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(br(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:f}=t;u.transform&&(f.transform=u.transform,delete u.transform),(f.transform||u.transformOrigin)&&(f.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),f.transform&&(f.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&&dg(u,s,o,r,!1)}const Wl=()=>({...wr(),attrs:{}}),zl=t=>typeof t=="string"&&t.toLowerCase()==="svg";function ug(t,e,n,i){const s=ze(()=>{const o=Wl();return Gl(o,e,zl(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Hl(o,t.style,t),s.style={...o,...s.style}}return s}const hg=["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 Sr(t){return typeof t!="string"||t.includes("-")?!1:!!(hg.indexOf(t)>-1||/[A-Z]/u.test(t))}function fg(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(Sr(n)?ug:ag)(i,o,r,n),c=$p(i,typeof n=="string",t),d=n!==rt?{...c,...l,ref:s}:{},{children:u}=i,f=ze(()=>Pe(u)?u.get():u,[u]);return We(n,{...d,children:f})}}function ql(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Cr(t,e,n,i){if(typeof e=="function"){const[s,o]=ql(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]=ql(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function Ni(t){return Pe(t)?t.get():t}function pg({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:gg(n,i,s,t),renderState:e()}}const Kl=t=>(e,n)=>{const i=Te(Mi),s=Te(Ci),o=()=>pg(t,e,i,s);return n?o():Si(o)};function gg(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=Ni(o[f]);let{initial:r,animate:a}=t;const l=Oi(t),c=Fl(t);e&&c&&!l&&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"&&!Di(u)){const f=Array.isArray(u)?u:[u];for(let m=0;m<f.length;m++){const _=Cr(t,f[m]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const C in y){let k=y[C];if(Array.isArray(k)){const T=d?k.length-1:0;k=k[T]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function xr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Pe(i[r])||e.style&&Pe(e.style[r])||$l(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const mg={useVisualState:Kl({scrapeMotionValuesFromProps:xr,createRenderState:wr})};function Xl(t,e,n){const i=xr(t,e,n);for(const s in t)if(Pe(t[s])||Pe(e[s])){const o=an.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const vg={useVisualState:Kl({scrapeMotionValuesFromProps:Xl,createRenderState:Wl})};function yg(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Sr(i)?vg:mg,preloadedFeatures:t,useRender:fg(s),createVisualElement:e,Component:i};return Jp(r)}}function Gn(t,e,n){const i=t.getProps();return Cr(i,e,n!==void 0?n:i.custom,t)}const kr=t=>Array.isArray(t);function _g(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,cn(n))}function bg(t){return kr(t)?t[t.length-1]||0:t}function wg(t,e){const n=Gn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=bg(o[r]);_g(t,r,a)}}function Sg(t){return!!(Pe(t)&&t.add)}function Tr(t,e){const n=t.getValue("willChange");if(Sg(n))return n.add(e);if(!n&&bt.WillChange){const i=new bt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Yl(t){return t.props[Bl]}const Cg=t=>t!==null;function xg(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Cg),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const kg={type:"spring",stiffness:500,damping:25,restSpeed:10},Tg=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Ag={type:"keyframes",duration:.8},Eg={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ig=(t,{keyframes:e})=>e.length>2?Ag:ln.has(t)?t.startsWith("scale")?Tg(e[1]):kg:Eg;function Rg({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Ar=(t,e,n,i={},s,o)=>r=>{const a=ur(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-at(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Rg(a)||Object.assign(d,Ig(t,d)),d.duration&&(d.duration=at(d.duration)),d.repeatDelay&&(d.repeatDelay=at(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)),(bt.instantAnimations||bt.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const f=xg(d.keyframes,a);if(f!==void 0){ue.update(()=>{d.onUpdate(f),d.onComplete()});return}}return a.isSync?new tr(d):new up(d)};function Lg({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function Jl(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const d in a){const u=t.getValue(d,t.latestValues[d]??null),f=a[d];if(f===void 0||c&&Lg(c,d))continue;const m={delay:n,...ur(o||{},d)},_=u.get();if(_!==void 0&&!u.isAnimating&&!Array.isArray(f)&&f===_&&!m.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Yl(t);if(y){const C=window.MotionHandoffAnimation(y,d,ue);C!==null&&(m.startTime=C,v=!0)}}Tr(t,d),u.start(Ar(d,u,f,t.shouldReduceMotion&&gl.has(d)?{type:!1}:m,t,v));const w=u.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{ue.update(()=>{r&&wg(t,r)})}),l}function Er(t,e,n={}){var l;const i=Gn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(Jl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:f}=s;return Pg(t,e,c,d,u,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,d]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>d())}else return Promise.all([o(),r(n.delay)])}function Pg(t,e,n=0,i=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,d=typeof i=="function",u=d?f=>i(f,l):o===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(Mg).forEach((f,m)=>{f.notify("AnimationStart",e),a.push(Er(f,e,{...r,delay:n+(d?0:i)+u(m)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function Mg(t,e){return t.sortNodePosition(e)}function Dg(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>Er(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=Er(t,e,n);else{const s=typeof e=="function"?Gn(t,e,n.custom):e;i=Promise.all(Jl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Zl(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 Og=yr.length;function Ql(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Ql(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Og;n++){const i=yr[n],s=t.props[i];($n(s)||s===!1)&&(e[i]=s)}return e}const Ng=[...vr].reverse(),Fg=vr.length;function Vg(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Dg(t,n,i)))}function Bg(t){let e=Vg(t),n=ec(),i=!0;const s=l=>(c,d)=>{var f;const u=Gn(t,d,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(u){const{transition:m,transitionEnd:_,...v}=u;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,d=Ql(t.parent)||{},u=[],f=new Set;let m={},_=1/0;for(let w=0;w<Fg;w++){const y=Ng[w],C=n[y],k=c[y]!==void 0?c[y]:d[y],T=$n(k),E=y===l?C.isActive:null;E===!1&&(_=w);let D=k===d[y]&&k!==c[y]&&T;if(D&&i&&t.manuallyAnimateOnMount&&(D=!1),C.protectedKeys={...m},!C.isActive&&E===null||!k&&!C.prevProp||Di(k)||typeof k=="boolean")continue;const S=jg(C.prevProp,k);let x=S||y===l&&C.isActive&&!D&&T||w>_&&T,p=!1;const g=Array.isArray(k)?k:[k];let h=g.reduce(s(y),{});E===!1&&(h={});const{prevResolvedValues:b={}}=C,I={...b,...h},P=M=>{x=!0,f.has(M)&&(p=!0,f.delete(M)),C.needsAnimating[M]=!0;const N=t.getValue(M);N&&(N.liveStyle=!1)};for(const M in I){const N=h[M],W=b[M];if(m.hasOwnProperty(M))continue;let j=!1;kr(N)&&kr(W)?j=!Zl(N,W):j=N!==W,j?N!=null?P(M):f.add(M):N!==void 0&&f.has(M)?P(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=h,C.isActive&&(m={...m,...h}),i&&t.blockInitialAnimation&&(x=!1),x&&(!(D&&S)||p)&&u.push(...g.map(M=>({animation:M,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=Gn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const C=t.getBaseTarget(y),k=t.getValue(y);k&&(k.liveStyle=!0),w[y]=C??null}),u.push({animation:w})}let v=!!u.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),i=!1,v?e(u):Promise.resolve()}function a(l,c){var u;if(n[l].isActive===c)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(f=>{var m;return(m=f.animationState)==null?void 0:m.setActive(l,c)}),n[l].isActive=c;const d=r(l);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=ec(),i=!0}}}function jg(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Zl(e,t):!1}function Wt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ec(){return{animate:Wt(!0),whileInView:Wt(),whileHover:Wt(),whileTap:Wt(),whileDrag:Wt(),whileFocus:Wt(),exit:Wt()}}class Rt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Ug extends Rt{constructor(e){super(e),e.animationState||(e.animationState=Bg(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Di(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 $g=0;class Hg extends Rt{constructor(){super(...arguments),this.id=$g++}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 Gg={animation:{Feature:Ug},exit:{Feature:Hg}};function Wn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function zn(t){return{point:{x:t.pageX,y:t.pageY}}}const Wg=t=>e=>gr(e)&&t(e,zn(e));function qn(t,e,n,i){return Wn(t,e,Wg(n),i)}function tc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function zg({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function qg(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 nc=1e-4,Kg=1-nc,Xg=1+nc,ic=.01,Yg=0-ic,Jg=0+ic;function Oe(t){return t.max-t.min}function Zg(t,e,n){return Math.abs(t-e)<=n}function sc(t,e,n,i=.5){t.origin=i,t.originPoint=ve(e.min,e.max,t.origin),t.scale=Oe(n)/Oe(e),t.translate=ve(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Kg&&t.scale<=Xg||isNaN(t.scale))&&(t.scale=1),(t.translate>=Yg&&t.translate<=Jg||isNaN(t.translate))&&(t.translate=0)}function Kn(t,e,n,i){sc(t.x,e.x,n.x,i?i.originX:void 0),sc(t.y,e.y,n.y,i?i.originY:void 0)}function rc(t,e,n){t.min=n.min+e.min,t.max=t.min+Oe(e)}function Qg(t,e,n){rc(t.x,e.x,n.x),rc(t.y,e.y,n.y)}function oc(t,e,n){t.min=e.min-n.min,t.max=t.min+Oe(e)}function Xn(t,e,n){oc(t.x,e.x,n.x),oc(t.y,e.y,n.y)}const ac=()=>({translate:0,scale:1,origin:0,originPoint:0}),hn=()=>({x:ac(),y:ac()}),lc=()=>({min:0,max:0}),be=()=>({x:lc(),y:lc()});function Ke(t){return[t("x"),t("y")]}function Ir(t){return t===void 0||t===1}function Rr({scale:t,scaleX:e,scaleY:n}){return!Ir(t)||!Ir(e)||!Ir(n)}function zt(t){return Rr(t)||cc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function cc(t){return dc(t.x)||dc(t.y)}function dc(t){return t&&t!=="0%"}function Fi(t,e,n){const i=t-n,s=e*i;return n+s}function uc(t,e,n,i,s){return s!==void 0&&(t=Fi(t,s,i)),Fi(t,n,i)+e}function Lr(t,e=0,n=1,i,s){t.min=uc(t.min,e,n,i,s),t.max=uc(t.max,e,n,i,s)}function hc(t,{x:e,y:n}){Lr(t.x,e.translate,e.scale,e.originPoint),Lr(t.y,n.translate,n.scale,n.originPoint)}const fc=.999999999999,pc=1.0000000000001;function em(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:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&pn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,hc(t,r)),i&&zt(o.latestValues)&&pn(t,o.latestValues))}e.x<pc&&e.x>fc&&(e.x=1),e.y<pc&&e.y>fc&&(e.y=1)}function fn(t,e){t.min=t.min+e,t.max=t.max+e}function gc(t,e,n,i,s=.5){const o=ve(t.min,t.max,s);Lr(t,e,n,o,i)}function pn(t,e){gc(t.x,e.x,e.scaleX,e.scale,e.originX),gc(t.y,e.y,e.scaleY,e.scale,e.originY)}function mc(t,e){return tc(qg(t.getBoundingClientRect(),e))}function tm(t,e,n){const i=mc(t,n),{scroll:s}=e;return s&&(fn(i.x,s.offset.x),fn(i.y,s.offset.y)),i}const vc=({current:t})=>t?t.ownerDocument.defaultView:null,yc=(t,e)=>Math.abs(t-e);function nm(t,e){const n=yc(t.x,e.x),i=yc(t.y,e.y);return Math.sqrt(n**2+i**2)}class _c{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 f=Mr(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,_=nm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!_)return;const{point:v}=f,{timestamp:w}=Ee;this.history.push({...v,timestamp:w});const{onStart:y,onMove:C}=this.handlers;m||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Pr(m,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Mr(f.type==="pointercancel"?this.lastMoveEventInfo:Pr(m,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,y),v&&v(f,y)},!gr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=zn(e),l=Pr(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Ee;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Mr(l,this.history)),this.removeListeners=Pn(qn(this.contextWindow,"pointermove",this.handlePointerMove),qn(this.contextWindow,"pointerup",this.handlePointerUp),qn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),At(this.updatePoint)}}function Pr(t,e){return e?{point:e(t.point)}:t}function bc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Mr({point:t},e){return{point:t,delta:bc(t,wc(e)),offset:bc(t,im(e)),velocity:sm(e,.1)}}function im(t){return t[0]}function wc(t){return t[t.length-1]}function sm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=wc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>at(e)));)n--;if(!i)return{x:0,y:0};const o=lt(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 rm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ve(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ve(n,t,i.max):Math.min(t,n)),t}function Sc(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 om(t,{top:e,left:n,bottom:i,right:s}){return{x:Sc(t.x,n,s),y:Sc(t.y,e,i)}}function Cc(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 am(t,e){return{x:Cc(t.x,e.x),y:Cc(t.y,e.y)}}function lm(t,e){let n=.5;const i=Oe(t),s=Oe(e);return s>i?n=Mn(e.min,e.max-i,t.min):i>s&&(n=Mn(t.min,t.max-s,e.min)),_t(0,1,n)}function cm(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 Dr=.35;function dm(t=Dr){return t===!1?t=0:t===!0&&(t=Dr),{x:xc(t,"left","right"),y:xc(t,"top","bottom")}}function xc(t,e,n){return{min:kc(t,e),max:kc(t,n)}}function kc(t,e){return typeof t=="number"?t:t[e]||0}const um=new WeakMap;class hm{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=be(),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:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(zn(u).point)},r=(u,f)=>{const{drag:m,dragPropagation:_,onDragStart:v}=this.getProps();if(m&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Tp(m),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ke(y=>{let C=this.getAxisMotionValue(y).get()||0;if(ct.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const T=k.layout.layoutBox[y];T&&(C=Oe(T)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&ue.postRender(()=>v(u,f)),Tr(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f;const{dragPropagation:m,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:y}=f;if(_&&this.currentDirection===null){this.currentDirection=fm(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(u,f)},l=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f,this.stop(u,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ke(u=>{var f;return this.getAnimationState(u)==="paused"&&((f=this.getAxisMotionValue(u).animation)==null?void 0:f.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _c(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:i,contextWindow:vc(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&&ue.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||!Vi(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=rm(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&&un(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=om(i.layoutBox,e):this.constraints=!1,this.elastic=dm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Ke(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=cm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!un(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=tm(i,s.root,this.visualElement.getTransformPagePoint());let r=am(s.layout.layoutBox,o);if(n){const a=n(zg(r));this.hasMutatedConstraints=!!a,a&&(r=tc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ke(d=>{if(!Vi(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const f=s?200:1e6,m=s?40:1e7,_={type:"inertia",velocity:i?e[d]:0,bounceStiffness:f,bounceDamping:m,timeConstant:750,restDelta:1,restSpeed:10,...o,...u};return this.startAxisValueAnimation(d,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Tr(this.visualElement,e),i.start(Ar(e,i,0,n,this.visualElement,!1))}stopAnimation(){Ke(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Ke(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){Ke(n=>{const{drag:i}=this.getProps();if(!Vi(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]-ve(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!un(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Ke(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=lm({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Ke(r=>{if(!Vi(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ve(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;um.set(this.visualElement,this);const e=this.visualElement.current,n=qn(e,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();un(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ue.read(i);const r=Wn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ke(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=l[d].translate,u.set(u.get()+l[d].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Dr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Vi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function fm(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class pm extends Rt{constructor(e){super(e),this.removeGroupControls=qe,this.removeListeners=qe,this.controls=new hm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Tc=t=>(e,n)=>{t&&ue.postRender(()=>t(e,n))};class gm extends Rt{constructor(){super(...arguments),this.removePointerDownListener=qe}onPointerDown(e){this.session=new _c(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:vc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Tc(e),onStart:Tc(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&ue.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=qn(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 Bi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ac(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Yn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ac(t,e.target.x),i=Ac(t,e.target.y);return`${n}% ${i}%`}},mm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=It.parse(t);if(s.length>5)return i;const o=It.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=ve(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Ec=!1;class vm extends et{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;tg(ym),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Ec&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Bi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Ec=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||ue.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),pr.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 Ic(t){const[e,n]=Ll(),i=Te(Is);return R(vm,{...t,layoutGroup:i,switchLayoutGroup:Te(jl),isPresent:e,safeToRemove:n})}const ym={borderRadius:{...Yn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Yn,borderTopRightRadius:Yn,borderBottomLeftRadius:Yn,borderBottomRightRadius:Yn,boxShadow:mm};function _m(t,e,n){const i=Pe(t)?t:cn(t);return i.start(Ar("",i,e,n)),i.animation}const bm=(t,e)=>t.depth-e.depth;class wm{constructor(){this.children=[],this.isDirty=!1}add(e){Ls(this.children,e),this.isDirty=!0}remove(e){Ps(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(bm),this.isDirty=!1,this.children.forEach(e)}}function Sm(t,e){const n=Be.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(At(i),t(o-e))};return ue.setup(i,!0),()=>At(i)}const Rc=["TopLeft","TopRight","BottomLeft","BottomRight"],Cm=Rc.length,Lc=t=>typeof t=="string"?parseFloat(t):t,Pc=t=>typeof t=="number"||z.test(t);function xm(t,e,n,i,s,o){s?(t.opacity=ve(0,n.opacity??1,km(i)),t.opacityExit=ve(e.opacity??1,0,Tm(i))):o&&(t.opacity=ve(e.opacity??1,n.opacity??1,i));for(let r=0;r<Cm;r++){const a=`border${Rc[r]}Radius`;let l=Mc(e,a),c=Mc(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Pc(l)===Pc(c)?(t[a]=Math.max(ve(Lc(l),Lc(c),i),0),(ct.test(c)||ct.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ve(e.rotate||0,n.rotate||0,i))}function Mc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const km=Dc(0,.5,Pa),Tm=Dc(.5,.95,qe);function Dc(t,e,n){return i=>i<t?0:i>e?1:n(Mn(t,e,i))}function Oc(t,e){t.min=e.min,t.max=e.max}function Xe(t,e){Oc(t.x,e.x),Oc(t.y,e.y)}function Nc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Fc(t,e,n,i,s){return t-=e,t=Fi(t,1/n,i),s!==void 0&&(t=Fi(t,1/s,i)),t}function Am(t,e=0,n=1,i=.5,s,o=t,r=t){if(ct.test(e)&&(e=parseFloat(e),e=ve(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ve(o.min,o.max,i);t===o&&(a-=e),t.min=Fc(t.min,e,n,a,s),t.max=Fc(t.max,e,n,a,s)}function Vc(t,e,[n,i,s],o,r){Am(t,e[n],e[i],e[s],e.scale,o,r)}const Em=["x","scaleX","originX"],Im=["y","scaleY","originY"];function Bc(t,e,n,i){Vc(t.x,e,Em,n?n.x:void 0,i?i.x:void 0),Vc(t.y,e,Im,n?n.y:void 0,i?i.y:void 0)}function jc(t){return t.translate===0&&t.scale===1}function Uc(t){return jc(t.x)&&jc(t.y)}function $c(t,e){return t.min===e.min&&t.max===e.max}function Rm(t,e){return $c(t.x,e.x)&&$c(t.y,e.y)}function Hc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Gc(t,e){return Hc(t.x,e.x)&&Hc(t.y,e.y)}function Wc(t){return Oe(t.x)/Oe(t.y)}function zc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Lm{constructor(){this.members=[]}add(e){Ls(this.members,e),e.scheduleRender()}remove(e){if(Ps(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 Pm(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:c,rotate:d,rotateX:u,rotateY:f,skewX:m,skewY:_}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),f&&(i+=`rotateY(${f}deg) `),m&&(i+=`skewX(${m}deg) `),_&&(i+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Or=["","X","Y","Z"],Mm=1e3;let Dm=0;function Nr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function qc(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Yl(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&qc(i)}function Kc({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Dm++,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(Fm),this.nodes.forEach(Um),this.nodes.forEach($m),this.nodes.forEach(Vm)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new wm)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Os),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=Rl(r)&&!Pp(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let d,u=0;const f=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{u=window.innerWidth}),t(r,()=>{const m=window.innerWidth;m!==u&&(u=m,this.root.updateBlockedByResize=!0,d&&d(),d=Sm(f,250),Bi.hasAnimatedSinceResize&&(Bi.hasAnimatedSinceResize=!1,this.nodes.forEach(Jc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:f,layout:m})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||qm,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Gc(this.targetLayout,m),C=!u&&f;if(this.options.layoutRoot||this.resumeFrom||C||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...ur(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,C)}else u||Jc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=m})}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(),At(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(Hm),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&&qc(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const u=this.path[d];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Xc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Yc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(jm),this.nodes.forEach(Om),this.nodes.forEach(Nm)):this.nodes.forEach(Yc),this.clearAllSnapshots();const a=Be.now();Ee.delta=_t(0,1e3/60,a-Ee.timestamp),Ee.timestamp=a,Ee.isProcessing=!0,Vs.update.process(Ee),Vs.preRender.process(Ee),Vs.render.process(Ee),Ee.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,pr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Bm),this.sharedNodes.forEach(Gm)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Oe(this.snapshot.measuredBox.x)&&!Oe(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=be(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Uc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||zt(this.latestValues)||d)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),Km(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return be();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Xm))){const{scroll:d}=this.root;d&&(fn(a.x,d.offset.x),fn(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=be();if(Xe(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const d=this.path[c],{scroll:u,options:f}=d;d!==this.root&&u&&f.layoutScroll&&(u.wasRoot&&Xe(a,r),fn(a.x,u.offset.x),fn(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=be();Xe(l,r);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&pn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),zt(d.latestValues)&&pn(l,d.latestValues)}return zt(this.latestValues)&&pn(l,this.latestValues),l}removeTransform(r){const a=be();Xe(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!zt(c.latestValues))continue;Rr(c.latestValues)&&c.updateSnapshot();const d=be(),u=c.measurePageBox();Xe(d,u),Bc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return zt(this.latestValues)&&Bc(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 f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.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 m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=be(),this.targetWithTransforms=be()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Qg(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Xe(this.target,this.layout.layoutBox),hc(this.target,this.targetDelta)):Xe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.target,m.target),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Rr(this.parent.latestValues)||cc(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 l=!0;if((this.isProjectionDirty||(_=this.parent)!=null&&_.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Ee.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;Xe(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,f=this.treeScale.y;em(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=be());const{target:m}=r;if(!m){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Nc(this.prevProjectionDelta.x,this.projectionDelta.x),Nc(this.prevProjectionDelta.y,this.projectionDelta.y)),Kn(this.projectionDelta,this.layoutCorrected,m,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==f||!zc(this.projectionDelta.x,this.prevProjectionDelta.x)||!zc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",m))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=hn(),this.projectionDelta=hn(),this.projectionDeltaWithTransform=hn()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=hn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=be(),m=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=m!==_,w=this.getStack(),y=!w||w.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(zm));this.animationProgress=0;let k;this.mixTargetDelta=T=>{const E=T/1e3;Zc(u.x,r.x,E),Zc(u.y,r.y,E),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Wm(this.relativeTarget,this.relativeTargetOrigin,f,E),k&&Rm(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=be()),Xe(k,this.relativeTarget)),v&&(this.animationValues=d,xm(d,c,this.latestValues,E,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(At(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{Bi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=cn(0)),this.currentAnimation=_m(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(Mm),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&id(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||be();const u=Oe(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const f=Oe(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Xe(a,l),pn(a,d),Kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Lm),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Nr("z",r,c,this.animationValues);for(let d=0;d<Or.length;d++)Nr(`rotate${Or[d]}`,r,c,this.animationValues),Nr(`skew${Or[d]}`,r,c,this.animationValues);r.render();for(const d in c)r.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Ni(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Ni(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=Pm(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:f,y:m}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${m.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const _ in Hn){if(d[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=Hn[_],C=u==="none"?d[_]:v(d[_],c);if(w){const k=w.length;for(let T=0;T<k;T++)r[w[T]]=C}else y?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Ni(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(Xc),this.root.sharedNodes.clear()}}}function Om(t){t.updateLayout()}function Nm(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"?Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(f);f.min=i[u].min,f.max=f.min+m}):id(o,e.layoutBox,i)&&Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(i[u]);f.max=f.min+m,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+m)});const a=hn();Kn(a,i,e.layoutBox);const l=hn();r?Kn(l,t.applyTransform(s,!0),e.measuredBox):Kn(l,i,e.layoutBox);const c=!Uc(a);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:f,layout:m}=u;if(f&&m){const _=be();Xn(_,e.layoutBox,f.layoutBox);const v=be();Xn(v,i,m.layoutBox),Gc(_,v)||(d=!0),u.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:d})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function Fm(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 Vm(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Bm(t){t.clearSnapshot()}function Xc(t){t.clearMeasurements()}function Yc(t){t.isLayoutDirty=!1}function jm(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Jc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Um(t){t.resolveTargetDelta()}function $m(t){t.calcProjection()}function Hm(t){t.resetSkewAndRotation()}function Gm(t){t.removeLeadSnapshot()}function Zc(t,e,n){t.translate=ve(e.translate,0,n),t.scale=ve(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Qc(t,e,n,i){t.min=ve(e.min,n.min,i),t.max=ve(e.max,n.max,i)}function Wm(t,e,n,i){Qc(t.x,e.x,n.x,i),Qc(t.y,e.y,n.y,i)}function zm(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const qm={duration:.45,ease:[.4,0,.1,1]},ed=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),td=ed("applewebkit/")&&!ed("chrome/")?Math.round:qe;function nd(t){t.min=td(t.min),t.max=td(t.max)}function Km(t){nd(t.x),nd(t.y)}function id(t,e,n){return t==="position"||t==="preserve-aspect"&&!Zg(Wc(e),Wc(n),.2)}function Xm(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Ym=Kc({attachResizeListener:(t,e)=>Wn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Fr={current:void 0},sd=Kc({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Fr.current){const t=new Ym({});t.mount(window),t.setOptions({layoutScroll:!0}),Fr.current=t}return Fr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Jm={pan:{Feature:gm},drag:{Feature:pm,ProjectionNode:sd,MeasureLayout:Ic}};function rd(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&&ue.postRender(()=>o(e,zn(e)))}class Zm extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Ap(e,(n,i)=>(rd(this.node,i,"Start"),s=>rd(this.node,s,"End"))))}unmount(){}}class Qm extends Rt{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=Pn(Wn(this.node.current,"focus",()=>this.onFocus()),Wn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function od(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&&ue.postRender(()=>o(e,zn(e)))}class ev extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Lp(e,(n,i)=>(od(this.node,i,"Start"),(s,{success:o})=>od(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Vr=new WeakMap,Br=new WeakMap,tv=t=>{const e=Vr.get(t.target);e&&e(t)},nv=t=>{t.forEach(tv)};function iv({root:t,...e}){const n=t||document;Br.has(n)||Br.set(n,{});const i=Br.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(nv,{root:t,...e})),i[s]}function sv(t,e,n){const i=iv(e);return Vr.set(t,n),i.observe(t),()=>{Vr.delete(t),i.unobserve(t)}}const rv={some:0,all:1};class ov extends Rt{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:rv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),f=c?d:u;f&&f(l)};return sv(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(av(e,n))&&this.startObserver()}unmount(){}}function av({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const lv={inView:{Feature:ov},tap:{Feature:ev},focus:{Feature:Qm},hover:{Feature:Zm}},cv={layout:{ProjectionNode:sd,MeasureLayout:Ic}},jr={current:null},ad={current:!1};function dv(){if(ad.current=!0,!!Rs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>jr.current=t.matches;t.addEventListener("change",e),e()}else jr.current=!1}const uv=new WeakMap;function hv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Pe(s))t.addValue(i,s);else if(Pe(o))t.addValue(i,cn(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,cn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const ld=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class fv{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=cr,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 f=Be.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ue.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=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=Oi(n),this.isVariantNode=Fl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in u){const m=u[f];l[f]!==void 0&&Pe(m)&&m.set(l[f],!1)}}mount(e){this.current=e,uv.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)),ad.current||dv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:jr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),At(this.notifyUpdate),At(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=ln.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ue.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 dn){const n=dn[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):be()}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<ld.length;i++){const s=ld[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=hv(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=cn(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"&&(Sa(i)||xa(i))?i=parseFloat(i):!Dp(i)&&It.test(n)&&(i=wl(e,n)),this.setBaseTarget(e,Pe(i)?i.get():i)),Pe(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=Cr(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&&!Pe(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 Os),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class cd extends fv{constructor(){super(...arguments),this.KeyframeResolver=Sp}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;Pe(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function dd(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 pv(t){return window.getComputedStyle(t)}class gv extends cd{constructor(){super(...arguments),this.type="html",this.renderInstance=dd}readValueFromInstance(e,n){var i;if(ln.has(n))return(i=this.projection)!=null&&i.isProjecting?sr(n):$f(e,n);{const s=pv(e),o=(Bs(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return mc(e,n)}build(e,n,i){br(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return xr(e,n,i)}}const ud=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 mv(t,e,n,i){dd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(ud.has(s)?s:_r(s),e.attrs[s])}class vv extends cd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=be}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(ln.has(n)){const i=bl(n);return i&&i.default||0}return n=ud.has(n)?n:_r(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Xl(e,n,i)}build(e,n,i){Gl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){mv(e,n,i,s)}mount(e){this.isSVGTag=zl(e.tagName),super.mount(e)}}const yv=(t,e)=>Sr(t)?new vv(e):new gv(e,{allowProjection:t!==rt}),_v=yg({...Gg,...lv,...Jm,...cv},yv),gn=Gp(_v),bv=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region"],Jn="widget-layout-id";function hd(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=hd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function wt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=hd(t))&&(i&&(i+=" "),i+=e);return i}const wv=_i("listening"),Ur=()=>ba(wv);function Sv(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 ji={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},fd=_i(ji),Cv=()=>{const t=wi(fd);return yt(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=ji.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=ji.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=ji.speak_to_interrupt_text),n}),[t])},qt=()=>Es(fd),pd=({size:t="large",className:e})=>{const n=qt(),[i]=Ur();return R("h1",{className:wt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},gd=({stream:t,chatMode:e})=>{const n=me(null);return ke(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:R("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
|
|
9
|
+
`),()=>{_.removeChild(v),_.contains(v)&&_.removeChild(v)}},[e]),R(Kp,{isPresent:e,childRef:r,sizeRef:o,children:Kh(t,{ref:r})})}const Yp=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:r,mode:o,anchorX:a,root:l})=>{const c=Ii(Jp),u=Ts();let d=!0,f=Xe(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:g=>{c.set(g,!0);for(const v of c.values())if(!v)return;i&&i()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[n,c,i]);return r&&d&&(f={...f}),Xe(()=>{c.forEach((g,v)=>c.set(v,!1))},[n]),Ee(()=>{!n&&!c.size&&i&&i()},[n]),o==="popLayout"&&(t=R(Xp,{isPresent:n,anchorX:a,root:l,children:t})),R(Ai.Provider,{value:f,children:t})};function Jp(){return new Map}function Vl(t=!0){const e=Ie(Ai);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,r=Ts();Ee(()=>{if(t)return s(r)},[t]);const o=Ge(()=>t&&i&&i(r),[r,i,t]);return!n&&i?[!1,o]:[!0]}const Fi=t=>t.key||"";function Bl(t){const e=[];return Fh.forEach(t,n=>{Ca(n)&&e.push(n)}),e}const Zp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:r="sync",propagate:o=!1,anchorX:a="left",root:l})=>{const[c,u]=Vl(o),d=Xe(()=>Bl(t),[t]),f=o&&!c?[]:d.map(Fi),g=de(!0),v=de(d),_=Ii(()=>new Map),[w,y]=xe(d),[T,x]=xe(d);Ia(()=>{g.current=!1,v.current=d;for(let M=0;M<T.length;M++){const S=Fi(T[M]);f.includes(S)?_.delete(S):_.get(S)!==!0&&_.set(S,!1)}},[T,f.length,f.join("-")]);const I=[];if(d!==w){let M=[...d];for(let S=0;S<T.length;S++){const C=T[S],p=Fi(C);f.includes(p)||(M.splice(S,0,C),I.push(C))}return r==="wait"&&I.length&&(M=I),x(Bl(M)),y(d),null}const{forceRender:A}=Ie(Os);return R(lt,{children:T.map(M=>{const S=Fi(M),C=o&&!c?!1:d===T||f.includes(S),p=()=>{if(_.has(S))_.set(S,!0);else return;let m=!0;_.forEach(h=>{h||(m=!1)}),m&&(A==null||A(),x(v.current),o&&(u==null||u()),i&&i())};return R(Yp,{isPresent:C,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:r,root:l,onExitComplete:C?void 0:p,anchorX:a,children:M},S)})})},Ul=bt({strict:!1}),jl={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"]},hn={};for(const t in jl)hn[t]={isEnabled:e=>jl[t].some(n=>!!e[n])};function Qp(t){for(const e in t)hn[e]={...hn[e],...t[e]}}const em=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 Vi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||em.has(t)}let $l=t=>!Vi(t);function Hl(t){typeof t=="function"&&($l=e=>e.startsWith("on")?!Vi(e):t(e))}try{Hl(require("@emotion/is-prop-valid").default)}catch{}function tm(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||($l(s)||n===!0&&Vi(s)||!e&&!Vi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function nm({children:t,isValidProp:e,...n}){e&&Hl(e),n={...Ie(Hn),...n},n.isStatic=Ii(()=>n.isStatic);const i=Xe(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return R(Hn.Provider,{value:i,children:t})}function im(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 Bi=bt({});function Ui(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Wn(t){return typeof t=="string"||Array.isArray(t)}const ko=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],xo=["initial",...ko];function ji(t){return Ui(t.animate)||xo.some(e=>Wn(t[e]))}function Wl(t){return!!(ji(t)||t.variants)}function sm(t,e){if(ji(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Wn(n)?n:void 0,animate:Wn(i)?i:void 0}}return t.inherit!==!1?e:{}}function om(t){const{initial:e,animate:n}=sm(t,Ie(Bi));return Xe(()=>({initial:e,animate:n}),[Gl(e),Gl(n)])}function Gl(t){return Array.isArray(t)?t.join(" "):t}const rm=Symbol.for("motionComponentSymbol");function fn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function am(t,e,n){return Ge(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):fn(n)&&(n.current=i))},[e])}const Eo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),zl="data-"+Eo("framerAppearId"),ql=bt({});function lm(t,e,n,i,s){var _,w;const{visualElement:r}=Ie(Bi),o=Ie(Ul),a=Ie(Ai),l=Ie(Hn).reducedMotion,c=de(null);i=i||o.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:r,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Ie(ql);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&cm(c.current,n,s,d);const f=de(!1);ca(()=>{u&&f.current&&u.update(n,a)});const g=n[zl],v=de(!!g&&!((_=window.MotionHandoffIsComplete)!=null&&_.call(window,g))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,g)));return Ia(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),So.render(u.render),v.current&&u.animationState&&u.animationState.animateChanges())}),Ee(()=>{u&&(!v.current&&u.animationState&&u.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),v.current=!1))}),u}function cm(t,e,n,i){const{layoutId:s,layout:r,drag:o,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Kl(t.parent)),t.projection.setOptions({layoutId:s,layout:r,alwaysMeasureLayout:!!o||a&&fn(a),visualElement:t,animationType:typeof r=="string"?r:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:c})}function Kl(t){if(t)return t.options.allowProjection!==!1?t.projection:Kl(t.parent)}function dm({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&Qp(t);function r(a,l){let c;const u={...Ie(Hn),...a,layoutId:um(a)},{isStatic:d}=u,f=om(a),g=i(a,d);if(!d&&Fs){hm();const v=fm(u);c=v.MeasureLayout,f.visualElement=lm(s,g,u,e,v.ProjectionNode)}return R(Bi.Provider,{value:f,children:[c&&f.visualElement?R(c,{visualElement:f.visualElement,...u}):null,n(s,a,am(g,f.visualElement,l),g,d,f.visualElement)]})}r.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const o=Oh(r);return o[rm]=s,o}function um({layoutId:t}){const e=Ie(Os).id;return e&&t!==void 0?e+"-"+t:t}function hm(t,e){Ie(Ul).strict}function fm(t){const{drag:e,layout:n}=hn;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 Gn={};function pm(t){for(const e in t)Gn[e]=t[e],zs(e)&&(Gn[e].isCSSVariable=!0)}function Xl(t,{layout:e,layoutId:n}){return dn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Gn[t]||t==="opacity")}const mm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},gm=cn.length;function vm(t,e,n){let i="",s=!0;for(let r=0;r<gm;r++){const o=cn[r],a=t[o];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(o.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Al(a,wo[o]);if(!l){s=!1;const u=mm[o]||o;i+=`${u}(${c}) `}n&&(e[o]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function Io(t,e,n){const{style:i,vars:s,transformOrigin:r}=t;let o=!1,a=!1;for(const l in e){const c=e[l];if(dn.has(l)){o=!0;continue}else if(zs(l)){s[l]=c;continue}else{const u=Al(c,wo[l]);l.startsWith("origin")?(a=!0,r[l]=u):i[l]=u}}if(e.transform||(o||n?i.transform=vm(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=r;i.transformOrigin=`${l} ${c} ${u}`}}const Ao=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Yl(t,e,n){for(const i in e)!Ne(e[i])&&!Xl(i,n)&&(t[i]=e[i])}function ym({transformTemplate:t},e){return Xe(()=>{const n=Ao();return Io(n,e,t),Object.assign({},n.vars,n.style)},[e])}function _m(t,e){const n=t.style||{},i={};return Yl(i,n,t),Object.assign(i,ym(t,e)),i}function bm(t,e){const n={},i=_m(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 wm={offset:"stroke-dashoffset",array:"stroke-dasharray"},Sm={offset:"strokeDashoffset",array:"strokeDasharray"};function Cm(t,e,n=1,i=0,s=!0){t.pathLength=1;const r=s?wm:Sm;t[r.offset]=z.transform(-i);const o=z.transform(e),a=z.transform(n);t[r.array]=`${o} ${a}`}function Jl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:r=1,pathOffset:o=0,...a},l,c,u){if(Io(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:f}=t;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),s!==void 0&&Cm(d,s,r,o,!1)}const Zl=()=>({...Ao(),attrs:{}}),Ql=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Tm(t,e,n,i){const s=Xe(()=>{const r=Zl();return Jl(r,e,Ql(i),t.transformTemplate,t.style),{...r.attrs,style:{...r.style}}},[e]);if(t.style){const r={};Yl(r,t.style,t),s.style={...r,...s.style}}return s}const km=["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 Ro(t){return typeof t!="string"||t.includes("-")?!1:!!(km.indexOf(t)>-1||/[A-Z]/u.test(t))}function xm(t=!1){return(n,i,s,{latestValues:r},o)=>{const l=(Ro(n)?Tm:bm)(i,r,o,n),c=tm(i,typeof n=="string",t),u=n!==lt?{...c,...l,ref:s}:{},{children:d}=i,f=Xe(()=>Ne(d)?d.get():d,[d]);return Ke(n,{...u,children:f})}}function ec(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Lo(t,e,n,i){if(typeof e=="function"){const[s,r]=ec(i);e=e(n!==void 0?n:t.custom,s,r)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,r]=ec(i);e=e(n!==void 0?n:t.custom,s,r)}return e}function $i(t){return Ne(t)?t.get():t}function Em({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Im(n,i,s,t),renderState:e()}}const tc=t=>(e,n)=>{const i=Ie(Bi),s=Ie(Ai),r=()=>Em(t,e,i,s);return n?r():Ii(r)};function Im(t,e,n,i){const s={},r=i(t,{});for(const f in r)s[f]=$i(r[f]);let{initial:o,animate:a}=t;const l=ji(t),c=Wl(t);e&&c&&!l&&t.inherit!==!1&&(o===void 0&&(o=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!Ui(d)){const f=Array.isArray(d)?d:[d];for(let g=0;g<f.length;g++){const v=Lo(t,f[g]);if(v){const{transitionEnd:_,transition:w,...y}=v;for(const T in y){let x=y[T];if(Array.isArray(x)){const I=u?x.length-1:0;x=x[I]}x!==null&&(s[T]=x)}for(const T in _)s[T]=_[T]}}}return s}function Do(t,e,n){var r;const{style:i}=t,s={};for(const o in i)(Ne(i[o])||e.style&&Ne(e.style[o])||Xl(o,t)||((r=n==null?void 0:n.getValue(o))==null?void 0:r.liveStyle)!==void 0)&&(s[o]=i[o]);return s}const Am={useVisualState:tc({scrapeMotionValuesFromProps:Do,createRenderState:Ao})};function nc(t,e,n){const i=Do(t,e,n);for(const s in t)if(Ne(t[s])||Ne(e[s])){const r=cn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[r]=t[s]}return i}const Rm={useVisualState:tc({scrapeMotionValuesFromProps:nc,createRenderState:Zl})};function Lm(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const o={...Ro(i)?Rm:Am,preloadedFeatures:t,useRender:xm(s),createVisualElement:e,Component:i};return dm(o)}}function zn(t,e,n){const i=t.getProps();return Lo(i,e,n!==void 0?n:i.custom,t)}const Po=t=>Array.isArray(t);function Dm(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,un(n))}function Pm(t){return Po(t)?t[t.length-1]||0:t}function Mm(t,e){const n=zn(t,e);let{transitionEnd:i={},transition:s={},...r}=n||{};r={...r,...i};for(const o in r){const a=Pm(r[o]);Dm(t,o,a)}}function Nm(t){return!!(Ne(t)&&t.add)}function Mo(t,e){const n=t.getValue("willChange");if(Nm(n))return n.add(e);if(!n&&St.WillChange){const i=new St.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function ic(t){return t.props[zl]}const Om=t=>t!==null;function Fm(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Om),r=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[r]}const Vm={type:"spring",stiffness:500,damping:25,restSpeed:10},Bm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Um={type:"keyframes",duration:.8},jm={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},$m=(t,{keyframes:e})=>e.length>2?Um:dn.has(t)?t.startsWith("scale")?Bm(e[1]):Vm:jm;function Hm({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:r,repeatType:o,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const No=(t,e,n,i={},s,r)=>o=>{const a=_o(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-dt(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:r?void 0:s};Hm(a)||Object.assign(u,$m(t,u)),u.duration&&(u.duration=dt(u.duration)),u.repeatDelay&&(u.repeatDelay=dt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(St.instantAnimations||St.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!r&&e.get()!==void 0){const f=Fm(u.keyframes,a);if(f!==void 0){me.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new lo(u):new Tp(u)};function Wm({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function sc(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:o,...a}=e;i&&(r=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),f=a[u];if(f===void 0||c&&Wm(c,u))continue;const g={delay:n,..._o(r||{},u)},v=d.get();if(v!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===v&&!g.velocity)continue;let _=!1;if(window.MotionHandoffAnimation){const y=ic(t);if(y){const T=window.MotionHandoffAnimation(y,u,me);T!==null&&(g.startTime=T,_=!0)}}Mo(t,u),d.start(No(u,d,f,t.shouldReduceMotion&&Sl.has(u)?{type:!1}:g,t,_));const w=d.animation;w&&l.push(w)}return o&&Promise.all(l).then(()=>{me.update(()=>{o&&Mm(t,o)})}),l}function Oo(t,e,n={}){var l;const i=zn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const r=i?()=>Promise.all(sc(t,i,n)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=s;return Gm(t,e,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[r,o]:[o,r];return c().then(()=>u())}else return Promise.all([r(),o(n.delay)])}function Gm(t,e,n=0,i=0,s=0,r=1,o){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof i=="function",d=u?f=>i(f,l):r===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(zm).forEach((f,g)=>{f.notify("AnimationStart",e),a.push(Oo(f,e,{...o,delay:n+(u?0:i)+d(g)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function zm(t,e){return t.sortNodePosition(e)}function qm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(r=>Oo(t,r,n));i=Promise.all(s)}else if(typeof e=="string")i=Oo(t,e,n);else{const s=typeof e=="function"?zn(t,e,n.custom):e;i=Promise.all(sc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function oc(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 Km=xo.length;function rc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?rc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Km;n++){const i=xo[n],s=t.props[i];(Wn(s)||s===!1)&&(e[i]=s)}return e}const Xm=[...ko].reverse(),Ym=ko.length;function Jm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>qm(t,n,i)))}function Zm(t){let e=Jm(t),n=ac(),i=!0;const s=l=>(c,u)=>{var f;const d=zn(t,u,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:g,transitionEnd:v,..._}=d;c={...c,..._,...v}}return c};function r(l){e=l(t)}function o(l){const{props:c}=t,u=rc(t.parent)||{},d=[],f=new Set;let g={},v=1/0;for(let w=0;w<Ym;w++){const y=Xm[w],T=n[y],x=c[y]!==void 0?c[y]:u[y],I=Wn(x),A=y===l?T.isActive:null;A===!1&&(v=w);let M=x===u[y]&&x!==c[y]&&I;if(M&&i&&t.manuallyAnimateOnMount&&(M=!1),T.protectedKeys={...g},!T.isActive&&A===null||!x&&!T.prevProp||Ui(x)||typeof x=="boolean")continue;const S=Qm(T.prevProp,x);let C=S||y===l&&T.isActive&&!M&&I||w>v&&I,p=!1;const m=Array.isArray(x)?x:[x];let h=m.reduce(s(y),{});A===!1&&(h={});const{prevResolvedValues:b={}}=T,E={...b,...h},D=P=>{C=!0,f.has(P)&&(p=!0,f.delete(P)),T.needsAnimating[P]=!0;const B=t.getValue(P);B&&(B.liveStyle=!1)};for(const P in E){const B=h[P],X=b[P];if(g.hasOwnProperty(P))continue;let j=!1;Po(B)&&Po(X)?j=!oc(B,X):j=B!==X,j?B!=null?D(P):f.add(P):B!==void 0&&f.has(P)?D(P):T.protectedKeys[P]=!0}T.prevProp=x,T.prevResolvedValues=h,T.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(C=!1),C&&(!(M&&S)||p)&&d.push(...m.map(P=>({animation:P,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=zn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const T=t.getBaseTarget(y),x=t.getValue(y);x&&(x.liveStyle=!0),w[y]=T??null}),d.push({animation:w})}let _=!!d.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(_=!1),i=!1,_?e(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(l,c)}),n[l].isActive=c;const u=o(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:r,getState:()=>n,reset:()=>{n=ac(),i=!0}}}function Qm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!oc(e,t):!1}function qt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ac(){return{animate:qt(!0),whileInView:qt(),whileHover:qt(),whileTap:qt(),whileDrag:qt(),whileFocus:qt(),exit:qt()}}class Lt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class eg extends Lt{constructor(e){super(e),e.animationState||(e.animationState=Zm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ui(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 tg=0;class ng extends Lt{constructor(){super(...arguments),this.id=tg++}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 ig={animation:{Feature:eg},exit:{Feature:ng}};function qn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Kn(t){return{point:{x:t.pageX,y:t.pageY}}}const sg=t=>e=>Co(e)&&t(e,Kn(e));function Xn(t,e,n,i){return qn(t,e,sg(n),i)}function lc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function og({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function rg(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 cc=1e-4,ag=1-cc,lg=1+cc,dc=.01,cg=0-dc,dg=0+dc;function Ve(t){return t.max-t.min}function ug(t,e,n){return Math.abs(t-e)<=n}function uc(t,e,n,i=.5){t.origin=i,t.originPoint=_e(e.min,e.max,t.origin),t.scale=Ve(n)/Ve(e),t.translate=_e(n.min,n.max,t.origin)-t.originPoint,(t.scale>=ag&&t.scale<=lg||isNaN(t.scale))&&(t.scale=1),(t.translate>=cg&&t.translate<=dg||isNaN(t.translate))&&(t.translate=0)}function Yn(t,e,n,i){uc(t.x,e.x,n.x,i?i.originX:void 0),uc(t.y,e.y,n.y,i?i.originY:void 0)}function hc(t,e,n){t.min=n.min+e.min,t.max=t.min+Ve(e)}function hg(t,e,n){hc(t.x,e.x,n.x),hc(t.y,e.y,n.y)}function fc(t,e,n){t.min=e.min-n.min,t.max=t.min+Ve(e)}function Jn(t,e,n){fc(t.x,e.x,n.x),fc(t.y,e.y,n.y)}const pc=()=>({translate:0,scale:1,origin:0,originPoint:0}),pn=()=>({x:pc(),y:pc()}),mc=()=>({min:0,max:0}),Se=()=>({x:mc(),y:mc()});function Je(t){return[t("x"),t("y")]}function Fo(t){return t===void 0||t===1}function Vo({scale:t,scaleX:e,scaleY:n}){return!Fo(t)||!Fo(e)||!Fo(n)}function Kt(t){return Vo(t)||gc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function gc(t){return vc(t.x)||vc(t.y)}function vc(t){return t&&t!=="0%"}function Hi(t,e,n){const i=t-n,s=e*i;return n+s}function yc(t,e,n,i,s){return s!==void 0&&(t=Hi(t,s,i)),Hi(t,n,i)+e}function Bo(t,e=0,n=1,i,s){t.min=yc(t.min,e,n,i,s),t.max=yc(t.max,e,n,i,s)}function _c(t,{x:e,y:n}){Bo(t.x,e.translate,e.scale,e.originPoint),Bo(t.y,n.translate,n.scale,n.originPoint)}const bc=.999999999999,wc=1.0000000000001;function fg(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let r,o;for(let a=0;a<s;a++){r=n[a],o=r.projectionDelta;const{visualElement:l}=r.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&r.options.layoutScroll&&r.scroll&&r!==r.root&&gn(t,{x:-r.scroll.offset.x,y:-r.scroll.offset.y}),o&&(e.x*=o.x.scale,e.y*=o.y.scale,_c(t,o)),i&&Kt(r.latestValues)&&gn(t,r.latestValues))}e.x<wc&&e.x>bc&&(e.x=1),e.y<wc&&e.y>bc&&(e.y=1)}function mn(t,e){t.min=t.min+e,t.max=t.max+e}function Sc(t,e,n,i,s=.5){const r=_e(t.min,t.max,s);Bo(t,e,n,r,i)}function gn(t,e){Sc(t.x,e.x,e.scaleX,e.scale,e.originX),Sc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Cc(t,e){return lc(rg(t.getBoundingClientRect(),e))}function pg(t,e,n){const i=Cc(t,n),{scroll:s}=e;return s&&(mn(i.x,s.offset.x),mn(i.y,s.offset.y)),i}const Tc=({current:t})=>t?t.ownerDocument.defaultView:null,kc=(t,e)=>Math.abs(t-e);function mg(t,e){const n=kc(t.x,e.x),i=kc(t.y,e.y);return Math.sqrt(n**2+i**2)}class xc{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:r=!1,distanceThreshold:o=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 f=jo(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=mg(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:_}=f,{timestamp:w}=Le;this.history.push({..._,timestamp:w});const{onStart:y,onMove:T}=this.handlers;g||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Uo(g,this.transformPagePoint),me.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:v,onSessionEnd:_,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=jo(f.type==="pointercancel"?this.lastMoveEventInfo:Uo(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(f,y),_&&_(f,y)},!Co(e))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=s||window;const a=Kn(e),l=Uo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Le;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,jo(l,this.history)),this.removeListeners=Mn(Xn(this.contextWindow,"pointermove",this.handlePointerMove),Xn(this.contextWindow,"pointerup",this.handlePointerUp),Xn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),It(this.updatePoint)}}function Uo(t,e){return e?{point:e(t.point)}:t}function Ec(t,e){return{x:t.x-e.x,y:t.y-e.y}}function jo({point:t},e){return{point:t,delta:Ec(t,Ic(e)),offset:Ec(t,gg(e)),velocity:vg(e,.1)}}function gg(t){return t[0]}function Ic(t){return t[t.length-1]}function vg(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=Ic(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>dt(e)));)n--;if(!i)return{x:0,y:0};const r=ut(s.timestamp-i.timestamp);if(r===0)return{x:0,y:0};const o={x:(s.x-i.x)/r,y:(s.y-i.y)/r};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function yg(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?_e(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?_e(n,t,i.max):Math.min(t,n)),t}function Ac(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 _g(t,{top:e,left:n,bottom:i,right:s}){return{x:Ac(t.x,n,s),y:Ac(t.y,e,i)}}function Rc(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 bg(t,e){return{x:Rc(t.x,e.x),y:Rc(t.y,e.y)}}function wg(t,e){let n=.5;const i=Ve(t),s=Ve(e);return s>i?n=Nn(e.min,e.max-i,t.min):i>s&&(n=Nn(t.min,t.max-s,e.min)),wt(0,1,n)}function Sg(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 $o=.35;function Cg(t=$o){return t===!1?t=0:t===!0&&(t=$o),{x:Lc(t,"left","right"),y:Lc(t,"top","bottom")}}function Lc(t,e,n){return{min:Dc(t,e),max:Dc(t,n)}}function Dc(t,e){return typeof t=="number"?t:t[e]||0}const Tg=new WeakMap;class kg{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=Se(),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 r=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Kn(d).point)},o=(d,f)=>{const{drag:g,dragPropagation:v,onDragStart:_}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Bp(g),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Je(y=>{let T=this.getAxisMotionValue(y).get()||0;if(ht.test(T)){const{projection:x}=this.visualElement;if(x&&x.layout){const I=x.layout.layoutBox[y];I&&(T=Ve(I)*(parseFloat(T)/100))}}this.originPoint[y]=T}),_&&me.postRender(()=>_(d,f)),Mo(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:_,onDrag:w}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(v&&this.currentDirection===null){this.currentDirection=xg(y),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Je(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)==null?void 0:f.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new xc(e,{onSessionStart:r,onStart:o,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:Tc(this.visualElement)})}stop(e,n){const i=e||this.latestPointerEvent,s=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!s||!i)return;const{velocity:o}=s;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&me.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||!Wi(e,s,this.currentDirection))return;const r=this.getAxisMotionValue(e);let o=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(o=yg(o,this.constraints[e],this.elastic[e])),r.set(o)}resolveConstraints(){var r;const{dragConstraints:e,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(r=this.visualElement.projection)==null?void 0:r.layout,s=this.constraints;e&&fn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=_g(i.layoutBox,e):this.constraints=!1,this.elastic=Cg(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Je(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Sg(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!fn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const r=pg(i,s.root,this.visualElement.getTransformPagePoint());let o=bg(s.layout.layoutBox,r);if(n){const a=n(og(o));this.hasMutatedConstraints=!!a,a&&(o=lc(a))}return o}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:r,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Je(u=>{if(!Wi(u,n,this.currentDirection))return;let d=l&&l[u]||{};o&&(d={min:0,max:0});const f=s?200:1e6,g=s?40:1e7,v={type:"inertia",velocity:i?e[u]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...r,...d};return this.startAxisValueAnimation(u,v)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Mo(this.visualElement,e),i.start(No(e,i,0,n,this.visualElement,!1))}stopAnimation(){Je(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Je(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){Je(n=>{const{drag:i}=this.getProps();if(!Wi(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,r=this.getAxisMotionValue(n);if(s&&s.layout){const{min:o,max:a}=s.layout.layoutBox[n];r.set(e[n]-_e(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!fn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Je(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const l=a.get();s[o]=wg({min:l,max:l},this.constraints[o])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Je(o=>{if(!Wi(o,e,null))return;const a=this.getAxisMotionValue(o),{min:l,max:c}=this.constraints[o];a.set(_e(l,c,s[o]))})}addListeners(){if(!this.visualElement.current)return;Tg.set(this.visualElement,this);const e=this.visualElement.current,n=Xn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();fn(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,r=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),me.read(i);const o=qn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Je(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{o(),n(),r(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:r=!1,dragElastic:o=$o,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:r,dragElastic:o,dragMomentum:a}}}function Wi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function xg(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Eg extends Lt{constructor(e){super(e),this.removeGroupControls=Ye,this.removeListeners=Ye,this.controls=new kg(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ye}unmount(){this.removeGroupControls(),this.removeListeners()}}const Pc=t=>(e,n)=>{t&&me.postRender(()=>t(e,n))};class Ig extends Lt{constructor(){super(...arguments),this.removePointerDownListener=Ye}onPointerDown(e){this.session=new xc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Tc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Pc(e),onStart:Pc(n),onMove:i,onEnd:(r,o)=>{delete this.session,s&&me.postRender(()=>s(r,o))}}}mount(){this.removePointerDownListener=Xn(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 Gi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Mc(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Zn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Mc(t,e.target.x),i=Mc(t,e.target.y);return`${n}% ${i}%`}},Ag={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Rt.parse(t);if(s.length>5)return i;const r=Rt.createTransformer(t),o=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+o]/=a,s[1+o]/=l;const c=_e(a,l,.5);return typeof s[2+o]=="number"&&(s[2+o]/=c),typeof s[3+o]=="number"&&(s[3+o]/=c),r(s)}};let Nc=!1;class Rg extends it{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:r}=e;pm(Lg),r&&(n.group&&n.group.add(r),i&&i.register&&s&&i.register(r),Nc&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),Gi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:r}=this.props,{projection:o}=i;return o&&(o.isPresent=r,Nc=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==r?o.willUpdate():this.safeToRemove(),e.isPresent!==r&&(r?o.promote():o.relegate()||me.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),So.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 Oc(t){const[e,n]=Vl(),i=Ie(Os);return R(Rg,{...t,layoutGroup:i,switchLayoutGroup:Ie(ql),isPresent:e,safeToRemove:n})}const Lg={borderRadius:{...Zn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Zn,borderTopRightRadius:Zn,borderBottomLeftRadius:Zn,borderBottomRightRadius:Zn,boxShadow:Ag};function Dg(t,e,n){const i=Ne(t)?t:un(t);return i.start(No("",i,e,n)),i.animation}const Pg=(t,e)=>t.depth-e.depth;class Mg{constructor(){this.children=[],this.isDirty=!1}add(e){Vs(this.children,e),this.isDirty=!0}remove(e){Bs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Pg),this.isDirty=!1,this.children.forEach(e)}}function Ng(t,e){const n=$e.now(),i=({timestamp:s})=>{const r=s-n;r>=e&&(It(i),t(r-e))};return me.setup(i,!0),()=>It(i)}const Fc=["TopLeft","TopRight","BottomLeft","BottomRight"],Og=Fc.length,Vc=t=>typeof t=="string"?parseFloat(t):t,Bc=t=>typeof t=="number"||z.test(t);function Fg(t,e,n,i,s,r){s?(t.opacity=_e(0,n.opacity??1,Vg(i)),t.opacityExit=_e(e.opacity??1,0,Bg(i))):r&&(t.opacity=_e(e.opacity??1,n.opacity??1,i));for(let o=0;o<Og;o++){const a=`border${Fc[o]}Radius`;let l=Uc(e,a),c=Uc(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Bc(l)===Bc(c)?(t[a]=Math.max(_e(Vc(l),Vc(c),i),0),(ht.test(c)||ht.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=_e(e.rotate||0,n.rotate||0,i))}function Uc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Vg=jc(0,.5,Ba),Bg=jc(.5,.95,Ye);function jc(t,e,n){return i=>i<t?0:i>e?1:n(Nn(t,e,i))}function $c(t,e){t.min=e.min,t.max=e.max}function Ze(t,e){$c(t.x,e.x),$c(t.y,e.y)}function Hc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Wc(t,e,n,i,s){return t-=e,t=Hi(t,1/n,i),s!==void 0&&(t=Hi(t,1/s,i)),t}function Ug(t,e=0,n=1,i=.5,s,r=t,o=t){if(ht.test(e)&&(e=parseFloat(e),e=_e(o.min,o.max,e/100)-o.min),typeof e!="number")return;let a=_e(r.min,r.max,i);t===r&&(a-=e),t.min=Wc(t.min,e,n,a,s),t.max=Wc(t.max,e,n,a,s)}function Gc(t,e,[n,i,s],r,o){Ug(t,e[n],e[i],e[s],e.scale,r,o)}const jg=["x","scaleX","originX"],$g=["y","scaleY","originY"];function zc(t,e,n,i){Gc(t.x,e,jg,n?n.x:void 0,i?i.x:void 0),Gc(t.y,e,$g,n?n.y:void 0,i?i.y:void 0)}function qc(t){return t.translate===0&&t.scale===1}function Kc(t){return qc(t.x)&&qc(t.y)}function Xc(t,e){return t.min===e.min&&t.max===e.max}function Hg(t,e){return Xc(t.x,e.x)&&Xc(t.y,e.y)}function Yc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Jc(t,e){return Yc(t.x,e.x)&&Yc(t.y,e.y)}function Zc(t){return Ve(t.x)/Ve(t.y)}function Qc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Wg{constructor(){this.members=[]}add(e){Vs(this.members,e),e.scheduleRender()}remove(e){if(Bs(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 r=this.members[s];if(r.isPresent!==!1){i=r;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 Gg(t,e,n){let i="";const s=t.x.translate/e.x,r=t.y.translate/e.y,o=(n==null?void 0:n.z)||0;if((s||r||o)&&(i=`translate3d(${s}px, ${r}px, ${o}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:g,skewY:v}=n;c&&(i=`perspective(${c}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),f&&(i+=`rotateY(${f}deg) `),g&&(i+=`skewX(${g}deg) `),v&&(i+=`skewY(${v}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Ho=["","X","Y","Z"],zg=1e3;let qg=0;function Wo(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function ed(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=ic(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:r}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",me,!(s||r))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&ed(i)}function td({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(o={},a=e==null?void 0:e()){this.id=qg++,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(Yg),this.nodes.forEach(ev),this.nodes.forEach(tv),this.nodes.forEach(Jg)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Mg)}addEventListener(o,a){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new $s),this.eventHandlers.get(o).add(a)}notifyListeners(o,...a){const l=this.eventHandlers.get(o);l&&l.notify(...a)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=Fl(o)&&!Gp(o),this.instance=o;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const f=()=>this.root.updateBlockedByResize=!1;me.read(()=>{d=window.innerWidth}),t(o,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=Ng(f,250),Gi.hasAnimatedSinceResize&&(Gi.hasAnimatedSinceResize=!1,this.nodes.forEach(sd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||rv,{onLayoutAnimationStart:_,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Jc(this.targetLayout,g),T=!d&&f;if(this.options.layoutRoot||this.resumeFrom||T||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const x={..._o(v,"layout"),onPlay:_,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(x.delay=0,x.type=!1),this.startAnimation(x),this.setAnimationOrigin(u,T)}else d||sd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),It(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(nv),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&ed(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(nd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(id);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Qg),this.nodes.forEach(Kg),this.nodes.forEach(Xg)):this.nodes.forEach(id),this.clearAllSnapshots();const a=$e.now();Le.delta=wt(0,1e3/60,a-Le.timestamp),Le.timestamp=a,Le.isProcessing=!0,Gs.update.process(Le),Gs.preRender.process(Le),Gs.render.process(Le),Le.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,So.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Zg),this.sharedNodes.forEach(iv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,me.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){me.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ve(this.snapshot.measuredBox.x)&&!Ve(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Se(),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,o?o.layoutBox:void 0)}updateScroll(o="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Kc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;o&&this.instance&&(a||Kt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return o&&(l=this.removeTransform(l)),av(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:o}=this.options;if(!o)return Se();const a=o.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(lv))){const{scroll:u}=this.root;u&&(mn(a.x,u.offset.x),mn(a.y,u.offset.y))}return a}removeElementScroll(o){var l;const a=Se();if(Ze(a,o),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Ze(a,o),mn(a.x,d.offset.x),mn(a.y,d.offset.y))}return a}applyTransform(o,a=!1){const l=Se();Ze(l,o);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&gn(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Kt(u.latestValues)&&gn(l,u.latestValues)}return Kt(this.latestValues)&&gn(l,this.latestValues),l}removeTransform(o){const a=Se();Ze(a,o);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Kt(c.latestValues))continue;Vo(c.latestValues)&&c.updateSnapshot();const u=Se(),d=c.measurePageBox();Ze(u,d),zc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Kt(this.latestValues)&&zc(a,this.latestValues),a}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.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!==Le.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(o||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Le.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Se(),this.relativeTargetOrigin=Se(),Jn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Se(),this.targetWithTransforms=Se()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),hg(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ze(this.target,this.layout.layoutBox),_c(this.target,this.targetDelta)):Ze(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=Se(),this.relativeTargetOrigin=Se(),Jn(this.relativeTargetOrigin,this.target,g.target),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Vo(this.parent.latestValues)||gc(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 o=this.getLead(),a=!!this.resumingFrom||this!==o;let l=!0;if((this.isProjectionDirty||(v=this.parent)!=null&&v.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Le.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;Ze(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;fg(this.layoutCorrected,this.treeScale,this.path,a),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=Se());const{target:g}=o;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Hc(this.prevProjectionDelta.x,this.projectionDelta.x),Hc(this.prevProjectionDelta.y,this.projectionDelta.y)),Yn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!Qc(this.projectionDelta.x,this.prevProjectionDelta.x)||!Qc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),o){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=pn(),this.projectionDelta=pn(),this.projectionDeltaWithTransform=pn()}setAnimationOrigin(o,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=pn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=Se(),g=l?l.source:void 0,v=this.layout?this.layout.source:void 0,_=g!==v,w=this.getStack(),y=!w||w.members.length<=1,T=!!(_&&!y&&this.options.crossfade===!0&&!this.path.some(ov));this.animationProgress=0;let x;this.mixTargetDelta=I=>{const A=I/1e3;od(d.x,o.x,A),od(d.y,o.y,A),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Jn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),sv(this.relativeTarget,this.relativeTargetOrigin,f,A),x&&Hg(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=Se()),Ze(x,this.relativeTarget)),_&&(this.animationValues=u,Fg(u,c,this.latestValues,A,T,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(It(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=me.update(()=>{Gi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=un(0)),this.currentAnimation=Dg(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),o.onUpdate&&o.onUpdate(u)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.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 o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(zg),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=o;if(!(!a||!l||!c)){if(this!==o&&this.layout&&c&&dd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||Se();const d=Ve(this.layout.layoutBox.x);l.x.min=o.target.x.min,l.x.max=l.x.min+d;const f=Ve(this.layout.layoutBox.y);l.y.min=o.target.y.min,l.y.max=l.y.min+f}Ze(a,l),gn(a,u),Yn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new Wg),this.sharedNodes.get(o).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var a;const{layoutId:o}=this.options;return o?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:o}=this.options;return o?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:l}=o;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Wo("z",o,c,this.animationValues);for(let u=0;u<Ho.length;u++)Wo(`rotate${Ho[u]}`,o,c,this.animationValues),Wo(`skew${Ho[u]}`,o,c,this.animationValues);o.render();for(const u in c)o.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);o.scheduleRender()}applyProjectionStyles(o,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||"",o.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Kt(this.latestValues)&&(o.transform=l?l({},""):"none",this.hasProjected=!1);return}o.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Gg(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),o.transform=d;const{x:f,y:g}=this.projectionDelta;o.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,c.animationValues?o.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:o.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const v in Gn){if(u[v]===void 0)continue;const{correct:_,applyTo:w,isCSSVariable:y}=Gn[v],T=d==="none"?u[v]:_(u[v],c);if(w){const x=w.length;for(let I=0;I<x;I++)o[w[I]]=T}else y?this.options.visualElement.renderState.vars[v]=T:o[v]=T}this.options.layoutId&&(o.pointerEvents=c===this?$i(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var a;return(a=o.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(nd),this.root.sharedNodes.clear()}}}function Kg(t){t.updateLayout()}function Xg(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:r}=t.options,o=e.source!==t.layout.source;r==="size"?Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],g=Ve(f);f.min=i[d].min,f.max=f.min+g}):dd(r,e.layoutBox,i)&&Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],g=Ve(i[d]);f.max=f.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=pn();Yn(a,i,e.layoutBox);const l=pn();o?Yn(l,t.applyTransform(s,!0),e.measuredBox):Yn(l,i,e.layoutBox);const c=!Kc(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:g}=d;if(f&&g){const v=Se();Jn(v,e.layoutBox,f.layoutBox);const _=Se();Jn(_,i,g.layoutBox),Jc(v,_)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=_,t.relativeTargetOrigin=v,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function Yg(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 Jg(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Zg(t){t.clearSnapshot()}function nd(t){t.clearMeasurements()}function id(t){t.isLayoutDirty=!1}function Qg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function sd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ev(t){t.resolveTargetDelta()}function tv(t){t.calcProjection()}function nv(t){t.resetSkewAndRotation()}function iv(t){t.removeLeadSnapshot()}function od(t,e,n){t.translate=_e(e.translate,0,n),t.scale=_e(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function rd(t,e,n,i){t.min=_e(e.min,n.min,i),t.max=_e(e.max,n.max,i)}function sv(t,e,n,i){rd(t.x,e.x,n.x,i),rd(t.y,e.y,n.y,i)}function ov(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const rv={duration:.45,ease:[.4,0,.1,1]},ad=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),ld=ad("applewebkit/")&&!ad("chrome/")?Math.round:Ye;function cd(t){t.min=ld(t.min),t.max=ld(t.max)}function av(t){cd(t.x),cd(t.y)}function dd(t,e,n){return t==="position"||t==="preserve-aspect"&&!ug(Zc(e),Zc(n),.2)}function lv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const cv=td({attachResizeListener:(t,e)=>qn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Go={current:void 0},ud=td({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Go.current){const t=new cv({});t.mount(window),t.setOptions({layoutScroll:!0}),Go.current=t}return Go.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),dv={pan:{Feature:Ig},drag:{Feature:Eg,ProjectionNode:ud,MeasureLayout:Oc}};function hd(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,r=i[s];r&&me.postRender(()=>r(e,Kn(e)))}class uv extends Lt{mount(){const{current:e}=this.node;e&&(this.unmount=Up(e,(n,i)=>(hd(this.node,i,"Start"),s=>hd(this.node,s,"End"))))}unmount(){}}class hv extends Lt{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=Mn(qn(this.node.current,"focus",()=>this.onFocus()),qn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fd(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),r=i[s];r&&me.postRender(()=>r(e,Kn(e)))}class fv extends Lt{mount(){const{current:e}=this.node;e&&(this.unmount=Wp(e,(n,i)=>(fd(this.node,i,"Start"),(s,{success:r})=>fd(this.node,s,r?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const zo=new WeakMap,qo=new WeakMap,pv=t=>{const e=zo.get(t.target);e&&e(t)},mv=t=>{t.forEach(pv)};function gv({root:t,...e}){const n=t||document;qo.has(n)||qo.set(n,{});const i=qo.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(mv,{root:t,...e})),i[s]}function vv(t,e,n){const i=gv(e);return zo.set(t,n),i.observe(t),()=>{zo.delete(t),i.unobserve(t)}}const yv={some:0,all:1};class _v extends Lt{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:r}=e,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:yv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,r&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),f=c?u:d;f&&f(l)};return vv(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(bv(e,n))&&this.startObserver()}unmount(){}}function bv({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const wv={inView:{Feature:_v},tap:{Feature:fv},focus:{Feature:hv},hover:{Feature:uv}},Sv={layout:{ProjectionNode:ud,MeasureLayout:Oc}},Ko={current:null},pd={current:!1};function Cv(){if(pd.current=!0,!!Fs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Ko.current=t.matches;t.addEventListener("change",e),e()}else Ko.current=!1}const Tv=new WeakMap;function kv(t,e,n){for(const i in e){const s=e[i],r=n[i];if(Ne(s))t.addValue(i,s);else if(Ne(r))t.addValue(i,un(s,{owner:t}));else if(r!==s)if(t.hasValue(i)){const o=t.getValue(i);o.liveStyle===!0?o.jump(s):o.hasAnimated||o.set(s)}else{const o=t.getStaticValue(i);t.addValue(i,un(o!==void 0?o:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const md=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class xv{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:r,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=vo,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 f=$e.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,me.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=o;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!r,this.isControllingVariants=ji(n),this.isVariantNode=Wl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const g=d[f];l[f]!==void 0&&Ne(g)&&g.set(l[f],!1)}}mount(e){this.current=e,Tv.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)),pd.current||Cv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ko.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),It(this.notifyUpdate),It(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=dn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&me.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),r=n.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),r(),o&&o(),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 hn){const n=hn[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 r=this.features[e];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Se()}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<md.length;i++){const s=md[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const r="on"+s,o=e[r];o&&(this.propEventSubscriptions[s]=this.on(s,o))}this.prevMotionValues=kv(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=un(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"&&(Aa(i)||La(i))?i=parseFloat(i):!qp(i)&&Rt.test(n)&&(i=Il(e,n)),this.setBaseTarget(e,Ne(i)?i.get():i)),Ne(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var r;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const o=Lo(this.props,n,(r=this.presenceContext)==null?void 0:r.custom);o&&(i=o[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ne(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 $s),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class gd extends xv{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;Ne(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function vd(t,{style:e,vars:n},i,s){const r=t.style;let o;for(o in e)r[o]=e[o];s==null||s.applyProjectionStyles(r,i);for(o in n)r.setProperty(o,n[o])}function Ev(t){return window.getComputedStyle(t)}class Iv extends gd{constructor(){super(...arguments),this.type="html",this.renderInstance=vd}readValueFromInstance(e,n){var i;if(dn.has(n))return(i=this.projection)!=null&&i.isProjecting?ho(n):tp(e,n);{const s=Ev(e),r=(zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return Cc(e,n)}build(e,n,i){Io(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return Do(e,n,i)}}const yd=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 Av(t,e,n,i){vd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(yd.has(s)?s:Eo(s),e.attrs[s])}class Rv extends gd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Se}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(dn.has(n)){const i=El(n);return i&&i.default||0}return n=yd.has(n)?n:Eo(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return nc(e,n,i)}build(e,n,i){Jl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){Av(e,n,i,s)}mount(e){this.isSVGTag=Ql(e.tagName),super.mount(e)}}const Lv=(t,e)=>Ro(t)?new Rv(e):new Iv(e,{allowProjection:t!==lt}),Dv=Lm({...ig,...wv,...dv,...Sv},Lv),vn=im(Dv),Pv=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region"],Qn="widget-layout-id";function _d(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=_d(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function Ct(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=_d(t))&&(i&&(i+=" "),i+=e);return i}const Mv=ki("listening"),Xo=()=>Ea(Mv);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 zi={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},bd=ki(zi),Ov=()=>{const t=Ei(bd);return Ge(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=zi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=zi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=zi.speak_to_interrupt_text),n}),[t])},Xt=()=>Ns(bd),wd=({size:t="large",className:e})=>{const n=Xt(),[i]=Xo();return R("h1",{className:Ct({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},Sd=({stream:t,chatMode:e})=>{const n=de(null);return Ee(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:R("audio",{muted:!0,ref:n,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 xv="4.5.1",$r=Math.PI,mn=2*$r,Hr=$r/2,md=8.17579892,vd="dual-combined",Ui="dual-horizontal",St="single",dt="dual-vertical",yd="bar-index",_d="bar-level",$i="gradient",bd=60,wd="click",kv="fullscreenchange",Sd="resize",Tv="#111",Cd="",xd="A",kd="B",Td="C",Ad="D",Ed="468",Hi="sans-serif",Av="#0f0",Ev="#7f7f7f22",vn=10,Id="create",Rd="fschange",Iv="lores",Rv=Sd,Gr="user",Lv="#000c",Ld="#fff",Pv="#4f4",Pd="#888",Mv="#555",Wr="bark",Zn="linear",yn="log",zr="mel",Md=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Dd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Md}],["rainbow",{dir:"h",colorStops:["#817",...Md,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Qn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:St,colorMode:$i,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:yn,gradient:Dd[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:Cd,width:void 0},Dv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],Ov=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Nv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],qr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Fv=["ERR_INVALID_MODE","Invalid mode"],Vv=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Bv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],jv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Uv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],$v=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ye extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Od=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Nd=t=>{for(const e in t)return!1;return!0},Gi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],Hv=(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 Gv{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||(Nd(n)&&!Nd(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,f]of Dd)this.registerGradient(u,f);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 Ye(Dv)}}if(!s.createGain)throw new Ye(Ov);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const u of[0,1])r.connect(o[u],u);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const u of["_scaleX","_scaleR"])this[u]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Rv),this._fsTimeout=0)},bd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Sd,l,{signal:c}),i.addEventListener(kv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Rd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},bd)},{signal:c});const d=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(wd,d))};window.addEventListener(wd,d),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Id)}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=Gi(e,[St,Ui,dt,vd]),this._input.disconnect(),this._input.connect(this._chLayout!=St?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=St?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Gi(e,[$i,yd,_d])}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=Gi(e,[yn,Wr,zr,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(Gr)}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(Iv)}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 Ye(qr);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 Ye(qr);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 Ye(Fv,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 Ye(Vv);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=-Hr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Od("stereo","channelLayout"),this._chLayout!=St}set stereo(e){Od("stereo","channelLayout"),this.channelLayout=e?dt:St}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=Gi(e,[Cd,xd,kd,Td,Ad,Ed],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Gr)}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 xv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ye(Bv);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==St&&!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:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&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==St?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(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 Ye(jv);if(typeof n!="object")throw new Ye(Uv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ye($v);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||Tv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Gr)}setFreqRange(e,n){if(e<1||n<1)throw new Ye(qr);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:l,_mode:c,_radial:d,_radialInvert:u,_reflexRatio:f}=this,m=s.width>>1,_=s.height>>1,v=o==dt&&!d,w=o==Ui,y=c%10!=0,C=y&&this._frequencyScale==yn,k=this._showLeds&&y&&!d,T=this._lumiBars&&y&&!d,E=this._alphaBars&&!T&&c!=vn,D=this._outlineBars&&y&&!T&&!k,S=this._roundBars&&y&&!T&&!k,x=o!=dt||f>0&&!T,p=s.height-(v&&!k?.5:0)>>v,g=p*(T||d?1:1-f)|0,h=s.width-m*(w||l!=0),b=v?s.height-p*2:0,I=m*(l==-1&&!w&&!d);let P=Math.min(s.width,s.height)*.375*(o==dt?1:this._radius)|0,L=Math.min(m,_);u&&o!=dt&&([P,L]=[L,P]);const O=U=>e.push({...U,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=U=>{const q=this._freqToBin(U,"floor"),Z=this._binToFreq(q),ne=this._binToFreq(q+1),he=Math.log2(U/Z)/Math.log2(ne/Z);return[q,he]};let N,W,j;if(C){const U=(oe,pe,se)=>+oe.toPrecision(se?Math.max(pe,1+Math.log10(oe)|0):pe),q=oe=>{const pe=[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],se=Math.log10(oe)|0,ft=oe/10**se;let nt=1;for(;nt<pe.length&&ft>pe[nt];)nt++;return ft-pe[nt-1]<pe[nt]-ft&&nt--,(pe[nt]*10**(se+5)|0)/1e5},Z=[0,24,12,8,6,4,3,2,1][c],ne=n?10**(3/(Z*10)):2**(1/Z),he=ne**.5;let Fe=n?7.94328235/(Z%2?1:he):md;do{let oe=Fe;const pe=U(oe/he,4,!0),se=U(oe*he,4,!0),[ft,nt]=M(pe),[li,pt]=M(se);n?oe=Z<4?q(oe):U(oe,oe.toString()[0]<5?3:2):oe=U(oe,4,!0),oe>=a&&O({posX:0,freq:oe,freqLo:pe,freqHi:se,binLo:ft,binHi:li,ratioLo:nt,ratioHi:pt}),Fe*=ne}while(Fe<=r);N=h/e.length,e.forEach((oe,pe)=>oe.posX=I+pe*N);const fe=e[0],De=e[e.length-1];W=this._freqScaling(fe.freqLo),j=h/(this._freqScaling(De.freqHi)-W),fe.freqLo<a&&(fe.freqLo=a,[fe.binLo,fe.ratioLo]=M(a)),De.freqHi>r&&(De.freqHi=r,[De.binHi,De.ratioHi]=M(r))}else if(y){const U=[0,24,12,8,6,4,3,2,1][c]*10,q=Z=>{switch(this._frequencyScale){case Wr:return 1960/(26.81/(Z+.53)-1);case zr:return 700*(2**Z-1);case Zn:return Z}};N=h/U,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);for(let Z=0,ne=0;Z<U;Z++,ne+=N){const he=q(W+ne/j),Fe=q(W+(ne+N/2)/j),fe=q(W+(ne+N)/j),[De,oe]=M(he),[pe,se]=M(fe);O({posX:I+ne,freq:Fe,freqLo:he,freqHi:fe,binLo:De,binHi:pe,ratioLo:oe,ratioHi:se})}}else{N=1,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);const U=this._freqToBin(a,"floor"),q=this._freqToBin(r);let Z=-999;for(let ne=U;ne<=q;ne++){const he=this._binToFreq(ne),Fe=I+Math.round(j*(this._freqScaling(he)-W));if(Fe>Z)O({posX:Fe,freq:he,freqLo:he,freqHi:he,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),Z=Fe;else if(e.length){const fe=e[e.length-1];fe.binHi=ne,fe.freqHi=he,fe.freq=(fe.freqLo*he)**.5}}}let re=0,te=0;if(k){const U=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),q=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Z=this._ledParams,[ne,he,Fe]=Z||q[c];let fe,De=g;if(Z){const oe=2*U;let pe;fe=ne+1;do fe--,pe=De/fe/(1+he),te=pe*he;while((pe<oe||te<oe)&&fe>1)}else{const oe=540/he;te=Math.min(he*U,Math.max(2,De/oe+.1|0))}x&&(De+=te),Z||(fe=Math.min(ne,De/(te*2)|0)),re=Fe>=1?Fe:N*Fe,this._leds=[fe,re,te,De/fe-te]}const $=Math.min(N-1,i*(i>0&&i<1?N:1));y&&(N-=Math.max(k?re:0,$)),e.forEach((U,q)=>{let Z=U.posX,ne=N;y&&(i==0&&!k?(Z|=0,ne|=0,q>0&&Z>e[q-1].posX+e[q-1].width&&(Z--,ne++)):Z+=Math.max(k?re:0,$)/2,U.posX=Z),U.barCenter=Z+(N==1?0:ne/2),U.width=ne});const ae=[];for(const U of[0,1]){const q=o==dt?(p+b)*U:0,Z=q+p,ne=q+g-(!k||x?0:te);ae.push({channelTop:q,channelBottom:Z,analyzerBottom:ne})}this._aux={analyzerHeight:g,analyzerWidth:h,centerX:m,centerY:_,channelCoords:ae,channelHeight:p,channelGap:b,initialX:I,innerRadius:P,outerRadius:L,scaleMin:W,unitWidth:j},this._flg={isAlpha:E,isBands:y,isLeds:k,isLumi:T,isOctaves:C,isOutline:D,isRound:S,noLedGap:x},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:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:f}=this,m=u.canvas,_=f.canvas,v=[],w=this._chLayout==Ui,y=this._chLayout==dt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],T=C/34|0,E=m.height>>1,D=T>>1,S=E*(c?.7:1.5),x=D*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=yn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Zn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let L=md;for(let O=-1;O<11;O++)for(let M=0;M<12;M++){if(L>=this._minFreq&&L<=this._maxFreq){const N=k[M],W=N=="C";(N&&c&&!l&&!w||W)&&v.push(c?[L,N+(W?O:"")]:L)}L*=p}}_.width=_.height=Math.max(C*.15,(i<<1)+y*T);const g=_.width>>1,h=g-T*.7,b=(L,O)=>{const M=mn*(L/r.width),N=M-Hr,W=h*Math.cos(N),j=h*Math.sin(N);f.save(),f.translate(g+W,g+j),f.rotate(M),f.fillText(O,0,0),f.restore()};m.width|=0,u.fillStyle=f.strokeStyle=Lv,u.fillRect(0,0,m.width,m.height),f.arc(g,g,g-T/2,0,mn),f.lineWidth=T,f.stroke(),u.fillStyle=f.fillStyle=Ld,u.font=`${E}px ${Hi}`,f.font=`${D}px ${Hi}`,u.textAlign=f.textAlign="center";let I=-S/4,P=-x;for(const L of v){const[O,M]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],N=o*(this._freqScaling(O)-s),W=m.height*.75,j=M[0]=="C",re=E*(c&&!l&&!w?j?1.2:.6:3);if(u.fillStyle=f.fillStyle=j&&!l&&!w?Pv:Ld,c){const te=a==yn,$=a==Zn;let ae=["C"];if((te||O>2e3||!$&&O>250||(!d||y)&&(!$&&O>125||O>1e3))&&ae.push("G"),(te||O>4e3||!$&&O>500||(!d||y)&&(!$&&O>250||O>2e3))&&ae.push("E"),($&&O>4e3||(!d||y)&&(te||O>2e3||!$&&O>500))&&ae.push("D","F","A","B"),!ae.includes(M[0]))continue}N>=I+S/2&&N<=e&&(u.fillText(M,w&&l==-1?e-N:n+N,W,re),(w||l&&(N>S||l==1))&&u.fillText(M,w&&l!=1?e+N:(n||r.width)-N,W,re),I=N+Math.min(re,u.measureText(M).width)/2),N>=P+x&&N<e-x&&(b(w&&l==1?e-N:N,M),(w||l&&(N>x||l==1))&&b(w&&l!=-1?e+N:-N,M),P=N)}}_draw(e){this._runId=requestAnimationFrame(F=>this._draw(F));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:l,isOctaves:c,isOutline:d,isRound:u,noLedGap:f}=this._flg,{analyzerHeight:m,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:C,initialX:k,innerRadius:T,outerRadius:E}=this._aux,{_bars:D,canvas:S,_canvasGradients:x,_chLayout:p,_colorMode:g,_ctx:h,_energy:b,_fadePeaks:I,fillAlpha:P,_fps:L,_linearAmplitude:O,_lineWidth:M,maxDecibels:N,minDecibels:W,_mirror:j,_mode:re,overlay:te,_radial:$,showBgColor:ae,showPeaks:U,useCanvas:q,_weightingFilter:Z}=this,ne=this._scaleX.canvas,he=this._scaleR.canvas,Fe=L*this._peakFadeTime/1e3,fe=L**2,De=this._gravity*1e3,oe=L*this._peakHoldTime/1e3,pe=p==vd,se=p==Ui,ft=p==dt,nt=p==St,li=a&&this._trueLeds&&g==$i,pt=$?S.width:this._aux.analyzerWidth,ao=k+pt,ci=U&&this._peakLine&&re==vn,Ot=$?E-T:m,e0=Ot/this._pixelRatio,[t0,u0,di,lo]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*mn/60/L);const n0=F=>{if(this._reflexRatio>0&&!l&&!$){let ie,gt;this.reflexFit||ft?(ie=ft&&F==0?y+C:0,gt=y-m):(ie=S.height-m*2,gt=m),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[F].channelTop,S.width,m,0,ie,S.width,gt),h.restore()}},i0=()=>{this.showScaleX&&($?(h.save(),h.translate(_,v),this._spinSpeed&&h.rotate(this._spinAngle+Hr),h.drawImage(he,-he.width>>1,-he.width>>1),h.restore()):h.drawImage(ne,0,S.height-ne.height))},s0=F=>{const ie=F**2,gt=424.36,Le=11599.29,ss=25122.25,Nt=544496.41,kt=148693636,Jt=Zt=>20*Math.log10(Zt);switch(Z){case xd:const Zt=kt*ie**2/((ie+gt)*Math.sqrt((ie+Le)*(ie+Nt))*(ie+kt));return 2+Jt(Zt);case kd:const Qt=kt*ie*F/((ie+gt)*Math.sqrt(ie+ss)*(ie+kt));return .17+Jt(Qt);case Td:const ho=kt*ie/((ie+gt)*(ie+kt));return .06+Jt(ho);case Ad:const rs=((103791848e-2-ie)**2+108076816e-2*ie)/((9837328-ie)**2+11723776*ie),fo=F/68966888496476e-18*Math.sqrt(rs/((ie+79919.29)*(ie+1345600)));return Jt(fo);case Ed:const os=-4737338981378384e-39*F**6+2043828333606125e-30*F**4-1363894795463638e-22*ie+1,en=1306612257412824e-34*F**5-2118150887518656e-26*F**3+.0005559488023498642*F,Ge=.0001246332637532143*F/Math.hypot(os,en);return 18.2+Jt(Ge)}return 0},co=(F,ie,gt)=>{h.beginPath(),h.moveTo(F,ie),h.lineTo(F,gt),h.stroke()},uo=F=>{if(F&&M){const ie=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ie}},Yt=F=>Math.max(0,(F*t0|0)*(lo+di)-di),r0=F=>{b.val=F,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*De/fe/S.height*this._pixelRatio)),F>=b.peak&&(b.peak=F,b.hold=oe)};te&&h.clearRect(0,0,S.width,S.height);let Wu=0;const zu=D.length,qu=nt?1:2;for(let F=0;F<qu;F++){const{channelTop:ie,channelBottom:gt,analyzerBottom:Le}=w[F],ss=this._gradients[this._selectedGrads[F]],Nt=ss.colorStops,kt=Nt.length,Jt=!ae||a&&!te?"#000":ss.bgColor,Zt=ft&&$&&F?-1:1,Qt=!F&&j==-1||F&&j==1,ho=!se||F&&j!=1?0:pt>>(F||!Qt),rs=se&&Qt?-1:1,fo=()=>{const H=ne.height,K=H>>1,Q=O?100:N,de=O?0:W,Se=O?20:5,$e=m/(Q-de),mt=j!=-1&&(!se||F==0||j==1),Ft=j!=1&&(!se||F!=j);h.save(),h.fillStyle=Pd,h.font=`${K}px ${Hi}`,h.textAlign="right",h.lineWidth=1;for(let Vt=Q;Vt>de;Vt-=Se){const xn=ie+(Q-Vt)*$e,Ae=Vt%2==0|0;if(Ae){const Ve=xn+K*(xn==ie?.8:.35);mt&&h.fillText(Vt,H*.85,Ve),Ft&&h.fillText(Vt,(se?pt:S.width)-H*.1,Ve),h.strokeStyle=Pd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=Mv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(k+H*Ae*mt,~~xn+.5),h.lineTo(ao-H*Ae*Ft,~~xn+.5),h.stroke()}h.restore()},os=(H,K)=>{const Q=it[H]+(H<it.length-1?(it[H+1]-it[H])*K:0);return isNaN(Q)?-1/0:Q},en=(H,K=rs)=>K*mn*((H+ho)/S.width)+this._spinAngle,Ge=(H,K,Q)=>{const de=T+K*Zt,Se=en(H,Q);return[_+de*Math.cos(Se),v+de*Math.sin(Se)]},po=(H,K,Q,de,Se)=>{h.beginPath();for(const $e of j&&!se?[1,-1]:[rs]){const[mt,Ft]=u?[en(H,$e),en(H+Q,$e)]:[];h.moveTo(...Ge(H,K,$e)),h.lineTo(...Ge(H,K+de,$e)),u?h.arc(_,v,T+(K+de)*Zt,mt,Ft,$e!=1):h.lineTo(...Ge(H+Q,K+de,$e)),h.lineTo(...Ge(H+Q,K,$e)),u&&!Se&&h.arc(_,v,T+K*Zt,Ft,mt,$e==1)}uo(Se),h.fill()},go=(H=0,K=0)=>{let Q;if(g==$i&&!li||re==vn)Q=x[F];else{const de=g==yd?K%kt:Nt.findLastIndex(Se=>a?Yt(H)<=Yt(Se.level):H<=Se.level);Q=Nt[de].color}h.fillStyle=h.strokeStyle=Q};if(q){if(se&&!$){const H=pt*(F+Qt),K=Qt?-1:1;h.setTransform(K,0,0,1,H,0)}if((!te||ae)&&(te&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Jt,(F==0||!$&&!pe)&&h.fillRect(k,ie-C,pt,(te&&this.reflexAlpha==1?m:y)+C),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(F==0||!pe)&&fo(),a?(h.setLineDash([lo,di]),h.lineWidth=D[0].width):h.lineWidth=d?Math.min(M,D[0].width/2):M,h.save(),!$){const H=new Path2D;H.rect(0,ie,S.width,m),h.clip(H)}}let it=this._fftData[F];this._analyzer[F].getFloatFrequencyData(it),Z&&(it=it.map((H,K)=>H+s0(this._binToFreq(K)))),h.beginPath();let ui=[];for(let H=0;H<zu;H++){const K=D[H],{posX:Q,barCenter:de,width:Se,freq:$e,binLo:mt,binHi:Ft,ratioLo:Vt,ratioHi:xn}=K;let Ae=Math.max(os(mt,Vt),os(Ft,xn));for(let le=mt+1;le<Ft;le++)it[le]>Ae&&(Ae=it[le]);if(Ae=this._normalizedB(Ae),K.value[F]=Ae,Wu+=Ae,K.peak[F]>0&&K.alpha[F]>0&&(K.hold[F]--,K.hold[F]<0)){if(I&&!ci){const le=!o||d&&M>0?1:o?K.peak[F]:P;K.alpha[F]=le*(1+K.hold[F]/Fe)}else K.peak[F]+=K.hold[F]*De/fe/e0;K.alpha[F]<=0&&(K.peak[F]=0)}if(Ae>=K.peak[F]&&(K.peak[F]=Ae,K.hold[F]=oe,K.alpha[F]=!o||d&&M>0?1:o?Ae:P),!q)continue;h.globalAlpha=l||o?Ae:d?P:1,go(Ae,H);const Ve=l?Ot:a?Yt(Ae):Ae*Ot|0;if(re==vn){const le=H?0:(this._normalizedB(it[D[1].binLo])*Ot+Ve)/2;if($){if(H==0&&(se&&h.moveTo(...Ge(0,0)),h.lineTo(...Ge(0,Q<0?le:Ve))),Q>=0){const Ze=[Q,Ve];h.lineTo(...Ge(...Ze)),ui.push(Ze)}}else{if(H==0)if(j==-1&&!se)h.moveTo(k,Le-(Q<k?le:Ve));else{const Ze=mt?this._normalizedB(it[mt-1])*Ot:Ve;h.moveTo(k-M,Le-Ze)}(se||j!=-1||Q>=k)&&h.lineTo(Q,Le-Ve)}}else if(a){if(ae&&!te&&(F==0||!pe)){const le=h.globalAlpha;h.strokeStyle=Ev,h.globalAlpha=1,co(de,ie,Le),h.strokeStyle=h.fillStyle,h.globalAlpha=le}if(li){const le=l?0:Nt.findLastIndex(tn=>Yt(Ae)<=Yt(tn.level));let Ze=Le;for(let tn=kt-1;tn>=le;tn--){h.strokeStyle=Nt[tn].color;let Xu=Le-(tn==le?Ve:Yt(Nt[tn].level));co(de,Ze,Xu),Ze=Xu-di}}else co(de,Le,Le-Ve)}else if(Q>=k)if($)po(Q,0,Se,Ve,d);else if(u){const le=Se/2,Ze=Le+le;h.beginPath(),h.moveTo(Q,Ze),h.lineTo(Q,Ze-Ve),h.arc(de,Ze-Ve,le,$r,mn),h.lineTo(Q+Se,Ze),uo(d),h.fill()}else{const le=d?h.lineWidth:0;h.beginPath(),h.rect(Q,Le+le,Se,-Ve-le),uo(d),h.fill()}const kn=K.peak[F],Ku=K.alpha[F];if(kn>0&&Ku>0&&U&&!ci&&!l&&Q>=k&&Q<ao){if(I?h.globalAlpha=Ku:d&&M>0?h.globalAlpha=1:o&&(h.globalAlpha=kn),(g==_d||li)&&go(kn),a){const le=Yt(kn);le>=di&&h.fillRect(Q,Le-le,Se,lo)}else if(!$)h.fillRect(Q,Le-kn*Ot,Se,2);else if(re!=vn){const le=kn*Ot;po(Q,le,Se,!this._radialInvert||ft||le+T>=2?-2:2)}}}if(q){if(h.globalAlpha=1,re==vn){if(go(),$&&!se){if(j){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1))}h.closePath()}if(M>0&&h.stroke(),P>0){if($){const H=se?en(pt>>1):0,K=se?en(pt):mn;h.moveTo(...Ge(se?pt>>1:0,0)),h.arc(_,v,T,H,K,se?!Qt:!0)}else h.lineTo(ao,Le),h.lineTo(k,Le);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((ci||$&&U)&&(ui=[],h.beginPath(),D.forEach((H,K)=>{let Q=H.posX,de=H.peak[F],Se=K?"lineTo":"moveTo";if($&&Q<0){const $e=D[K+1];de=Hv(Q,de,$e.posX,$e.peak[F],0),Q=0}de*=Ot,ci?(h[Se](...$?Ge(Q,de):[Q,Le-de]),$&&j&&!se&&ui.push([Q,de])):de>0&&po(Q,de,1,-2)}),ci)){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1));h.lineWidth=1,h.stroke()}}h.restore(),se&&!$&&h.setTransform(1,0,0,1,0,0),(!se&&!pe||F)&&n0(F)}}if(r0(Wu/(zu<<qu-1)),q&&(j&&!$&&!se&&(h.setTransform(-1,0,0,1,S.width-k,0),h.drawImage(S,k,0,_,S.height,0,0,_,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),i0()),this.showFPS){const F=ne.height;h.font=`bold ${F}px ${Hi}`,h.fillStyle=Av,h.textAlign="right",h.fillText(Math.round(L),S.width-F,F*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=x[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:x}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case yn:return Math.log2(e);case Wr:return 26.81*e/(1960+e)-.53;case zr: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:l,innerRadius:c,outerRadius:d}=this._aux,{isLumi:u}=this._flg,f=this._chLayout==dt,m=1-s,_=u?e.height:e.height*(1-s*!f)|0;for(const v of[0,1]){const w=this._gradients[this._selectedGrads[v]],y=w.colorStops,C=w.dir=="h";let k;if(i?k=n.createRadialGradient(r,a,d,r,a,c-(d-c)*f):k=n.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),y){const T=f&&!this._splitGradient&&(!C||i);for(let E=0;E<1+T;E++){const D=y.length-1;y.forEach((S,x)=>{let p=S.pos;if(T&&(p/=2),f&&!u&&!i&&!C&&(p*=m,!T&&p>.5*m&&(p+=.5*s)),E==1)if(i||u){const g=D-x;S=y[g],p=1-S.pos/2}else x==0&&p>0&&k.addColorStop(.5,S.color),p+=.5;k.addColorStop(p,S.color),f&&x==D&&p<.5&&k.addColorStop(.5,S.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,d)=>l<=c?c:l>=d?d:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),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 l=this.isFullscreen,c=l&&this._fsEl==n,d=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,u=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Id&&n.width==d&&n.height==u)&&(n.width=d,n.height=u,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,d,u)),i.lineJoin="bevel",s.width=d,s.height=Math.max(20*o,Math.min(d,u)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Rd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Ye(Nv,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 Wv={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}]}},Fd=({stream:t,className:e,onClick:n})=>{var o;const i=me(null),s=qt();return ke(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Gv(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 l.registerGradient("gradient",Wv[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),R("div",{onClick:n,className:wt("w-full",e),ref:i})};/**
|
|
16
|
+
*/const Fv="4.5.1",Yo=Math.PI,yn=2*Yo,Jo=Yo/2,Cd=8.17579892,Td="dual-combined",qi="dual-horizontal",Tt="single",ft="dual-vertical",kd="bar-index",xd="bar-level",Ki="gradient",Ed=60,Id="click",Vv="fullscreenchange",Ad="resize",Bv="#111",Rd="",Ld="A",Dd="B",Pd="C",Md="D",Nd="468",Xi="sans-serif",Uv="#0f0",jv="#7f7f7f22",_n=10,Od="create",Fd="fschange",$v="lores",Hv=Ad,Zo="user",Wv="#000c",Vd="#fff",Gv="#4f4",Bd="#888",zv="#555",Qo="bark",ei="linear",bn="log",er="mel",Ud=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],jd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Ud}],["rainbow",{dir:"h",colorStops:["#817",...Ud,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],ti={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Tt,colorMode:Ki,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:bn,gradient:jd[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:Rd,width:void 0},qv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],Kv=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Xv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],tr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Yv=["ERR_INVALID_MODE","Invalid mode"],Jv=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Zv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Qv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],ey=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],ty=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Qe extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const $d=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Hd=t=>{for(const e in t)return!1;return!0},Yi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],ny=(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 iy{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||(Hd(n)&&!Hd(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[d,f]of jd)this.registerGradient(d,f);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 Qe(qv)}}if(!s.createGain)throw new Qe(Kv);const r=this._analyzer=[s.createAnalyser(),s.createAnalyser()],o=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 d of[0,1])o.connect(r[d],d);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Hv),this._fsTimeout=0)},Ed))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Ad,l,{signal:c}),i.addEventListener(Vv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Fd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ed)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Id,u))};window.addEventListener(Id,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Od)}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=Yi(e,[Tt,qi,ft,Td]),this._input.disconnect(),this._input.connect(this._chLayout!=Tt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Tt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Yi(e,[Ki,kd,xd])}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=Yi(e,[bn,Qo,er,ei]),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||ti.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Zo)}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($v)}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 Qe(tr);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 Qe(tr);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 Qe(Yv,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||ti.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 Qe(Jv);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=-Jo),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return $d("stereo","channelLayout"),this._chLayout!=Tt}set stereo(e){$d("stereo","channelLayout"),this.channelLayout=e?ft:Tt}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=Yi(e,[Rd,Ld,Dd,Pd,Md,Nd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Zo)}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 Fv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Qe(Zv);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==Tt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:r,_observer:o,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),o&&o.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),r.disconnect(),l&&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 r of i.mediaStream.getAudioTracks())r.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:r,peak:o,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:r,peak:o,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,r=this._chLayout==Tt?1:2;let o=0;for(let a=0;a<r;a++)for(let l=i;l<=s;l++)o+=this._normalizedB(this._fftData[a][l]);return o/(s-i+1)/r}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(ti))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 Qe(Qv);if(typeof n!="object")throw new Qe(ey);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Qe(ty);const s=i.length,r=o=>+o!=o||o<0||o>1;i.forEach((o,a)=>{const l=a/Math.max(1,s-1);typeof o!="object"?i[a]={pos:l,color:o}:r(o.pos)&&(o.pos=l),r(o.level)&&(i[a].level=1-a/s)}),i.sort((o,a)=>o.level<a.level?1:o.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(Zo)}setFreqRange(e,n){if(e<1||n<1)throw new Qe(tr);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:r,_maxFreq:o,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:f}=this,g=s.width>>1,v=s.height>>1,_=r==ft&&!u,w=r==qi,y=c%10!=0,T=y&&this._frequencyScale==bn,x=this._showLeds&&y&&!u,I=this._lumiBars&&y&&!u,A=this._alphaBars&&!I&&c!=_n,M=this._outlineBars&&y&&!I&&!x,S=this._roundBars&&y&&!I&&!x,C=r!=ft||f>0&&!I,p=s.height-(_&&!x?.5:0)>>_,m=p*(I||u?1:1-f)|0,h=s.width-g*(w||l!=0),b=_?s.height-p*2:0,E=g*(l==-1&&!w&&!u);let D=Math.min(s.width,s.height)*.375*(r==ft?1:this._radius)|0,L=Math.min(g,v);d&&r!=ft&&([D,L]=[L,D]);const N=Y=>e.push({...Y,peak:[0,0],hold:[0],alpha:[0],value:[0]}),P=Y=>{const Q=this._freqToBin(Y,"floor"),ee=this._binToFreq(Q),H=this._binToFreq(Q+1),se=Math.log2(Y/ee)/Math.log2(H/ee);return[Q,se]};let B,X,j;if(T){const Y=(le,ve,re)=>+le.toPrecision(re?Math.max(ve,1+Math.log10(le)|0):ve),Q=le=>{const ve=[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(le)|0,gt=le/10**re;let ot=1;for(;ot<ve.length&>>ve[ot];)ot++;return gt-ve[ot-1]<ve[ot]-gt&&ot--,(ve[ot]*10**(re+5)|0)/1e5},ee=[0,24,12,8,6,4,3,2,1][c],H=n?10**(3/(ee*10)):2**(1/ee),se=H**.5;let Ae=n?7.94328235/(ee%2?1:se):Cd;do{let le=Ae;const ve=Y(le/se,4,!0),re=Y(le*se,4,!0),[gt,ot]=P(ve),[pi,vt]=P(re);n?le=ee<4?Q(le):Y(le,le.toString()[0]<5?3:2):le=Y(le,4,!0),le>=a&&N({posX:0,freq:le,freqLo:ve,freqHi:re,binLo:gt,binHi:pi,ratioLo:ot,ratioHi:vt}),Ae*=H}while(Ae<=o);B=h/e.length,e.forEach((le,ve)=>le.posX=E+ve*B);const ge=e[0],Fe=e[e.length-1];X=this._freqScaling(ge.freqLo),j=h/(this._freqScaling(Fe.freqHi)-X),ge.freqLo<a&&(ge.freqLo=a,[ge.binLo,ge.ratioLo]=P(a)),Fe.freqHi>o&&(Fe.freqHi=o,[Fe.binHi,Fe.ratioHi]=P(o))}else if(y){const Y=[0,24,12,8,6,4,3,2,1][c]*10,Q=ee=>{switch(this._frequencyScale){case Qo:return 1960/(26.81/(ee+.53)-1);case er:return 700*(2**ee-1);case ei:return ee}};B=h/Y,X=this._freqScaling(a),j=h/(this._freqScaling(o)-X);for(let ee=0,H=0;ee<Y;ee++,H+=B){const se=Q(X+H/j),Ae=Q(X+(H+B/2)/j),ge=Q(X+(H+B)/j),[Fe,le]=P(se),[ve,re]=P(ge);N({posX:E+H,freq:Ae,freqLo:se,freqHi:ge,binLo:Fe,binHi:ve,ratioLo:le,ratioHi:re})}}else{B=1,X=this._freqScaling(a),j=h/(this._freqScaling(o)-X);const Y=this._freqToBin(a,"floor"),Q=this._freqToBin(o);let ee=-999;for(let H=Y;H<=Q;H++){const se=this._binToFreq(H),Ae=E+Math.round(j*(this._freqScaling(se)-X));if(Ae>ee)N({posX:Ae,freq:se,freqLo:se,freqHi:se,binLo:H,binHi:H,ratioLo:0,ratioHi:0}),ee=Ae;else if(e.length){const ge=e[e.length-1];ge.binHi=H,ge.freqHi=se,ge.freq=(ge.freqLo*se)**.5}}}let ie=0,ne=0;if(x){const Y=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Q=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],ee=this._ledParams,[H,se,Ae]=ee||Q[c];let ge,Fe=m;if(ee){const le=2*Y;let ve;ge=H+1;do ge--,ve=Fe/ge/(1+se),ne=ve*se;while((ve<le||ne<le)&&ge>1)}else{const le=540/se;ne=Math.min(se*Y,Math.max(2,Fe/le+.1|0))}C&&(Fe+=ne),ee||(ge=Math.min(H,Fe/(ne*2)|0)),ie=Ae>=1?Ae:B*Ae,this._leds=[ge,ie,ne,Fe/ge-ne]}const $=Math.min(B-1,i*(i>0&&i<1?B:1));y&&(B-=Math.max(x?ie:0,$)),e.forEach((Y,Q)=>{let ee=Y.posX,H=B;y&&(i==0&&!x?(ee|=0,H|=0,Q>0&&ee>e[Q-1].posX+e[Q-1].width&&(ee--,H++)):ee+=Math.max(x?ie:0,$)/2,Y.posX=ee),Y.barCenter=ee+(B==1?0:H/2),Y.width=H});const ce=[];for(const Y of[0,1]){const Q=r==ft?(p+b)*Y:0,ee=Q+p,H=Q+m-(!x||C?0:ne);ce.push({channelTop:Q,channelBottom:ee,analyzerBottom:H})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:v,channelCoords:ce,channelHeight:p,channelGap:b,initialX:E,innerRadius:D,outerRadius:L,scaleMin:X,unitWidth:j},this._flg={isAlpha:A,isBands:y,isLeds:x,isLumi:I,isOctaves:T,isOutline:M,isRound:S,noLedGap:C},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:r}=this._aux,{canvas:o,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:f}=this,g=d.canvas,v=f.canvas,_=[],w=this._chLayout==qi,y=this._chLayout==ft,T=Math.min(o.width,o.height),x=["C",,"D",,"E","F",,"G",,"A",,"B"],I=T/34|0,A=g.height>>1,M=I>>1,S=A*(c?.7:1.5),C=M*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=bn))_.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ei?_.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):_.push(8e3,16e3);else{let L=Cd;for(let N=-1;N<11;N++)for(let P=0;P<12;P++){if(L>=this._minFreq&&L<=this._maxFreq){const B=x[P],X=B=="C";(B&&c&&!l&&!w||X)&&_.push(c?[L,B+(X?N:"")]:L)}L*=p}}v.width=v.height=Math.max(T*.15,(i<<1)+y*I);const m=v.width>>1,h=m-I*.7,b=(L,N)=>{const P=yn*(L/o.width),B=P-Jo,X=h*Math.cos(B),j=h*Math.sin(B);f.save(),f.translate(m+X,m+j),f.rotate(P),f.fillText(N,0,0),f.restore()};g.width|=0,d.fillStyle=f.strokeStyle=Wv,d.fillRect(0,0,g.width,g.height),f.arc(m,m,m-I/2,0,yn),f.lineWidth=I,f.stroke(),d.fillStyle=f.fillStyle=Vd,d.font=`${A}px ${Xi}`,f.font=`${M}px ${Xi}`,d.textAlign=f.textAlign="center";let E=-S/4,D=-C;for(const L of _){const[N,P]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],B=r*(this._freqScaling(N)-s),X=g.height*.75,j=P[0]=="C",ie=A*(c&&!l&&!w?j?1.2:.6:3);if(d.fillStyle=f.fillStyle=j&&!l&&!w?Gv:Vd,c){const ne=a==bn,$=a==ei;let ce=["C"];if((ne||N>2e3||!$&&N>250||(!u||y)&&(!$&&N>125||N>1e3))&&ce.push("G"),(ne||N>4e3||!$&&N>500||(!u||y)&&(!$&&N>250||N>2e3))&&ce.push("E"),($&&N>4e3||(!u||y)&&(ne||N>2e3||!$&&N>500))&&ce.push("D","F","A","B"),!ce.includes(P[0]))continue}B>=E+S/2&&B<=e&&(d.fillText(P,w&&l==-1?e-B:n+B,X,ie),(w||l&&(B>S||l==1))&&d.fillText(P,w&&l!=1?e+B:(n||o.width)-B,X,ie),E=B+Math.min(ie,d.measureText(P).width)/2),B>=D+C&&B<e-C&&(b(w&&l==1?e-B:B,P),(w||l&&(B>C||l==1))&&b(w&&l!=-1?e+B:-B,P),D=B)}}_draw(e){this._runId=requestAnimationFrame(V=>this._draw(V));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:r,isBands:o,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:f}=this._flg,{analyzerHeight:g,centerX:v,centerY:_,channelCoords:w,channelHeight:y,channelGap:T,initialX:x,innerRadius:I,outerRadius:A}=this._aux,{_bars:M,canvas:S,_canvasGradients:C,_chLayout:p,_colorMode:m,_ctx:h,_energy:b,_fadePeaks:E,fillAlpha:D,_fps:L,_linearAmplitude:N,_lineWidth:P,maxDecibels:B,minDecibels:X,_mirror:j,_mode:ie,overlay:ne,_radial:$,showBgColor:ce,showPeaks:Y,useCanvas:Q,_weightingFilter:ee}=this,H=this._scaleX.canvas,se=this._scaleR.canvas,Ae=L*this._peakFadeTime/1e3,ge=L**2,Fe=this._gravity*1e3,le=L*this._peakHoldTime/1e3,ve=p==Td,re=p==qi,gt=p==ft,ot=p==Tt,pi=a&&this._trueLeds&&m==Ki,vt=$?S.width:this._aux.analyzerWidth,mr=x+vt,mi=Y&&this._peakLine&&ie==_n,Ft=$?A-I:g,J0=Ft/this._pixelRatio,[Z0,lb,gi,gr]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*yn/60/L);const Q0=V=>{if(this._reflexRatio>0&&!l&&!$){let oe,yt;this.reflexFit||gt?(oe=gt&&V==0?y+T:0,yt=y-g):(oe=S.height-g*2,yt=g),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[V].channelTop,S.width,g,0,oe,S.width,yt),h.restore()}},eb=()=>{this.showScaleX&&($?(h.save(),h.translate(v,_),this._spinSpeed&&h.rotate(this._spinAngle+Jo),h.drawImage(se,-se.width>>1,-se.width>>1),h.restore()):h.drawImage(H,0,S.height-H.height))},tb=V=>{const oe=V**2,yt=424.36,Me=11599.29,us=25122.25,Vt=544496.41,xt=148693636,Qt=en=>20*Math.log10(en);switch(ee){case Ld:const en=xt*oe**2/((oe+yt)*Math.sqrt((oe+Me)*(oe+Vt))*(oe+xt));return 2+Qt(en);case Dd:const tn=xt*oe*V/((oe+yt)*Math.sqrt(oe+us)*(oe+xt));return .17+Qt(tn);case Pd:const _r=xt*oe/((oe+yt)*(oe+xt));return .06+Qt(_r);case Md:const hs=((103791848e-2-oe)**2+108076816e-2*oe)/((9837328-oe)**2+11723776*oe),br=V/68966888496476e-18*Math.sqrt(hs/((oe+79919.29)*(oe+1345600)));return Qt(br);case Nd:const fs=-4737338981378384e-39*V**6+2043828333606125e-30*V**4-1363894795463638e-22*oe+1,nn=1306612257412824e-34*V**5-2118150887518656e-26*V**3+.0005559488023498642*V,qe=.0001246332637532143*V/Math.hypot(fs,nn);return 18.2+Qt(qe)}return 0},vr=(V,oe,yt)=>{h.beginPath(),h.moveTo(V,oe),h.lineTo(V,yt),h.stroke()},yr=V=>{if(V&&P){const oe=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=oe}},Zt=V=>Math.max(0,(V*Z0|0)*(gr+gi)-gi),nb=V=>{b.val=V,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*Fe/ge/S.height*this._pixelRatio)),V>=b.peak&&(b.peak=V,b.hold=le)};ne&&h.clearRect(0,0,S.width,S.height);let sh=0;const oh=M.length,rh=ot?1:2;for(let V=0;V<rh;V++){const{channelTop:oe,channelBottom:yt,analyzerBottom:Me}=w[V],us=this._gradients[this._selectedGrads[V]],Vt=us.colorStops,xt=Vt.length,Qt=!ce||a&&!ne?"#000":us.bgColor,en=gt&&$&&V?-1:1,tn=!V&&j==-1||V&&j==1,_r=!re||V&&j!=1?0:vt>>(V||!tn),hs=re&&tn?-1:1,br=()=>{const W=H.height,K=W>>1,Z=N?100:B,pe=N?0:X,ke=N?20:5,We=g/(Z-pe),_t=j!=-1&&(!re||V==0||j==1),Bt=j!=1&&(!re||V!=j);h.save(),h.fillStyle=Bd,h.font=`${K}px ${Xi}`,h.textAlign="right",h.lineWidth=1;for(let Ut=Z;Ut>pe;Ut-=ke){const xn=oe+(Z-Ut)*We,Re=Ut%2==0|0;if(Re){const je=xn+K*(xn==oe?.8:.35);_t&&h.fillText(Ut,W*.85,je),Bt&&h.fillText(Ut,(re?vt:S.width)-W*.1,je),h.strokeStyle=Bd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=zv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(x+W*Re*_t,~~xn+.5),h.lineTo(mr-W*Re*Bt,~~xn+.5),h.stroke()}h.restore()},fs=(W,K)=>{const Z=rt[W]+(W<rt.length-1?(rt[W+1]-rt[W])*K:0);return isNaN(Z)?-1/0:Z},nn=(W,K=hs)=>K*yn*((W+_r)/S.width)+this._spinAngle,qe=(W,K,Z)=>{const pe=I+K*en,ke=nn(W,Z);return[v+pe*Math.cos(ke),_+pe*Math.sin(ke)]},wr=(W,K,Z,pe,ke)=>{h.beginPath();for(const We of j&&!re?[1,-1]:[hs]){const[_t,Bt]=d?[nn(W,We),nn(W+Z,We)]:[];h.moveTo(...qe(W,K,We)),h.lineTo(...qe(W,K+pe,We)),d?h.arc(v,_,I+(K+pe)*en,_t,Bt,We!=1):h.lineTo(...qe(W+Z,K+pe,We)),h.lineTo(...qe(W+Z,K,We)),d&&!ke&&h.arc(v,_,I+K*en,Bt,_t,We==1)}yr(ke),h.fill()},Sr=(W=0,K=0)=>{let Z;if(m==Ki&&!pi||ie==_n)Z=C[V];else{const pe=m==kd?K%xt:Vt.findLastIndex(ke=>a?Zt(W)<=Zt(ke.level):W<=ke.level);Z=Vt[pe].color}h.fillStyle=h.strokeStyle=Z};if(Q){if(re&&!$){const W=vt*(V+tn),K=tn?-1:1;h.setTransform(K,0,0,1,W,0)}if((!ne||ce)&&(ne&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Qt,(V==0||!$&&!ve)&&h.fillRect(x,oe-T,vt,(ne&&this.reflexAlpha==1?g:y)+T),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(V==0||!ve)&&br(),a?(h.setLineDash([gr,gi]),h.lineWidth=M[0].width):h.lineWidth=u?Math.min(P,M[0].width/2):P,h.save(),!$){const W=new Path2D;W.rect(0,oe,S.width,g),h.clip(W)}}let rt=this._fftData[V];this._analyzer[V].getFloatFrequencyData(rt),ee&&(rt=rt.map((W,K)=>W+tb(this._binToFreq(K)))),h.beginPath();let vi=[];for(let W=0;W<oh;W++){const K=M[W],{posX:Z,barCenter:pe,width:ke,freq:We,binLo:_t,binHi:Bt,ratioLo:Ut,ratioHi:xn}=K;let Re=Math.max(fs(_t,Ut),fs(Bt,xn));for(let he=_t+1;he<Bt;he++)rt[he]>Re&&(Re=rt[he]);if(Re=this._normalizedB(Re),K.value[V]=Re,sh+=Re,K.peak[V]>0&&K.alpha[V]>0&&(K.hold[V]--,K.hold[V]<0)){if(E&&!mi){const he=!r||u&&P>0?1:r?K.peak[V]:D;K.alpha[V]=he*(1+K.hold[V]/Ae)}else K.peak[V]+=K.hold[V]*Fe/ge/J0;K.alpha[V]<=0&&(K.peak[V]=0)}if(Re>=K.peak[V]&&(K.peak[V]=Re,K.hold[V]=le,K.alpha[V]=!r||u&&P>0?1:r?Re:D),!Q)continue;h.globalAlpha=l||r?Re:u?D:1,Sr(Re,W);const je=l?Ft:a?Zt(Re):Re*Ft|0;if(ie==_n){const he=W?0:(this._normalizedB(rt[M[1].binLo])*Ft+je)/2;if($){if(W==0&&(re&&h.moveTo(...qe(0,0)),h.lineTo(...qe(0,Z<0?he:je))),Z>=0){const tt=[Z,je];h.lineTo(...qe(...tt)),vi.push(tt)}}else{if(W==0)if(j==-1&&!re)h.moveTo(x,Me-(Z<x?he:je));else{const tt=_t?this._normalizedB(rt[_t-1])*Ft:je;h.moveTo(x-P,Me-tt)}(re||j!=-1||Z>=x)&&h.lineTo(Z,Me-je)}}else if(a){if(ce&&!ne&&(V==0||!ve)){const he=h.globalAlpha;h.strokeStyle=jv,h.globalAlpha=1,vr(pe,oe,Me),h.strokeStyle=h.fillStyle,h.globalAlpha=he}if(pi){const he=l?0:Vt.findLastIndex(sn=>Zt(Re)<=Zt(sn.level));let tt=Me;for(let sn=xt-1;sn>=he;sn--){h.strokeStyle=Vt[sn].color;let lh=Me-(sn==he?je:Zt(Vt[sn].level));vr(pe,tt,lh),tt=lh-gi}}else vr(pe,Me,Me-je)}else if(Z>=x)if($)wr(Z,0,ke,je,u);else if(d){const he=ke/2,tt=Me+he;h.beginPath(),h.moveTo(Z,tt),h.lineTo(Z,tt-je),h.arc(pe,tt-je,he,Yo,yn),h.lineTo(Z+ke,tt),yr(u),h.fill()}else{const he=u?h.lineWidth:0;h.beginPath(),h.rect(Z,Me+he,ke,-je-he),yr(u),h.fill()}const En=K.peak[V],ah=K.alpha[V];if(En>0&&ah>0&&Y&&!mi&&!l&&Z>=x&&Z<mr){if(E?h.globalAlpha=ah:u&&P>0?h.globalAlpha=1:r&&(h.globalAlpha=En),(m==xd||pi)&&Sr(En),a){const he=Zt(En);he>=gi&&h.fillRect(Z,Me-he,ke,gr)}else if(!$)h.fillRect(Z,Me-En*Ft,ke,2);else if(ie!=_n){const he=En*Ft;wr(Z,he,ke,!this._radialInvert||gt||he+I>=2?-2:2)}}}if(Q){if(h.globalAlpha=1,ie==_n){if(Sr(),$&&!re){if(j){let W;for(;W=vi.pop();)h.lineTo(...qe(...W,-1))}h.closePath()}if(P>0&&h.stroke(),D>0){if($){const W=re?nn(vt>>1):0,K=re?nn(vt):yn;h.moveTo(...qe(re?vt>>1:0,0)),h.arc(v,_,I,W,K,re?!tn:!0)}else h.lineTo(mr,Me),h.lineTo(x,Me);h.globalAlpha=D,h.fill(),h.globalAlpha=1}if((mi||$&&Y)&&(vi=[],h.beginPath(),M.forEach((W,K)=>{let Z=W.posX,pe=W.peak[V],ke=K?"lineTo":"moveTo";if($&&Z<0){const We=M[K+1];pe=ny(Z,pe,We.posX,We.peak[V],0),Z=0}pe*=Ft,mi?(h[ke](...$?qe(Z,pe):[Z,Me-pe]),$&&j&&!re&&vi.push([Z,pe])):pe>0&&wr(Z,pe,1,-2)}),mi)){let W;for(;W=vi.pop();)h.lineTo(...qe(...W,-1));h.lineWidth=1,h.stroke()}}h.restore(),re&&!$&&h.setTransform(1,0,0,1,0,0),(!re&&!ve||V)&&Q0(V)}}if(nb(sh/(oh<<rh-1)),Q&&(j&&!$&&!re&&(h.setTransform(-1,0,0,1,S.width-x,0),h.drawImage(S,x,0,v,S.height,0,0,v,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),eb()),this.showFPS){const V=H.height;h.font=`bold ${V}px ${Xi}`,h.fillStyle=Uv,h.textAlign="right",h.fillText(Math.round(L),S.width-V,V*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=C[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:C}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case bn:return Math.log2(e);case Qo:return 26.81*e/(1960+e)-.53;case er:return Math.log2(1+e/700);case ei: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:r,centerX:o,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,f=this._chLayout==ft,g=1-s,v=d?e.height:e.height*(1-s*!f)|0;for(const _ of[0,1]){const w=this._gradients[this._selectedGrads[_]],y=w.colorStops,T=w.dir=="h";let x;if(i?x=n.createRadialGradient(o,a,u,o,a,c-(u-c)*f):x=n.createLinearGradient(...T?[l,0,l+r,0]:[0,0,0,v]),y){const I=f&&!this._splitGradient&&(!T||i);for(let A=0;A<1+I;A++){const M=y.length-1;y.forEach((S,C)=>{let p=S.pos;if(I&&(p/=2),f&&!d&&!i&&!T&&(p*=g,!I&&p>.5*g&&(p+=.5*s)),A==1)if(i||d){const m=M-C;S=y[m],p=1-S.pos/2}else C==0&&p>0&&x.addColorStop(.5,S.color),p+=.5;x.addColorStop(p,S.color),f&&C==M&&p<.5&&x.addColorStop(.5,S.color)})}}this._canvasGradients[_]=x}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,r=l=>10**(l/20);let o=this.maxDecibels,a=this.minDecibels;return n&&(o=r(o),a=r(a),e=r(e)**i),s((e-a)/(o-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,r=window.devicePixelRatio/(this._loRes+1);let o=window.screen.width*r,a=window.screen.height*r;Math.abs(window.orientation)==90&&o<a&&([o,a]=[a,o]);const l=this.isFullscreen,c=l&&this._fsEl==n,u=c?o:(this._width||this._container.clientWidth||this._defaultWidth)*r|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*r|0;this._pixelRatio=r,this._fsWidth=o,this._fsHeight=a,!(e!=Od&&n.width==u&&n.height==d)&&(n.width=u,n.height=d,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,u,d)),i.lineJoin="bevel",s.width=u,s.height=Math.max(20*r,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Fd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Qe(Xv,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"],r=Object.keys(ti).filter(o=>o!="start").concat(i,s);(n||e===void 0)&&(e={...ti,...e});for(const o of Object.keys(e))i.includes(o)&&typeof e[o]!="function"?this[o]=void 0:r.includes(o)&&(this[o]=e[o]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const sy={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}]}},Wd=({stream:t,className:e,onClick:n})=>{var r;const i=de(null),s=Xt();return Ee(()=>{var c;if(!i.current||!t)return;const o=new AudioContext,a=o.createMediaStreamSource(t),l=new iy(i.current,{source:a,audioCtx:o,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 l.registerGradient("gradient",sy[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(r=s.audio_visualizer_config)==null?void 0:r.color,t]),R("div",{onClick:n,className:Ct("w-full",e),ref:i})},Gd=ki(null),zd=({className:t,debug:e=!1})=>{const n=Ns(Gd);return!e||!n||!(n.region||n.dc)?null:R("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[n.region&&R("span",{"data-testid":"connection-info-region",children:["region: ",n.region]}),n.region&&n.dc&&R("span",{children:" · "}),n.dc&&R("span",{"data-testid":"connection-info-dc",children:["dc: ",n.dc]})]})};/**
|
|
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
|
|
21
|
+
*/const qd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),oy=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Kd=t=>{const e=oy(t);return e.charAt(0).toUpperCase()+e.slice(1)},ry=(...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
|
|
26
|
+
*/var ay={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
|
|
31
|
+
*/const ly=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:r,class:o="",...a})=>Ke("svg",{...ay,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",o].join(" "),...a},[...r.map(([l,c])=>Ke(l,c)),...ct(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
|
|
36
|
+
*/const Be=(t,e)=>{const n=({class:i="",children:s,...r})=>Ke(ly,{...r,iconNode:e,class:ry(`lucide-${qd(Kd(t))}`,`lucide-${qd(t)}`,i)},s);return n.displayName=Kd(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
|
|
41
|
+
*/const Xd=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
|
|
46
|
+
*/const cy=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
|
|
51
|
+
*/const Yd=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
|
|
56
|
+
*/const dy=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
|
|
61
|
+
*/const uy=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
|
|
66
|
+
*/const hy=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
|
|
71
|
+
*/const fy=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
|
|
76
|
+
*/const py=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
|
|
81
|
+
*/const my=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
|
|
86
|
+
*/const gy=Be("rotate-ccw",[["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"}]]);/**
|
|
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
|
|
91
|
+
*/const vy=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"}]]);/**
|
|
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
|
|
96
|
+
*/const yy=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"}]]);/**
|
|
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
|
|
101
|
+
*/const _y=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"}]]);/**
|
|
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 Kr=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$d=_i(!1),ay=()=>ba($d),Ct=({children:t,className:e,onClick:n,tooltip:i})=>R("button",{title:i,onClick:n,className:wt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Hd=({call:t,chatMode:e})=>{const[n,i]=ay(),s=()=>{i(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return R("div",{className:"flex items-center justify-center gap-2",children:[!e&&R(Ct,{tooltip:n?"Unmute":"Mute",onClick:s,className:wt(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?R(Qv,{className:"w-5 h-5 text-black dark:text-white"}):R(ey,{className:"w-5 h-5 text-black dark:text-white"})}),R(Ct,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:R(ny,{className:"w-4 h-4 text-black dark:text-white"})})]})},Gd=({call:t,onExpand:e,chatMode:n})=>R(gn.div,{layoutId:Jn,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:[!n&&R(Fd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),R(gd,{stream:t.remoteStream,chatMode:n}),R(pd,{size:"small"}),R(Hd,{call:t,chatMode:n})]}),Wd=_i(null),ly=({className:t})=>{const e=Es(Wd);return!e||!(e.region||e.dc)?null:R("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[e.region&&R("span",{"data-testid":"connection-info-region",children:["region: ",e.region]}),e.region&&e.dc&&R("span",{children:" · "}),e.dc&&R("span",{"data-testid":"connection-info-dc",children:["dc: ",e.dc]})]})};function cy(){const[t,e]=xe(!1),n=qt();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 R("div",{children:[R(Ct,{tooltip:"More",onClick:()=>e(!t),children:R(Ud,{className:"text-black dark:text-white"})}),t&&R("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:[R(Ct,{tooltip:"More",onClick:()=>e(!t),children:R(Ud,{className:"text-black dark:text-white"})}),R("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&R("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",R(ry,{className:"w-4 h-4"})]}),n.report_issue_url&&R("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",R(oy,{className:"w-4 h-4"})]}),n.view_history_url&&R("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",R(Jv,{className:"w-4 h-4"})]})]})]})]})}function dy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Wi={exports:{}},uy=Wi.exports,zd;function hy(){return zd||(zd=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(uy,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,T,E="loglevel";typeof v=="string"?E+=":"+v:typeof v=="symbol"&&(E=void 0);function D(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!E)){try{window.localStorage[E]=b;return}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!E)){try{h=window.localStorage[E]}catch{}if(typeof h===n)try{var b=window.document.cookie,I=encodeURIComponent(E),P=b.indexOf(I+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+I.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!E)){try{window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return T??k??C},y.setLevel=function(h,b){return T=p(h),b!==!1&&D(T),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){T=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(T=p(g)),d.call(y)}r=new m,r.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[w];return y||(y=o[w]=new m(w,r.methodFactory)),y};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Wi)),Wi.exports}var fy=hy();const py=dy(fy),gy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),my="[ai-agent-widget]",Ce=py.getLogger("telnyx-ai-agent-widget"),vy=Ce.methodFactory;Ce.methodFactory=(t,e,n)=>{const i=vy(t,e,n);return function(...s){i(gy(),my,...s)}},Ce.setLevel("info");function yy({onCapture:t,onClose:e}){const n=me(null),i=me(null),s=me(null),[o,r]=xe(null),[a,l]=xe(!0);ke(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){Ce.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?r("No camera found on this device."):f.name==="NotReadableError"||f.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."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const u=n.current,f=i.current,m=f.getContext("2d");if(!m)return;f.width=u.videoWidth,f.height=u.videoHeight,m.drawImage(u,0,0,f.width,f.height);const _=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},d=()=>{s.current&&s.current.getTracks().forEach(u=>u.stop()),e()};return R("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:[R("div",{className:"absolute top-2 right-2 z-10",children:R(Ct,{tooltip:"Close",onClick:d,children:R(Kr,{className:"text-white w-5 h-5"})})}),R("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&R("div",{className:"absolute text-white text-center",children:R("p",{className:"text-sm",children:"Loading camera..."})}),o&&R("div",{className:"text-white text-center max-w-xs",children:[R("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),R("p",{className:"text-xs",children:o}),R("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&&R(rt,{children:[R("video",{ref:n,autoPlay:!0,playsInline:!0,className:wt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),R("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&R("div",{className:"p-3 flex justify-center",children:R("button",{onClick:c,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:[R(jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function _y({item:t,containerRef:e}){const n=me(null);return ke(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),R("li",{className:wt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[R("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),R("div",{className:wt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&R("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&R("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&&R("p",{className:wt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const by=({transcript:t,call:e})=>{const n=me(null),i=me(null),s=me(null),[o,r]=xe([]),[a,l]=xe(!1),[c,d]=xe([]),[,u]=Ur();ke(()=>()=>{o.forEach(S=>URL.revokeObjectURL(S.preview))},[o]),ke(()=>{if(c.length===0)return;const S=t.filter(x=>x.role==="user"&&!x.id.startsWith("optimistic-"));if(S.length>0){const x=S[S.length-1];d(p=>p.filter(g=>g.timestamp>x.timestamp))}},[t,c]);const f=S=>new Promise((x,p)=>{const g=new FileReader;g.onload=()=>x(g.result),g.onerror=p,g.readAsDataURL(S)}),m=async S=>{if(S.type.startsWith("image/"))try{const x=await f(S),p=URL.createObjectURL(S),g={id:Date.now().toString(),file:S,base64:x,preview:p};r(h=>[...h,g])}catch(x){Ce.error("Error processing image:",x)}},_=S=>{r(x=>{const p=x.find(g=>g.id===S);return p&&URL.revokeObjectURL(p.preview),x.filter(g=>g.id!==S)})},v=S=>{const x=S.target,p=x.files;p&&p.length>0&&(Array.from(p).forEach(m),x.value="")},w=S=>{var p;const x=(p=S.clipboardData)==null?void 0:p.items;x&&Array.from(x).forEach(g=>{if(g.type.startsWith("image/")){const h=g.getAsFile();h&&m(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},C=()=>{l(!0)},k=S=>{fetch(S).then(x=>x.blob()).then(x=>{const p=new File([x],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});m(p)}).catch(x=>{Ce.error("Error processing camera capture:",x)})},T=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",x=o.length>0;if(S||x){const g=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:g,timestamp:h,attachments:o.map(I=>({type:"image",url:I.base64}))};d(I=>[...I,b]),x&&u("processing_image"),e.sendConversationMessage(g,o.map(I=>I.base64)),n.current&&(n.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},E=S=>{S.key==="Enter"&&(S.preventDefault(),T())},D=[...t,...c];return R("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:[R("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((S,x)=>R(_y,{item:S,containerRef:s},S.id+x))}),o.length>0&&R("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(S=>R("div",{className:"relative",children:[R("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),R("button",{onClick:()=>_(S.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:R(Kr,{className:"w-3 h-3"})})]},S.id))}),R("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:[R("input",{ref:n,type:"text",onKeyDown:E,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),R("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),R(Ct,{tooltip:"Attach image",onClick:y,children:R(ty,{className:"text-[#969696] w-4 h-4"})}),R(Ct,{tooltip:"Take photo",onClick:C,children:R(jd,{className:"text-[#969696] w-4 h-4"})}),R(Ct,{tooltip:"Send",children:R(iy,{onClick:T,className:"text-[#969696] w-4 h-4"})})]}),a&&R(yy,{onCapture:k,onClose:()=>l(!1)})]})};function wy({onCollapse:t}){return R("div",{className:"flex items-center justify-between w-full",children:[R(cy,{}),R(Ct,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:R(Kr,{className:"text-black dark:text-white"})})]})}const Sy=({call:t,onCollapse:e,transcript:n,chatMode:i})=>R(Bp,{children:R(gn.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:[R("div",{className:"p-4 text-center",children:[R(wy,{onCollapse:e}),!i&&R(Fd,{className:"h-[144px]",stream:t.remoteStream}),R(pd,{size:"large",className:"mb-4"}),R(Hd,{call:t,chatMode:i}),R(ly,{className:"mt-2"})]}),R(gd,{stream:t.remoteStream,chatMode:i}),R(by,{call:t,transcript:n})]})});function zi(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 B(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(d){o(d)}}function a(c){try{l(i.throw(c))}catch(d){o(d)}}function l(c){var d;c.done?s(c.value):(d=c.value,d instanceof n?d:new n(function(u){u(d)})).then(r,a)}l((i=i.apply(t,[])).next())})}var qd=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 xy(){if(!qd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qd(Cy)}for(var Kd=[],qi=0;qi<256;++qi)Kd[qi]=(qi+256).toString(16).substr(1);function _n(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||xy)();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 l=0,c=Kd;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const Xd="wss://rtc.telnyx.com",ky=1006,Yd={urls:"stun:stun.l.google.com:19302"},Ty=[{urls:"stun:stun.telnyx.com:3478"},Yd,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Ay=[{urls:"stun:stundev.telnyx.com:3478"},Yd,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var V;(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",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"})(V||(V={}));var Ey=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jd(t,e){return t(e={exports:{}},e.exports),e.exports}var Iy=Jd(function(t){var e,n;e=Ey,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(w,y){var C=w[y];if(typeof C.bind=="function")return C.bind(w);try{return Function.prototype.bind.call(C,w)}catch{return function(){return Function.prototype.apply.apply(C,[w,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(w,y){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<w?i:this.methodFactory(k,w,y)}this.log=this.debug}function d(w,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[w].apply(this,arguments))}}function u(w,y,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):i)}(w)||d.apply(this,arguments)}function f(w,y,C){var k,T=this;y=y??"WARN";var E="loglevel";function D(){var x;if(typeof window!==s&&E){try{x=window.localStorage[E]}catch{}if(typeof x===s)try{var p=window.document.cookie,g=p.indexOf(encodeURIComponent(E)+"=");g!==-1&&(x=/^([^;]+)/.exec(p.slice(g))[1])}catch{}return T.levels[x]===void 0&&(x=void 0),x}}typeof w=="string"?E+=":"+w:typeof w=="symbol"&&(E=void 0),T.name=w,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=C||u,T.getLevel=function(){return k},T.setLevel=function(x,p){if(typeof x=="string"&&T.levels[x.toUpperCase()]!==void 0&&(x=T.levels[x.toUpperCase()]),!(typeof x=="number"&&x>=0&&x<=T.levels.SILENT))throw"log.setLevel() called with invalid level: "+x;if(k=x,p!==!1&&function(g){var h=(r[g]||"silent").toUpperCase();if(typeof window!==s&&E){try{return void(window.localStorage[E]=h)}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+h+";"}catch{}}}(x),c.call(T,x,w),typeof console===s&&x<T.levels.SILENT)return"No console available for logging"},T.setDefaultLevel=function(x){y=x,D()||T.setLevel(x,!1)},T.resetLevel=function(){T.setLevel(y,!1),function(){if(typeof window!==s&&E){try{return void window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},T.enableAll=function(x){T.setLevel(T.levels.TRACE,x)},T.disableAll=function(x){T.setLevel(T.levels.SILENT,x)};var S=D();S==null&&(S=y),T.setLevel(S,!1)}var m=new f,_={};m.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=_[w];return y||(y=_[w]=new f(w,m.getLevel(),m.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return m.noConflict=function(){return typeof window!==s&&window.log===m&&(window.log=v),m},m.getLoggers=function(){return _},m.default=m,m},t.exports?t.exports=n():e.log=n()});const Zd={debug:0,info:1,warn:2,error:3};class Ry{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||Zd[e]<Zd[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Qd=null;function eu(){return Qd}function tu(t){Qd=t}const A=Iy.getLogger("telnyx"),Ki={trace:0,debug:1,info:2,warn:3,error:4};let nu=Ki.info;function iu(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const Ly=A.methodFactory;A.methodFactory=(t,e,n)=>{const i=Ly(t,e,n);return function(...s){if(Ki[t]>=nu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);i(...r)}const o=eu();if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?iu(a[0]):{args:a.map(iu)}),o.addEntry(t,l,c)}}},A.setLevel("debug",!1);const Xi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{A.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},su=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},bn=t=>t instanceof Function||typeof t=="function",Yi=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Py=/^(ws|wss):\/\//,ru=(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?ru(a,r):{result:s}},ou=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Ji=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),ei=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Xr=t=>{var e,n,i,s,o,r;let a="",l="";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&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function au({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?My(i,t):i,n=s}),resolve:e,reject:n}}const My=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Yr="telnyx-voice-sdk-id";function Kt(){return sessionStorage.getItem(Yr)}var Ie,ut,ee;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Yr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ie||(Ie={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(ut||(ut={})),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"}(ee||(ee={}));const Je={generic:"event",[ee.Display]:"participantData",[ee.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Dy={invalidCredentialsOptions:"InvalidCredentialsOptions"},Oy={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,prefetchIceCandidates:!0};var X,Jr,He,ht,Ne;(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"})(X||(X={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Jr||(Jr={})),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"}(He||(He={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(ht||(ht={})),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"}(Ne||(Ne={}));const wn="GLOBAL",Ue={},ti=(t,e)=>`${t}|${e}`,lu=(t,e=wn)=>ti(t,e)in Ue,Lt=(t,e,n=wn)=>{const i=ti(t,n);i in Ue||(Ue[i]=[]),Ue[i].push(e)},cu=(t,e,n=wn)=>{const i=function(s){Pt(t,i,n),e(s)};return i.prototype.targetRef=e,Lt(t,i,n)},Pt=(t,e,n=wn)=>{if(!lu(t,n))return!1;const i=ti(t,n);if(bn(e))for(let s=Ue[i].length-1;s>=0;s--){const o=Ue[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Ue[i].splice(s,1)}else Ue[i]=[];return Ue[i].length===0&&delete Ue[i],!0},J=(t,e,n=wn,i=!0)=>{const s=i&&n!==wn;if(!lu(t,n))return s&&J(t,e),!1;const o=ti(t,n),r=Ue[o].length;if(!r)return s&&J(t,e),!1;for(let a=r-1;a>=0;a--)Ue[o][a](e);return s&&J(t,e),!0},Zr=t=>{const e=ti(t,"");Object.keys(Ue).filter(n=>n.indexOf(e)===0).forEach(n=>delete Ue[n])};let Ny=typeof WebSocket<"u"?WebSocket:null;const Fy=0,Vy=1,By=2,du=3;class uu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Xd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Xd),n&&(this._host=(r=>`${Py.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===Vy}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Fy}get closing(){return!!this._wsClient&&this._wsClient.readyState===By}get closed(){return!!this._wsClient&&this._wsClient.readyState===du}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=Kt();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"),A.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new Ny(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){const s=i instanceof Error?i:new Error(`Failed to create WebSocket: ${String(i)}`);J(V.Error,{error:s},this.session.uuid),A.error("WebSocket connection failed:",s)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((o,r)=>{if(i.hasOwnProperty("result"))return o();cu(i.id,a=>{const{result:l,error:c}=ru(a);return c?r(c):o(l)})});return A.debug(`SEND:
|
|
106
|
+
*/const by=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"}]]);/**
|
|
107
|
+
* @license lucide-preact v0.515.0 - ISC
|
|
108
|
+
*
|
|
109
|
+
* This source code is licensed under the ISC license.
|
|
110
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
+
*/const nr=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Jd=ki(!1),wy=()=>Ea(Jd),kt=({children:t,className:e,onClick:n,tooltip:i})=>R("button",{title:i,onClick:n,className:Ct("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Zd=({call:t,chatMode:e})=>{const[n,i]=wy(),s=()=>{i(o=>{const a=!o;return a?t.muteAudio():t.unmuteAudio(),a})},r=()=>{t.hangup()};return R("div",{className:"flex items-center justify-center gap-2",children:[!e&&R(kt,{tooltip:n?"Unmute":"Mute",onClick:s,className:Ct(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?R(hy,{className:"w-5 h-5 text-black dark:text-white"}):R(fy,{className:"w-5 h-5 text-black dark:text-white"})}),R(kt,{tooltip:"End Call",onClick:r,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:R(my,{className:"w-4 h-4 text-black dark:text-white"})})]})},Qd=({call:t,onExpand:e,chatMode:n,debug:i=!1})=>R(vn.div,{layoutId:Qn,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:[!n&&R(Wd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),R(Sd,{stream:t.remoteStream,chatMode:n}),R(wd,{size:"small"}),R(Zd,{call:t,chatMode:n}),R(zd,{debug:i})]});function Sy(){const[t,e]=xe(!1),n=Xt();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)},r=()=>{i(n.report_issue_url)},o=()=>{i(n.view_history_url)};return R("div",{children:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Yd,{className:"text-black dark:text-white"})}),t&&R("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:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Yd,{className:"text-black dark:text-white"})}),R("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&R("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",R(_y,{className:"w-4 h-4"})]}),n.report_issue_url&&R("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",R(by,{className:"w-4 h-4"})]}),n.view_history_url&&R("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",R(dy,{className:"w-4 h-4"})]})]})]})]})}function Cy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ji={exports:{}},Ty=Ji.exports,eu;function ky(){return eu||(eu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(Ty,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(_){return _==="debug"&&(_="log"),typeof console===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function g(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),D=b.indexOf(E+"=");D!==-1&&(h=/^([^;]+)/.exec(b.slice(D+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var m=S();m!=null&&(I=p(m)),u.call(y)}o=new g,o.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=r[w];return y||(y=r[w]=new g(w,o.methodFactory)),y};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(Ji)),Ji.exports}var xy=ky();const Ey=Cy(xy),Iy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Ay="[ai-agent-widget]",ue=Ey.getLogger("telnyx-ai-agent-widget"),Ry=ue.methodFactory;ue.methodFactory=(t,e,n)=>{const i=Ry(t,e,n);return function(...s){i(Iy(),Ay,...s)}},ue.setLevel("info");function Ly({onCapture:t,onClose:e}){const n=de(null),i=de(null),s=de(null),[r,o]=xe(null),[a,l]=xe(!0);Ee(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){ue.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?o("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?o("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?o("Camera is already in use by another application."):o("Unable to access camera. Please try again."):o("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const d=n.current,f=i.current,g=f.getContext("2d");if(!g)return;f.width=d.videoWidth,f.height=d.videoHeight,g.drawImage(d,0,0,f.width,f.height);const v=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(_=>_.stop()),t(v),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return R("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:[R("div",{className:"absolute top-2 right-2 z-10",children:R(kt,{tooltip:"Close",onClick:u,children:R(nr,{className:"text-white w-5 h-5"})})}),R("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!r&&R("div",{className:"absolute text-white text-center",children:R("p",{className:"text-sm",children:"Loading camera..."})}),r&&R("div",{className:"text-white text-center max-w-xs",children:[R("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),R("p",{className:"text-xs",children:r}),R("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!r&&R(lt,{children:[R("video",{ref:n,autoPlay:!0,playsInline:!0,className:Ct("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),R("canvas",{ref:i,className:"hidden"})]})]}),!r&&!a&&R("div",{className:"p-3 flex justify-center",children:R("button",{onClick:c,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:[R(Xd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function Dy({item:t,containerRef:e}){const n=de(null);return Ee(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),R("li",{className:Ct("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[R("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),R("div",{className:Ct("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&R("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&R("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&&R("p",{className:Ct("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const Py=({transcript:t,call:e})=>{const n=de(null),i=de(null),s=de(null),[r,o]=xe([]),[a,l]=xe(!1),[c,u]=xe([]),[,d]=Xo();Ee(()=>()=>{r.forEach(S=>URL.revokeObjectURL(S.preview))},[r]),Ee(()=>{if(c.length===0)return;const S=t.filter(C=>C.role==="user"&&!C.id.startsWith("optimistic-"));if(S.length>0){const C=S[S.length-1];u(p=>p.filter(m=>m.timestamp>C.timestamp))}},[t,c]);const f=S=>new Promise((C,p)=>{const m=new FileReader;m.onload=()=>C(m.result),m.onerror=p,m.readAsDataURL(S)}),g=async S=>{if(S.type.startsWith("image/"))try{const C=await f(S),p=URL.createObjectURL(S),m={id:Date.now().toString(),file:S,base64:C,preview:p};o(h=>[...h,m])}catch(C){ue.error("Error processing image:",C)}},v=S=>{o(C=>{const p=C.find(m=>m.id===S);return p&&URL.revokeObjectURL(p.preview),C.filter(m=>m.id!==S)})},_=S=>{const C=S.target,p=C.files;p&&p.length>0&&(Array.from(p).forEach(g),C.value="")},w=S=>{var p;const C=(p=S.clipboardData)==null?void 0:p.items;C&&Array.from(C).forEach(m=>{if(m.type.startsWith("image/")){const h=m.getAsFile();h&&g(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},T=()=>{l(!0)},x=S=>{fetch(S).then(C=>C.blob()).then(C=>{const p=new File([C],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(C=>{ue.error("Error processing camera capture:",C)})},I=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",C=r.length>0;if(S||C){const m=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:m,timestamp:h,attachments:r.map(E=>({type:"image",url:E.base64}))};u(E=>[...E,b]),C&&d("processing_image"),e.sendConversationMessage(m,r.map(E=>E.base64)),n.current&&(n.current.value=""),r.forEach(E=>URL.revokeObjectURL(E.preview)),o([])}},A=S=>{S.key==="Enter"&&(S.preventDefault(),I())},M=[...t,...c];return R("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:[R("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:M.map((S,C)=>R(Dy,{item:S,containerRef:s},S.id+C))}),r.length>0&&R("div",{className:"flex flex-wrap gap-2 mb-2",children:r.map(S=>R("div",{className:"relative",children:[R("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),R("button",{onClick:()=>v(S.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:R(nr,{className:"w-3 h-3"})})]},S.id))}),R("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:[R("input",{ref:n,type:"text",onKeyDown:A,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),R("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:_,className:"hidden"}),R(kt,{tooltip:"Attach image",onClick:y,children:R(py,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Take photo",onClick:T,children:R(Xd,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Send",children:R(vy,{onClick:I,className:"text-[#969696] w-4 h-4"})})]}),a&&R(Ly,{onCapture:x,onClose:()=>l(!1)})]})};function My({onCollapse:t}){return R("div",{className:"flex items-center justify-between w-full",children:[R(Sy,{}),R(kt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:R(nr,{className:"text-black dark:text-white"})})]})}const Ny=({call:t,onCollapse:e,transcript:n,chatMode:i,debug:s=!1})=>R(Zp,{children:R(vn.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:[R("div",{className:"p-4 text-center",children:[R(My,{onCollapse:e}),!i&&R(Wd,{className:"h-[144px]",stream:t.remoteStream}),R(wd,{size:"large",className:"mb-4"}),R(Zd,{call:t,chatMode:i}),R(zd,{className:"mt-2",debug:s})]}),R(Sd,{stream:t.remoteStream,chatMode:i}),R(Py,{call:t,transcript:n})]})});function Zi(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 F(t,e,n,i){return new(n||(n=Promise))(function(s,r){function o(c){try{l(i.next(c))}catch(u){r(u)}}function a(c){try{l(i.throw(c))}catch(u){r(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof n?u:new n(function(d){d(u)})).then(o,a)}l((i=i.apply(t,[])).next())})}var tu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Oy=new Uint8Array(16);function Fy(){if(!tu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return tu(Oy)}for(var nu=[],Qi=0;Qi<256;++Qi)nu[Qi]=(Qi+256).toString(16).substr(1);function wn(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||Fy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var r=0;r<16;++r)e[i+r]=s[r];return e||function(o,a){var l=0,c=nu;return[c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]]].join("")}(s)}const Vy={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,NETWORK_OFFLINE:48001,UNEXPECTED_ERROR:49001},By={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001},{SDP_CREATE_OFFER_FAILED:Uy,SDP_CREATE_ANSWER_FAILED:jy,SDP_SET_LOCAL_DESCRIPTION_FAILED:$y,SDP_SET_REMOTE_DESCRIPTION_FAILED:iu,SDP_SEND_FAILED:su,MEDIA_MICROPHONE_PERMISSION_DENIED:Hy,MEDIA_DEVICE_NOT_FOUND:Wy,MEDIA_GET_USER_MEDIA_FAILED:ou,HOLD_FAILED:Gy,INVALID_CALL_PARAMETERS:zy,BYE_SEND_FAILED:qy,SUBSCRIBE_FAILED:Ky,WEBSOCKET_CONNECTION_FAILED:Xy,WEBSOCKET_ERROR:Yy,RECONNECTION_EXHAUSTED:Jy,GATEWAY_FAILED:Zy,LOGIN_FAILED:ru,INVALID_CREDENTIALS:Qy,AUTHENTICATION_REQUIRED:e_,NETWORK_OFFLINE:t_,UNEXPECTED_ERROR:au}=Vy,{HIGH_RTT:n_,HIGH_JITTER:i_,HIGH_PACKET_LOSS:s_,LOW_MOS:lu,LOW_BYTES_RECEIVED:o_,LOW_BYTES_SENT:r_,ICE_CONNECTIVITY_LOST:a_,ICE_GATHERING_TIMEOUT:l_,ICE_GATHERING_EMPTY:c_,PEER_CONNECTION_FAILED:d_,ONLY_HOST_ICE_CANDIDATES:u_,TOKEN_EXPIRING_SOON:h_,SESSION_NOT_REATTACHED:f_}=By,p_=/^a=candidate:.+typ (srflx|prflx|relay)/m,cu="wss://rtc.telnyx.com",m_=1006,du={urls:"stun:stun.l.google.com:19302"},g_=[{urls:"stun:stun.telnyx.com:3478"},du,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],v_=[{urls:"stun:stundev.telnyx.com:3478"},du,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var O;(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.Warning="telnyx.warning",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",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"})(O||(O={}));const y_={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"]},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"]},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"]},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"]},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"]},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"]},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"]},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"]},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"]},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"]},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"]},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"]},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"]},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"]},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED or FAIL_WAIT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"]},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"]},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"]},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"]},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"]},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"]}},__={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},35001:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server returned an empty reattached_sessions list while the SDK still has an active call. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"]}};function Dt(t,e){const n=__[t];return{code:t,name:n.name,message:n.message,description:n.description,causes:[...n.causes],solutions:[...n.solutions]}}class ni extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,Object.setPrototypeOf(this,ni.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function ii(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Hy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Wy}return ou}function ae(t,e,n){const i=y_[t],s=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new ni({code:t,name:i.name,description:i.description,message:n||i.message,causes:[...i.causes],solutions:[...i.solutions],originalError:s})}var b_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function uu(t,e){return t(e={exports:{}},e.exports),e.exports}var w_=uu(function(t){var e,n;e=b_,n=function(){var i=function(){},s="undefined",r=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function a(w,y){var T=w[y];if(typeof T.bind=="function")return T.bind(w);try{return Function.prototype.bind.call(T,w)}catch{return function(){return Function.prototype.apply.apply(T,[w,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(w,y){for(var T=0;T<o.length;T++){var x=o[T];this[x]=T<w?i:this.methodFactory(x,w,y)}this.log=this.debug}function u(w,y,T){return function(){typeof console!==s&&(c.call(this,y,T),this[w].apply(this,arguments))}}function d(w,y,T){return function(x){return x==="debug"&&(x="log"),typeof console!==s&&(x==="trace"&&r?l:console[x]!==void 0?a(console,x):console.log!==void 0?a(console,"log"):i)}(w)||u.apply(this,arguments)}function f(w,y,T){var x,I=this;y=y??"WARN";var A="loglevel";function M(){var C;if(typeof window!==s&&A){try{C=window.localStorage[A]}catch{}if(typeof C===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(A)+"=");m!==-1&&(C=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return I.levels[C]===void 0&&(C=void 0),C}}typeof w=="string"?A+=":"+w:typeof w=="symbol"&&(A=void 0),I.name=w,I.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},I.methodFactory=T||d,I.getLevel=function(){return x},I.setLevel=function(C,p){if(typeof C=="string"&&I.levels[C.toUpperCase()]!==void 0&&(C=I.levels[C.toUpperCase()]),!(typeof C=="number"&&C>=0&&C<=I.levels.SILENT))throw"log.setLevel() called with invalid level: "+C;if(x=C,p!==!1&&function(m){var h=(o[m]||"silent").toUpperCase();if(typeof window!==s&&A){try{return void(window.localStorage[A]=h)}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+h+";"}catch{}}}(C),c.call(I,C,w),typeof console===s&&C<I.levels.SILENT)return"No console available for logging"},I.setDefaultLevel=function(C){y=C,M()||I.setLevel(C,!1)},I.resetLevel=function(){I.setLevel(y,!1),function(){if(typeof window!==s&&A){try{return void window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},I.enableAll=function(C){I.setLevel(I.levels.TRACE,C)},I.disableAll=function(C){I.setLevel(I.levels.SILENT,C)};var S=M();S==null&&(S=y),I.setLevel(S,!1)}var g=new f,v={};g.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=v[w];return y||(y=v[w]=new f(w,g.getLevel(),g.methodFactory)),y};var _=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=_),g},g.getLoggers=function(){return v},g.default=g,g},t.exports?t.exports=n():e.log=n()});const hu={debug:0,info:1,warn:2,error:3};class S_{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||hu[e]<hu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let fu=null;const k=w_.getLogger("telnyx"),es={trace:0,debug:1,info:2,warn:3,error:4};let pu=es.info;function mu(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const C_=k.methodFactory;k.methodFactory=(t,e,n)=>{const i=C_(t,e,n);return function(...s){if(es[t]>=pu){const o=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)o.push(a);i(...o)}const r=fu;if(r!=null&&r.isActive()){const[o,...a]=s,l=typeof o=="string"?o:JSON.stringify(o);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?mu(a[0]):{args:a.map(mu)}),r.addEntry(t,l,c)}}},k.setLevel("debug",!1);const ts=t=>{const[e,n,i,s,r,o]=t;let a={};try{a=JSON.parse(r.replace(/ID"/g,'Id"'))}catch{k.warn("Verto LA invalid media JSON string:",r)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:o}},gu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Sn=t=>t instanceof Function||typeof t=="function",ns=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):\/\//,vu=(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:r=null,node_id:o=null,result:a=null}=s;return r&&r!=="200"?{error:s}:a?vu(a,o):{result:s}},yu=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),is=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),si=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,ir=t=>{var e,n,i,s,r,o;let a="",l="";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),!((r=t==null?void 0:t.params)===null||r===void 0)&&r.state&&(l=(o=t==null?void 0:t.params)===null||o===void 0?void 0:o.state),a||l};function _u({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?k_(i,t):i,n=s}),resolve:e,reject:n}}const k_=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},sr="telnyx-voice-sdk-id";function Yt(){return sessionStorage.getItem(sr)}var De,pt,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(sr)}),function(t){t.Offer="offer",t.Answer="answer"}(De||(De={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(pt||(pt={})),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 et={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},x_={invalidCredentialsOptions:"InvalidCredentialsOptions"},E_={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,prefetchIceCandidates:!0};var q,or,ze,mt,Ue;(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"})(q||(q={})),function(t){t.Participant="participant",t.Moderator="moderator"}(or||(or={})),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"}(ze||(ze={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(mt||(mt={})),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"}(Ue||(Ue={}));const Cn="GLOBAL",He={},oi=(t,e)=>`${t}|${e}`,bu=(t,e=Cn)=>oi(t,e)in He,Pt=(t,e,n=Cn)=>{const i=oi(t,n);i in He||(He[i]=[]),He[i].push(e)},wu=(t,e,n=Cn)=>{const i=function(s){Mt(t,i,n),e(s)};return i.prototype.targetRef=e,Pt(t,i,n)},Mt=(t,e,n=Cn)=>{if(!bu(t,n))return!1;const i=oi(t,n);if(Sn(e))for(let s=He[i].length-1;s>=0;s--){const r=He[i][s];(e===r||r.prototype&&e===r.prototype.targetRef)&&He[i].splice(s,1)}else He[i]=[];return He[i].length===0&&delete He[i],!0},U=(t,e,n=Cn,i=!0)=>{const s=i&&n!==Cn;if(!bu(t,n))return s&&U(t,e),!1;const r=oi(t,n),o=He[r].length;if(!o)return s&&U(t,e),!1;for(let a=o-1;a>=0;a--)He[r][a](e);return s&&U(t,e),!0},rr=t=>{const e=oi(t,"");Object.keys(He).filter(n=>n.indexOf(e)===0).forEach(n=>delete He[n])};let I_=typeof WebSocket<"u"?WebSocket:null;const A_=0,R_=1,L_=2,Su=3;class Cu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=cu,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":cu),n&&(this._host=(o=>`${T_.test(o)?"":"wss://"}${o}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),r&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===R_}get connecting(){return!!this._wsClient&&this._wsClient.readyState===A_}get closing(){return!!this._wsClient&&this._wsClient.readyState===L_}get closed(){return!!this._wsClient&&this._wsClient.readyState===Su}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=Yt();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"),k.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new I_(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){k.error("WebSocket connection failed:",i);const s=ae(Xy,i);U(O.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((r,o)=>{if(i.hasOwnProperty("result"))return r();wu(i.id,a=>{const{result:l,error:c}=vu(a);return c?o(c):r(l)})});return k.debug(`SEND:
|
|
107
112
|
`,JSON.stringify(i,null,2),`
|
|
108
|
-
`),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;
|
|
109
|
-
`,JSON.stringify(
|
|
110
|
-
`),Ne[`${(s=(i=o==null?void 0:o.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!J(o.id,o)){const a=Xr(o);J(V.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==du?(A.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||J(V.SocketClose,{code:ky,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):A.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(A.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(A.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):A.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_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)),J(V.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else A.warn("Unknown message from socket",e)}}class ni{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:_n()},e)}}const hu={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 Me extends ni{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=zi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in hu)i&&n.hasOwnProperty(i)&&(n[hu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class fu extends Me{constructor(e){super(),this.method=ee.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class jy{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>B(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Xr(n))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const n=new fu(Kt());this.pendingRequestId=n.request.id,this.gatewayStateTask=au({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ne.REGISTER,Ne.REGED].includes(i)}),this.session=e,this.gatewayStateTask=au({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class pu extends Me{constructor(e){super(),this.method=ee.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var gu="2.25.25",Qr=gu;class Uy extends Me{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:Qr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class $y extends Me{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class mu extends Me{toString(){return ee.Invite}}class vu extends Me{toString(){return ee.Answer}}class yu extends Me{toString(){return ee.Attach}}class Hy extends Me{toString(){return ee.Bye}}class Gy extends Me{toString(){return ee.Candidate}}class Wy extends Me{toString(){return ee.EndOfCandidates}}class eo extends Me{toString(){return ee.Modify}}class _u extends Me{toString(){return ee.Info}}class zy extends Me{toString(){return ee.Broadcast}}class qy extends Me{toString(){return ee.Subscribe}}class Ky extends Me{toString(){return ee.Unsubscribe}}class Xy extends Me{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Qr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class Yy{constructor(e){if(this.options=e,this.uuid=_n(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",nu=(i=Ki[n])!==null&&i!==void 0?i:Ki.info,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 uu(this),this.registerAgent=new jy(this)}get __logger(){return A}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*ou(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}),A.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Ji(this.options)||ei(this.options)}broadcast(e){}disconnect(){return B(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(),A.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Lt(e,n,this.uuid),this}off(e,n){return Pt(e,n,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(A.debug("No existing connection found, creating a new one."),this.connection=new uu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(A.debug("Initiating connection to the server..."),this.connection.connect()),A.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){J(V.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return B(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),Ji(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(ei(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";return A.error(s),void J(V.Error,{error:new Error(s),type:Dy.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return B(this,void 0,void 0,function*(){let s;s=e==="login"?new Uy(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Kt()):new Xy({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Kt()});const o=yield this.execute(s).catch(r=>{this._handleLoginError(r),i&&i(r)});o&&(this.sessionid=o.sessid,n&&n())})}_onSocketOpen(){return B(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Zr(this.relayProtocol);for(const e in this.subscriptions)Zr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{A.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Pt(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]={},bn(n)&&Lt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(V.SocketOpen,this._onSocketOpen),this.on(V.SocketClose,this.onNetworkClose),this.on(V.SocketError,this.onNetworkClose),this.on(V.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(V.SocketOpen,this._onSocketOpen),this.off(V.SocketClose,this.onNetworkClose),this.off(V.SocketError,this.onNetworkClose),this.off(V.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&&(A.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new pu(Kt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){A.debug("Ping received"),this._pong=!0}static on(e,n){Lt(e,n)}static off(e){Pt(e)}static uuid(){return _n()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Zi=t=>navigator.mediaDevices.getUserMedia(t),Sn=t=>t&&t instanceof MediaStream,ii=(t,e)=>{const n=Yi(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},bu=(t,e)=>B(void 0,void 0,void 0,function*(){const n=Yi(t);if(n===null)return A.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return A.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Jy=t=>{t&&t.readyState==="live"&&t.stop()},si=t=>{Sn(t)&&t.getTracks().forEach(Jy),t=null},Qi=t=>B(void 0,void 0,void 0,function*(){A.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Zi(t)}catch(i){if(A.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,d=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const u=zi(r,["deviceId"]);c=Object.keys(u).length===0||u}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const u=zi(a,["deviceId"]);d=Object.keys(u).length===0||u}return l?{audio:c,video:d}:null})(t);if(s){A.warn("Device not found or not readable, falling back to default device");try{return yield Zi(s)}catch(o){throw A.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),ri=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===ht.AudioIn||s===ht.AudioOut,video:!s||s===ht.Video}))(t)).catch(s=>(A.error(s),null));if(i){if(si(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}),wu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],es=(t,e,n)=>B(void 0,void 0,void 0,function*(){const i=yield ri(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}),Zy=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},to=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=no(t);return n.includes(e)||i.includes(e)},no=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},Cn=(t,e=null,n=null)=>{if(!Sn(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=>{Cn(t,"audio",!0)},io=t=>{Cn(t,"audio",!1)},Cu=t=>{Cn(t,"audio",null)},Qy=t=>((e,n=null)=>{if(!Sn(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 e_(){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],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,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],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,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("/"),f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,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],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Qi}}catch(t){return t.message}}var _e;function xu(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 ku(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{A.error("playAudio",e),t._playFulfilled=!0}))}function Tu(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"})(_e||(_e={}));const Au=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class t_ extends ni{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:_n(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class xt{constructor(e,n){this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(i){return new Ry(i)}(this.logCollectorOptions),this.logCollector.start(),tu(this.logCollector))}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,A.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return B(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),A.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,o=this.statsBuffer;this.statsBuffer=[];const r=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:o},r.length>0?{logs:r}:{}),{segment:s});return A.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:o.length,logEntries:r.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void A.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void A.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,d=this._segmentIndex,u=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:d}:{});yield this._sendPayload(u,n,i,s)})}sendPayload(e,n,i,s){return B(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";A.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(r=(o=e.logs)===null||o===void 0?void 0:o.length)!==null&&r!==void 0?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:d,body:u}),m=yield f();if(m.ok)A.info(`CallReportCollector: Successfully posted ${c}`);else{const _=yield m.text();A.error(`CallReportCollector: Failed to post ${c}`,{status:m.status,error:_})}}catch(a){A.warn(`CallReportCollector: Network error posting call report, retrying in ${xt.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,xt.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=yield fetch(c,{method:"POST",headers:d,body:JSON.stringify(e)});if(u.ok)A.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield u.text();A.error("CallReportCollector: Failed to post call report on retry",{status:u.status,error:f})}}catch(l){A.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),eu()===this.logCollector&&tu(null),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return B(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const o=yield this.peerConnection.getStats(),r=new Date;let a,l,c=null,d=null,u=null,f=null;if(o.forEach(_=>{switch(_.type){case"outbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(c=_);break;case"inbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(d=_);break;case"candidate-pair":(_.nominated||_.state==="succeeded")&&(u=_);break;case"transport":f=_}}),c){const _=this._getOutboundAudioLevel(o,c);if(_!==null&&this.intervalAudioLevels.outbound.push(_),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.outbound.push(y)}}this.previousStats.outboundBytes=c.bytesSent}if(d){const _=this._getInboundAudioLevel(o,d);if(_!==null&&this.intervalAudioLevels.inbound.push(_),d.jitter!==void 0&&this.intervalJitters.push(1e3*d.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(d.bytesReceived||0)-this.previousStats.inboundBytes,w=(d.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.inbound.push(y)}}this.previousStats.inboundBytes=d.bytesReceived}u&&(u.currentRoundTripTime!==void 0&&this.intervalRTTs.push(u.currentRoundTripTime),this.previousCandidatePairId!==null&&u.id!==this.previousCandidatePairId&&A.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:u.id}),this.previousCandidatePairId=(n=u.id)!==null&&n!==void 0?n:null),u&&(a=this._resolveCandidate(o,u.localCandidateId),l=this._resolveCandidate(o,u.remoteCandidateId)),this.previousStats.timestamp=r.getTime();const m=r.getTime()-this.intervalStartTime.getTime();if(e||m>=this.options.interval){const _=this._createStatsEntry(this.intervalStartTime,r,c,d,u,a,l,f);if(this.statsBuffer.push(_),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),A.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const v=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(v>=xt.STATS_FLUSH_THRESHOLD||w>=xt.LOGS_FLUSH_THRESHOLD){A.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:v,logEntries:w});try{this.onFlushNeeded()}catch(y){A.error("CallReportCollector: onFlushNeeded callback error",{error:y})}}}this.intervalStartTime=r,this._resetIntervalAccumulators()}}catch(o){A.error("CallReportCollector: Error collecting stats",{error:o})}})}_createStatsEntry(e,n,i,s,o,r,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),o&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived},c.ice=Object.assign(Object.assign({id:o.id,state:o.state,nominated:o.nominated,writable:o.writable,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(c.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{})),c}_resolveCandidate(e,n){if(!n)return void A.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void A.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;A.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=n,r===void 0||a===void 0)return null;const l=e-r,c=n-a;if(c<=0)return null;const d=Math.sqrt(l/c);return Math.min(1,Math.max(0,d))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}xt.STATS_FLUSH_THRESHOLD=300,xt.LOGS_FLUSH_THRESHOLD=800,xt.RETRY_DELAY_MS=500;var ts,Eu=Jd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,g,h,b){var I,P,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=p._events)?(P.newListener&&(p.emit("newListener",g,h.listener?h.listener:h),P=p._events),L=P[g]):(P=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=P[g]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(I=o(p))&&0<I&&L.length>I){L.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+g+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=p,O.type=g,O.count=L.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(O)}}else L=P[g]=h,++p._eventsCount;return p}function a(p,g,h){function b(){p.removeListener(g,b),I||(I=!0,h.apply(p,arguments))}var I=!1;return b.listener=h,b}function l(p){var g=this._events;if(g){var h=g[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,g){for(var h=Array(g);g--;)h[g]=p[g];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(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var g,h,b,I,P,L,O,M=p==="error";if(L=this._events)M=M&&L.error==null;else if(!M)return!1;if(O=this.domain,M){if(g=arguments[1],!O){if(g instanceof Error)throw g;var N=new Error('Uncaught, unspecified "error" event. ('+g+")");throw N.context=g,N}return g||(g=new Error('Uncaught, unspecified "error" event')),g.domainEmitter=this,g.domain=O,g.domainThrown=!1,O.emit("error",g),!1}if(!(h=L[p]))return!1;var W=typeof h=="function";switch(b=arguments.length){case 1:(function(j,re,te){if(re)j.call(te);else for(var $=j.length,ae=c(j,$),U=0;U<$;++U)ae[U].call(te)})(h,W,this);break;case 2:(function(j,re,te,$){if(re)j.call(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].call(te,$)})(h,W,this,arguments[1]);break;case 3:(function(j,re,te,$,ae){if(re)j.call(te,$,ae);else for(var U=j.length,q=c(j,U),Z=0;Z<U;++Z)q[Z].call(te,$,ae)})(h,W,this,arguments[1],arguments[2]);break;case 4:(function(j,re,te,$,ae,U){if(re)j.call(te,$,ae,U);else for(var q=j.length,Z=c(j,q),ne=0;ne<q;++ne)Z[ne].call(te,$,ae,U)})(h,W,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(b-1),P=1;P<b;P++)I[P-1]=arguments[P];(function(j,re,te,$){if(re)j.apply(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].apply(te,$)})(h,W,this,I)}return!0},s.prototype.addListener=function(p,g){return r(this,p,g,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,g){return r(this,p,g,!0)},s.prototype.once=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,g)),this},s.prototype.prependOnceListener=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,g)),this},s.prototype.removeListener=function(p,g){var h,b,I,P,L;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===g||h.listener&&h.listener===g)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||g));else if(typeof h!="function"){for(I=-1,P=h.length;0<P--;)if(h[P]===g||h[P].listener&&h[P].listener===g){L=h[P].listener,I=P;break}if(0>I)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(O,M){for(var N=M,W=N+1,j=O.length;W<j;N+=1,W+=1)O[N]=O[W];O.pop()})(h,I);b.removeListener&&this.emit("removeListener",p,L||g)}return this},s.prototype.removeAllListeners=function(p){var g,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,I=Object.keys(h),P=0;P<I.length;++P)(b=I[P])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(g=h[p])=="function")this.removeListener(p,g);else if(g)do this.removeListener(p,g[g.length-1]);while(g[0]);return this},s.prototype.listeners=function(p){var g,h,b=this._events;return b?h=(g=b[p])?typeof g=="function"?[g.listener||g]:function(I){for(var P=Array(I.length),L=0;L<P.length;++L)P[L]=I[L].listener||I[L];return P}(g):[]:h=[],h},s.listenerCount=function(p,g){return typeof p.listenerCount=="function"?p.listenerCount(g):l.call(p,g)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function f(){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 m=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],v=0;256>v;++v)_.push((v+256).toString(16).substr(1));function w(p){var g=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[p[g+0]]+_[p[g+1]]+_[p[g+2]]+_[p[g+3]]+"-"+_[p[g+4]]+_[p[g+5]]+"-"+_[p[g+6]]+_[p[g+7]]+"-"+_[p[g+8]]+_[p[g+9]]+"-"+_[p[g+10]]+_[p[g+11]]+_[p[g+12]]+_[p[g+13]]+_[p[g+14]]+_[p[g+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&m.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(p,g,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function C(p,g){if(!p||!g)return{};const h={...p};if(h.localCandidateId){const b=g.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=g.get(h.remoteCandidateId);h.remote={...b}}return h}function k(p,g,h){return 8*function(b,I,P){const L=b[P],O=I?I[P]:null;return L===null||O===null?null:(L-O)/(b.timestamp-I.timestamp)*1e3}(p,g,h)}function T(p){if(!p.entries)return p;const g={};return p.forEach(function(h,b){g[b]=h}),g}function E(p,g,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of p.values())switch(I.type){case"outbound-rtp":{const P=I.mediaType||I.kind,L={};let O={};if(!["audio","video"].includes(P))continue;if(I.codecId){const M=p.get(I.codecId);M&&(L.clockRate=M.clockRate,L.mimeType=M.mimeType,L.payloadType=M.payloadType)}O=p.get(I.mediaSourceId)||p.get(I.trackId)||{},b[P].outbound.push({...I,...L,track:{...O}});break}case"inbound-rtp":{let P=I.mediaType||I.kind,L={};const O={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const M=p.get(I.codecId);M&&(O.clockRate=M.clockRate,O.mimeType=M.mimeType,O.payloadType=M.payloadType)}if(!b.connection.id&&I.transportId){const M=p.get(I.transportId);if(M&&M.selectedCandidatePairId){const N=p.get(M.selectedCandidatePairId);b.connection=C(N,p)}}L=p.get(I.mediaSourceId)||p.get(I.trackId)||{},b[P].inbound.push({...I,...O,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=I.dataChannelsClosed,b.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=I.mediaType||I.kind;const L={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const O=p.get(I.codecId);O&&(L.clockRate=O.clockRate,L.mimeType=O.mimeType,L.payloadType=O.payloadType)}if(!b.connection.id&&I.transportId){const O=p.get(I.transportId);if(O&&O.selectedCandidatePairId){const M=p.get(O.selectedCandidatePairId);b.connection=C(M,p)}}b.remote[P].inbound.push({...I,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=I.mediaType||I.kind,L={};if(!["audio","video"].includes(P))continue;if(I.codecId){const O=p.get(I.codecId);O&&(L.clockRate=O.clockRate,L.mimeType=O.mimeType,L.payloadType=O.payloadType)}b.remote[P].outbound.push({...I,...L});break}}if(!b.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(b.connection=C(I,p));return b=function(I,P){return P&&(I.audio.inbound.map(L=>{let O=P.audio.inbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesReceived"),L.packetRate=k(L,O,"packetsReceived")}),I.audio.outbound.map(L=>{let O=P.audio.outbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesSent"),L.packetRate=k(L,O,"packetsSent")}),I.video.inbound.map(L=>{let O=P.video.inbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesReceived"),L.packetRate=k(L,O,"packetsReceived")}),I.video.outbound.map(L=>{let O=P.video.outbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesSent"),L.packetRate=k(L,O,"packetsSent")})),I}(b,g),b}let D,S={},x=[];e.WebRTCStats=class extends s{constructor(p){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 g={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=g.getStatsInterval||1e3,this.rawStats=!!g.rawStats,this.statsObject=!!g.statsObject,this.filteredStats=!!g.filteredStats,this.shouldWrapGetUserMedia=!!g.wrapGetUserMedia,typeof g.remote=="boolean"&&(this.remote=g.remote),this.debug=!!g.debug,this.logLevel=g.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,g){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:g})}async addConnection(p){const{pc:g,peerId:h}=p;let{connectionId:b,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(g&&g instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const O=this.peersToMonitor[h][L];if(O.pc===g)throw new Error(`We are already monitoring peer with id ${h}.`);O.pc.connectionState==="closed"&&this.removeConnection({pc:O.pc})}}const P=g.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(L){delete L.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:b,pc:g,remote:I}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((g,h)=>g.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(g=>g.tag===p):this.timeline}get logger(){const p=g=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(g)>-1};return{error(...g){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...g)},warn(...g){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...g)},info(...g){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...g)},debug(...g){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...g)}}}removeConnection(p){let g,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)h in this.peersToMonitor[I]&&(b=this.peersToMonitor[I][h].pc,g=I)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let P in this.peersToMonitor[I])this.peersToMonitor[I][P].pc===b&&(h=P,g=I)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[g][h],Object.values(this.peersToMonitor[g]).length===0&&delete this.peersToMonitor[g],{connectionId:h}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let g in this.peersToMonitor[p]){let h=this.peersToMonitor[p][g].pc;this.removePeerConnectionEventListeners(g,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),x.forEach(p=>{this.removeTrackEventListeners(p)}),x=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(p){let{peerId:g,connectionId:h,pc:b,remote:I}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[g]){if(h in this.peersToMonitor[g])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[g][h]=P}else this.peersToMonitor[g]={[h]:P};this.addPeerConnectionEventListeners(g,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(g=>{this.emitEvent(g)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let g={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);g[p]=this.peersToMonitor[p]}else g=this.peersToMonitor;let h=[];for(const b in g)for(const I in g[b]){const P=g[b][I],L=P.pc;if(L&&!this.checkIfConnectionIsClosed(b,I,L))try{const O=this.getTimestamp(),M=L.getStats(null);if(M){const N=await M,W=this.getTimestamp(),j=T(N),re={remote:P.options.remote},te=E(N,P.stats.parsed,re),$={event:"stats",tag:"stats",peerId:b,connectionId:I,timeTaken:W-O,data:te};this.rawStats===!0&&($.rawStats=N),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),P.stats.parsed=te}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(O){this.logger.error(O)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const g in this.peersToMonitor[p]){const h=this.peersToMonitor[p][g].pc;this.checkIfConnectionIsClosed(p,g,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,g,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let I=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:g,tag:"connection",data:"closed"})}return b}isConnectionClosed(p){return p.connectionState==="closed"||p.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 p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(g=>(p({stream:g}),g),g=>(p({error:g}),Promise.reject(g)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const g={...p};for(const b in g){var h=g[b];this.statsToMonitor.includes(h.type)||delete g[b]}return g}get peerConnectionListeners(){return{icecandidate:(p,g,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:g,data:b.candidate})},track:(p,g,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const I=b.track,P=b.streams[0];p in this.peersToMonitor&&g in this.peersToMonitor[p]&&(this.peersToMonitor[p][g].stream=P),this.addTrackEventListeners(I,g),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:g,data:{stream:P?this.getStreamDetails(P):null,track:I?this.getMediaTrackDetails(I):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:g,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceConnectionState})},icegatheringstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceGatheringState})},icecandidateerror:(p,g,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:g,error:{errorCode:b.errorCode}})},connectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.connectionState})},negotiationneeded:(p,g,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:g})},datachannel:(p,g,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:g,data:b.channel})}}}addPeerConnectionEventListeners(p,g,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${g}.`),S[g]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[g][b]=this.peerConnectionListeners[b].bind(this,p,g,h),h.addEventListener(b,S[g][b],!1)})}parseGetUserMedia(p){try{const g={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(g.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),x.push(h)})),this.emitEvent(g)}catch{}}parseStream(p){const g={audio:[],video:[]};return p.getTracks().forEach(h=>{g[h.kind].push(this.getMediaTrackDetails(h))}),g}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:g=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:g}})},unmute:g=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:g}})},overconstrained:g=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:g}})},ended:g=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:g}}),this.removeTrackEventListeners(g.target)}}}addTrackEventListeners(p,g){S[p.id]={};const h=this.getTrackEventObject(g);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const g=this.getTrackEventObject();Object.keys(g).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const g={...p,timestamp:new Date};this.addToTimeline(g),g.tag&&this.emit(g.tag,g)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,g){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{g.removeEventListener(h,S[p][h],!1)}),delete S[p]),g.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),g.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const g=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),g.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(ts=Eu)&&ts.__esModule&&Object.prototype.hasOwnProperty.call(ts,"default")&&ts.default;var n_=Eu.WebRTCStats;function i_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(c){const{jitter:d,rtt:u}=c,f=d+u/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,f=d/(u+d)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function s_(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 r_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class o_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class a_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function Iu(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 l_(t,e){const n=_n();let i=!1;const s=new n_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&J(V.StatsFrame,function({data:a}){var l,c,d,u,f,m,_,v;const{audio:w,remote:y}=a,{audio:C}=y,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,T=(u=(d=C.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&u!==void 0?u:1/0,E=(m=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&m!==void 0?m:-1,D=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,S=i_({jitter:1e3*k,rtt:1e3*T,packetsLost:D,packetsReceived:E});return{jitter:k,rtt:T,mos:S,quality:s_(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new a_(n,r))});return{get isRunning(){return i},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(i)A.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new r_(n,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0}catch(c){A.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();J(V.StatsReport,a,t.uuid),r==="file"&&function(l,c){const d=new Blob([JSON.stringify(l)],{type:"application/json"}),u=URL.createObjectURL(d),f=document.createElement("a");f.href=u,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(u)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new o_(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const Ru=(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:Je.conferenceUpdate,call:t.calls[s],canvasInfo:c_(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:He.LayerInfo},a);J(V.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:He.LayoutInfo},a);J(V.Notification,l,t.uuid);break}}},c_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return su(e)};class Lu{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=()=>B(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(A.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${r}`),r==="failed"||r==="disconnected"){const a=()=>B(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,d){return B(this,void 0,void 0,function*(){const u={connectionState:c.connectionState,previousConnectionState:d,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const m=f[0].sender,_=m==null?void 0:m.transport;_&&(u.dtlsState=_.state)}c.sctp&&(u.sctpState=c.sctp.state);try{const m=yield c.getStats();m.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(u.candidatePairState=_.state,m.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(u.localCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(u.remoteCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(u.dtlsCipher=_.dtlsCipher,u.srtpCipher=_.srtpCipher,u.tlsVersion=_.tlsVersion,_.dtlsState&&(u.dtlsState=_.dtlsState))})}catch(m){A.error("Error gathering connection state details:",m)}return u})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}r==="failed"&&J(V.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${r}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=r,this._isTrickleIce()&&(r==="connecting"&&performance.mark("peer-connection-connecting"),r==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=()=>{A.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{A.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},A.debug("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===Ie.Offer}get isAnswer(){return this.type===Ie.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return B(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(){this.instance?(A.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{A.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),A.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):A.warn("Cannot log transceivers: peer connection is null")}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=l=>`${l.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(){switch(A.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":J(V.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(A.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){A.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?A.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;this.options.remoteStream=n,s===!1&&ii(i,this.options.remoteStream)}createPeerConnection(){return B(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:Ie.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(J(V.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&Sn(this.options.localStream)&&(A.info("Muting local audio tracks on start"),io(this.options.localStream)),this.options.localStream||(A.warn("No local media stream available"),!this.options.audio)?performance.mark("peer-creation-end"):A.warn("Audio is required but no local stream — skipping negotiation")})}init(){var e;return B(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=l_(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(Sn(i)){const o=i.getAudioTracks();let r=[...o];if(A.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{A.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],A.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(d=>{A.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Au(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={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,c);d.kind==="audio"&&a.length>0&&this._setCodecs(u,a),d.kind==="video"&&l.length>0&&this._setCodecs(u,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&ii(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});A.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Au(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}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);A.info("Add transceiver",e,n)}}_createOffer(){return B(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,A.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){A.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){A.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return A.debug("Skipping negotiation, state:",this.instance.signalingState),A.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:Ie.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){A.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){bn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(Sn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,B(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield es(s,a,ht.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield es(r,l,ht.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Qi(e)})}_isOffer(){return this.type===Ie.Offer}_isAnswer(){return this.type===Ie.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 A.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?A.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(A.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):A.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}const ns=Qr;class Pu{constructor(e,n,i=!1){this.session=e,this._isRecovering=i,this._callReportCollector=null,this.id="",this.state=X[X.New],this.prevState="",this.channels=[],this.role=Jr.Participant,this.extension=null,this._state=X.New,this._prevState=X.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._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(const T in k.constraints)if(k.constraints.hasOwnProperty(T)&&k.constraints[T]!==C[T])return}k.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:d,remoteElement:u,options:f,mediaConstraints:{audio:m,video:_},ringtoneFile:v,ringbackFile:w}=e;this.options=Object.assign({},Oy,{audio:m,video:_,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:s,localElement:d,remoteElement:u,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:w,debug:f.debug,debugOutput:f.debugOutput,trickleIce:f.trickleIce,prefetchIceCandidates:f.prefetchIceCandidates,forceRelayCandidate:f.forceRelayCandidate,keepConnectionAliveOnSocketClose:f.keepConnectionAliveOnSocketClose,mutedMicOnStart:f.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.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=xu(this.options.ringtoneFile,"_ringtone"),this._ringback=xu(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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!Qy(this.options.localStream)}invite(){return B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=ut.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new Lu(Ie.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1})}answer(e={}){var n;return B(this,void 0,void 0,function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=ut.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 Lu(Ie.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1})}playRingtone(){ku(this._ringtone)}stopRingtone(){Tu(this._ringtone)}playRingback(){ku(this._ringback)}stopRingback(){Tu(this._ringback)}hangup(e,n){var i,s,o;const r=e||{},a=n!==!1,l=this._state<X.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=r.cause||l.cause,this.causeCode=r.causeCode||l.causeCode,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:[]],r.isRecovering)return this._isRecovering=!0,this.setState(X.Recovering),void this._finalize();this.setState(X.Hangup);const c=()=>{var d;A.debug(`[${this.id}] Closing peer from hangup`),(d=this.peer)===null||d===void 0||d.close(),this.setState(X.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const d=new Hy({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(d).catch(u=>{A.error("telnyx_rtc.bye failed!",u),J(V.Error,{error:u,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new eo({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 eo({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 eo({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 _u({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 _u({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){io(this.options.localStream)}unmuteAudio(){Su(this.options.localStream)}toggleAudioMute(){Cu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return B(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 Zi({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(l=>l.stop()),a.getVideoTracks().forEach(l=>o.addTrack(l)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,Cn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Cn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Cn(e,"video",null)}setVideoDevice(e){return B(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 Zi({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ii(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){io(this.options.remoteStream)}undeaf(){Su(this.options.remoteStream)}toggleDeaf(){Cu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void A.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 A.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"}]),A.info("Parameters: ",r),A.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{A.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>A.error(a))}else A.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){var n;switch(this._prevState=this._state,this._state=e,this.state=X[this._state].toLowerCase(),this.prevState=X[this._prevState].toLowerCase(),A.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case X.Purge:A.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case X.Active:this._isRecovering&&(this._isRecovering=!1,A.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:i,speakerId:s}=this.options;i&&s&&bu(i,s)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case X.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case ee.Answer:if(this.gotAnswer=!0,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),this._state>=X.Active)return;this._state>=X.Early&&this.setState(X.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case ee.Media:if(this._state>=X.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case ee.Display:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===ut.Inbound?ut.Outbound:ut.Inbound,c={type:Je[n],call:this,displayName:o,displayNumber:r,displayDirection:l};J(V.Notification,c,this.id)||J(V.Notification,c,this.session.uuid);break}case ee.Candidate:this._addIceCandidate(i);break;case ee.Info:case ee.Event:{const o=Object.assign(Object.assign({},i),{type:Je.generic,call:this});J(V.Notification,o,this.id)||J(V.Notification,o,this.session.uuid);break}case ee.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 ee.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 B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return A.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:l,modChannel:c,laName:d,conferenceMemberID:u,role:f}=n;this._dispatchConferenceUpdate({action:He.Join,conferenceName:d,participantId:Number(u),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const m=[];for(const _ in s)m.push(Object.assign({callId:s[_][0],index:Number(_)},Xi(s[_][1])));this._dispatchConferenceUpdate({action:He.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:He.Add,callId:o,index:r},Xi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:He.Modify,callId:o,index:r},Xi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:He.Delete,callId:o,index:r},Xi(s)));break;case"clear":this._dispatchConferenceUpdate({action:He.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 B(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:He.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{A.error("ConfChat subscription error:",s)});to(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 B(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,Ru(this.session,o)):A.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{A.error("ConfInfo subscription error:",s)});to(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(X.Active):this.setState(X.Held),!0}_handleChangeHoldStateError(e){return A.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return B(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ie.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(X.Early),this.gotAnswer&&this.setState(X.Active)}).catch(i=>{A.error("Call setRemoteDescription Error: ",i),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})})}_requestAnotherLocalDescription(){bn(this.peer.onSdpReadyTwice)?J(V.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 A.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-${ns}`};switch(o){case Ie.Offer:this.setState(X.Requesting),r=new mu(a);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),r=this.options.attach===!0?new yu(a):new vu(a);break;default:return A.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(l=>{A.error(`${this.id} - Sending ${o} error:`,l),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return A.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-${ns}`};switch(i){case Ie.Offer:this.setState(X.Requesting),s=new mu(o);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),s=this.options.attach===!0?new yu(o):new vu(o);break;default:return A.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===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(r=>{A.error(`${this.id} - Sending ${i} error:`,r),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;if(this._iceTimeout===null){const i=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),i)}e.candidate?A.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(A.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new Gy({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 A.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(()=>{A.debug("Successfully added ICE candidate:",e)}).catch(i=>{A.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Wy({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(A.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Iu(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&&ii(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{A.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&A.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(A.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Iu(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&&ii(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error";this._dispatchNotification({type:Je.userMediaError,error:e,call:this,errorName:n,errorMessage:i}),A.error(`Media error (${n}): ${i}`,e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),A.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),A.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Je.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(J(V.Notification,e,this.id,!1)||J(V.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():_n(),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,Lt(V.MediaError,this._onMediaError,this.id),Lt(V.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Lt(V.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),bn(s)&&Lt(V.Notification,s.bind(this),this.id);const r=this.session.options.enableCallReports!==!1,a=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",c=this.session.options.debugLogMaxEntries||1e3;r&&(this._callReportCollector=new xt({enabled:!0,interval:a},{enabled:!0,level:l,maxEntries:c}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(X.Recovering):this.setState(X.New),A.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),A.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;si(n),si(i),Pt(V.MediaError,null,this.id),Pt(V.PeerConnectionFailureError,null,this.id),Pt(V.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{A.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void A.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void A.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ns},o=this._callReportCollector.flush(s);if(!o)return;const r=Kt()||void 0;this._callReportCollector.sendPayload(o,n,i,r).catch(a=>{A.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void A.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return A.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ns},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void A.error("Cannot post call report: connection host not available");const o=Kt()||void 0;this._callReportCollector.postReport(i,n,s,o).catch(r=>{A.error("Failed to post call report",{error:r})}).finally(()=>{var r;(r=this._callReportCollector)===null||r===void 0||r.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),A.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),A.debug("Stats stopped")}}Pu.setStateTelnyx=t=>{if(t){switch(t._state){case X.Recovering:t.state="recovering";break;case X.Requesting:case X.Trying:case X.Early:t.state="connecting";break;case X.Active:t.state="active";break;case X.Held:t.state="held";break;case X.Hangup:case X.Destroy:t.state="done";break;case X.Answering:t.state="ringing";break;case X.New:t.state="new"}return t}};class Xt extends Pu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new t_(e,n))}hangup(e={},n=!0){this.screenShare instanceof Xt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return B(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Xt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Xt&&this.screenShare.hangup()}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&bu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(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
|
-
${
|
|
113
|
-
`,Object.keys(
|
|
114
|
-
`)}))}),A.info(i)}),2e3)}}class d_ extends Yy{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return B(this,void 0,void 0,function*(){try{const i=yield Qi({audio:e,video:n});return si(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(X.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(cu(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.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 ri().catch(e=>(J(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return ri(ht.Video).catch(e=>(J(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ri(ht.AudioIn).catch(e=>(J(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ri(ht.AudioOut).catch(e=>(A.error("getAudioOutDevices",e),J(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return es(e,n,i)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(n=>B(void 0,void 0,void 0,function*(){const i=[],s=yield Qi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<wu.length;r++){const[a,l]=wu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return si(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(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=zi(e,["micId","micLabel"]);return Zy(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield es(o,r,a).catch(u=>null);d&&(l.deviceId={exact:d})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?Ay:Ty}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Yi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Yi(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 zy({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 B(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new qy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=no(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return B(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new Ky({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=no(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&&(A.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,A.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 Xt.setStateTelnyx(e)}}class Mu{constructor(e,n){this.code=n,this.message=e}}class u_{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,n){const i=new $y(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ou(2,6)}handleMessage(e){var n,i,s;const{session:o}=this,{id:r,method:a,params:l={},voice_sdk_id:c}=e,d=l==null?void 0:l.callID,u=l==null?void 0:l.eventChannel,f=l==null?void 0:l.eventType,m=o.calls[d],_=(n=m==null?void 0:m.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(f==="channelPvtData")return this._handlePvtEvent(l.pvtData);const v=(C=!1)=>{var k,T,E,D,S,x;const p={audio:!0,video:o.options.video,remoteSdp:l.sdp,destinationNumber:l.callee_id_number,remoteCallerName:l.caller_id_name,remoteCallerNumber:l.caller_id_number,callerName:l.callee_id_name,callerNumber:l.callee_id_number,attach:a===ee.Attach,mediaSettings:l.mediaSettings,debug:(k=o.options.debug)!==null&&k!==void 0&&k,debugOutput:(T=o.options.debugOutput)!==null&&T!==void 0?T:"socket",trickleIce:a!==ee.Attach&&(E=o.options.trickleIce)!==null&&E!==void 0&&E,prefetchIceCandidates:(D=o.options.prefetchIceCandidates)===null||D===void 0||D,forceRelayCandidate:(S=o.options.forceRelayCandidate)!==null&&S!==void 0&&S,keepConnectionAliveOnSocketClose:(x=o.options.keepConnectionAliveOnSocketClose)!==null&&x!==void 0&&x};d&&(p.id=d),l.telnyx_call_control_id&&(p.telnyxCallControlId=l.telnyx_call_control_id),l.telnyx_session_id&&(p.telnyxSessionId=l.telnyx_session_id),l.telnyx_leg_id&&(p.telnyxLegId=l.telnyx_leg_id),l.client_state&&(p.clientState=l.client_state),l.dialogParams&&l.dialogParams.custom_headers&&l.dialogParams.custom_headers.length&&(p.customHeaders=l.dialogParams.custom_headers);const g=new Xt(o,p,C);return g.nodeId=this.nodeId,g},w=new fu(c),y=new pu(c);switch(a){case ee.Answer:case ee.Display:case ee.Candidate:case ee.Ringing:case ee.Bye:case ee.Media:if(!d||!m)return void A.error(`Received ${a} for non existing call:`,l);m.handleMessage(e),this._ack(r,a);break;case ee.Ping:this.session.setPingReceived(),this.session.execute(y).then(()=>{this.receivedAuthenticationRequired=0}).catch(T=>B(this,void 0,void 0,function*(){T.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(A.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}));break;case ee.Punt:o.options.keepConnectionAliveOnSocketClose&&_?(A.info(`[${new Date().toISOString()}][${d}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case ee.Invite:{const T=v();T.direction=ut.Inbound,T.playRingtone(),T.setState(X.Ringing),this._ack(r,a);break}case ee.Attach:{if(!m)return v().answer(),void this._ack(r,a);const T=!!m;A.info(`[${new Date().toISOString()}][${d}] closing existing call on ATTACH.`),m.hangup({isRecovering:T},!1),A.info(`[${new Date().toISOString()}][${d}] Attach: Creating new call for recovery`),v(T).answer(),this._ack(r,a);break}case ee.Event:case"webrtc.event":if(!u)return void A.error("Verto received an unknown event:",l);const C=o.relayProtocol,k=u.split(".")[0];o._existsSubscription(C,u)?J(C,l,u):u===o.sessionid?this._handleSessionEvent(l.eventData):o._existsSubscription(C,k)?J(C,l,k):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):J(V.Notification,l,o.uuid);break;case ee.Info:l.type=Je.generic,J(V.Notification,l,o.uuid);break;case ee.ClientReady:this.session.execute(w);break;default:{const T=Xr(e);if(T){switch(T){case Ne.REGISTER:case Ne.REGED:if(o.connection.previousGatewayState!==Ne.REGED&&o.connection.previousGatewayState!==Ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const E=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;E&&(o.callReportId=E,A.debug("Captured call_report_id from REGED:",E)),l.type=Je.vertoClientReady,J(V.Ready,l,o.uuid)}break;case Ne.UNREGED:case Ne.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0,J(V.Error,{error:new Mu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{this.session.execute(w)},this.reconnectDelay());break;case Ne.FAILED:case Ne.FAIL_WAIT:if(o.connection.previousGatewayState!==Ne.FAILED&&o.connection.previousGatewayState!==Ne.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,J(V.Error,{error:new Mu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,J(V.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{if(A.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(o.calls).some(E=>{var D;return((D=E.peer)===null||D===void 0?void 0:D.instance)&&!E.signalingStateClosed}))return A.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();A.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:A.warn("GatewayState message unknown method:",e)}break}A.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 B(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const y=f||this._retrieveCallId(w,o);if(y&&n.calls.hasOwnProperty(y)){const C=n.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&m()})}}},v=yield n.vertoSubscribe(_).catch(w=>{A.error("liveArray subscription error:",w)});to(v,o)&&m();break}case"conference-liveArray-part":{let m=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(m=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};J(V.Notification,w,v,!1)||J(V.Notification,w,n.uuid),m===null&&Pt(V.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{m&&(m.channels=m.channels.filter(w=>!v.includes(w)))}).catch(v=>{A.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Ru(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};J(V.Notification,n,this.session.uuid);break}}}}class h_ extends d_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new u_(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(A.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Ji(this.options)||ei(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 Xt(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!!ei(this.options)||!!e.destinationNumber}_onSocketOpen(){return B(this,void 0,void 0,function*(){return Ji(this.options)?this.handleLoginOnSocketOpen():ei(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class f_ extends h_{constructor(e){super(e),A.info(`SDK version: ${gu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return e_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:_e.not_supported},{browserName:"Firefox",supported:_e.not_supported},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",features:["audio"],supported:_e.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",features:["audio"],supported:_e.partial}]}]}}function Du(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ou={exports:{}},Nu;function p_(){return Nu||(Nu=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(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function o(l,c,d,u,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],m]:l._events[_].push(m):(l._events[_]=m,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,m=new Array(f);u<f;u++)m[u]=d[u].fn;return m},a.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,f,m){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],w=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),w){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,u),!0;case 5:return v.fn.call(v.context,c,d,u,f),!0;case 6:return v.fn.call(v.context,c,d,u,f,m),!0}for(C=1,y=new Array(w-1);C<w;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var k=v.length,T;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),w){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,d);break;case 4:v[C].fn.call(v[C].context,c,d,u);break;default:if(!y)for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,d){return o(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return o(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!d||m.context===d)&&r(this,f);else{for(var _=0,v=[],w=m.length;_<w;_++)(m[_].fn!==c||u&&!m[_].once||d&&m[_].context!==d)&&v.push(m[_]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(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}(Ou)),Ou.exports}var g_=p_();const so=Du(g_),is=new so;var ro={exports:{}},m_=ro.exports,Fu;function v_(){return Fu||(Fu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(m_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,T,E="loglevel";typeof v=="string"?E+=":"+v:typeof v=="symbol"&&(E=void 0);function D(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!E)){try{window.localStorage[E]=b;return}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!E)){try{h=window.localStorage[E]}catch{}if(typeof h===n)try{var b=window.document.cookie,I=encodeURIComponent(E),P=b.indexOf(I+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+I.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!E)){try{window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return T??k??C},y.setLevel=function(h,b){return T=p(h),b!==!1&&D(T),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){T=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(T=p(g)),d.call(y)}r=new m,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var w=o[v];return w||(w=o[v]=new m(v,r.methodFactory)),w};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(ro)),ro.exports}var y_=v_();const __=Du(y_),b_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Re=__.getLogger("telnyx-ai-agent"),w_=Re.methodFactory;Re.methodFactory=(t,e,n)=>{const i=w_(t,e,n);return function(...s){i(b_(),"-",...s)}},Re.setLevel("info");function S_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const C_=10,x_=500,k_=100,Vu=20;class T_{constructor(e){Y(this,"remoteIntervalId",null);Y(this,"localIntervalId",null);Y(this,"remoteStream",null);Y(this,"localStream",null);Y(this,"remoteAudioContext",null);Y(this,"remoteSource",null);Y(this,"remoteAnalyser",null);Y(this,"localAudioContext",null);Y(this,"localSource",null);Y(this,"localAnalyser",null);Y(this,"thinkingStartTime",null);Y(this,"lastState",null);Y(this,"userIsSpeaking",!1);Y(this,"lastUserAudioTime",null);Y(this,"userSpeechStartTime",null);Y(this,"userSilenceStartTime",null);Y(this,"isFirstAgentSpeech",!0);Y(this,"monitorStartTime",null);Y(this,"volumeThreshold");Y(this,"silenceDurationMs");Y(this,"minSpeechDurationMs");Y(this,"maxLatencyMs");Y(this,"updateAgentState",S_(e=>{Re.debug("AudioStreamMonitor updateAgentState",e),Re.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,is.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??C_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??x_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??k_,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Re.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Re.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Re.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Re.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Re.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=r};this.remoteIntervalId=window.setInterval(s,Vu)}startLocalMonitor(){if(!this.localStream){Re.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Re.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Re.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Re.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Vu)}destroy(){this.stopAudioStreamMonitor()}}function A_(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 I_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function R_(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function L_(t){return E_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function P_(t){if(!I_(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 M_ extends so{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcript",[]);Y(this,"onSocketMessage",n=>{if(A_(n))switch(n.params.type){case"response.text.delta":{const i=L_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),is.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(R_(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=P_(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(V.SocketMessage,this.onSocketMessage)}}class D_ extends so{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcription");Y(this,"agentId");Y(this,"versionId");Y(this,"conversationId");Y(this,"debug");Y(this,"audioStreamMonitor");Y(this,"activeCall");Y(this,"chatMode");Y(this,"dc",null);Y(this,"region",null);Y(this,"callReportId",null);Y(this,"onClientReady",()=>{const n=this.telnyxRTC;this.dc=n.dc??null,this.region=n.region??null,this.callReportId=n.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});Y(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Y(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Y(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Y(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Re.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new f_({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(V.Ready,this.onClientReady),this.telnyxRTC.on(V.Error,this.onClientOrSocketError),this.telnyxRTC.on(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(V.Notification,this.onNotification),this.transcription=new M_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),is.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new T_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(V.Ready,this.onClientReady),this.telnyxRTC.off(V.Error,this.onClientOrSocketError),this.telnyxRTC.off(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(V.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),is.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Re.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){Re.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.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}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Bu={exports:{}},oi={},ju;function O_(){if(ju)return oi;ju=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 oi.Fragment=e,oi.jsx=n,oi.jsxs=n,oi}var Uu;function N_(){return Uu||(Uu=1,Bu.exports=O_()),Bu.exports}N_(),vt(void 0),vt(null);const F_=(t,e,n,i,s,o,r,a,l)=>new D_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l}),V_=(t,e,n,i,s,o,r,a,l)=>{const[c,d]=xe(null),[u,f]=xe(!1),[m,_]=xe(null);return ke(()=>{if(!t)return;const v=F_(t,e,n,i,s,o,r,a,l),w=()=>{f(!0),_(null)},y=()=>{f(!1)},C=k=>{_(k),Ce.error("AI Agent error:",k)};return v.on("agent.connected",w),v.on("agent.disconnected",y),v.on("agent.error",C),v.connect(),d(v),()=>{v.off("agent.connected",w),v.off("agent.disconnected",y),v.off("agent.error",C),v.disconnect()}},[t,e,n,i,s,o,r,a,l]),{client:c,isConnected:u,error:m}},B_="telnyx-ai-agent",Mt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function $u(){const t=document.querySelector(B_);return t instanceof HTMLElement?t:null}function Dt(t,e,n){const i=n||$u();if(!i){Ce.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Ce.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const j_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=me(null),a=wi(Wd);ke(()=>{r.current=$u()},[]),ke(()=>{if(!t)return;const l=r.current,c=()=>{n();const E=t.telnyxRTC,D={dc:(E==null?void 0:E.dc)??null,region:(E==null?void 0:E.region)??null,callReportId:(E==null?void 0:E.callReportId)??null};a(D),Dt(Mt.AGENT_CONNECTED,D,l)},d=()=>{a(null),Dt(Mt.AGENT_DISCONNECTED,void 0,l)},u=T=>{s(T);const E={message:T.message,name:T.name};Dt(Mt.AGENT_ERROR,E,l)},f=T=>{var E;i(T),Dt(Mt.CONVERSATION_UPDATE,{type:T.type,callState:(E=T.call)==null?void 0:E.state},l)},m=T=>{Dt(Mt.TRANSCRIPT_ITEM,T,l)},_=T=>{Dt(Mt.CONVERSATION_AGENT_STATE,T,l)},v=T=>{Dt(Mt.AGENT_AUDIO_MUTE,{muted:T},l)},y=t.telnyxRTC,C=T=>{o(T)},k=T=>{const E=T,D={code:E==null?void 0:E.code,reason:E==null?void 0:E.reason,wasClean:E==null?void 0:E.wasClean,timestamp:new Date().toISOString()};Ce.info("[socket.close]",D),Dt(Mt.SOCKET_CLOSE,D,l)};return y&&typeof y=="object"&&(y.on(V.SocketMessage,C),y.on(V.SocketClose,k)),t.on("agent.connected",c),t.on("agent.disconnected",d),t.on("agent.error",u),t.on("conversation.update",f),t.on("transcript.item",m),t.on("conversation.agent.state",_),t.on("agent.audio.mute",v),()=>{t.off("agent.connected",c),t.off("agent.disconnected",d),t.off("agent.error",u),t.off("conversation.update",f),t.off("transcript.item",m),t.off("conversation.agent.state",_),t.off("agent.audio.mute",v),y&&typeof y=="object"&&(y.off(V.SocketMessage,C),y.off(V.SocketClose,k))}},[t,n,i,s,o,a])},U_=2e3;async function $_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Hu(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 H_=(t,e)=>{const[n,i]=xe([]),[,s]=Ur(),o=me(e);ke(()=>{o.current=e},[e]);const r=me(void 0),a=me(void 0);return ke(()=>{if(!t)return;const c=f=>{i(m=>{const _=m[m.length-1];if(f.role==="assistant"&&_&&Hu(_.id)===Hu(f.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,w=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,y={..._,content:_.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const y={...f,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...m,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=m.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...m];return y[v]={...m[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<U_){const C={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),C]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},d=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:_,thinkingStartedAt:v})=>{(m!==void 0||_!==void 0)&&Ce.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),m!==void 0&&(r.current=m),_!==void 0&&(a.current=_)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var _;const m=(_=f.call)==null?void 0:_.state;(m==="destroy"||m==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",d),t.on("conversation.update",u),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",d),t.off("conversation.update",u)}},[t,s]),{transcript:n,sendMessage:async(c,d)=>{if(!t)return;const u=[];if(d&&d.length>0)for(const f of d)try{const m=await $_(f);u.push(m)}catch(m){throw Ce.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,u)}}},G_=({call:t,client:e,latencySettings:n,chatMode:i})=>{const s=qt(),[o,r]=xe(i?"expanded":s.default_state),a=()=>r("expanded"),l=()=>r("collapsed"),{transcript:c}=H_(e,n),d=me(!1);switch(ke(()=>{if(i&&t&&!d.current){const u="remoteStream"in t?t.remoteStream:null;u&&(d.current=!0,u.getAudioTracks().forEach(f=>{f.enabled=!1,Ce.info(`[ChatMode] Disabled remote audio track: ${f.label}`)}))}},[i,t]),o){case"collapsed":return R(Gd,{onExpand:a,call:t,client:e,chatMode:i});case"expanded":return R(Sy,{transcript:c,onCollapse:l,call:t,chatMode:i});default:return R(Gd,{onExpand:a,call:t,client:e,chatMode:i})}},oo=()=>R(gn.div,{layoutId:Jn,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:R("div",{className:"rounded-full animate-spin",children:R(Zv,{})})}),W_=({call:t,client:e,latencySettings:n,chatMode:i})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(oo,{});case"done":case"purged":case"destroy":return null;case"active":return R(G_,{client:e,call:t,latencySettings:n,chatMode:i});default:return R(oo,{})}},z_=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Gu(){const t=qt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R(z_,{className:"w-8 h-8 mr-2"})}const q_=({client:t,callProps:e,chatMode:n})=>{const i=qt(),s=me(!1),o=yt(()=>{if(!t){Ce.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return ke(()=>{n&&t&&!s.current&&(s.current=!0,Ce.info("[ChatMode] Auto-starting conversation"),o())},[n,t,o]),n?R(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[R(Gu,{}),"Connecting..."]}):R(gn.button,{layoutId:Jn,onClick:o,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:[R(Gu,{}),i.start_call_text]})},K_='@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-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.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}.opacity-60{opacity:.6}.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)}}',X_=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),Y_={duration:.1,ease:"circOut"},J_=({children:t,position:e="fixed"})=>{const n=qt(),s=(e??n.position??"fixed")==="fixed"?R(X_,{children:t}):t;return R("div",{className:wt(n.theme==="dark"&&"dark"),children:R(Hp,{transition:Y_,children:[R("style",{children:K_}),s]})})},Z_=t=>R(gn.div,{layoutId:Jn,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:[R(Yv,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(sy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function ai(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Q_({"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,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":d,"conversation-id":u,"chat-mode":f,region:m,environment:_,position:v="fixed","version-id":w}){const y=ai(e),C=ai(n),k=ai(f),T=ze(()=>{if(l)try{return JSON.parse(l)}catch(U){Ce.error("Invalid JSON for vad attribute:",l,U);return}},[l]),E=ze(()=>({showUserPerceivedLatency:ai(c),showGreetingLatency:ai(d)}),[c,d]),{client:D}=V_(t,_,w,y,C,T,u,k,m),[S,x]=xe(null),[p,g]=xe(!1),[h,b]=xe(!1),[I,P]=xe(!1),[L,O]=xe(!1),M=wi($d),N=Cv(),W={};if(i&&(W.destinationNumber=i),s&&(W.callerNumber=s),o&&(W.callerName=o),r)try{W.customHeaders=JSON.parse(r)}catch(U){Ce.error("Invalid JSON for call-custom-headers attribute:",r,U)}if(a)try{W.audio=JSON.parse(a);const U=W.audio;if(typeof U=="object"){const q=navigator.mediaDevices.getSupportedConstraints();Object.keys(U).forEach(Z=>{q[Z]||Ce.warn(`Audio constraint not supported by browser: ${Z}`)})}}catch(U){Ce.error("Invalid JSON for call-audio attribute:",a,U)}const j=yt(()=>{g(!1)},[]),re=yt(U=>{var q;if(((q=U.call)==null?void 0:q.state)==="destroy")return M(!1),O(!0),x(null);x(U)},[M]),te=yt(()=>{g(!1),b(!0)},[]),$=yt(U=>{if(Sv(U)){const q=U.params.widget_settings;q&&Object.keys(q).length>0&&(N(q),P(!0))}},[N]);return j_(D,{onReady:j,onConversationUpdate:re,onError:te,onConfigMessage:$}),R(J_,{position:v,children:t?h?R(Z_,{agentId:t}):p?R(oo,{}):S!=null&&S.call?R(W_,{call:S.call,client:D,latencySettings:E,chatMode:k}):I?R(q_,{client:D,callProps:W,chatMode:k&&!L}):null:R("div",{children:"Please provide an assistant ID."})})}ah(Q_,"telnyx-ai-agent",bv,{shadow:!0})})();
|
|
113
|
+
`),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;Sn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>U(O.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),U(O.SocketClose,n,this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=ae(Yy);return U(O.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),U(O.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=n=>{var i,s;const r=gu(n.data);var o;if(typeof r!="string"){if(r.voice_sdk_id&&(o=r.voice_sdk_id,sessionStorage.setItem(sr,o)),this._unsetTimer(r.id),k.debug(`RECV:
|
|
114
|
+
`,JSON.stringify(r,null,2),`
|
|
115
|
+
`),Ue[`${(s=(i=r==null?void 0:r.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!U(r.id,r)){const a=ir(r);U(O.SocketMessage,r,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Su?(k.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||U(O.SocketClose,{code:m_,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):k.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(k.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(k.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):k.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_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)),U(O.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else k.warn("Unknown message from socket",e)}}class ri{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:wn()},e)}}const Tu={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 Oe extends ri{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Zi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in Tu)i&&n.hasOwnProperty(i)&&(n[Tu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class ku extends Oe{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class D_{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>F(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(ir(n))}),this.getIsRegistered=()=>F(this,void 0,void 0,function*(){const n=new ku(Yt());this.pendingRequestId=n.request.id,this.gatewayStateTask=_u({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ue.REGISTER,Ue.REGED].includes(i)}),this.session=e,this.gatewayStateTask=_u({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class xu extends Oe{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var Eu="2.26.2",ar=Eu;class P_ extends Oe{constructor(e,n,i,s,r={},o){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:r,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:ar,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class M_ extends Oe{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Iu extends Oe{toString(){return te.Invite}}class Au extends Oe{toString(){return te.Answer}}class Ru extends Oe{toString(){return te.Attach}}class N_ extends Oe{toString(){return te.Bye}}class O_ extends Oe{toString(){return te.Candidate}}class F_ extends Oe{toString(){return te.EndOfCandidates}}class lr extends Oe{toString(){return te.Modify}}class Lu extends Oe{toString(){return te.Info}}class V_ extends Oe{toString(){return te.Broadcast}}class B_ extends Oe{toString(){return te.Subscribe}}class U_ extends Oe{toString(){return te.Unsubscribe}}class j_ extends Oe{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:r,userVariables:o,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:l,"User-Agent":{sdkVersion:ar,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),r&&(c.target_params=r),this.buildRequest({method:this.method,params:c})}}class ai{constructor(e){if(this.options=e,this.uuid=wn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._tokenExpiryTimeout=null,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",pu=(i=es[n])!==null&&i!==void 0?i:es.info,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 Cu(this),this.registerAgent=new D_(this)}get __logger(){return k}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return F(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*yu(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e).catch(n=>F(this,void 0,void 0,function*(){if((n==null?void 0:n.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const i=ae(e_,n);U(O.Error,{error:i,sessionId:this.sessionid},this.uuid)}yield this.login()}throw n})):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),k.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return is(this.options)||si(this.options)}broadcast(e){}disconnect(){return F(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),k.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Pt(e,n,this.uuid),this}off(e,n){return Mt(e,n,this.uuid),this}connect(){return F(this,void 0,void 0,function*(){this.connection||(k.debug("No existing connection found, creating a new one."),this.connection=new Cu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(k.debug("Initiating connection to the server..."),this.connection.connect()),k.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){const n=ae(ru,e);U(O.Error,{error:n,sessionId:this.sessionid},this.uuid)}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const n=e.split(".");if(n.length!==3)return;const i=JSON.parse(atob(n[1])).exp;if(typeof i!="number")return;const s=i-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ai.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const r=1e3*(s-ai.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},r)}}catch{k.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Dt(h_);U(O.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:n,onError:i}={}){return F(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),is(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(si(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";k.error(s);const r=ae(Qy,void 0,s);return void U(O.Error,{error:r,type:x_.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return F(this,void 0,void 0,function*(){let s;s=e==="login"?new P_(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Yt()):new j_({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Yt()});const r=yield this.execute(s).catch(o=>{this._handleLoginError(o),i&&i(o)});r&&(this.sessionid=r.sessid,this._checkTokenExpiry(),n&&n())})}_onSocketOpen(){return F(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&rr(this.relayProtocol);for(const e in this.subscriptions)rr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{k.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Mt(e,null,n)):(delete this.subscriptions[e],rr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Sn(n)&&Pt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(O.SocketOpen,this._onSocketOpen),this.on(O.SocketClose,this.onNetworkClose),this.on(O.SocketError,this.onNetworkClose),this.on(O.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(O.SocketOpen,this._onSocketOpen),this.off(O.SocketClose,this.onNetworkClose),this.off(O.SocketError,this.onNetworkClose),this.off(O.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&&(k.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new xu(Yt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){k.debug("Ping received"),this._pong=!0}static on(e,n){Pt(e,n)}static off(e){Mt(e)}static uuid(){return wn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ai.TOKEN_EXPIRY_WARNING_SECONDS=120;const ss=t=>navigator.mediaDevices.getUserMedia(t),Tn=t=>t&&t instanceof MediaStream,li=(t,e)=>{const n=ns(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},Du=(t,e)=>F(void 0,void 0,void 0,function*(){const n=ns(t);if(n===null)return k.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return k.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),$_=t=>{t&&t.readyState==="live"&&t.stop()},ci=t=>{Tn(t)&&t.getTracks().forEach($_),t=null},os=t=>F(void 0,void 0,void 0,function*(){k.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield ss(t)}catch(i){if(k.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(r=>{const{audio:o,video:a}=r;let l=!1,c=o,u=a;if(typeof o=="object"&&o!==null&&"deviceId"in o){l=!0;const d=Zi(o,["deviceId"]);c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Zi(a,["deviceId"]);u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){k.warn("Device not found or not readable, falling back to default device");try{return yield ss(s)}catch(r){throw k.error("Fallback getUserMedia also failed: ",r),i}}}throw i}}),di=(t=null,e=!1)=>F(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===mt.AudioIn||s===mt.AudioOut,video:!s||s===mt.Video}))(t)).catch(s=>(k.error(s),null));if(i){if(ci(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(r=>r.kind===t)),e===!0)return n;const s=[];n=n.filter(r=>{if(!r.groupId)return!0;const o=`${r.kind}-${r.groupId}`;return!s.includes(o)&&(s.push(o),!0)})}return n}),Pu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],rs=(t,e,n)=>F(void 0,void 0,void 0,function*(){const i=yield di(n,!0);for(let s=0;s<i.length;s++){const{deviceId:r,label:o}=i[s];if(t===r||e===o)return r}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]})},cr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=dr(t);return n.includes(e)||i.includes(e)},dr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},kn=(t,e=null,n=null)=>{if(!Tn(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}})},Mu=t=>{kn(t,"audio",!0)},ur=t=>{kn(t,"audio",!1)},Nu=t=>{kn(t,"audio",null)},W_=t=>((e,n=null)=>{if(!Tn(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 G_(){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 u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),r=window.RTCPeerConnection,o=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(r&&o&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!r,supportSessionDescription:!!o,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!os}}catch(t){return t.message}}var we;function Ou(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 Fu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{k.error("playAudio",e),t._playFulfilled=!0}))}function Vu(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"})(we||(we={}));const Bu=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class z_ extends ri{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:wn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class Ce{constructor(e,n){var i;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new S_(s)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,fu=i)}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,k.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return F(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),k.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,r=this.statsBuffer;this.statsBuffer=[];const o=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:r},o.length>0?{logs:o}:{}),{segment:s});return k.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:r.length,logEntries:o.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var r,o;return F(this,void 0,void 0,function*(){const a=(r=this.logCollector)===null||r===void 0?void 0:r.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void k.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void k.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(o=this.callEndTime)===null||o===void 0?void 0:o.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,n,i,s)})}sendPayload(e,n,i,s){return F(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var r,o;return F(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";k.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(o=(r=e.logs)===null||r===void 0?void 0:r.length)!==null&&o!==void 0?o:0,callId:e.summary.callId,segment:e.segment});const u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:u,body:d}),g=yield f();if(g.ok)k.info(`CallReportCollector: Successfully posted ${c}`);else{const v=yield g.text();k.error(`CallReportCollector: Failed to post ${c}`,{status:g.status,error:v})}}catch(a){k.warn(`CallReportCollector: Network error posting call report, retrying in ${Ce.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,Ce.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=yield fetch(c,{method:"POST",headers:u,body:JSON.stringify(e)});if(d.ok)k.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield d.text();k.error("CallReportCollector: Failed to post call report on retry",{status:d.status,error:f})}}catch(l){k.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return F(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const r=yield this.peerConnection.getStats(),o=new Date;let a,l,c=null,u=null,d=null,f=null;if(r.forEach(v=>{switch(v.type){case"outbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(c=v);break;case"inbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(u=v);break;case"candidate-pair":(v.nominated||v.state==="succeeded")&&(d=v);break;case"transport":f=v}}),c){const v=this._getOutboundAudioLevel(r,c);if(v!==null&&this.intervalAudioLevels.outbound.push(v),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const y=8*_*1e3/w;this.intervalBitrates.outbound.push(y)}}this.previousStats.outboundBytes=c.bytesSent}if(u){const v=this._getInboundAudioLevel(r,u);if(v!==null&&this.intervalAudioLevels.inbound.push(v),u.jitter!==void 0&&this.intervalJitters.push(1e3*u.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(u.bytesReceived||0)-this.previousStats.inboundBytes,w=(u.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const y=8*_*1e3/w;this.intervalBitrates.inbound.push(y)}}this.previousStats.inboundBytes=u.bytesReceived}d&&(d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),this.previousCandidatePairId!==null&&d.id!==this.previousCandidatePairId&&k.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:d.id}),this.previousCandidatePairId=(n=d.id)!==null&&n!==void 0?n:null),d&&(a=this._resolveCandidate(r,d.localCandidateId),l=this._resolveCandidate(r,d.remoteCandidateId)),this.previousStats.timestamp=o.getTime();const g=o.getTime()-this.intervalStartTime.getTime();if(e||g>=this.options.interval){const v=this._createStatsEntry(this.intervalStartTime,o,c,u,d,a,l,f);if(this.statsBuffer.push(v),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),k.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const _=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(_>=Ce.STATS_FLUSH_THRESHOLD||w>=Ce.LOGS_FLUSH_THRESHOLD){k.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:_,logEntries:w});try{this.onFlushNeeded()}catch(y){k.error("CallReportCollector: onFlushNeeded callback error",{error:y})}}}this._checkQualityWarnings(v,u),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(r){k.error("CallReportCollector: Error collecting stats",{error:r})}})}_checkQualityWarnings(e,n){var i,s,r,o,a,l,c,u,d,f,g,v,_,w,y,T,x;if(!this.onWarning)return;const I=(i=e.connection)===null||i===void 0?void 0:i.roundTripTimeAvg,A=(r=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||r===void 0?void 0:r.jitterAvg;let M;if(n){const S=(o=n.packetsReceived)!==null&&o!==void 0?o:0,C=(a=n.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const p=S-this._prevPacketsReceived,m=C-this._prevPacketsLost,h=p+m;h>0&&(M=m/h*100)}this._prevPacketsReceived=S,this._prevPacketsLost=C}if(this._trackBreach(n_,I!==void 0&&I>Ce.THRESHOLD_RTT_MS),this._trackBreach(i_,A!==void 0&&A>Ce.THRESHOLD_JITTER_MS),this._trackBreach(s_,M!==void 0&&M>Ce.THRESHOLD_PACKET_LOSS_PCT),I!==void 0&&A!==void 0&&M!==void 0){const S=93.2-.11*A-2.5*M-.01*(1e3*I),C=Math.max(1,Math.min(4.5,1+.035*S+S*(S-60)*(100-S)*7e-6));this._trackBreach(lu,C<Ce.THRESHOLD_MOS)}else this._trackBreach(lu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(f=(d=(u=S==null?void 0:S.audio)===null||u===void 0?void 0:u.inbound)===null||d===void 0?void 0:d.bytesReceived)!==null&&f!==void 0?f:0,p=(g=e.audio.inbound.bytesReceived)!==null&&g!==void 0?g:0;this._trackBreach(o_,p-C==0)}if(((_=(v=e.audio)===null||v===void 0?void 0:v.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(T=(y=(w=S==null?void 0:S.audio)===null||w===void 0?void 0:w.outbound)===null||y===void 0?void 0:y.bytesSent)!==null&&T!==void 0?T:0,p=(x=e.audio.outbound.bytesSent)!==null&&x!==void 0?x:0;this._trackBreach(r_,p-C==0)}}_trackBreach(e,n){var i,s,r;if(n){if(this._breachCounters[e]=((i=this._breachCounters[e])!==null&&i!==void 0?i:0)+1,this._breachCounters[e]>=Ce.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();if(o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=Ce.WARNING_THROTTLE_MS){this._lastWarningEmitted[e]=o;try{const a=Dt(e);k.warn(`CallReportCollector: warning ${a.code}: ${a.message}`),(r=this.onWarning)===null||r===void 0||r.call(this,a)}catch(a){k.error(`CallReportCollector: Failed to emit warning ${e}`,{error:a})}}}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_createStatsEntry(e,n,i,s,r,o,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),r&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:r.packetsSent,packetsReceived:r.packetsReceived,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},c.ice=Object.assign(Object.assign({id:r.id,state:r.state,nominated:r.nominated,writable:r.writable,requestsSent:r.requestsSent,responsesReceived:r.responsesReceived},o?{local:o}:{}),a?{remote:a}:{})),l&&(c.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{})),c}_resolveCandidate(e,n){if(!n)return void k.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void k.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;k.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",r=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",o=this.previousStats[s],a=this.previousStats[r];if(this.previousStats[s]=e,this.previousStats[r]=n,o===void 0||a===void 0)return null;const l=e-o,c=n-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}Ce.STATS_FLUSH_THRESHOLD=300,Ce.LOGS_FLUSH_THRESHOLD=800,Ce.CONSECUTIVE_BREACHES_REQUIRED=3,Ce.THRESHOLD_RTT_MS=.4,Ce.THRESHOLD_JITTER_MS=30,Ce.THRESHOLD_PACKET_LOSS_PCT=1,Ce.THRESHOLD_MOS=3.5,Ce.WARNING_THROTTLE_MS=15e3,Ce.RETRY_DELAY_MS=500;var as,Uu=uu(function(t,e){var n;function i(){}function s(){s.init.call(this)}function r(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function o(p,m,h,b){var E,D,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((D=p._events)?(D.newListener&&(p.emit("newListener",m,h.listener?h.listener:h),D=p._events),L=D[m]):(D=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=D[m]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(E=r(p))&&0<E&&L.length>E){L.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=m,N.count=L.length,function(P){typeof console.warn=="function"?console.warn(P):console.log(P)}(N)}}else L=D[m]=h,++p._eventsCount;return p}function a(p,m,h){function b(){p.removeListener(m,b),E||(E=!0,h.apply(p,arguments))}var E=!1;return b.listener=h,b}function l(p){var m=this._events;if(m){var h=m[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,m){for(var h=Array(m);m--;)h[m]=p[m];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(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return r(this)},s.prototype.emit=function(p){var m,h,b,E,D,L,N,P=p==="error";if(L=this._events)P=P&&L.error==null;else if(!P)return!1;if(N=this.domain,P){if(m=arguments[1],!N){if(m instanceof Error)throw m;var B=new Error('Uncaught, unspecified "error" event. ('+m+")");throw B.context=m,B}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(h=L[p]))return!1;var X=typeof h=="function";switch(b=arguments.length){case 1:(function(j,ie,ne){if(ie)j.call(ne);else for(var $=j.length,ce=c(j,$),Y=0;Y<$;++Y)ce[Y].call(ne)})(h,X,this);break;case 2:(function(j,ie,ne,$){if(ie)j.call(ne,$);else for(var ce=j.length,Y=c(j,ce),Q=0;Q<ce;++Q)Y[Q].call(ne,$)})(h,X,this,arguments[1]);break;case 3:(function(j,ie,ne,$,ce){if(ie)j.call(ne,$,ce);else for(var Y=j.length,Q=c(j,Y),ee=0;ee<Y;++ee)Q[ee].call(ne,$,ce)})(h,X,this,arguments[1],arguments[2]);break;case 4:(function(j,ie,ne,$,ce,Y){if(ie)j.call(ne,$,ce,Y);else for(var Q=j.length,ee=c(j,Q),H=0;H<Q;++H)ee[H].call(ne,$,ce,Y)})(h,X,this,arguments[1],arguments[2],arguments[3]);break;default:for(E=Array(b-1),D=1;D<b;D++)E[D-1]=arguments[D];(function(j,ie,ne,$){if(ie)j.apply(ne,$);else for(var ce=j.length,Y=c(j,ce),Q=0;Q<ce;++Q)Y[Q].apply(ne,$)})(h,X,this,E)}return!0},s.prototype.addListener=function(p,m){return o(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return o(this,p,m,!0)},s.prototype.once=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,m)),this},s.prototype.prependOnceListener=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,m)),this},s.prototype.removeListener=function(p,m){var h,b,E,D,L;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||m));else if(typeof h!="function"){for(E=-1,D=h.length;0<D--;)if(h[D]===m||h[D].listener&&h[D].listener===m){L=h[D].listener,E=D;break}if(0>E)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(N,P){for(var B=P,X=B+1,j=N.length;X<j;B+=1,X+=1)N[B]=N[X];N.pop()})(h,E);b.removeListener&&this.emit("removeListener",p,L||m)}return this},s.prototype.removeAllListeners=function(p){var m,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,E=Object.keys(h),D=0;D<E.length;++D)(b=E[D])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[p])=="function")this.removeListener(p,m);else if(m)do this.removeListener(p,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(p){var m,h,b=this._events;return b?h=(m=b[p])?typeof m=="function"?[m.listener||m]:function(E){for(var D=Array(E.length),L=0;L<D.length;++L)D[L]=E[L].listener||E[L];return D}(m):[]:h=[],h},s.listenerCount=function(p,m){return typeof p.listenerCount=="function"?p.listenerCount(m):l.call(p,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function f(){if(!u&&!(u=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 u(d)}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=[],_=0;256>_;++_)v.push((_+256).toString(16).substr(1));function w(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(v[p[m+0]]+v[p[m+1]]+v[p[m+2]]+v[p[m+3]]+"-"+v[p[m+4]]+v[p[m+5]]+"-"+v[p[m+6]]+v[p[m+7]]+"-"+v[p[m+8]]+v[p[m+9]]+"-"+v[p[m+10]]+v[p[m+11]]+v[p[m+12]]+v[p[m+13]]+v[p[m+14]]+v[p[m+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&g.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(p,m,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function T(p,m){if(!p||!m)return{};const h={...p};if(h.localCandidateId){const b=m.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=m.get(h.remoteCandidateId);h.remote={...b}}return h}function x(p,m,h){return 8*function(b,E,D){const L=b[D],N=E?E[D]:null;return L===null||N===null?null:(L-N)/(b.timestamp-E.timestamp)*1e3}(p,m,h)}function I(p){if(!p.entries)return p;const m={};return p.forEach(function(h,b){m[b]=h}),m}function A(p,m,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const E of p.values())switch(E.type){case"outbound-rtp":{const D=E.mediaType||E.kind,L={};let N={};if(!["audio","video"].includes(D))continue;if(E.codecId){const P=p.get(E.codecId);P&&(L.clockRate=P.clockRate,L.mimeType=P.mimeType,L.payloadType=P.payloadType)}N=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[D].outbound.push({...E,...L,track:{...N}});break}case"inbound-rtp":{let D=E.mediaType||E.kind,L={};const N={};if(!["audio","video"].includes(D))if(E.id.includes("Video"))D="video";else{if(!E.id.includes("Audio"))continue;D="audio"}if(E.codecId){const P=p.get(E.codecId);P&&(N.clockRate=P.clockRate,N.mimeType=P.mimeType,N.payloadType=P.payloadType)}if(!b.connection.id&&E.transportId){const P=p.get(E.transportId);if(P&&P.selectedCandidatePairId){const B=p.get(P.selectedCandidatePairId);b.connection=T(B,p)}}L=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[D].inbound.push({...E,...N,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=E.dataChannelsClosed,b.connection.dataChannelsOpened=E.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let D=E.mediaType||E.kind;const L={};if(!["audio","video"].includes(D))if(E.id.includes("Video"))D="video";else{if(!E.id.includes("Audio"))continue;D="audio"}if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}if(!b.connection.id&&E.transportId){const N=p.get(E.transportId);if(N&&N.selectedCandidatePairId){const P=p.get(N.selectedCandidatePairId);b.connection=T(P,p)}}b.remote[D].inbound.push({...E,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const D=E.mediaType||E.kind,L={};if(!["audio","video"].includes(D))continue;if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}b.remote[D].outbound.push({...E,...L});break}}if(!b.connection.id)for(const E of p.values())E.type==="candidate-pair"&&E.nominated&&E.state==="succeeded"&&(b.connection=T(E,p));return b=function(E,D){return D&&(E.audio.inbound.map(L=>{let N=D.audio.inbound.find(P=>P.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.audio.outbound.map(L=>{let N=D.audio.outbound.find(P=>P.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")}),E.video.inbound.map(L=>{let N=D.video.inbound.find(P=>P.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.video.outbound.map(L=>{let N=D.video.outbound.find(P=>P.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")})),E}(b,m),b}let M,S={},C=[];e.WebRTCStats=class extends s{constructor(p){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={...p};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(p,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:m})}async addConnection(p){const{pc:m,peerId:h}=p;let{connectionId:b,remote:E}=p;if(E=typeof E=="boolean"?E:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const N=this.peersToMonitor[h][L];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const D=m.getConfiguration();return D.iceServers&&D.iceServers.forEach(function(L){delete L.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:D}}),this.monitorPeer({peerId:h,connectionId:b,pc:m,remote:E}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(m=>m.tag===p):this.timeline}get logger(){const p=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(p){let m,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let E in this.peersToMonitor)h in this.peersToMonitor[E]&&(b=this.peersToMonitor[E][h].pc,m=E)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let E in this.peersToMonitor)for(let D in this.peersToMonitor[E])this.peersToMonitor[E][D].pc===b&&(h=D,m=E)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:h}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let m in this.peersToMonitor[p]){let h=this.peersToMonitor[p][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),C.forEach(p=>{this.removeTrackEventListeners(p)}),C=[],this.shouldWrapGetUserMedia&&M&&(navigator.mediaDevices.getUserMedia=M)}monitorPeer(p){let{peerId:m,connectionId:h,pc:b,remote:E}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const D={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:E}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=D}else this.peersToMonitor[m]={[h]:D};this.addPeerConnectionEventListeners(m,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let m={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);m[p]=this.peersToMonitor[p]}else m=this.peersToMonitor;let h=[];for(const b in m)for(const E in m[b]){const D=m[b][E],L=D.pc;if(L&&!this.checkIfConnectionIsClosed(b,E,L))try{const N=this.getTimestamp(),P=L.getStats(null);if(P){const B=await P,X=this.getTimestamp(),j=I(B),ie={remote:D.options.remote},ne=A(B,D.stats.parsed,ie),$={event:"stats",tag:"stats",peerId:b,connectionId:E,timeTaken:X-N,data:ne};this.rawStats===!0&&($.rawStats=B),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),D.stats.parsed=ne}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(N){this.logger.error(N)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const m in this.peersToMonitor[p]){const h=this.peersToMonitor[p][m].pc;this.checkIfConnectionIsClosed(p,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,m,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let E=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:E,peerId:p,connectionId:m,tag:"connection",data:"closed"})}return b}isConnectionClosed(p){return p.connectionState==="closed"||p.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."),M=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),M.apply(navigator.mediaDevices,arguments).then(m=>(p({stream:m}),m),m=>(p({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const m={...p};for(const b in m){var h=m[b];this.statsToMonitor.includes(h.type)||delete m[b]}return m}get peerConnectionListeners(){return{icecandidate:(p,m,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:m,data:b.candidate})},track:(p,m,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const E=b.track,D=b.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=D),this.addTrackEventListeners(E,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:D?this.getStreamDetails(D):null,track:E?this.getMediaTrackDetails(E):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(p,m,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:m,error:{errorCode:b.errorCode}})},connectionstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:h.connectionState})},negotiationneeded:(p,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:m})},datachannel:(p,m,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:m,data:b.channel})}}}addPeerConnectionEventListeners(p,m,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${m}.`),S[m]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[m][b]=this.peerConnectionListeners[b].bind(this,p,m,h),h.addEventListener(b,S[m][b],!1)})}parseGetUserMedia(p){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(m.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),C.push(h)})),this.emitEvent(m)}catch{}}parseStream(p){const m={audio:[],video:[]};return p.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(p,m){S[p.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const m={...p,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,m){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,S[p][h],!1)}),delete S[p]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(as=Uu)&&as.__esModule&&Object.prototype.hasOwnProperty.call(as,"default")&&as.default;var q_=Uu.WebRTCStats;function K_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,r=function(c){const{jitter:u,rtt:d}=c,f=u+d/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),o=function(c){const{packetsLost:u,packetsReceived:d}=c,f=u/(d+u)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-r-o+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function X_(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 Y_ extends ri{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class J_ extends ri{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class Z_ extends ri{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function ju(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 Q_(t,e){const n=wn();let i=!1;const s=new q_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=o=>F(this,void 0,void 0,function*(){o.event==="stats"&&U(O.StatsFrame,function({data:a}){var l,c,u,d,f,g,v,_;const{audio:w,remote:y}=a,{audio:T}=y,x=(c=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,I=(d=(u=T.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,A=(g=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&g!==void 0?g:-1,M=(_=(v=w.inbound[0])===null||v===void 0?void 0:v.packetsLost)!==null&&_!==void 0?_:-1,S=K_({jitter:1e3*x,rtt:1e3*I,packetsLost:M,packetsReceived:A});return{jitter:x,rtt:I,mos:S,quality:X_(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}}(o),t.uuid),yield t.execute(new Z_(n,o))});return{get isRunning(){return i},start:(o,a,l)=>F(this,void 0,void 0,function*(){if(i)k.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new Y_(n,e)),s.on("timeline",r);try{yield s.addConnection({pc:o,peerId:a,connectionId:l}),i=!0}catch(c){k.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:o=>F(this,void 0,void 0,function*(){const a=s.getTimeline();U(O.StatsReport,a,t.uuid),o==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),f=document.createElement("a");f.href=d,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new J_(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:o=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)},reportIceCandidateError:o=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)}}}const $u=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:r=null,currentLayerIdx:o=-1}=e;r&&i!=="mcu-personal-canvas"&&delete r.memberID;const a={type:et.conferenceUpdate,call:t.calls[s],canvasInfo:e0(r),currentLayerIdx:o};switch(n){case"layer-info":{const l=Object.assign({action:ze.LayerInfo},a);U(O.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ze.LayoutInfo},a);U(O.Notification,l,t.uuid);break}}},e0=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return gu(e)},Hu=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],t0={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function Wu(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}class ui{constructor(e,n,i,s,r){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._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this.handleConnectionStateChange=()=>F(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(k.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${o}`),o==="failed"||o==="disconnected"){const a=()=>F(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,u){return F(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const g=f[0].sender,v=g==null?void 0:g.transport;v&&(d.dtlsState=v.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(v=>{v.type==="candidate-pair"&&v.state==="succeeded"&&(d.candidatePairState=v.state,g.forEach(_=>{_.type==="local-candidate"&&_.id===v.localCandidateId&&(d.localCandidateType=_.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:_.address,port:_.port,protocol:_.protocol,candidateType:_.candidateType}),_.type==="remote-candidate"&&_.id===v.remoteCandidateId&&(d.remoteCandidateType=_.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:_.address,port:_.port,protocol:_.protocol,candidateType:_.candidateType})})),v.type==="transport"&&(d.dtlsCipher=v.dtlsCipher,d.srtpCipher=v.srtpCipher,d.tlsVersion=v.tlsVersion,v.dtlsState&&(d.dtlsState=v.dtlsState))})}catch(g){k.error("Error gathering connection state details:",g)}return d})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}if(o==="disconnected"){const a=Dt(a_);U(O.Warning,{warning:a,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(o==="failed"){const a=Dt(d_);U(O.PeerConnectionFailureError,{warning:a,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${o}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=o,o==="connected"&&(performance.mark("dtls-connected"),this.tryCollectTimings()),this._isTrickleIce()&&(o==="connecting"&&performance.mark("peer-connection-connecting"),o==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark("peer-connection-connected")))}),this._handleIceConnectionStateChange=()=>{const o=this.instance.iceConnectionState;k.debug(`[${new Date().toISOString()}] ICE Connection State`,o),o==="connected"&&performance.mark("ice-connected")},this._handleIceGatheringStateChange=()=>{const o=this.instance.iceGatheringState;k.debug(`[${new Date().toISOString()}] ICE Gathering State`,o),o==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):o==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(o,a)=>{if(o.setCodecPreferences)return o.setCodecPreferences(a)},k.debug("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=r}get isOffer(){return this.type===De.Offer}get isAnswer(){return this.type===De.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark("start-negotiation"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return F(this,void 0,void 0,function*(){performance.mark("start-negotiation"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){this.instance?(k.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{k.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),k.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):k.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(k.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":U(O.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(k.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){k.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?k.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark("first-remote-media-track"),this._firstMediaTrackMarked=!0);const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&li(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName("call-active","mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=function(n,i){const s=Wu("new-call-start");if(s===void 0)return{mode:n,direction:i,steps:[]};const r=[];for(const l of Hu){if(l==="new-call-start")continue;const c=Wu(l);c!==void 0&&r.push({label:t0[l]||l,fromStart:c-s})}r.sort((l,c)=>l.fromStart-c.fromStart);const o=[];let a=0;for(const l of r)o.push({label:l.label,fromStart:l.fromStart,delta:l.fromStart-a}),a=l.fromStart;return{mode:n,direction:i,steps:o}}(this._isTrickleIce()?"trickle":"non-trickle",this.isOffer?"outbound":"inbound");(function(n){const{mode:i,direction:s,steps:r}=n,o=`[CallTimings][${s}][${i}]`;if(r.length===0)return void k.info(`${o} No timing data collected`);const a=Math.max(...r.map(f=>f.label.length),4)+2,l=(f,g)=>{for(;f.length<g;)f+=" ";return f},c=(f,g)=>{for(;f.length<g;)f=" "+f;return f},u=l("Step",a)+c("Delta",14)+c("From Start",14);let d="";for(let f=0;f<u.length;f++)d+="-";k.info(`${o} Call establishment timing breakdown:`),k.info(`${o} ${u}`),k.info(`${o} ${d}`),k.info(`${o} ${l("Call Start",a)}${c("-",14)}${c("0.00ms",14)}`);for(const f of r){const g=f.delta.toFixed(2)+"ms",v=f.fromStart.toFixed(2)+"ms";k.info(`${o} ${l(f.label,a)}${c(g,14)}${c(v,14)}`)}k.info(`${o} ${d}`)})(e),function(){for(const n of Hu)try{performance.clearMarks(n)}catch{k.warn("Clearing performance marks is failed")}}()}createPeerConnection(){return F(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",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:De.Offer}),performance.mark("set-remote-description"));const n=!!this.options.receiveOnlyAudio&&!this.options.audio;let i=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>F(this,void 0,void 0,function*(){const r=this._session.options.mediaPermissionsRecovery;if(r!=null&&r.enabled&&this._isAnswer()){let o=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),r.timeout),U(O.Error,{error:ae(ii(s),s),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+r.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>F(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),o=yield this._retrieveLocalStream(),(l=r.onSuccess)===null||l===void 0||l.call(r)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),i=l,(c=r.onError)===null||c===void 0||c.call(r,l)}),o}return i=s,null})),!this.options.localStream&&!n)throw ae(i?ii(i):ou,i??void 0);performance.mark("get-user-media"),this.options.mutedMicOnStart&&Tn(this.options.localStream)&&(k.info("Muting local audio tracks on start"),ur(this.options.localStream)),performance.mark("peer-creation-end")})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Dt(c_);U(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Dt(l_);U(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ui.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return F(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=Q_(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(Tn(i)){const r=i.getAudioTracks();let o=[...r];if(k.info("Local audio tracks: ",r),typeof this.options.audio=="object"&&r.forEach(c=>{k.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();o=[...r,...c],k.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{k.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Bu(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};o.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(o.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&li(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const r=this.instance.addTransceiver("audio",{direction:"recvonly"});k.info("Added recvonly audio transceiver for receive-only mode",r);const{audioCodecs:o}=Bu(this.options.preferred_codecs);o.length>0&&this._setCodecs(r,o)}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);k.info("Add transceiver",e,n)}}_createOffer(){return F(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,k.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark("create-offer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),this._isTrickleIce()||this._sdpReady(),e}catch(e){k.error("Peer _createOffer error:",e);const n=ae(Uy,e);U(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setRemoteDescription(e){return F(this,void 0,void 0,function*(){k.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(n){k.error("Peer _setRemoteDescription error:",n);const i=ae(iu,n);throw U(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_createAnswer(){return F(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return k.debug("Skipping negotiation, state:",this.instance.signalingState),k.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:De.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark("create-answer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),e}catch(e){k.error("Peer _createAnswer error:",e);const n=ae(jy,e);U(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setLocalDescription(e){return F(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(n){k.error("Peer _setLocalDescription error:",n);const i=ae($y,n);throw U(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_sdpReady(){Sn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return F(this,void 0,void 0,function*(){if(Tn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,F(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:r=!1,camId:o}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield rs(s,a,mt.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),o&&(o=yield rs(o,l,mt.Video).catch(c=>null),o&&(typeof r=="boolean"&&(r={}),r.deviceId={exact:o})),{audio:i,video:r}}));var n;return os(e)})}_isOffer(){return this.type===De.Offer}_isAnswer(){return this.type===De.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 k.info("RTC config",s),s}restartStatsReporter(){return F(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?k.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(k.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):k.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return F(this,void 0,void 0,function*(){this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ui.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3;const ls=ar;class Gu{constructor(e,n){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=q[q.New],this.prevState="",this.channels=[],this.role=or.Participant,this.extension=null,this._state=q.New,this._prevState=q.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._signalingStateClosed=!1,this._creatingPeer=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=w=>{const y=w<0||!this._lastSerno||this._lastSerno&&w===this._lastSerno+1;return y&&w>=0&&(this._lastSerno=w),y},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(w=>{w.forEach(y=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const x in T.constraints)if(T.constraints.hasOwnProperty(x)&&T.constraints[x]!==y[x])return}T.callback(y)}})})})};const{iceServers:i,speaker:s,micId:r,micLabel:o,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:f,video:g},ringtoneFile:v,ringbackFile:_}=e;this.options=Object.assign({},E_,{audio:f,video:g,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:i,localElement:c,remoteElement:u,micId:r,micLabel:o,camId:a,camLabel:l,speakerId:s,ringtoneFile:v,ringbackFile:_,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.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=Ou(this.options.ringtoneFile,"_ringtone"),this._ringback=Ou(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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!W_(this.options.localStream)}invite(){return F(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=pt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new ui(De.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(e){k.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const n=e instanceof ni?e:ae(au,e instanceof Error?e:void 0);return U(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({},!1)}this._creatingPeer=!1})}answer(e={}){var n;return F(this,void 0,void 0,function*(){performance.mark("answer-called"),this._creatingPeer=!0,this.stopRingtone(),this.direction=pt.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("new-peer"),this.peer=new ui(De.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(i){k.error("Peer init failed, aborting call",i),this._creatingPeer=!1;const s=i instanceof ni?i:ae(au,i instanceof Error?i:void 0);return U(O.Error,{error:s,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup())}this._creatingPeer=!1})}playRingtone(){Fu(this._ringtone)}stopRingtone(){Vu(this._ringtone)}playRingback(){Fu(this._ringback)}stopRingback(){Vu(this._ringback)}hangup(e,n){var i,s,r,o;return F(this,void 0,void 0,function*(){const a=e||{},l=n!==!1,c=this._state<q.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=a.cause||c.cause,this.causeCode=a.causeCode||c.causeCode,this.sipCode=a.sipCode||null,this.sipReason=a.sipReason||null,this.sipCallId=a.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(r=(s=a==null?void 0:a.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&r!==void 0?r:[]],a.isRecovering)return this._isRecovering=!0,this.setState(q.Recovering),void this._finalize();if(this.setState(q.Hangup),this.stopRingtone(),this.stopRingback(),l){const u=new N_({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});try{yield this._execute(u)}catch(d){k.error("telnyx_rtc.bye failed!",d);const f=ae(qy,d);U(O.Error,{error:f,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}k.debug(`[${this.id}] Closing peer from hangup`),(o=this.peer)===null||o===void 0||o.close(),this.setState(q.Destroy)})}hold(){const e=new lr({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 lr({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 lr({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 Lu({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 Lu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){ur(this.options.localStream)}unmuteAudio(){Mu(this.options.localStream)}toggleAudioMute(){Nu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){var i;return F(this,void 0,void 0,function*(){const{instance:s}=this.peer,r=s.getSenders().find(({track:{kind:o}})=>o==="audio");if(r){let o;try{o=yield ss({audio:{deviceId:{exact:e}}})}catch(c){const u=ae(ii(c),c);return void U(O.MediaError,u,((i=this.options)===null||i===void 0?void 0:i.id)||this.id)}const a=o.getAudioTracks()[0];a.enabled=!n,r.replaceTrack(a),this.options.micId=e;const{localStream:l}=this.options;l.getAudioTracks().forEach(c=>c.stop()),l.getVideoTracks().forEach(c=>o.addTrack(c)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,kn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,kn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,kn(e,"video",null)}setVideoDevice(e){return F(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 ss({video:{deviceId:{exact:e}}}),r=s.getVideoTracks()[0];i.replaceTrack(r);const{localElement:o,localStream:a}=this.options;li(o,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){ur(this.options.remoteStream)}undeaf(){Mu(this.options.remoteStream)}toggleDeaf(){Nu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return F(this,void 0,void 0,function*(){if(!this||!this.peer)return void k.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 k.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const r=s.find(({track:{kind:o}})=>o===n);if(r){const o=r.getParameters();o.encodings||(o.encodings=[{rid:"h"}]),k.info("Parameters: ",o),k.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),o.encodings[0].maxBitrate=e,yield r.setParameters(o).then(()=>{k.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",r.getParameters())}).catch(a=>k.error(a))}else k.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){var n,i;switch(this._prevState=this._state,this._state=e,this.state=q[this._state].toLowerCase(),this.prevState=q[this._prevState].toLowerCase(),k.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:et.callUpdate,call:this}),e){case q.Purge:k.info(`[${this.id}] Entering Purge state.`);break;case q.Active:performance.mark("call-active"),(n=this.peer)===null||n===void 0||n.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,k.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:s,speakerId:r}=this.options;s&&r&&Du(s,r)},0),this._callReportCollector&&!((i=this.peer)===null||i===void 0)&&i.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case q.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(performance.mark("telnyx-rtc-answer"),this.gotAnswer=!0,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),this._state>=q.Active)return;this._state>=q.Early&&this.setState(q.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(performance.mark("telnyx-rtc-media"),this._state>=q.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:{const{display_name:r,display_number:o,display_direction:a}=i;this.extension=o;const l=a===pt.Inbound?pt.Outbound:pt.Inbound,c={type:et[n],call:this,displayName:r,displayNumber:o,displayDirection:l};U(O.Notification,c,this.id)||U(O.Notification,c,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const r=Object.assign(Object.assign({},i),{type:et.generic,call:this});U(O.Notification,r,this.id)||U(O.Notification,r,this.session.uuid);break}case te.Ringing:performance.mark("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 F(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return k.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:r=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:f}=n;this._dispatchConferenceUpdate({action:ze.Join,conferenceName:u,participantId:Number(d),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const g=[];for(const v in s)g.push(Object.assign({callId:s[v][0],index:Number(v)},ts(s[v][1])));this._dispatchConferenceUpdate({action:ze.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ze.Add,callId:r,index:o},ts(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ze.Modify,callId:r,index:o},ts(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ze.Delete,callId:r,index:o},ts(s)));break;case"clear":this._dispatchConferenceUpdate({action:ze.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:r,index:o})}})}_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 F(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:r,from:o,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ze.ChatMessage,direction:r,participantNumber:o,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfChat subscription error:",s)});cr(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,r)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:r}})}}}))})}_subscribeConferenceInfo(e){return F(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:r}=s;r.contentType==="layout-info"?(r.callID=this.id,$u(this.session,r)):k.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfInfo subscription error:",s)});cr(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(q.Active):this.setState(q.Held),!0}_handleChangeHoldStateError(e){k.error(`Failed to ${e.action} on call ${this.id}`);const n=ae(Gy,e);return U(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_onRemoteSdp(e){return F(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:De.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{performance.mark("set-remote-description"),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(q.Early),this.gotAnswer&&this.setState(q.Active)}).catch(i=>F(this,void 0,void 0,function*(){k.error("Call setRemoteDescription Error: ",i);const s=ae(iu,i);U(O.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(r){k.error("Error during hangup after setRemoteDescription failure:",r)}}))})}_requestAnotherLocalDescription(){Sn(this.peer.onSdpReadyTwice)?U(O.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;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0,!e)return void k.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:s,type:r}=e;if(s.indexOf("candidate")===-1)return k.info(`No candidate - retry
|
|
116
|
+
`),void this._requestAnotherLocalDescription();if((i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),!p_.test(s)){const l=Dt(u_);k.warn(`[${this.id}] Warning ${l.code}: ${l.message}`),U(O.Warning,{warning:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark("ice-gathering-end");let o=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${ls}`};switch(r){case De.Offer:this.setState(q.Requesting),o=new Iu(a);break;case De.Answer:this._isRecovering||this.setState(q.Answering),o=this.options.attach===!0?new Ru(a):new Au(a);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(o).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,r===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${r} error:`,l);const c=ae(su,l);U(O.Error,{error:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(u){k.error("Error during hangup after SDP send failure:",u)}}))}_onTrickleIceSdp(e){if(!e)return k.error("No SDP data provided"),void this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ls}`};switch(i){case De.Offer:this.setState(q.Requesting),s=new Iu(r);break;case De.Answer:this._isRecovering||this.setState(q.Answering),s=this.options.attach===!0?new Ru(r):new Au(r);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(s).then(o=>{const{node_id:a=null}=o;this._targetNodeId=a,i===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(o=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${i} error:`,o);const a=ae(su,o);U(O.Error,{error:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(l){k.error("Error during hangup after SDP send failure:",l)}}))}_onIce(e){var n;const{instance:i}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(i.localDescription),s)}e.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var n;e.candidate&&e.candidate.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new O_({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 k.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(()=>{k.debug("Successfully added ICE candidate:",e)}).catch(i=>{k.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new F_({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark("first-candidate"),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark("first-non-host-candidate"),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!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.onicegatheringstatechange=()=>{e.iceGatheringState==="complete"&&performance.mark("ice-gathering-completed")},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=ju(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:r}=this.options;r===!1&&li(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{k.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(k.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=ju(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:r}=this.options;r===!1&&li(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:et.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),k.error(`Media error (${n}): ${i}`,e),U(O.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:et.peerConnectionFailureError,error:e.error}),k.error("Peer connection failure error"),e.warning&&U(O.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:et.signalingStateClosed},e)),k.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:et.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(U(O.Notification,e,this.id,!1)||U(O.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){var e,n;const{id:i,userVariables:s,remoteCallerNumber:r,onNotification:o,recoveredCallId:a}=this.options;var l;this.options.id=i?i.toString():wn(),this.id=this.options.id,a&&(this.recoveredCallId=a,this._isRecovering=!0),s&&(l=s,Object.keys(l).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Pt(O.MediaError,this._onMediaError,this.id),Pt(O.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Pt(O.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Sn(o)&&Pt(O.Notification,o.bind(this),this.id);const c=this.session.options.enableCallReports!==!1,u=this.session.options.callReportInterval||5e3,d=this.session.options.debugLogLevel||"debug",f=this.session.options.debugLogMaxEntries||1e3;c&&(this._callReportCollector=new Ce({enabled:!0,interval:u},{enabled:!0,level:d,maxEntries:f}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=g=>{U(O.Warning,{warning:g,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(q.Recovering):this.setState(q.New),k.info(`New Call — region: ${(e=this.session.region)!==null&&e!==void 0?e:"unknown"}, dc: ${(n=this.session.dc)!==null&&n!==void 0?n:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),k.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;ci(n),ci(i),Mt(O.MediaError,null,this.id),Mt(O.PeerConnectionFailureError,null,this.id),Mt(O.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{k.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void k.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void k.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},r=this._callReportCollector.flush(s);if(!r)return;const o=Yt()||void 0;this._callReportCollector.sendPayload(r,n,i,o).catch(a=>{k.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return F(this,void 0,void 0,function*(){if(!this._callReportCollector)return void k.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return k.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void k.error("Cannot post call report: connection host not available");const r=Yt()||void 0;this._callReportCollector.postReport(i,n,s,r).catch(o=>{k.error("Failed to post call report",{error:o})}).finally(()=>{var o;(o=this._callReportCollector)===null||o===void 0||o.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),k.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),k.debug("Stats stopped")}}Gu.setStateTelnyx=t=>{if(t){switch(t._state){case q.Recovering:t.state="recovering";break;case q.Requesting:case q.Trying:case q.Early:t.state="connecting";break;case q.Active:t.state="active";break;case q.Held:t.state="held";break;case q.Hangup:case q.Destroy:t.state="done";break;case q.Answering:t.state="ringing";break;case q.New:t.state="new"}return t}};class Jt extends Gu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new z_(e,n))}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return F(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>F(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup())}))});const{remoteCallerName:s,remoteCallerNumber:r,callerName:o,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${r}-screen`,callerName:`${o} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Jt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup())})}setAudioOutDevice(e){return F(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Du(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>F(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"],r=["id","type","timestamp"];n.forEach(o=>{s.includes(o.type)||(i+=`
|
|
117
|
+
${o.type}
|
|
118
|
+
`,Object.keys(o).forEach(a=>{r.includes(a)||(i+=` ${a}: ${o[a]}
|
|
119
|
+
`)}))}),k.info(i)}),2e3)}}class n0 extends ai{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!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 F(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return F(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return F(this,void 0,void 0,function*(){try{const i=yield os({audio:e,video:n});return ci(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),k.info("Start hangup for ",i),yield i.hangup({},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),i.hangup({},!1)}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(wu(O.SpeedTest,o=>{const{upDur:a,downDur:l}=o,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.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 r=".".repeat(1024);for(let o=0;o<s;o++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return di().catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getVideoDevices(){return di(mt.Video).catch(e=>(U(O.MediaError,e,this.uuid),[]))}getAudioInDevices(){return di(mt.AudioIn).catch(e=>{const n=ae(ii(e),e);return U(O.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return di(mt.AudioOut).catch(e=>(k.error("getAudioOutDevices",e),U(O.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return rs(e,n,i)}getDeviceResolutions(e){return F(this,void 0,void 0,function*(){try{return yield(n=>F(void 0,void 0,void 0,function*(){const i=[],s=yield os({video:{deviceId:{exact:n}}}),r=s.getVideoTracks()[0];for(let o=0;o<Pu.length;o++){const[a,l]=Pu[o];(yield r.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return ci(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return F(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=Zi(e,["micId","micLabel"]);return H_(s),this._audioConstraints=yield((r,o,a,l)=>F(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(r||o)){const u=yield rs(r,o,a).catch(d=>null);u&&(l.deviceId={exact:u})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?v_:g_}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ns(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ns(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 V_({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new B_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const r=yield this.execute(s),{unauthorized:o=[],subscribed:a=[]}=dr(r);return o.length&&o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new U_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:r=[],notSubscribed:o=[]}=dr(s);return r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(k.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,k.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ae(t_);U(O.Error,{error:e,sessionId:this.sessionid},this.uuid)},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 Jt.setStateTelnyx(e)}}class zu{constructor(e,n){this.code=n,this.message=e}}class i0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new M_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*yu(2,6)}handleMessage(e){var n,i,s,r,o,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:f,method:g,params:v={},voice_sdk_id:_}=e,w=v==null?void 0:v.callID,y=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,x=d.calls[w],I=(n=x==null?void 0:x.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(v==null?void 0:v.reattached_sessions)&&v.reattached_sessions.length===0&&Object.keys(d.calls).length>0){const C=Dt(f_);U(O.Warning,{warning:C,sessionId:d.sessionid},d.uuid)}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const A=C=>{var p,m,h,b,E,D;const L={audio:!0,video:d.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===te.Attach,mediaSettings:v.mediaSettings,debug:(p=d.options.debug)!==null&&p!==void 0&&p,debugOutput:(m=d.options.debugOutput)!==null&&m!==void 0?m:"socket",trickleIce:(h=d.options.trickleIce)!==null&&h!==void 0&&h,prefetchIceCandidates:(b=d.options.prefetchIceCandidates)===null||b===void 0||b,forceRelayCandidate:(E=d.options.forceRelayCandidate)!==null&&E!==void 0&&E,keepConnectionAliveOnSocketClose:(D=d.options.keepConnectionAliveOnSocketClose)!==null&&D!==void 0&&D};w&&(L.id=w),v.telnyx_call_control_id&&(L.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(L.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(L.telnyxLegId=v.telnyx_leg_id),v.client_state&&(L.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(L.customHeaders=v.dialogParams.custom_headers),C&&(L.recoveredCallId=C),performance.mark("new-call-start");const N=new Jt(d,L);return N.nodeId=this.nodeId,N},M=new ku(_),S=new xu(_);switch(g){case te.Answer:case te.Display:case te.Candidate:case te.Ringing:case te.Bye:case te.Media:if(!w||!x)return void k.error(`Received ${g} for non existing call:`,v);x.handleMessage(e),this._ack(f,g);break;case te.Ping:this.session.setPingReceived(),this.session.execute(S);break;case te.Punt:d.options.keepConnectionAliveOnSocketClose&&I?(k.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(f,g)):(k.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case te.Invite:{const m=A();m.direction=pt.Inbound,m.playRingtone(),m.setState(q.Ringing),this._ack(f,g);break}case te.Attach:{if(!x)return A().answer(),void this._ack(f,g);const m=x.id;k.info(`[${new Date().toISOString()}][${w}] closing existing call on ATTACH.`),x.hangup({isRecovering:!0},!1),k.info(`[${new Date().toISOString()}][${w}] Attach: Creating new call for recovery (recoveredCallId: ${m})`),A(m).answer(),this._ack(f,g);break}case te.Event:case"webrtc.event":if(!y)return void k.error("Verto received an unknown event:",v);const C=d.relayProtocol,p=y.split(".")[0];d._existsSubscription(C,y)?U(C,v,y):y===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(C,p)?U(C,v,p):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(O.Notification,v,d.uuid);break;case te.Info:v.type=et.generic,U(O.Notification,v,d.uuid);break;case te.ClientReady:this.session.execute(M);break;default:{const m=ir(e);if(m){switch(m){case Ue.REGISTER:case Ue.REGED:if(d.connection.previousGatewayState!==Ue.REGED&&d.connection.previousGatewayState!==Ue.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const h=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;h&&(d.callReportId=h,k.debug("Captured call_report_id from REGED:",h));const b=(o=(r=e==null?void 0:e.result)===null||r===void 0?void 0:r.params)===null||o===void 0?void 0:o.dc;b&&(d.dc=b);const E=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;E&&(d.region=E),k.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),v.type=et.vertoClientReady,U(O.Ready,v,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const h=new zu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),b=ae(ru,h);U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(M)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:if(d.connection.previousGatewayState!==Ue.FAILED&&d.connection.previousGatewayState!==Ue.FAIL_WAIT){const h=ae(Zy,new Error(`Gateway state: ${m}`));if(U(O.Error,{error:h,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const b=new zu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),E=ae(Jy,b);U(O.Error,{error:E,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const b=ae(45003,new Error("Connection Retry Failed"));U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(k.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(b=>{var E;return((E=b.peer)===null||E===void 0?void 0:E.instance)&&!b.signalingStateClosed}))return k.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();k.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:k.warn("GatewayState message unknown method:",e)}break}k.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(r=>i.includes(r[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return F(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:r,laName:o,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:o}}})},v={nodeId:this.nodeId,channels:[r],handler:({data:w})=>{const y=f||this._retrieveCallId(w,r);if(y&&n.calls.hasOwnProperty(y)){const T=n.calls[y];T._addChannel(r),T.extension=o,T.handleConferenceUpdate(w,e).then(x=>{x==="INVALID_PACKET"&&g()})}}},_=yield n.vertoSubscribe(v).catch(w=>{k.error("liveArray subscription error:",w);const y=ae(Ky,w);U(O.Error,{error:y,sessionId:n.sessionid},n.uuid)});cr(_,r)&&g();break}case"conference-liveArray-part":{let g=null;if(r&&n._existsSubscription(i,r)){const{callId:_=null}=n.subscriptions[i][r];if(g=n.calls[_]||null,_!==null){const w={type:et.conferenceUpdate,action:ze.Leave,conferenceName:o,participantId:Number(u),role:d};U(O.Notification,w,_,!1)||U(O.Notification,w,n.uuid),g===null&&Mt(O.Notification,null,_)}}const v=[r,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:_=[]})=>{g&&(g.channels=g.channels.filter(w=>!_.includes(w)))}).catch(_=>{k.error("liveArray unsubscribe error:",_)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":$u(this.session,e);break;case"logo-info":{const n={type:et.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};U(O.Notification,n,this.session.uuid);break}}}}class s0 extends n0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new i0(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(k.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return is(this.options)||si(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(zy,void 0,"Error: destinationNumber is required");const n=new Jt(this,e);return performance.mark("new-call-start"),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!si(this.options)||!!e.destinationNumber}_onSocketOpen(){return F(this,void 0,void 0,function*(){return is(this.options)?this.handleLoginOnSocketOpen():si(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class o0 extends s0{constructor(e){super(e),k.info(`SDK version: ${Eu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return G_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:we.not_supported},{browserName:"Firefox",supported:we.not_supported},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",supported:we.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",features:["video","audio"],supported:we.full},{browserName:"Edge",features:["audio"],supported:we.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:we.full},{browserName:"Firefox",features:["audio"],supported:we.partial},{browserName:"Safari",supported:we.not_supported},{browserName:"Edge",features:["audio"],supported:we.partial}]}]}}function qu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ku={exports:{}},Xu;function r0(){return Xu||(Xu=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(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,f),v=n?n+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],g]:l._events[v].push(g):(l._events[v]=g,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,f,g){var v=n?n+l:l;if(!this._events[v])return!1;var _=this._events[v],w=arguments.length,y,T;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),w){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,u),!0;case 4:return _.fn.call(_.context,c,u,d),!0;case 5:return _.fn.call(_.context,c,u,d,f),!0;case 6:return _.fn.call(_.context,c,u,d,f,g),!0}for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];_.fn.apply(_.context,y)}else{var x=_.length,I;for(T=0;T<x;T++)switch(_[T].once&&this.removeListener(l,_[T].fn,void 0,!0),w){case 1:_[T].fn.call(_[T].context);break;case 2:_[T].fn.call(_[T].context,c);break;case 3:_[T].fn.call(_[T].context,c,u);break;case 4:_[T].fn.call(_[T].context,c,u,d);break;default:if(!y)for(I=1,y=new Array(w-1);I<w;I++)y[I-1]=arguments[I];_[T].fn.apply(_[T].context,y)}}return!0},a.prototype.on=function(l,c,u){return r(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return r(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&o(this,f);else{for(var v=0,_=[],w=g.length;v<w;v++)(g[v].fn!==c||d&&!g[v].once||u&&g[v].context!==u)&&_.push(g[v]);_.length?this._events[f]=_.length===1?_[0]:_:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(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}(Ku)),Ku.exports}var a0=r0();const hr=qu(a0),cs=new hr;var fr={exports:{}},l0=fr.exports,Yu;function c0(){return Yu||(Yu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(l0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(_){return _==="debug"&&(_="log"),typeof console===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function g(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),D=b.indexOf(E+"=");D!==-1&&(h=/^([^;]+)/.exec(b.slice(D+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var m=S();m!=null&&(I=p(m)),u.call(y)}o=new g,o.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var w=r[_];return w||(w=r[_]=new g(_,o.methodFactory)),w};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(fr)),fr.exports}var d0=c0();const u0=qu(d0),h0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Pe=u0.getLogger("telnyx-ai-agent"),f0=Pe.methodFactory;Pe.methodFactory=(t,e,n)=>{const i=f0(t,e,n);return function(...s){i(h0(),"-",...s)}},Pe.setLevel("info");function p0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const m0=10,g0=500,v0=100,Ju=20;class y0{constructor(e){J(this,"remoteIntervalId",null);J(this,"localIntervalId",null);J(this,"remoteStream",null);J(this,"localStream",null);J(this,"remoteAudioContext",null);J(this,"remoteSource",null);J(this,"remoteAnalyser",null);J(this,"localAudioContext",null);J(this,"localSource",null);J(this,"localAnalyser",null);J(this,"thinkingStartTime",null);J(this,"lastState",null);J(this,"userIsSpeaking",!1);J(this,"lastUserAudioTime",null);J(this,"userSpeechStartTime",null);J(this,"userSilenceStartTime",null);J(this,"isFirstAgentSpeech",!0);J(this,"monitorStartTime",null);J(this,"volumeThreshold");J(this,"silenceDurationMs");J(this,"minSpeechDurationMs");J(this,"maxLatencyMs");J(this,"updateAgentState",p0(e=>{Pe.debug("AudioStreamMonitor updateAgentState",e),Pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,cs.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??m0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??g0,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??v0,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var r;Pe.debug("AudioContext resumed, state:",(r=this.remoteAudioContext)==null?void 0:r.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const r=n.reduce((l,c)=>l+c,0)/n.length,o=r>=this.volumeThreshold;if(Math.random()<.01&&Pe.debug("Remote audio volume:",r,"threshold:",this.volumeThreshold,"above:",o),o)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=o};this.remoteIntervalId=window.setInterval(s,Ju)}startLocalMonitor(){if(!this.localStream){Pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Pe.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((r,o)=>r+o,0)/e.length;if(Math.random()<.02&&Pe.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const r=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:r})}};this.localIntervalId=window.setInterval(n,Ju)}destroy(){this.stopAudioStreamMonitor()}}function _0(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function b0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function w0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function S0(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function C0(t){return b0(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function T0(t){if(!w0(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 k0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcript",[]);J(this,"onSocketMessage",n=>{if(_0(n))switch(n.params.type){case"response.text.delta":{const i=C0(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),cs.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(S0(n)){const i=n.params.item_id,s=this.transcript.findIndex(r=>r.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=T0(n);if(i){const s=this.transcript.findIndex(r=>r.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(O.SocketMessage,this.onSocketMessage)}}class x0 extends hr{constructor(n){super();J(this,"telnyxRTC");J(this,"transcription");J(this,"agentId");J(this,"versionId");J(this,"conversationId");J(this,"debug");J(this,"audioStreamMonitor");J(this,"activeCall");J(this,"chatMode");J(this,"dc",null);J(this,"region",null);J(this,"callReportId",null);J(this,"onClientReady",()=>{const n=this.telnyxRTC;this.dc=n.dc??null,this.region=n.region??null,this.callReportId=n.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});J(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});J(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});J(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});J(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Pe.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new o0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(O.Ready,this.onClientReady),this.telnyxRTC.on(O.Error,this.onClientOrSocketError),this.telnyxRTC.on(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(O.Notification,this.onNotification),this.transcription=new k0(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),cs.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new y0(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(O.Ready,this.onClientReady),this.telnyxRTC.off(O.Error,this.onClientOrSocketError),this.telnyxRTC.off(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(O.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),cs.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){Pe.error("Client is not initialized.");return}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:r,...o}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...o,audio:this.chatMode?!1:r??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Zu={exports:{}},hi={},Qu;function E0(){if(Qu)return hi;Qu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,r){var o=null;if(r!==void 0&&(o=""+r),s.key!==void 0&&(o=""+s.key),"key"in s){r={};for(var a in s)a!=="key"&&(r[a]=s[a])}else r=s;return s=r.ref,{$$typeof:t,type:i,key:o,ref:s!==void 0?s:null,props:r}}return hi.Fragment=e,hi.jsx=n,hi.jsxs=n,hi}var eh;function I0(){return eh||(eh=1,Zu.exports=E0()),Zu.exports}I0(),bt(void 0),bt(null);const A0=(t,e,n,i,s,r,o,a,l)=>new x0({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:r,conversationId:o,chatMode:a,region:l}),ds=5,R0=2e3,L0=3e4,D0=["Login Incorrect","Authentication Required"];function P0(t){var n;const e=((n=t.message)==null?void 0:n.toLowerCase())||"";return D0.some(i=>e.includes(i.toLowerCase()))}function M0(t){return Math.min(R0*Math.pow(2,t-1),L0)+Math.random()*1e3}const N0=(t,e,n,i,s,r,o,a,l)=>{const[c,u]=xe(null),[d,f]=xe(!1),[g,v]=xe(null),[_,w]=xe(!1),y=de(0),T=de(null),x=de(null),I=Ge(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),A=Ge(S=>{if(T.current){ue.debug("Reconnect already scheduled, skipping duplicate");return}if(y.current>=ds){ue.error(`Max reconnection attempts (${ds}) exceeded`),w(!1);return}y.current+=1;const C=M0(y.current);ue.info(`Scheduling reconnect attempt ${y.current}/${ds} in ${C}ms due to: ${S}`),w(!0),T.current=window.setTimeout(()=>{T.current=null,x.current&&(ue.info(`Executing reconnect attempt ${y.current}`),x.current.connect())},C)},[]),M=Ge(()=>{I(),y.current=0,w(!1),v(null)},[I]);return Ee(()=>{if(!t)return;const S=A0(t,e,n,i,s,r,o,a,l);x.current=S;const C=()=>{ue.info("Agent connected successfully"),f(!0),M()},p=()=>{ue.info("Agent disconnected"),f(!1)},m=h=>{ue.error("AI Agent error:",h),P0(h)&&y.current<ds?(v(null),A(h.message)):(v(h),w(!1))};return S.on("agent.connected",C),S.on("agent.disconnected",p),S.on("agent.error",m),S.connect(),u(S),()=>{I(),S.off("agent.connected",C),S.off("agent.disconnected",p),S.off("agent.error",m),S.disconnect(),x.current=null}},[t,e,n,i,s,r,o,a,l,I,M,A]),{client:c,isConnected:d,error:g,isReconnecting:_}},O0="telnyx-ai-agent",Nt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function th(){const t=document.querySelector(O0);return t instanceof HTMLElement?t:null}function Ot(t,e,n){const i=n||th();if(!i){ue.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ue.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const F0=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:r}=e,o=de(null),a=Ei(Gd);Ee(()=>{o.current=th()},[]),Ee(()=>{if(!t)return;const l=o.current,c=()=>{n();const A=t.telnyxRTC,M={dc:(A==null?void 0:A.dc)??null,region:(A==null?void 0:A.region)??null,callReportId:(A==null?void 0:A.callReportId)??null};a(M),Ot(Nt.AGENT_CONNECTED,M,l)},u=()=>{a(null),Ot(Nt.AGENT_DISCONNECTED,void 0,l)},d=I=>{s(I);const A={message:I.message,name:I.name};Ot(Nt.AGENT_ERROR,A,l)},f=I=>{var A;i(I),Ot(Nt.CONVERSATION_UPDATE,{type:I.type,callState:(A=I.call)==null?void 0:A.state},l)},g=I=>{Ot(Nt.TRANSCRIPT_ITEM,I,l)},v=I=>{Ot(Nt.CONVERSATION_AGENT_STATE,I,l)},_=I=>{Ot(Nt.AGENT_AUDIO_MUTE,{muted:I},l)},y=t.telnyxRTC,T=I=>{r(I)},x=I=>{const A=I,M={code:A==null?void 0:A.code,reason:A==null?void 0:A.reason,wasClean:A==null?void 0:A.wasClean,timestamp:new Date().toISOString()};ue.info("[socket.close]",M),Ot(Nt.SOCKET_CLOSE,M,l)};return y&&typeof y=="object"&&(y.on(O.SocketMessage,T),y.on(O.SocketClose,x)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",g),t.on("conversation.agent.state",v),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",g),t.off("conversation.agent.state",v),t.off("agent.audio.mute",_),y&&typeof y=="object"&&(y.off(O.SocketMessage,T),y.off(O.SocketClose,x))}},[t,n,i,s,r,a])},V0=2e3;async function B0(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function nh(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 U0=(t,e)=>{const[n,i]=xe([]),[,s]=Xo(),r=de(e);Ee(()=>{r.current=e},[e]);const o=de(void 0),a=de(void 0);return Ee(()=>{if(!t)return;const c=f=>{i(g=>{const v=g[g.length-1];if(f.role==="assistant"&&v&&nh(v.id)===nh(f.id)&&v.role==="assistant"){const _=r.current.showUserPerceivedLatency&&o.current!==void 0&&v.userPerceivedLatencyMs===void 0,w=r.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,y={...v,content:v.content+f.content,timestamp:f.timestamp,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return _&&(o.current=void 0),w&&(a.current=void 0),[...g.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const _=r.current.showUserPerceivedLatency&&o.current!==void 0,w=r.current.showGreetingLatency&&a.current!==void 0;if(_||w){const y={...f,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return o.current=void 0,a.current=void 0,[...g,y]}o.current=void 0,a.current=void 0}if(f.role==="user"){const _=g.findIndex(y=>y.id===f.id);if(_!==-1){const y=[...g];return y[_]={...g[_],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(v&&v.role==="user"&&f.timestamp.getTime()-v.timestamp.getTime()<V0){const T={...v,id:f.id,content:v.content+" "+f.content,timestamp:f.timestamp,attachments:[...v.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),T]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...g,f]})},u=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:v,thinkingStartedAt:_})=>{(g!==void 0||v!==void 0)&&ue.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${v} thinkingStartedAt=${_}`),f==="speaking"?(s("speaking"),g!==void 0&&(o.current=g),v!==void 0&&(a.current=v)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=f=>{var v;const g=(v=f.call)==null?void 0:v.state;(g==="destroy"||g==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const f of u)try{const g=await B0(f);d.push(g)}catch(g){throw ue.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},j0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const r=Xt(),[o,a]=xe(i?"expanded":r.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=U0(e,n),d=de(!1);switch(Ee(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(g=>{g.enabled=!1,ue.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[i,t]),o){case"collapsed":return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return R(Ny,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return R(Qd,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},pr=()=>R(vn.div,{layoutId:Qn,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:R("div",{className:"rounded-full animate-spin",children:R(uy,{})})}),$0=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(pr,{});case"done":case"purged":case"destroy":return null;case"active":return R(j0,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return R(pr,{})}},H0=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function ih(){const t=Xt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R(H0,{className:"w-8 h-8 mr-2"})}const W0=({client:t,callProps:e,chatMode:n})=>{const i=Xt(),s=de(!1),r=Ge(()=>{if(!t){ue.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return Ee(()=>{n&&t&&!s.current&&(s.current=!0,ue.info("[ChatMode] Auto-starting conversation"),r())},[n,t,r]),n?R(vn.div,{layoutId:Qn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[R(ih,{}),"Connecting..."]}):R(vn.button,{layoutId:Qn,onClick:r,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:[R(ih,{}),i.start_call_text]})},G0='@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-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--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-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.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-green-500{background-color:var(--color-green-500)}.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}.opacity-60{opacity:.6}.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-green-600:hover{background-color:var(--color-green-600)}.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)}}',z0=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),q0={duration:.1,ease:"circOut"},K0=({children:t,position:e="fixed"})=>{const n=Xt(),s=(e??n.position??"fixed")==="fixed"?R(z0,{children:t}):t;return R("div",{className:Ct(n.theme==="dark"&&"dark"),children:R(nm,{transition:q0,children:[R("style",{children:G0}),s]})})},X0=t=>R(vn.div,{layoutId:Qn,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:[R(cy,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(yy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&R("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[R(gy,{className:"w-4 h-4"}),"Retry"]})]});function fi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Y0({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":r,"call-custom-headers":o,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:g,environment:v,position:_="fixed","version-id":w}){const y=fi(e),T=fi(n),x=fi(f),I=Xe(()=>{if(l)try{return JSON.parse(l)}catch(H){ue.error("Invalid JSON for vad attribute:",l,H);return}},[l]),A=Xe(()=>({showUserPerceivedLatency:fi(c),showGreetingLatency:fi(u)}),[c,u]),{client:M,error:S,isReconnecting:C}=N0(t,v,w,y,T,I,d,x,g),[p,m]=xe(null),[h,b]=xe(!1),[E,D]=xe(!1),[L,N]=xe(!1),[P,B]=xe(!1),X=Ei(Jd),j=Ov(),ie={};if(i&&(ie.destinationNumber=i),s&&(ie.callerNumber=s),r&&(ie.callerName=r),o)try{ie.customHeaders=JSON.parse(o)}catch(H){ue.error("Invalid JSON for call-custom-headers attribute:",o,H)}if(a)try{ie.audio=JSON.parse(a);const H=ie.audio;if(typeof H=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(H).forEach(Ae=>{se[Ae]||ue.warn(`Audio constraint not supported by browser: ${Ae}`)})}}catch(H){ue.error("Invalid JSON for call-audio attribute:",a,H)}const ne=Ge(()=>{b(!1)},[]),$=Ge(H=>{var se;if(((se=H.call)==null?void 0:se.state)==="destroy")return X(!1),B(!0),m(null);m(H)},[X]),ce=Ge(()=>{b(!1),C||D(!0)},[C]),Y=Ge(()=>{ue.info("User triggered retry"),D(!1),b(!0),M&&M.connect()},[M]),Q=Ge(H=>{if(Nv(H)){const se=H.params.widget_settings;se&&Object.keys(se).length>0&&(j(se),N(!0))}},[j]);return F0(M,{onReady:ne,onConversationUpdate:$,onError:ce,onConfigMessage:Q}),R(K0,{position:_,children:t?E||S?R(X0,{agentId:t,onRetry:Y}):h||C?R(pr,{}):p!=null&&p.call?R($0,{call:p.call,client:M,latencySettings:A,chatMode:x,debug:y}):L?R(W0,{client:M,callProps:ie,chatMode:x&&!P}):null:R("div",{children:"Please provide an assistant ID."})})}bh(Y0,"telnyx-ai-agent",Pv,{shadow:!0})})();
|