@telnyx/ai-agent-widget 0.31.3 → 0.32.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var q_=Object.defineProperty;var K_=(et,H,Ft)=>H in et?q_(et,H,{enumerable:!0,configurable:!0,writable:!0,value:Ft}):et[H]=Ft;var Q=(et,H,Ft)=>K_(et,typeof H!="symbol"?H+"":H,Ft);(function(){"use strict";var et,H,Ft,Vt,mo,go,vo,yo,is,ss,rs,_o,Cn={},bo=[],ju=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,kn=Array.isArray;function rt(t,e){for(var n in e)t[n]=e[n];return t}function os(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ze(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?et.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 Tn(t,r,i,s,null)}function Tn(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??++Ft,__i:-1,__u:0};return s==null&&H.vnode!=null&&H.vnode(o),o}function ot(t){return t.children}function tt(t,e){this.props=t,this.context=e}function tn(t,e){if(e==null)return t.__?tn(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"?tn(t):null}function wo(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 wo(t)}}function as(t){(!t.__d&&(t.__d=!0)&&Vt.push(t)&&!di.__r++||mo!=H.debounceRendering)&&((mo=H.debounceRendering)||go)(di)}function di(){for(var t,e,n,i,s,o,r,a=1;Vt.length;)Vt.length>a&&Vt.sort(vo),t=Vt.shift(),a=Vt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=rt({},i)).__v=i.__v+1,H.vnode&&H.vnode(n),ls(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??tn(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,To(o,n,r),n.__e!=s&&wo(n)));di.__r=0}function So(t,e,n,i,s,o,r,a,l,c,d){var u,f,g,_,v,w,y=i&&i.__k||bo,x=e.length;for(l=Uu(n,e,y,l,x),u=0;u<x;u++)(g=n.__k[u])!=null&&(f=g.__i==-1?Cn:y[g.__i]||Cn,g.__i=u,w=ls(t,g,f,s,o,r,a,l,c,d),_=g.__e,g.ref&&f.ref!=g.ref&&(f.ref&&cs(f.ref,null,g),d.push(g.ref,g.__c||_,g)),v==null&&_!=null&&(v=_),4&g.__u||f.__k===g.__k?l=xo(g,l,t):typeof g.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),g.__u&=-7);return n.__e=v,l}function Uu(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?Tn(null,r,null,null,null):kn(r)?Tn(ot,{children:r},null,null,null):r.constructor==null&&r.__b>0?Tn(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=$u(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=tn(a)),Ao(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=tn(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function at(t,e){return e=e||[],t==null||typeof t=="boolean"||(kn(t)?t.some(function(n){at(n,e)}):e.push(t)),e}function $u(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 Co(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||ju.test(e)?n:n+"px"}function ui(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||Co(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Co(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(yo,"$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=is,t.addEventListener(e,o?rs:ss,o)):t.removeEventListener(e,o?rs:ss,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 ko(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=is++;else if(e.t<n.u)return;return n(H.event?H.event(e):e)}}}function ls(t,e,n,i,s,o,r,a,l,c){var d,u,f,g,_,v,w,y,x,C,E,P,O,S,k,p,m,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(d=H.__b)&&d(e);e:if(typeof h=="function")try{if(y=e.props,x="prototype"in h&&h.prototype.render,C=(d=h.contextType)&&i[d.__c],E=d?C?C.props.value:d.__:i,n.__c?w=(u=e.__c=n.__c).__=u.__E:(x?e.__c=u=new h(y,E):(e.__c=u=new tt(y,E),u.constructor=h,u.render=Hu),C&&C.sub(u),u.props=y,u.state||(u.state={}),u.context=E,u.__n=i,f=u.__d=!0,u.__h=[],u._sb=[]),x&&u.__s==null&&(u.__s=u.state),x&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=rt({},u.__s)),rt(u.__s,h.getDerivedStateFromProps(y,u.__s))),g=u.props,_=u.state,u.__v=e,f)x&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),x&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(x&&h.getDerivedStateFromProps==null&&y!==g&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,E),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,E)===!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)}),P=0;P<u._sb.length;P++)u.__h.push(u._sb[P]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,E),x&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(g,_,v)})}if(u.context=E,u.props=y,u.__P=t,u.__e=!1,O=H.__r,S=0,x){for(u.state=u.__s,u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),k=0;k<u._sb.length;k++)u.__h.push(u._sb[k]);u._sb=[]}else do u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(i=rt(rt({},i),u.getChildContext())),x&&!f&&u.getSnapshotBeforeUpdate!=null&&(v=u.getSnapshotBeforeUpdate(g,_)),p=d,d!=null&&d.type===ot&&d.key==null&&(p=Eo(d.props.children)),a=So(t,kn(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(m=o.length;m--;)os(o[m]);else e.__e=n.__e,e.__k=n.__k;H.__e(b,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Gu(n.__e,e,n,i,s,o,r,l,c);return(d=H.diffed)&&d(e),128&e.__u?void 0:a}function To(t,e,n){for(var i=0;i<n.length;i++)cs(n[i],n[++i],n[++i]);H.__c&&H.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){H.__e(o,s.__v)}})}function Eo(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:kn(t)?t.map(Eo):rt({},t)}function Gu(t,e,n,i,s,o,r,a,l){var c,d,u,f,g,_,v,w=n.props,y=e.props,x=e.type;if(x=="svg"?s="http://www.w3.org/2000/svg":x=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!x&&(x?g.localName==x:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(x==null)return document.createTextNode(y);t=document.createElementNS(s,x,y.is&&y),a&&(H.__m&&H.__m(e,o),a=!1),o=null}if(x==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&et.call(t.childNodes),w=n.props||Cn,!a&&o!=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")u=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;ui(t,c,null,g,s)}}for(c in y)g=y[c],c=="children"?f=g:c=="dangerouslySetInnerHTML"?d=g:c=="value"?_=g:c=="checked"?v=g:a&&typeof g!="function"||w[c]===g||ui(t,c,g,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=""),So(e.type=="template"?t.content:t,kn(f)?f:[f],e,n,i,x=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&tn(n,0),a,l),o!=null)for(c=o.length;c--;)os(o[c]);a||(c="value",x=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||x=="progress"&&!_||x=="option"&&_!=w[c])&&ui(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&ui(t,c,v,w[c],s))}return t}function cs(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){H.__e(s,n)}}function Ao(t,e,n){var i,s;if(H.unmount&&H.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||cs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){H.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Ao(i[s],e,n||typeof t.type!="function");n||os(t.__e),t.__c=t.__=t.__e=void 0}function Hu(t,e,n){return this.constructor(t,n)}function hi(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),H.__&&H.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],ls(e,t=(!i&&n||e).__k=ze(ot,null,[t]),s||Cn,Cn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?et.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),To(o,t,r)}function Io(t,e){hi(t,e,Io)}function ds(t,e,n){var i,s,o,r,a=rt({},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?et.call(arguments,2):n),Tn(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,as(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"+_o++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}et=bo.slice,H={__e:function(t,e,n,i){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Ft=0,tt.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=rt({},this.state),typeof t=="function"&&(t=t(rt({},n),this.props)),t&&rt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),as(this))},tt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),as(this))},tt.prototype.render=ot,Vt=[],go=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,vo=function(t,e){return t.__v.__b-e.__v.__b},di.__r=0,yo=/(PointerCapture)$|Capture$/i,is=0,ss=ko(!1),rs=ko(!0),_o=0;var Wu=0;function A(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:--Wu,__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 H.vnode&&H.vnode(c),c}function us(){return(us=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 zu=["context","children"];function qu(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,zu);return ds(e,n)}function Ku(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=ze(qu,us({},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[Ro(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),d=l[r].slot;d?o[d]=ze(Po,{name:d},c):s[r]=c}var u=i?ze(Po,null,s):s;return ze(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Io:hi)(this._vdom,this._root)}function Ro(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Xu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ro(t)]=n,this._vdom=ds(this._vdom,i),hi(this._vdom,this._root)}}function Yu(){hi(this._vdom=null,this._root)}function Po(t,e){var n=this;return ze("slot",us({},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 Zu(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=Ku,s.prototype.attributeChangedCallback=Xu,s.prototype.disconnectedCallback=Yu,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 Ct,le,hs,Lo,En=0,Mo=[],me=H,Do=me.__b,Oo=me.__r,No=me.diffed,Fo=me.__c,Vo=me.unmount,Bo=me.__;function nn(t,e){me.__h&&me.__h(le,t,En||e),En=0;var n=le.__H||(le.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Te(t){return En=1,jo(Go,t)}function jo(t,e,n){var i=nn(Ct++,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=le,!le.__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 g=f.__[0];f.__=f.__N,f.__N=void 0,g!==f.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};le.__f=!0;var o=le.shouldComponentUpdate,r=le.componentWillUpdate;le.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)},le.shouldComponentUpdate=s}return i.__N||i.__}function Pe(t,e){var n=nn(Ct++,3);!me.__s&&ms(n.__H,e)&&(n.__=t,n.u=e,le.__H.__h.push(n))}function Uo(t,e){var n=nn(Ct++,4);!me.__s&&ms(n.__H,e)&&(n.__=t,n.u=e,le.__h.push(n))}function _e(t){return En=5,qe(function(){return{current:t}},[])}function qe(t,e){var n=nn(Ct++,7);return ms(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function kt(t,e){return En=8,qe(function(){return t},e)}function Ce(t){var e=le.context[t.__c],n=nn(Ct++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(le)),e.props.value):t.__}function Ju(t,e){me.useDebugValue&&me.useDebugValue(e?e(t):t)}function fs(){var t=nn(Ct++,11);if(!t.__){for(var e=le.__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 Qu(){for(var t;t=Mo.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(fi),t.__H.__h.forEach(ps),t.__H.__h=[]}catch(e){t.__H.__h=[],me.__e(e,t.__v)}}me.__b=function(t){le=null,Do&&Do(t)},me.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Bo&&Bo(t,e)},me.__r=function(t){Oo&&Oo(t),Ct=0;var e=(le=t.__c).__H;e&&(hs===le?(e.__h=[],le.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(fi),e.__h.forEach(ps),e.__h=[],Ct=0)),hs=le},me.diffed=function(t){No&&No(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Mo.push(e)!==1&&Lo===me.requestAnimationFrame||((Lo=me.requestAnimationFrame)||eh)(Qu)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),hs=le=null},me.__c=function(t,e){e.some(function(n){try{n.__h.forEach(fi),n.__h=n.__h.filter(function(i){return!i.__||ps(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],me.__e(i,n.__v)}}),Fo&&Fo(t,e)},me.unmount=function(t){Vo&&Vo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{fi(i)}catch(s){e=s}}),n.__H=void 0,e&&me.__e(e,n.__v))};var $o=typeof requestAnimationFrame=="function";function eh(t){var e,n=function(){clearTimeout(i),$o&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);$o&&(e=requestAnimationFrame(n))}function fi(t){var e=le,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),le=e}function ps(t){var e=le;t.__c=t.__(),le=e}function ms(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 An={},Ho=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Wo=t=>"init"in t,gs=t=>!!t.write,zo=t=>"v"in t||"e"in t,pi=t=>{if("e"in t)throw t.e;if((An?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},mi=new WeakMap,qo=t=>{var e;return gi(t)&&!!((e=mi.get(t))!=null&&e[0])},th=t=>{const e=mi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Ko=(t,e)=>{let n=mi.get(t);if(!n){n=[!0,new Set],mi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},gi=t=>typeof(t==null?void 0:t.then)=="function",Xo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},vs=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(gi(e))for(const r of i.d.keys())Xo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,gi(o)&&th(o))},Yo=(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},nh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},ys=()=>{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},ih=t=>(t.c||(t.c=ys()),t.m||(t.m=ys()),t.u||(t.u=ys()),t.f||(t.f=nh()),t),sh=Symbol(),Zo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...g)=>f.read(...g),l=(f,...g)=>f.write(...g),c=(f,g)=>{var _;return(_=f.unstable_onInit)==null?void 0:_.call(f,g)},d=(f,g)=>{var _;return(_=f.onMount)==null?void 0:_.call(f,g)},...u)=>{const f=u[0]||(S=>{if((An?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let k=t.get(S);return k||(k={d:new Map,p:new Set,n:0},t.set(S,k),c==null||c(S,O)),k}),g=u[1]||(()=>{const S=[],k=p=>{try{p()}catch(m){S.push(m)}};do{r.f&&k(r.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(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),p.forEach(k),i.size&&_()}while(i.size||o.size||s.size);if(S.length)throw new AggregateError(S)}),_=u[2]||(()=>{const S=[],k=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(k.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((An?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),m.pop();continue}k.add(h);for(const T of Yo(h,b,e))k.has(T)||m.push(T)}for(let h=S.length-1;h>=0;--h){const[b,T]=S[h];let L=!1;for(const I of T.d.keys())if(I!==b&&i.has(I)){L=!0;break}L&&(v(b),x(b)),n.delete(b)}}),v=u[3]||(S=>{var k;const p=f(S);if(zo(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([M,F])=>v(M).n===F)))return p;p.d.clear();let m=!0;const h=()=>{e.has(S)&&(x(S),_(),g())},b=M=>{var F;if(Ho(S,M)){const V=f(M);if(!zo(V))if(Wo(M))vs(M,M.init,f);else throw new Error("no atom init");return pi(V)}const U=v(M);try{return pi(U)}finally{p.d.set(M,U.n),qo(p.v)&&Xo(S,p.v,U),(F=e.get(M))==null||F.t.add(S),m||h()}};let T,L;const I={get signal(){return T||(T=new AbortController),T.signal},get setSelf(){return(An?"production":void 0)!=="production"&&!gs(S)&&console.warn("setSelf function cannot be used with read-only atom"),!L&&gs(S)&&(L=(...M)=>{if((An?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return y(S,...M)}finally{_(),g()}}),L}},D=p.n;try{const M=a(S,b,I);return vs(S,M,f),gi(M)&&(Ko(M,()=>T==null?void 0:T.abort()),M.then(h,h)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{m=!1,D!==p.n&&n.get(S)===D&&(n.set(S,p.n),i.add(S),(k=r.c)==null||k.call(r,S))}}),w=u[4]||(S=>{const k=[S];for(;k.length;){const p=k.pop(),m=f(p);for(const h of Yo(p,m,e)){const b=f(h);n.set(h,b.n),k.push(h)}}}),y=u[5]||((S,...k)=>{let p=!0;const m=b=>pi(v(b)),h=(b,...T)=>{var L;const I=f(b);try{if(Ho(S,b)){if(!Wo(b))throw new Error("atom not writable");const D=I.n,M=T[0];vs(b,M,f),x(b),D!==I.n&&(i.add(b),(L=r.c)==null||L.call(r,b),w(b));return}else return y(b,...T)}finally{p||(_(),g())}};try{return l(S,m,h,...k)}finally{p=!1}}),x=u[6]||(S=>{var k;const p=f(S),m=e.get(S);if(m&&!qo(p.v)){for(const[h,b]of p.d)if(!m.d.has(h)){const T=f(h);C(h).t.add(S),m.d.add(h),b!==T.n&&(i.add(h),(k=r.c)==null||k.call(r,h),w(h))}for(const h of m.d||[])if(!p.d.has(h)){m.d.delete(h);const b=E(h);b==null||b.t.delete(S)}}}),C=u[7]||(S=>{var k;const p=f(S);let m=e.get(S);if(!m){v(S);for(const h of p.d.keys())C(h).t.add(S);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,m),(k=r.m)==null||k.call(r,S),gs(S)){const h=()=>{let b=!0;const T=(...L)=>{try{return y(S,...L)}finally{b||(_(),g())}};try{const L=d(S,T);L&&(m.u=()=>{b=!0;try{L()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return m}),E=u[8]||(S=>{var k;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&&o.add(m.u),m=void 0,e.delete(S),(k=r.u)==null||k.call(r,S);for(const h of p.d.keys()){const b=E(h);b==null||b.t.delete(S)}return}return m}),P=[t,e,n,i,s,o,r,a,l,c,d,f,g,_,v,w,y,x,C,E],O={get:S=>pi(v(S)),set:(S,...k)=>{try{return y(S,...k)}finally{_(),g()}},sub:(S,k)=>{const m=C(S).l;return m.add(k),g(),()=>{m.delete(k),E(S),g()}}};return Object.defineProperty(O,sh,{value:P}),O},rh=ih,Jo=Ko,_s={};let oh=0;function bs(t,e){const n=`atom${++oh}`,i={toString(){return(_s?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=ah,i.write=lh),i}function ah(t){return t(this)}function lh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const ch=()=>{let t=0;const e=rh({}),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 dh(){return(_s?"production":void 0)!=="production"?ch():Zo()}let In;function uh(){return In||(In=dh(),(_s?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=In),globalThis.__JOTAI_DEFAULT_STORE__!==In&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),In}function Qo(t,e){for(var n in e)t[n]=e[n];return t}function ea(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 ta=Uo;function na(t,e){this.props=t,this.context=e}(na.prototype=new tt).isPureReactComponent=!0,na.prototype.shouldComponentUpdate=function(t,e){return ea(this.props,t)||ea(this.state,e)};var ia=H.__b;H.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ia&&ia(t)};var hh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function fh(t){function e(n){var i=Qo({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=hh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var sa=function(t,e){return t==null?null:at(at(t).map(e))},ph={map:sa,forEach:sa,count:function(t){return t?at(t).length:0},only:function(t){var e=at(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:at},mh=H.__e;H.__e=function(t,e,n,i){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}mh(t,e,n,i)};var ra=H.unmount;function oa(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=Qo({},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 oa(i,e,n)})),t}function aa(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return aa(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 ws(){this.__u=0,this.o=null,this.__b=null}function la(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function vi(){this.i=null,this.l=null}H.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),ra&&ra(t)},(ws.prototype=new tt).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=la(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]=aa(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)},ws.prototype.componentWillUnmount=function(){this.o=[]},ws.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]=oa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&ze(ot,null,t.fallback);return s&&(s.__u&=-33),[ze(ot,null,e.__a?null:t.children),s]};var ca=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]}};(vi.prototype=new tt).__a=function(t){var e=this,n=la(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),ca(e,t,i)):s()};n?n(o):o()}},vi.prototype.render=function(t){this.i=null,this.l=new Map;var e=at(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},vi.prototype.componentDidUpdate=vi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){ca(t,n,e)})};var da=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,gh=/^(?: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]/,vh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,yh=/[A-Z0-9]/g,_h=typeof document<"u",bh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};tt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(tt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var ua=H.event;function wh(){}function Sh(){return this.cancelBubble}function xh(){return this.defaultPrevented}H.event=function(t){return ua&&(t=ua(t)),t.persist=wh,t.isPropagationStopped=Sh,t.isDefaultPrevented=xh,t.nativeEvent=t};var Ch={enumerable:!1,configurable:!0,get:function(){return this.class}},ha=H.vnode;H.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||_h&&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"||bh(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":vh.test(r)&&(r=l):l=r="oninput":o&&gh.test(r)?r=r.replace(yh,"-$&").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=at(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=at(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",Ch)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=da,ha&&ha(t)};var fa=H.__r;H.__r=function(t){fa&&fa(t),t.__c};var pa=H.diffed;H.diffed=function(t){pa&&pa(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===da}function kh(t){return ma(t)?ds.apply(null,arguments):t}var ga={};const Th={},Eh=vt(void 0);function va(t){return Ce(Eh)||uh()}const Ss=t=>typeof(t==null?void 0:t.then)=="function",xs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Ah=ga.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(xs(t),t)}),Cs=new WeakMap,ya=(t,e)=>{let n=Cs.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();Ss(c)?(Cs.set(c,n),o=c,c.then(r(c),a(c)),Jo(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),Jo(t,l)}),Cs.set(t,n)),n};function _a(t,e){const{delay:n,unstable_promiseStatus:i=!ga.use}={},s=va(),[[o,r,a],l]=jo(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)),Pe(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);Ss(u)&&xs(ya(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),d},[s,t,n,i]),Ju(c),Ss(c)){const d=ya(c,()=>s.get(t));return i&&xs(d),Ah(d)}return c}function ks(t,e){const n=va();return kt((...s)=>{if((Th?"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[_a(t),ks(t)]}const Ts=vt({});function yi(t){const e=_e(null);return e.current===null&&(e.current=t()),e.current}const Es=typeof window<"u",wa=Es?Uo:Pe,_i=vt(null);function As(t,e){t.indexOf(e)===-1&&t.push(e)}function Is(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const yt=(t,e,n)=>n>e?e:n<t?t:n;let Rs=()=>{};const _t={},Sa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function xa(t){return typeof t=="object"&&t!==null}const Ca=t=>/^0[^.\s]+$/u.test(t);function Ps(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ke=t=>t,Ih=(t,e)=>n=>e(t(n)),Rn=(...t)=>t.reduce(Ih),Pn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Ls{constructor(){this.subscriptions=[]}add(e){return As(this.subscriptions,e),()=>Is(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 lt=t=>t*1e3,ct=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,Rh=1e-7,Ph=12;function Lh(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)>Rh&&++a<Ph);return r}function Ln(t,e,n,i){if(t===e&&n===i)return Ke;const s=o=>Lh(o,0,1,t,n);return o=>o===0||o===1?o:Ta(s(o),e,i)}const Ea=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Aa=t=>e=>1-t(1-e),Ia=Ln(.33,1.53,.69,.99),Ms=Aa(Ia),Ra=Ea(Ms),Pa=t=>(t*=2)<1?.5*Ms(t):.5*(2-Math.pow(2,-10*(t-1))),Ds=t=>1-Math.sin(Math.acos(t)),La=Aa(Ds),Ma=Ea(Ds),Mh=Ln(.42,0,1,1),Dh=Ln(0,0,.58,1),Da=Ln(.42,0,.58,1),Oh=t=>Array.isArray(t)&&typeof t[0]!="number",Oa=t=>Array.isArray(t)&&typeof t[0]=="number",Nh={linear:Ke,easeIn:Mh,easeInOut:Da,easeOut:Dh,circIn:Ds,circInOut:Ma,circOut:La,backIn:Ms,backInOut:Ra,backOut:Ia,anticipate:Pa},Fh=t=>typeof t=="string",Na=t=>{if(Oa(t)){Rs(t.length===4);const[e,n,i,s]=t;return Ln(e,n,i,s)}else if(Fh(t))return Nh[t];return t},bi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Fa={value:null};function Vh(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,g=!1)=>{const v=g&&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 Bh=40;function Va(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=bi.reduce((C,E)=>(C[E]=Vh(o,e?E:void 0),C),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:f,render:g,postRender:_}=r,v=()=>{const C=_t.useManualTiming?s.timestamp:performance.now();n=!1,_t.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(C-s.timestamp,Bh),1)),s.timestamp=C,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),d.process(s),u.process(s),f.process(s),g.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},w=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:bi.reduce((C,E)=>{const P=r[E];return C[E]=(O,S=!1,k=!1)=>(n||w(),P.schedule(O,S,k)),C},{}),cancel:C=>{for(let E=0;E<bi.length;E++)r[bi[E]].cancel(C)},state:s,steps:r}}const{schedule:ue,cancel:Tt,state:Ee,steps:Os}=Va(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ke,!0);let wi;function jh(){wi=void 0}const je={now:()=>(wi===void 0&&je.set(Ee.isProcessing||_t.useManualTiming?Ee.timestamp:performance.now()),wi),set:t=>{wi=t,queueMicrotask(jh)}},Ba=t=>e=>typeof e=="string"&&e.startsWith(t),Ns=Ba("--"),Uh=Ba("var(--"),Fs=t=>Uh(t)?$h.test(t.split("/*")[0].trim()):!1,$h=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,sn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Mn={...sn,transform:t=>yt(0,1,t)},Si={...sn,default:1},Dn=t=>Math.round(t*1e5)/1e5,Vs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Gh(t){return t==null}const Hh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Bs=(t,e)=>n=>!!(typeof n=="string"&&Hh.test(n)&&n.startsWith(t)||e&&!Gh(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(Vs);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Wh=t=>yt(0,255,t),js={...sn,transform:t=>Math.round(Wh(t))},Bt={test:Bs("rgb","red"),parse:ja("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+js.transform(t)+", "+js.transform(e)+", "+js.transform(n)+", "+Dn(Mn.transform(i))+")"};function zh(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 Us={test:Bs("#"),parse:zh,transform:Bt.transform},On=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Et=On("deg"),dt=On("%"),W=On("px"),qh=On("vh"),Kh=On("vw"),Ua={...dt,parse:t=>dt.parse(t)/100,transform:t=>dt.transform(t*100)},rn={test:Bs("hsl","hue"),parse:ja("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+dt.transform(Dn(e))+", "+dt.transform(Dn(n))+", "+Dn(Mn.transform(i))+")"},we={test:t=>Bt.test(t)||Us.test(t)||rn.test(t),parse:t=>Bt.test(t)?Bt.parse(t):rn.test(t)?rn.parse(t):Us.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Bt.transform(t):rn.transform(t),getAnimatableNone:t=>{const e=we.parse(t);return e.alpha=0,we.transform(e)}},Xh=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Yh(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Vs))==null?void 0:e.length)||0)+(((n=t.match(Xh))==null?void 0:n.length)||0)>0}const $a="number",Ga="color",Zh="var",Jh="var(",Ha="${}",Qh=/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 Nn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Qh,l=>(we.test(l)?(i.color.push(o),s.push(Ga),n.push(we.parse(l))):l.startsWith(Jh)?(i.var.push(o),s.push(Zh),n.push(l)):(i.number.push(o),s.push($a),n.push(parseFloat(l))),++o,Ha)).split(Ha);return{values:n,split:a,indexes:i,types:s}}function Wa(t){return Nn(t).values}function za(t){const{split:e,types:n}=Nn(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+=Dn(s[r]):a===Ga?o+=we.transform(s[r]):o+=s[r]}return o}}const ef=t=>typeof t=="number"?0:we.test(t)?we.getAnimatableNone(t):t;function tf(t){const e=Wa(t);return za(t)(e.map(ef))}const At={test:Yh,parse:Wa,createTransformer:za,getAnimatableNone:tf};function $s(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 nf({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=$s(l,a,t+1/3),o=$s(l,a,t),r=$s(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function xi(t,e){return n=>n>0?e:t}const ge=(t,e,n)=>t+(e-t)*n,Gs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},sf=[Us,Bt,rn],rf=t=>sf.find(e=>e.test(t));function qa(t){const e=rf(t);if(!e)return!1;let n=e.parse(t);return e===rn&&(n=nf(n)),n}const Ka=(t,e)=>{const n=qa(t),i=qa(e);if(!n||!i)return xi(t,e);const s={...n};return o=>(s.red=Gs(n.red,i.red,o),s.green=Gs(n.green,i.green,o),s.blue=Gs(n.blue,i.blue,o),s.alpha=ge(n.alpha,i.alpha,o),Bt.transform(s))},Hs=new Set(["none","hidden"]);function of(t,e){return Hs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function af(t,e){return n=>ge(t,e,n)}function Ws(t){return typeof t=="number"?af:typeof t=="string"?Fs(t)?xi:we.test(t)?Ka:df:Array.isArray(t)?Xa:typeof t=="object"?we.test(t)?Ka:lf:xi}function Xa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ws(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);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]=Ws(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function cf(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 df=(t,e)=>{const n=At.createTransformer(e),i=Nn(t),s=Nn(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?Hs.has(t)&&!s.values.length||Hs.has(e)&&!i.values.length?of(t,e):Rn(Xa(cf(i,s),s.values),n):xi(t,e)};function Ya(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ge(t,e,n):Ws(t)(t,e)}const uf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ue.update(e,n),stop:()=>Tt(e),now:()=>Ee.isProcessing?Ee.timestamp:je.now()}},Za=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ci=2e4;function zs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ci;)e+=n,i=t.next(e);return e>=Ci?1/0:e}function hf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(zs(i),Ci);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:ct(s)}}const ff=5;function Ja(t,e,n){const i=Math.max(e-ff,0);return ka(n-t(i),e-i)}const ve={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},qs=.001;function pf({duration:t=ve.duration,bounce:e=ve.bounce,velocity:n=ve.velocity,mass:i=ve.mass}){let s,o,r=1-e;r=yt(ve.minDamping,ve.maxDamping,r),t=yt(ve.minDuration,ve.maxDuration,ct(t)),r<1?(s=c=>{const d=c*r,u=d*t,f=d-n,g=Ks(c,r),_=Math.exp(-u);return qs-f/g*_},o=c=>{const u=c*r*t,f=u*n+n,g=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-u),v=Ks(Math.pow(c,2),r);return(-s(c)+qs>0?-1:1)*((f-g)*_)/v}):(s=c=>{const d=Math.exp(-c*t),u=(c-n)*t+1;return-qs+d*u},o=c=>{const d=Math.exp(-c*t),u=(n-c)*(t*t);return d*u});const a=5/t,l=gf(s,o,a);if(t=lt(t),isNaN(l))return{stiffness:ve.stiffness,damping:ve.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const mf=12;function gf(t,e,n){let i=n;for(let s=1;s<mf;s++)i=i-t(i)/e(i);return i}function Ks(t,e){return t*Math.sqrt(1-e*e)}const vf=["duration","bounce"],yf=["stiffness","damping","mass"];function Qa(t,e){return e.some(n=>t[n]!==void 0)}function _f(t){let e={velocity:ve.velocity,stiffness:ve.stiffness,damping:ve.damping,mass:ve.mass,isResolvedFromDuration:!1,...t};if(!Qa(t,yf)&&Qa(t,vf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*yt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ve.mass,stiffness:s,damping:o}}else{const n=pf(t);e={...e,...n,mass:ve.mass},e.isResolvedFromDuration=!0}return e}function ki(t=ve.visualDuration,e=ve.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:g}=_f({...n,velocity:-ct(n.velocity||0)}),_=f||0,v=c/(2*Math.sqrt(l*d)),w=r-o,y=ct(Math.sqrt(l/d)),x=Math.abs(w)<5;i||(i=x?ve.restSpeed.granular:ve.restSpeed.default),s||(s=x?ve.restDelta.granular:ve.restDelta.default);let C;if(v<1){const P=Ks(y,v);C=O=>{const S=Math.exp(-v*y*O);return r-S*((_+v*y*w)/P*Math.sin(P*O)+w*Math.cos(P*O))}}else if(v===1)C=P=>r-Math.exp(-y*P)*(w+(_+y*w)*P);else{const P=y*Math.sqrt(v*v-1);C=O=>{const S=Math.exp(-v*y*O),k=Math.min(P*O,300);return r-S*((_+v*y*w)*Math.sinh(k)+P*w*Math.cosh(k))/P}}const E={calculatedDuration:g&&u||null,next:P=>{const O=C(P);if(g)a.done=P>=u;else{let S=P===0?_:0;v<1&&(S=P===0?lt(_):Ja(C,P,O));const k=Math.abs(S)<=i,p=Math.abs(r-O)<=s;a.done=k&&p}return a.value=a.done?r:O,a},toString:()=>{const P=Math.min(zs(E),Ci),O=Za(S=>E.next(P*S).value,P,30);return P+"ms "+O},toTransition:()=>{}};return E}ki.applyToOptions=t=>{const e=hf(t,100,ki);return t.ease=e.ease,t.duration=lt(e.duration),t.type="keyframes",t};function Xs({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},g=k=>a!==void 0&&k<a||l!==void 0&&k>l,_=k=>a===void 0?l:l===void 0||Math.abs(a-k)<Math.abs(l-k)?a:l;let v=n*e;const w=u+v,y=r===void 0?w:r(w);y!==w&&(v=y-u);const x=k=>-v*Math.exp(-k/i),C=k=>y+x(k),E=k=>{const p=x(k),m=C(k);f.done=Math.abs(p)<=c,f.value=f.done?y:m};let P,O;const S=k=>{g(f.value)&&(P=k,O=ki({keyframes:[f.value,_(f.value)],velocity:Ja(C,k,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return S(0),{calculatedDuration:null,next:k=>{let p=!1;return!O&&P===void 0&&(p=!0,E(k),S(k)),P!==void 0&&k>=P?O.next(k-P):(!p&&E(k),f)}}}function bf(t,e,n){const i=[],s=n||_t.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]||Ke:e;a=Rn(l,a)}i.push(a)}return i}function wf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Rs(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=bf(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=Pn(t[u],t[u+1],d);return a[u](f)};return n?d=>c(yt(t[0],t[o-1],d)):c}function Sf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Pn(0,e,i);t.push(ge(n,1,s))}}function xf(t){const e=[0];return Sf(e,t.length-1),e}function Cf(t,e){return t.map(n=>n*e)}function kf(t,e){return t.map(()=>e||Da).splice(0,t.length-1)}function Fn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Oh(i)?i.map(Na):Na(i),o={done:!1,value:e[0]},r=Cf(n&&n.length===e.length?n:xf(e),t),a=wf(r,e,{ease:Array.isArray(s)?s:kf(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Tf=t=>t!==null;function Ys(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Tf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Ef={decay:Xs,inertia:Xs,tween:Fn,keyframes:Fn,spring:ki};function el(t){typeof t.type=="string"&&(t.type=Ef[t.type])}class Zs{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 Af=t=>t/100;class Js extends Zs{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!==je.now()&&this.tick(je.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=Fn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||Fn;l!==Fn&&typeof a[0]!="number"&&(this.mixKeyframes=Rn(Af,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=zs(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:g,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),x=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let C=this.currentTime,E=i;if(u){const k=Math.min(this.currentTime,s)/a;let p=Math.floor(k),m=k%1;!m&&k>=1&&(m=1),m===1&&p--,p=Math.min(p,u+1),!!(p%2)&&(f==="reverse"?(m=1-m,g&&(m-=g/a)):f==="mirror"&&(E=r)),C=yt(0,1,m)*a}const P=x?{done:!1,value:d[0]}:E.next(C);o&&(P.value=o(P.value));let{done:O}=P;!x&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return S&&_!==Xs&&(P.value=Ys(d,this.options,w,this.speed)),v&&v(P.value),S&&this.finish(),P}then(e,n){return this.finished.then(e,n)}get duration(){return ct(this.calculatedDuration)}get time(){return ct(this.currentTime)}set time(e){var n;e=lt(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(je.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=ct(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=uf,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(je.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 If(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const jt=t=>t*180/Math.PI,Qs=t=>{const e=jt(Math.atan2(t[1],t[0]));return er(e)},Rf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Qs,rotateZ:Qs,skewX:t=>jt(Math.atan(t[1])),skewY:t=>jt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},er=t=>(t=t%360,t<0&&(t+=360),t),tl=Qs,nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),il=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Pf={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=>er(jt(Math.atan2(t[6],t[5]))),rotateY:t=>er(jt(Math.atan2(-t[2],t[0]))),rotateZ:tl,rotate:tl,skewX:t=>jt(Math.atan(t[4])),skewY:t=>jt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function tr(t){return t.includes("scale")?1:0}function nr(t,e){if(!t||t==="none")return tr(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Pf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Rf,s=a}if(!s)return tr(e);const o=i[e],r=s[1].split(",").map(Mf);return typeof o=="function"?o(r):r[o]}const Lf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return nr(n,e)};function Mf(t){return parseFloat(t.trim())}const on=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],an=new Set(on),sl=t=>t===sn||t===W,Df=new Set(["x","y","z"]),Of=on.filter(t=>!Df.has(t));function Nf(t){const e=[];return Of.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ut={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})=>nr(e,"x"),y:(t,{transform:e})=>nr(e,"y")};Ut.translateX=Ut.x,Ut.translateY=Ut.y;const $t=new Set;let ir=!1,sr=!1,rr=!1;function rl(){if(sr){const t=Array.from($t).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Nf(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)})}sr=!1,ir=!1,$t.forEach(t=>t.complete(rr)),$t.clear()}function ol(){$t.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(sr=!0)})}function Ff(){rr=!0,ol(),rl(),rr=!1}class or{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?($t.add(this),ir||(ir=!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])}If(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),$t.delete(this)}cancel(){this.state==="scheduled"&&($t.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Vf=t=>t.startsWith("--");function Bf(t,e,n){Vf(e)?t.style.setProperty(e,n):t.style[e]=n}const jf=Ps(()=>window.ScrollTimeline!==void 0),Uf={};function $f(t,e){const n=Ps(t);return()=>Uf[e]??n()}const al=$f(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Vn=([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:Vn([0,.65,.55,1]),circOut:Vn([.55,0,1,.45]),backIn:Vn([.31,.01,.66,-.59]),backOut:Vn([.33,1.53,.69,.99])};function cl(t,e){if(t)return typeof t=="function"?al()?Za(t,e):"ease-out":Oa(t)?Vn(t):Array.isArray(t)?t.map(n=>cl(n,e)||ll.easeOut):ll[t]}function Gf(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 Hf({type:t,...e}){return dl(t)&&al()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Wf extends Zs{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,Rs(typeof e.type!="string");const c=Hf(e);this.animation=Gf(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Ys(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Bf(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 ct(Number(e))}get time(){return ct(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=lt(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&&jf()?(this.animation.timeline=e,Ke):n(this)}}const ul={anticipate:Pa,backInOut:Ra,circInOut:Ma};function zf(t){return t in ul}function qf(t){typeof t.ease=="string"&&zf(t.ease)&&(t.ease=ul[t.ease])}const hl=10;class Kf extends Wf{constructor(e){qf(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 Js({...r,autoplay:!1}),l=lt(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"&&(At.test(t)||t==="0")&&!t.startsWith("url("));function Xf(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 Yf(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:Xf(t)||(n==="spring"||dl(n))&&i}function ar(t){return xa(t)&&"offsetHeight"in t}const Zf=new Set(["opacity","clipPath","filter","transform"]),Jf=Ps(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Qf(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!ar((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return Jf()&&n&&Zf.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const ep=40;class tp extends Zs{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=je.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},g=(d==null?void 0:d.KeyframeResolver)||or;this.keyframeResolver=new g(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=je.now(),Yf(e,o,r,a)||((_t.instantAnimations||!l)&&(d==null||d(Ys(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>ep?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!c&&Qf(f)?new Kf({...f,element:f.motionValue.owner.current}):new Js(f);g.finished.then(()=>this.notifyFinished()).catch(Ke),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(),Ff()),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 np=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ip(t){const e=np.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function pl(t,e,n=1){const[i,s]=ip(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Sa(r)?parseFloat(r):r}return Fs(s)?pl(s,e,n+1):s}function lr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const ml=new Set(["width","height","top","left","right","bottom",...on]),sp={test:t=>t==="auto",parse:t=>t},gl=t=>e=>e.test(t),vl=[sn,W,dt,Et,Kh,qh,sp],yl=t=>vl.find(gl(t));function rp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ca(t):!0}const op=new Set(["brightness","contrast","saturate","opacity"]);function ap(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Vs)||[];if(!i)return t;const s=n.replace(i,"");let o=op.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const lp=/\b([a-z-]*)\(.*?\)/gu,cr={...At,getAnimatableNone:t=>{const e=t.match(lp);return e?e.map(ap).join(" "):t}},_l={...sn,transform:Math.round},dr={borderWidth:W,borderTopWidth:W,borderRightWidth:W,borderBottomWidth:W,borderLeftWidth:W,borderRadius:W,radius:W,borderTopLeftRadius:W,borderTopRightRadius:W,borderBottomRightRadius:W,borderBottomLeftRadius:W,width:W,maxWidth:W,height:W,maxHeight:W,top:W,right:W,bottom:W,left:W,padding:W,paddingTop:W,paddingRight:W,paddingBottom:W,paddingLeft:W,margin:W,marginTop:W,marginRight:W,marginBottom:W,marginLeft:W,backgroundPositionX:W,backgroundPositionY:W,...{rotate:Et,rotateX:Et,rotateY:Et,rotateZ:Et,scale:Si,scaleX:Si,scaleY:Si,scaleZ:Si,skew:Et,skewX:Et,skewY:Et,distance:W,translateX:W,translateY:W,translateZ:W,x:W,y:W,z:W,perspective:W,transformPerspective:W,opacity:Mn,originX:Ua,originY:Ua,originZ:W},zIndex:_l,fillOpacity:Mn,strokeOpacity:Mn,numOctaves:_l},cp={...dr,color:we,backgroundColor:we,outlineColor:we,fill:we,stroke:we,borderColor:we,borderTopColor:we,borderRightColor:we,borderBottomColor:we,borderLeftColor:we,filter:cr,WebkitFilter:cr},bl=t=>cp[t];function wl(t,e){let n=bl(t);return n!==cr&&(n=At),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const dp=new Set(["auto","none","0"]);function up(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!dp.has(o)&&Nn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=wl(n,s)}class hp extends or{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(),Fs(c))){const d=pl(c,n.current);d!==void 0&&(e[l]=d),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!ml.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 Ut[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||rp(e[s]))&&i.push(s);i.length&&up(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=Ut[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]=Ut[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 fp(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,xl=30,pp=t=>!isNaN(parseFloat(t));class mp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=je.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=je.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=pp(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 Ls);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=je.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>xl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,xl);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 ln(t,e){return new mp(t,e)}const{schedule:ur}=Va(queueMicrotask,!1),nt={x:!1,y:!1};function Cl(){return nt.x||nt.y}function gp(t){return t==="x"||t==="y"?nt[t]?null:(nt[t]=!0,()=>{nt[t]=!1}):nt.x||nt.y?null:(nt.x=nt.y=!0,()=>{nt.x=nt.y=!1})}function kl(t,e){const n=fp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Tl(t){return!(t.pointerType==="touch"||Cl())}function vp(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 El=(t,e)=>e?t===e?!0:El(t,e.parentElement):!1,hr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,yp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function _p(t){return yp.has(t.tagName)||t.tabIndex!==-1}const Ti=new WeakSet;function Al(t){return e=>{e.key==="Enter"&&t(e)}}function fr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const bp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Al(()=>{if(Ti.has(n))return;fr(n,"down");const s=Al(()=>{fr(n,"up")}),o=()=>fr(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 hr(t)&&!Cl()}function wp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{const l=a.currentTarget;if(!Il(a))return;Ti.add(l);const c=e(l,a),d=(g,_)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),Ti.has(l)&&Ti.delete(l),Il(g)&&typeof c=="function"&&c(g,{success:_})},u=g=>{d(g,l===window||l===document||n.useGlobalTarget||El(l,g.target))},f=g=>{d(g,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),ar(a)&&(a.addEventListener("focus",c=>bp(c,s)),!_p(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Rl(t){return xa(t)&&"ownerSVGElement"in t}function Sp(t){return Rl(t)&&t.tagName==="svg"}const Le=t=>!!(t&&t.getVelocity),xp=[...vl,we,At],Cp=t=>xp.find(gl(t)),Bn=vt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class kp extends tt{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=ar(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 Tp({children:t,isPresent:e,anchorX:n,root:i}){const s=fs(),o=_e(null),r=_e({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Ce(Bn);return ta(()=>{const{width:l,height:c,top:d,left:u,right:f}=r.current;if(e||!o.current||!l||!c)return;const g=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 q_=Object.defineProperty;var K_=(et,G,Ft)=>G in et?q_(et,G,{enumerable:!0,configurable:!0,writable:!0,value:Ft}):et[G]=Ft;var J=(et,G,Ft)=>K_(et,typeof G!="symbol"?G+"":G,Ft);(function(){"use strict";var et,G,Ft,Vt,mo,go,vo,yo,is,ss,rs,_o,Cn={},bo=[],ju=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,kn=Array.isArray;function rt(t,e){for(var n in e)t[n]=e[n];return t}function os(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ze(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?et.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 Tn(t,r,i,s,null)}function Tn(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??++Ft,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(o),o}function ot(t){return t.children}function tt(t,e){this.props=t,this.context=e}function tn(t,e){if(e==null)return t.__?tn(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"?tn(t):null}function wo(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 wo(t)}}function as(t){(!t.__d&&(t.__d=!0)&&Vt.push(t)&&!di.__r++||mo!=G.debounceRendering)&&((mo=G.debounceRendering)||go)(di)}function di(){for(var t,e,n,i,s,o,r,a=1;Vt.length;)Vt.length>a&&Vt.sort(vo),t=Vt.shift(),a=Vt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=rt({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),ls(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??tn(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,To(o,n,r),n.__e!=s&&wo(n)));di.__r=0}function So(t,e,n,i,s,o,r,a,l,c,d){var u,f,g,_,v,w,y=i&&i.__k||bo,x=e.length;for(l=Uu(n,e,y,l,x),u=0;u<x;u++)(g=n.__k[u])!=null&&(f=g.__i==-1?Cn:y[g.__i]||Cn,g.__i=u,w=ls(t,g,f,s,o,r,a,l,c,d),_=g.__e,g.ref&&f.ref!=g.ref&&(f.ref&&cs(f.ref,null,g),d.push(g.ref,g.__c||_,g)),v==null&&_!=null&&(v=_),4&g.__u||f.__k===g.__k?l=xo(g,l,t):typeof g.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),g.__u&=-7);return n.__e=v,l}function Uu(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?Tn(null,r,null,null,null):kn(r)?Tn(ot,{children:r},null,null,null):r.constructor==null&&r.__b>0?Tn(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=$u(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=tn(a)),Eo(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=tn(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function at(t,e){return e=e||[],t==null||typeof t=="boolean"||(kn(t)?t.some(function(n){at(n,e)}):e.push(t)),e}function $u(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 Co(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||ju.test(e)?n:n+"px"}function ui(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||Co(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Co(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(yo,"$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=is,t.addEventListener(e,o?rs:ss,o)):t.removeEventListener(e,o?rs:ss,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 ko(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=is++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function ls(t,e,n,i,s,o,r,a,l,c){var d,u,f,g,_,v,w,y,x,k,A,P,O,S,C,p,m,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,x="prototype"in h&&h.prototype.render,k=(d=h.contextType)&&i[d.__c],A=d?k?k.props.value:d.__:i,n.__c?w=(u=e.__c=n.__c).__=u.__E:(x?e.__c=u=new h(y,A):(e.__c=u=new tt(y,A),u.constructor=h,u.render=Hu),k&&k.sub(u),u.props=y,u.state||(u.state={}),u.context=A,u.__n=i,f=u.__d=!0,u.__h=[],u._sb=[]),x&&u.__s==null&&(u.__s=u.state),x&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=rt({},u.__s)),rt(u.__s,h.getDerivedStateFromProps(y,u.__s))),g=u.props,_=u.state,u.__v=e,f)x&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),x&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(x&&h.getDerivedStateFromProps==null&&y!==g&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,A),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,A)===!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)}),P=0;P<u._sb.length;P++)u.__h.push(u._sb[P]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,A),x&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(g,_,v)})}if(u.context=A,u.props=y,u.__P=t,u.__e=!1,O=G.__r,S=0,x){for(u.state=u.__s,u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),C=0;C<u._sb.length;C++)u.__h.push(u._sb[C]);u._sb=[]}else do u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(i=rt(rt({},i),u.getChildContext())),x&&!f&&u.getSnapshotBeforeUpdate!=null&&(v=u.getSnapshotBeforeUpdate(g,_)),p=d,d!=null&&d.type===ot&&d.key==null&&(p=Ao(d.props.children)),a=So(t,kn(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(m=o.length;m--;)os(o[m]);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=Gu(n.__e,e,n,i,s,o,r,l,c);return(d=G.diffed)&&d(e),128&e.__u?void 0:a}function To(t,e,n){for(var i=0;i<n.length;i++)cs(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 Ao(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:kn(t)?t.map(Ao):rt({},t)}function Gu(t,e,n,i,s,o,r,a,l){var c,d,u,f,g,_,v,w=n.props,y=e.props,x=e.type;if(x=="svg"?s="http://www.w3.org/2000/svg":x=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!x&&(x?g.localName==x:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(x==null)return document.createTextNode(y);t=document.createElementNS(s,x,y.is&&y),a&&(G.__m&&G.__m(e,o),a=!1),o=null}if(x==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&et.call(t.childNodes),w=n.props||Cn,!a&&o!=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")u=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;ui(t,c,null,g,s)}}for(c in y)g=y[c],c=="children"?f=g:c=="dangerouslySetInnerHTML"?d=g:c=="value"?_=g:c=="checked"?v=g:a&&typeof g!="function"||w[c]===g||ui(t,c,g,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=""),So(e.type=="template"?t.content:t,kn(f)?f:[f],e,n,i,x=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&tn(n,0),a,l),o!=null)for(c=o.length;c--;)os(o[c]);a||(c="value",x=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||x=="progress"&&!_||x=="option"&&_!=w[c])&&ui(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&ui(t,c,v,w[c],s))}return t}function cs(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 Eo(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||cs(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]&&Eo(i[s],e,n||typeof t.type!="function");n||os(t.__e),t.__c=t.__=t.__e=void 0}function Hu(t,e,n){return this.constructor(t,n)}function hi(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=[],ls(e,t=(!i&&n||e).__k=ze(ot,null,[t]),s||Cn,Cn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?et.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),To(o,t,r)}function Io(t,e){hi(t,e,Io)}function ds(t,e,n){var i,s,o,r,a=rt({},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?et.call(arguments,2):n),Tn(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,as(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"+_o++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}et=bo.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}},Ft=0,tt.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=rt({},this.state),typeof t=="function"&&(t=t(rt({},n),this.props)),t&&rt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),as(this))},tt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),as(this))},tt.prototype.render=ot,Vt=[],go=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,vo=function(t,e){return t.__v.__b-e.__v.__b},di.__r=0,yo=/(PointerCapture)$|Capture$/i,is=0,ss=ko(!1),rs=ko(!0),_o=0;var Wu=0;function E(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:--Wu,__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 us(){return(us=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 zu=["context","children"];function qu(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,zu);return ds(e,n)}function Ku(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=ze(qu,us({},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[Ro(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),d=l[r].slot;d?o[d]=ze(Po,{name:d},c):s[r]=c}var u=i?ze(Po,null,s):s;return ze(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Io:hi)(this._vdom,this._root)}function Ro(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Xu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ro(t)]=n,this._vdom=ds(this._vdom,i),hi(this._vdom,this._root)}}function Yu(){hi(this._vdom=null,this._root)}function Po(t,e){var n=this;return ze("slot",us({},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 Zu(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=Ku,s.prototype.attributeChangedCallback=Xu,s.prototype.disconnectedCallback=Yu,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 Ct,le,hs,Lo,An=0,Mo=[],me=G,Do=me.__b,Oo=me.__r,No=me.diffed,Fo=me.__c,Vo=me.unmount,Bo=me.__;function nn(t,e){me.__h&&me.__h(le,t,An||e),An=0;var n=le.__H||(le.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Te(t){return An=1,jo(Go,t)}function jo(t,e,n){var i=nn(Ct++,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=le,!le.__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 g=f.__[0];f.__=f.__N,f.__N=void 0,g!==f.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};le.__f=!0;var o=le.shouldComponentUpdate,r=le.componentWillUpdate;le.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)},le.shouldComponentUpdate=s}return i.__N||i.__}function Pe(t,e){var n=nn(Ct++,3);!me.__s&&ms(n.__H,e)&&(n.__=t,n.u=e,le.__H.__h.push(n))}function Uo(t,e){var n=nn(Ct++,4);!me.__s&&ms(n.__H,e)&&(n.__=t,n.u=e,le.__h.push(n))}function _e(t){return An=5,qe(function(){return{current:t}},[])}function qe(t,e){var n=nn(Ct++,7);return ms(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function kt(t,e){return An=8,qe(function(){return t},e)}function Ce(t){var e=le.context[t.__c],n=nn(Ct++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(le)),e.props.value):t.__}function Ju(t,e){me.useDebugValue&&me.useDebugValue(e?e(t):t)}function fs(){var t=nn(Ct++,11);if(!t.__){for(var e=le.__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 Qu(){for(var t;t=Mo.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(fi),t.__H.__h.forEach(ps),t.__H.__h=[]}catch(e){t.__H.__h=[],me.__e(e,t.__v)}}me.__b=function(t){le=null,Do&&Do(t)},me.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Bo&&Bo(t,e)},me.__r=function(t){Oo&&Oo(t),Ct=0;var e=(le=t.__c).__H;e&&(hs===le?(e.__h=[],le.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(fi),e.__h.forEach(ps),e.__h=[],Ct=0)),hs=le},me.diffed=function(t){No&&No(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Mo.push(e)!==1&&Lo===me.requestAnimationFrame||((Lo=me.requestAnimationFrame)||eh)(Qu)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),hs=le=null},me.__c=function(t,e){e.some(function(n){try{n.__h.forEach(fi),n.__h=n.__h.filter(function(i){return!i.__||ps(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],me.__e(i,n.__v)}}),Fo&&Fo(t,e)},me.unmount=function(t){Vo&&Vo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{fi(i)}catch(s){e=s}}),n.__H=void 0,e&&me.__e(e,n.__v))};var $o=typeof requestAnimationFrame=="function";function eh(t){var e,n=function(){clearTimeout(i),$o&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);$o&&(e=requestAnimationFrame(n))}function fi(t){var e=le,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),le=e}function ps(t){var e=le;t.__c=t.__(),le=e}function ms(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 En={},Ho=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Wo=t=>"init"in t,gs=t=>!!t.write,zo=t=>"v"in t||"e"in t,pi=t=>{if("e"in t)throw t.e;if((En?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},mi=new WeakMap,qo=t=>{var e;return gi(t)&&!!((e=mi.get(t))!=null&&e[0])},th=t=>{const e=mi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Ko=(t,e)=>{let n=mi.get(t);if(!n){n=[!0,new Set],mi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},gi=t=>typeof(t==null?void 0:t.then)=="function",Xo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},vs=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(gi(e))for(const r of i.d.keys())Xo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,gi(o)&&th(o))},Yo=(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},nh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},ys=()=>{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},ih=t=>(t.c||(t.c=ys()),t.m||(t.m=ys()),t.u||(t.u=ys()),t.f||(t.f=nh()),t),sh=Symbol(),Zo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...g)=>f.read(...g),l=(f,...g)=>f.write(...g),c=(f,g)=>{var _;return(_=f.unstable_onInit)==null?void 0:_.call(f,g)},d=(f,g)=>{var _;return(_=f.onMount)==null?void 0:_.call(f,g)},...u)=>{const f=u[0]||(S=>{if((En?"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,O)),C}),g=u[1]||(()=>{const S=[],C=p=>{try{p()}catch(m){S.push(m)}};do{r.f&&C(r.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(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),p.forEach(C),i.size&&_()}while(i.size||o.size||s.size);if(S.length)throw new AggregateError(S)}),_=u[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((En?"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 T of Yo(h,b,e))C.has(T)||m.push(T)}for(let h=S.length-1;h>=0;--h){const[b,T]=S[h];let R=!1;for(const I of T.d.keys())if(I!==b&&i.has(I)){R=!0;break}R&&(v(b),x(b)),n.delete(b)}}),v=u[3]||(S=>{var C;const p=f(S);if(zo(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([M,V])=>v(M).n===V)))return p;p.d.clear();let m=!0;const h=()=>{e.has(S)&&(x(S),_(),g())},b=M=>{var V;if(Ho(S,M)){const N=f(M);if(!zo(N))if(Wo(M))vs(M,M.init,f);else throw new Error("no atom init");return pi(N)}const q=v(M);try{return pi(q)}finally{p.d.set(M,q.n),qo(p.v)&&Xo(S,p.v,q),(V=e.get(M))==null||V.t.add(S),m||h()}};let T,R;const I={get signal(){return T||(T=new AbortController),T.signal},get setSelf(){return(En?"production":void 0)!=="production"&&!gs(S)&&console.warn("setSelf function cannot be used with read-only atom"),!R&&gs(S)&&(R=(...M)=>{if((En?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return y(S,...M)}finally{_(),g()}}),R}},D=p.n;try{const M=a(S,b,I);return vs(S,M,f),gi(M)&&(Ko(M,()=>T==null?void 0:T.abort()),M.then(h,h)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{m=!1,D!==p.n&&n.get(S)===D&&(n.set(S,p.n),i.add(S),(C=r.c)==null||C.call(r,S))}}),w=u[4]||(S=>{const C=[S];for(;C.length;){const p=C.pop(),m=f(p);for(const h of Yo(p,m,e)){const b=f(h);n.set(h,b.n),C.push(h)}}}),y=u[5]||((S,...C)=>{let p=!0;const m=b=>pi(v(b)),h=(b,...T)=>{var R;const I=f(b);try{if(Ho(S,b)){if(!Wo(b))throw new Error("atom not writable");const D=I.n,M=T[0];vs(b,M,f),x(b),D!==I.n&&(i.add(b),(R=r.c)==null||R.call(r,b),w(b));return}else return y(b,...T)}finally{p||(_(),g())}};try{return l(S,m,h,...C)}finally{p=!1}}),x=u[6]||(S=>{var C;const p=f(S),m=e.get(S);if(m&&!qo(p.v)){for(const[h,b]of p.d)if(!m.d.has(h)){const T=f(h);k(h).t.add(S),m.d.add(h),b!==T.n&&(i.add(h),(C=r.c)==null||C.call(r,h),w(h))}for(const h of m.d||[])if(!p.d.has(h)){m.d.delete(h);const b=A(h);b==null||b.t.delete(S)}}}),k=u[7]||(S=>{var C;const p=f(S);let m=e.get(S);if(!m){v(S);for(const h of p.d.keys())k(h).t.add(S);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,m),(C=r.m)==null||C.call(r,S),gs(S)){const h=()=>{let b=!0;const T=(...R)=>{try{return y(S,...R)}finally{b||(_(),g())}};try{const R=d(S,T);R&&(m.u=()=>{b=!0;try{R()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return m}),A=u[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&&o.add(m.u),m=void 0,e.delete(S),(C=r.u)==null||C.call(r,S);for(const h of p.d.keys()){const b=A(h);b==null||b.t.delete(S)}return}return m}),P=[t,e,n,i,s,o,r,a,l,c,d,f,g,_,v,w,y,x,k,A],O={get:S=>pi(v(S)),set:(S,...C)=>{try{return y(S,...C)}finally{_(),g()}},sub:(S,C)=>{const m=k(S).l;return m.add(C),g(),()=>{m.delete(C),A(S),g()}}};return Object.defineProperty(O,sh,{value:P}),O},rh=ih,Jo=Ko,_s={};let oh=0;function bs(t,e){const n=`atom${++oh}`,i={toString(){return(_s?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=ah,i.write=lh),i}function ah(t){return t(this)}function lh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const ch=()=>{let t=0;const e=rh({}),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 dh(){return(_s?"production":void 0)!=="production"?ch():Zo()}let In;function uh(){return In||(In=dh(),(_s?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=In),globalThis.__JOTAI_DEFAULT_STORE__!==In&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),In}function Qo(t,e){for(var n in e)t[n]=e[n];return t}function ea(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 ta=Uo;function na(t,e){this.props=t,this.context=e}(na.prototype=new tt).isPureReactComponent=!0,na.prototype.shouldComponentUpdate=function(t,e){return ea(this.props,t)||ea(this.state,e)};var ia=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ia&&ia(t)};var hh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function fh(t){function e(n){var i=Qo({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=hh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var sa=function(t,e){return t==null?null:at(at(t).map(e))},ph={map:sa,forEach:sa,count:function(t){return t?at(t).length:0},only:function(t){var e=at(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:at},mh=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)}mh(t,e,n,i)};var ra=G.unmount;function oa(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=Qo({},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 oa(i,e,n)})),t}function aa(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return aa(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 ws(){this.__u=0,this.o=null,this.__b=null}function la(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function vi(){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),ra&&ra(t)},(ws.prototype=new tt).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=la(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]=aa(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)},ws.prototype.componentWillUnmount=function(){this.o=[]},ws.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]=oa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&ze(ot,null,t.fallback);return s&&(s.__u&=-33),[ze(ot,null,e.__a?null:t.children),s]};var ca=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]}};(vi.prototype=new tt).__a=function(t){var e=this,n=la(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),ca(e,t,i)):s()};n?n(o):o()}},vi.prototype.render=function(t){this.i=null,this.l=new Map;var e=at(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},vi.prototype.componentDidUpdate=vi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){ca(t,n,e)})};var da=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,gh=/^(?: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]/,vh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,yh=/[A-Z0-9]/g,_h=typeof document<"u",bh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};tt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(tt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var ua=G.event;function wh(){}function Sh(){return this.cancelBubble}function xh(){return this.defaultPrevented}G.event=function(t){return ua&&(t=ua(t)),t.persist=wh,t.isPropagationStopped=Sh,t.isDefaultPrevented=xh,t.nativeEvent=t};var Ch={enumerable:!1,configurable:!0,get:function(){return this.class}},ha=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||_h&&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"||bh(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":vh.test(r)&&(r=l):l=r="oninput":o&&gh.test(r)?r=r.replace(yh,"-$&").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=at(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=at(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",Ch)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=da,ha&&ha(t)};var fa=G.__r;G.__r=function(t){fa&&fa(t),t.__c};var pa=G.diffed;G.diffed=function(t){pa&&pa(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===da}function kh(t){return ma(t)?ds.apply(null,arguments):t}var ga={};const Th={},Ah=vt(void 0);function va(t){return Ce(Ah)||uh()}const Ss=t=>typeof(t==null?void 0:t.then)=="function",xs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Eh=ga.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(xs(t),t)}),Cs=new WeakMap,ya=(t,e)=>{let n=Cs.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();Ss(c)?(Cs.set(c,n),o=c,c.then(r(c),a(c)),Jo(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),Jo(t,l)}),Cs.set(t,n)),n};function _a(t,e){const{delay:n,unstable_promiseStatus:i=!ga.use}={},s=va(),[[o,r,a],l]=jo(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)),Pe(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);Ss(u)&&xs(ya(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),d},[s,t,n,i]),Ju(c),Ss(c)){const d=ya(c,()=>s.get(t));return i&&xs(d),Eh(d)}return c}function ks(t,e){const n=va();return kt((...s)=>{if((Th?"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[_a(t),ks(t)]}const Ts=vt({});function yi(t){const e=_e(null);return e.current===null&&(e.current=t()),e.current}const As=typeof window<"u",wa=As?Uo:Pe,_i=vt(null);function Es(t,e){t.indexOf(e)===-1&&t.push(e)}function Is(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const yt=(t,e,n)=>n>e?e:n<t?t:n;let Rs=()=>{};const _t={},Sa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function xa(t){return typeof t=="object"&&t!==null}const Ca=t=>/^0[^.\s]+$/u.test(t);function Ps(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ke=t=>t,Ih=(t,e)=>n=>e(t(n)),Rn=(...t)=>t.reduce(Ih),Pn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Ls{constructor(){this.subscriptions=[]}add(e){return Es(this.subscriptions,e),()=>Is(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 lt=t=>t*1e3,ct=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,Rh=1e-7,Ph=12;function Lh(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)>Rh&&++a<Ph);return r}function Ln(t,e,n,i){if(t===e&&n===i)return Ke;const s=o=>Lh(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=Ln(.33,1.53,.69,.99),Ms=Ea(Ia),Ra=Aa(Ms),Pa=t=>(t*=2)<1?.5*Ms(t):.5*(2-Math.pow(2,-10*(t-1))),Ds=t=>1-Math.sin(Math.acos(t)),La=Ea(Ds),Ma=Aa(Ds),Mh=Ln(.42,0,1,1),Dh=Ln(0,0,.58,1),Da=Ln(.42,0,.58,1),Oh=t=>Array.isArray(t)&&typeof t[0]!="number",Oa=t=>Array.isArray(t)&&typeof t[0]=="number",Nh={linear:Ke,easeIn:Mh,easeInOut:Da,easeOut:Dh,circIn:Ds,circInOut:Ma,circOut:La,backIn:Ms,backInOut:Ra,backOut:Ia,anticipate:Pa},Fh=t=>typeof t=="string",Na=t=>{if(Oa(t)){Rs(t.length===4);const[e,n,i,s]=t;return Ln(e,n,i,s)}else if(Fh(t))return Nh[t];return t},bi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Fa={value:null};function Vh(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,g=!1)=>{const v=g&&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 Bh=40;function Va(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=bi.reduce((k,A)=>(k[A]=Vh(o,e?A:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:f,render:g,postRender:_}=r,v=()=>{const k=_t.useManualTiming?s.timestamp:performance.now();n=!1,_t.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(k-s.timestamp,Bh),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),g.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},w=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:bi.reduce((k,A)=>{const P=r[A];return k[A]=(O,S=!1,C=!1)=>(n||w(),P.schedule(O,S,C)),k},{}),cancel:k=>{for(let A=0;A<bi.length;A++)r[bi[A]].cancel(k)},state:s,steps:r}}const{schedule:ue,cancel:Tt,state:Ae,steps:Os}=Va(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ke,!0);let wi;function jh(){wi=void 0}const je={now:()=>(wi===void 0&&je.set(Ae.isProcessing||_t.useManualTiming?Ae.timestamp:performance.now()),wi),set:t=>{wi=t,queueMicrotask(jh)}},Ba=t=>e=>typeof e=="string"&&e.startsWith(t),Ns=Ba("--"),Uh=Ba("var(--"),Fs=t=>Uh(t)?$h.test(t.split("/*")[0].trim()):!1,$h=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,sn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Mn={...sn,transform:t=>yt(0,1,t)},Si={...sn,default:1},Dn=t=>Math.round(t*1e5)/1e5,Vs=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Gh(t){return t==null}const Hh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Bs=(t,e)=>n=>!!(typeof n=="string"&&Hh.test(n)&&n.startsWith(t)||e&&!Gh(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(Vs);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Wh=t=>yt(0,255,t),js={...sn,transform:t=>Math.round(Wh(t))},Bt={test:Bs("rgb","red"),parse:ja("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+js.transform(t)+", "+js.transform(e)+", "+js.transform(n)+", "+Dn(Mn.transform(i))+")"};function zh(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 Us={test:Bs("#"),parse:zh,transform:Bt.transform},On=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),At=On("deg"),dt=On("%"),H=On("px"),qh=On("vh"),Kh=On("vw"),Ua={...dt,parse:t=>dt.parse(t)/100,transform:t=>dt.transform(t*100)},rn={test:Bs("hsl","hue"),parse:ja("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+dt.transform(Dn(e))+", "+dt.transform(Dn(n))+", "+Dn(Mn.transform(i))+")"},we={test:t=>Bt.test(t)||Us.test(t)||rn.test(t),parse:t=>Bt.test(t)?Bt.parse(t):rn.test(t)?rn.parse(t):Us.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Bt.transform(t):rn.transform(t),getAnimatableNone:t=>{const e=we.parse(t);return e.alpha=0,we.transform(e)}},Xh=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Yh(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Vs))==null?void 0:e.length)||0)+(((n=t.match(Xh))==null?void 0:n.length)||0)>0}const $a="number",Ga="color",Zh="var",Jh="var(",Ha="${}",Qh=/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 Nn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Qh,l=>(we.test(l)?(i.color.push(o),s.push(Ga),n.push(we.parse(l))):l.startsWith(Jh)?(i.var.push(o),s.push(Zh),n.push(l)):(i.number.push(o),s.push($a),n.push(parseFloat(l))),++o,Ha)).split(Ha);return{values:n,split:a,indexes:i,types:s}}function Wa(t){return Nn(t).values}function za(t){const{split:e,types:n}=Nn(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+=Dn(s[r]):a===Ga?o+=we.transform(s[r]):o+=s[r]}return o}}const ef=t=>typeof t=="number"?0:we.test(t)?we.getAnimatableNone(t):t;function tf(t){const e=Wa(t);return za(t)(e.map(ef))}const Et={test:Yh,parse:Wa,createTransformer:za,getAnimatableNone:tf};function $s(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 nf({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=$s(l,a,t+1/3),o=$s(l,a,t),r=$s(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function xi(t,e){return n=>n>0?e:t}const ge=(t,e,n)=>t+(e-t)*n,Gs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},sf=[Us,Bt,rn],rf=t=>sf.find(e=>e.test(t));function qa(t){const e=rf(t);if(!e)return!1;let n=e.parse(t);return e===rn&&(n=nf(n)),n}const Ka=(t,e)=>{const n=qa(t),i=qa(e);if(!n||!i)return xi(t,e);const s={...n};return o=>(s.red=Gs(n.red,i.red,o),s.green=Gs(n.green,i.green,o),s.blue=Gs(n.blue,i.blue,o),s.alpha=ge(n.alpha,i.alpha,o),Bt.transform(s))},Hs=new Set(["none","hidden"]);function of(t,e){return Hs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function af(t,e){return n=>ge(t,e,n)}function Ws(t){return typeof t=="number"?af:typeof t=="string"?Fs(t)?xi:we.test(t)?Ka:df:Array.isArray(t)?Xa:typeof t=="object"?we.test(t)?Ka:lf:xi}function Xa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ws(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);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]=Ws(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function cf(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 df=(t,e)=>{const n=Et.createTransformer(e),i=Nn(t),s=Nn(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?Hs.has(t)&&!s.values.length||Hs.has(e)&&!i.values.length?of(t,e):Rn(Xa(cf(i,s),s.values),n):xi(t,e)};function Ya(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ge(t,e,n):Ws(t)(t,e)}const uf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ue.update(e,n),stop:()=>Tt(e),now:()=>Ae.isProcessing?Ae.timestamp:je.now()}},Za=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ci=2e4;function zs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ci;)e+=n,i=t.next(e);return e>=Ci?1/0:e}function hf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(zs(i),Ci);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:ct(s)}}const ff=5;function Ja(t,e,n){const i=Math.max(e-ff,0);return ka(n-t(i),e-i)}const ve={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},qs=.001;function pf({duration:t=ve.duration,bounce:e=ve.bounce,velocity:n=ve.velocity,mass:i=ve.mass}){let s,o,r=1-e;r=yt(ve.minDamping,ve.maxDamping,r),t=yt(ve.minDuration,ve.maxDuration,ct(t)),r<1?(s=c=>{const d=c*r,u=d*t,f=d-n,g=Ks(c,r),_=Math.exp(-u);return qs-f/g*_},o=c=>{const u=c*r*t,f=u*n+n,g=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-u),v=Ks(Math.pow(c,2),r);return(-s(c)+qs>0?-1:1)*((f-g)*_)/v}):(s=c=>{const d=Math.exp(-c*t),u=(c-n)*t+1;return-qs+d*u},o=c=>{const d=Math.exp(-c*t),u=(n-c)*(t*t);return d*u});const a=5/t,l=gf(s,o,a);if(t=lt(t),isNaN(l))return{stiffness:ve.stiffness,damping:ve.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const mf=12;function gf(t,e,n){let i=n;for(let s=1;s<mf;s++)i=i-t(i)/e(i);return i}function Ks(t,e){return t*Math.sqrt(1-e*e)}const vf=["duration","bounce"],yf=["stiffness","damping","mass"];function Qa(t,e){return e.some(n=>t[n]!==void 0)}function _f(t){let e={velocity:ve.velocity,stiffness:ve.stiffness,damping:ve.damping,mass:ve.mass,isResolvedFromDuration:!1,...t};if(!Qa(t,yf)&&Qa(t,vf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*yt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ve.mass,stiffness:s,damping:o}}else{const n=pf(t);e={...e,...n,mass:ve.mass},e.isResolvedFromDuration=!0}return e}function ki(t=ve.visualDuration,e=ve.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:g}=_f({...n,velocity:-ct(n.velocity||0)}),_=f||0,v=c/(2*Math.sqrt(l*d)),w=r-o,y=ct(Math.sqrt(l/d)),x=Math.abs(w)<5;i||(i=x?ve.restSpeed.granular:ve.restSpeed.default),s||(s=x?ve.restDelta.granular:ve.restDelta.default);let k;if(v<1){const P=Ks(y,v);k=O=>{const S=Math.exp(-v*y*O);return r-S*((_+v*y*w)/P*Math.sin(P*O)+w*Math.cos(P*O))}}else if(v===1)k=P=>r-Math.exp(-y*P)*(w+(_+y*w)*P);else{const P=y*Math.sqrt(v*v-1);k=O=>{const S=Math.exp(-v*y*O),C=Math.min(P*O,300);return r-S*((_+v*y*w)*Math.sinh(C)+P*w*Math.cosh(C))/P}}const A={calculatedDuration:g&&u||null,next:P=>{const O=k(P);if(g)a.done=P>=u;else{let S=P===0?_:0;v<1&&(S=P===0?lt(_):Ja(k,P,O));const C=Math.abs(S)<=i,p=Math.abs(r-O)<=s;a.done=C&&p}return a.value=a.done?r:O,a},toString:()=>{const P=Math.min(zs(A),Ci),O=Za(S=>A.next(P*S).value,P,30);return P+"ms "+O},toTransition:()=>{}};return A}ki.applyToOptions=t=>{const e=hf(t,100,ki);return t.ease=e.ease,t.duration=lt(e.duration),t.type="keyframes",t};function Xs({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},g=C=>a!==void 0&&C<a||l!==void 0&&C>l,_=C=>a===void 0?l:l===void 0||Math.abs(a-C)<Math.abs(l-C)?a:l;let v=n*e;const w=u+v,y=r===void 0?w:r(w);y!==w&&(v=y-u);const x=C=>-v*Math.exp(-C/i),k=C=>y+x(C),A=C=>{const p=x(C),m=k(C);f.done=Math.abs(p)<=c,f.value=f.done?y:m};let P,O;const S=C=>{g(f.value)&&(P=C,O=ki({keyframes:[f.value,_(f.value)],velocity:Ja(k,C,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return S(0),{calculatedDuration:null,next:C=>{let p=!1;return!O&&P===void 0&&(p=!0,A(C),S(C)),P!==void 0&&C>=P?O.next(C-P):(!p&&A(C),f)}}}function bf(t,e,n){const i=[],s=n||_t.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]||Ke:e;a=Rn(l,a)}i.push(a)}return i}function wf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Rs(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=bf(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=Pn(t[u],t[u+1],d);return a[u](f)};return n?d=>c(yt(t[0],t[o-1],d)):c}function Sf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Pn(0,e,i);t.push(ge(n,1,s))}}function xf(t){const e=[0];return Sf(e,t.length-1),e}function Cf(t,e){return t.map(n=>n*e)}function kf(t,e){return t.map(()=>e||Da).splice(0,t.length-1)}function Fn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Oh(i)?i.map(Na):Na(i),o={done:!1,value:e[0]},r=Cf(n&&n.length===e.length?n:xf(e),t),a=wf(r,e,{ease:Array.isArray(s)?s:kf(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Tf=t=>t!==null;function Ys(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Tf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Af={decay:Xs,inertia:Xs,tween:Fn,keyframes:Fn,spring:ki};function el(t){typeof t.type=="string"&&(t.type=Af[t.type])}class Zs{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 Ef=t=>t/100;class Js extends Zs{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!==je.now()&&this.tick(je.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=Fn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||Fn;l!==Fn&&typeof a[0]!="number"&&(this.mixKeyframes=Rn(Ef,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=zs(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:g,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),x=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,A=i;if(u){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,u+1),!!(p%2)&&(f==="reverse"?(m=1-m,g&&(m-=g/a)):f==="mirror"&&(A=r)),k=yt(0,1,m)*a}const P=x?{done:!1,value:d[0]}:A.next(k);o&&(P.value=o(P.value));let{done:O}=P;!x&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return S&&_!==Xs&&(P.value=Ys(d,this.options,w,this.speed)),v&&v(P.value),S&&this.finish(),P}then(e,n){return this.finished.then(e,n)}get duration(){return ct(this.calculatedDuration)}get time(){return ct(this.currentTime)}set time(e){var n;e=lt(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(je.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=ct(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=uf,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(je.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 If(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const jt=t=>t*180/Math.PI,Qs=t=>{const e=jt(Math.atan2(t[1],t[0]));return er(e)},Rf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Qs,rotateZ:Qs,skewX:t=>jt(Math.atan(t[1])),skewY:t=>jt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},er=t=>(t=t%360,t<0&&(t+=360),t),tl=Qs,nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),il=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Pf={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=>er(jt(Math.atan2(t[6],t[5]))),rotateY:t=>er(jt(Math.atan2(-t[2],t[0]))),rotateZ:tl,rotate:tl,skewX:t=>jt(Math.atan(t[4])),skewY:t=>jt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function tr(t){return t.includes("scale")?1:0}function nr(t,e){if(!t||t==="none")return tr(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Pf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Rf,s=a}if(!s)return tr(e);const o=i[e],r=s[1].split(",").map(Mf);return typeof o=="function"?o(r):r[o]}const Lf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return nr(n,e)};function Mf(t){return parseFloat(t.trim())}const on=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],an=new Set(on),sl=t=>t===sn||t===H,Df=new Set(["x","y","z"]),Of=on.filter(t=>!Df.has(t));function Nf(t){const e=[];return Of.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ut={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})=>nr(e,"x"),y:(t,{transform:e})=>nr(e,"y")};Ut.translateX=Ut.x,Ut.translateY=Ut.y;const $t=new Set;let ir=!1,sr=!1,rr=!1;function rl(){if(sr){const t=Array.from($t).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Nf(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)})}sr=!1,ir=!1,$t.forEach(t=>t.complete(rr)),$t.clear()}function ol(){$t.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(sr=!0)})}function Ff(){rr=!0,ol(),rl(),rr=!1}class or{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?($t.add(this),ir||(ir=!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])}If(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),$t.delete(this)}cancel(){this.state==="scheduled"&&($t.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Vf=t=>t.startsWith("--");function Bf(t,e,n){Vf(e)?t.style.setProperty(e,n):t.style[e]=n}const jf=Ps(()=>window.ScrollTimeline!==void 0),Uf={};function $f(t,e){const n=Ps(t);return()=>Uf[e]??n()}const al=$f(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Vn=([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:Vn([0,.65,.55,1]),circOut:Vn([.55,0,1,.45]),backIn:Vn([.31,.01,.66,-.59]),backOut:Vn([.33,1.53,.69,.99])};function cl(t,e){if(t)return typeof t=="function"?al()?Za(t,e):"ease-out":Oa(t)?Vn(t):Array.isArray(t)?t.map(n=>cl(n,e)||ll.easeOut):ll[t]}function Gf(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 Hf({type:t,...e}){return dl(t)&&al()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Wf extends Zs{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,Rs(typeof e.type!="string");const c=Hf(e);this.animation=Gf(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Ys(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Bf(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 ct(Number(e))}get time(){return ct(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=lt(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&&jf()?(this.animation.timeline=e,Ke):n(this)}}const ul={anticipate:Pa,backInOut:Ra,circInOut:Ma};function zf(t){return t in ul}function qf(t){typeof t.ease=="string"&&zf(t.ease)&&(t.ease=ul[t.ease])}const hl=10;class Kf extends Wf{constructor(e){qf(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 Js({...r,autoplay:!1}),l=lt(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"&&(Et.test(t)||t==="0")&&!t.startsWith("url("));function Xf(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 Yf(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:Xf(t)||(n==="spring"||dl(n))&&i}function ar(t){return xa(t)&&"offsetHeight"in t}const Zf=new Set(["opacity","clipPath","filter","transform"]),Jf=Ps(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Qf(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!ar((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return Jf()&&n&&Zf.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const ep=40;class tp extends Zs{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=je.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},g=(d==null?void 0:d.KeyframeResolver)||or;this.keyframeResolver=new g(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=je.now(),Yf(e,o,r,a)||((_t.instantAnimations||!l)&&(d==null||d(Ys(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>ep?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!c&&Qf(f)?new Kf({...f,element:f.motionValue.owner.current}):new Js(f);g.finished.then(()=>this.notifyFinished()).catch(Ke),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(),Ff()),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 np=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ip(t){const e=np.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function pl(t,e,n=1){const[i,s]=ip(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Sa(r)?parseFloat(r):r}return Fs(s)?pl(s,e,n+1):s}function lr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const ml=new Set(["width","height","top","left","right","bottom",...on]),sp={test:t=>t==="auto",parse:t=>t},gl=t=>e=>e.test(t),vl=[sn,H,dt,At,Kh,qh,sp],yl=t=>vl.find(gl(t));function rp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ca(t):!0}const op=new Set(["brightness","contrast","saturate","opacity"]);function ap(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Vs)||[];if(!i)return t;const s=n.replace(i,"");let o=op.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const lp=/\b([a-z-]*)\(.*?\)/gu,cr={...Et,getAnimatableNone:t=>{const e=t.match(lp);return e?e.map(ap).join(" "):t}},_l={...sn,transform:Math.round},dr={borderWidth:H,borderTopWidth:H,borderRightWidth:H,borderBottomWidth:H,borderLeftWidth:H,borderRadius:H,radius:H,borderTopLeftRadius:H,borderTopRightRadius:H,borderBottomRightRadius:H,borderBottomLeftRadius:H,width:H,maxWidth:H,height:H,maxHeight:H,top:H,right:H,bottom:H,left:H,padding:H,paddingTop:H,paddingRight:H,paddingBottom:H,paddingLeft:H,margin:H,marginTop:H,marginRight:H,marginBottom:H,marginLeft:H,backgroundPositionX:H,backgroundPositionY:H,...{rotate:At,rotateX:At,rotateY:At,rotateZ:At,scale:Si,scaleX:Si,scaleY:Si,scaleZ:Si,skew:At,skewX:At,skewY:At,distance:H,translateX:H,translateY:H,translateZ:H,x:H,y:H,z:H,perspective:H,transformPerspective:H,opacity:Mn,originX:Ua,originY:Ua,originZ:H},zIndex:_l,fillOpacity:Mn,strokeOpacity:Mn,numOctaves:_l},cp={...dr,color:we,backgroundColor:we,outlineColor:we,fill:we,stroke:we,borderColor:we,borderTopColor:we,borderRightColor:we,borderBottomColor:we,borderLeftColor:we,filter:cr,WebkitFilter:cr},bl=t=>cp[t];function wl(t,e){let n=bl(t);return n!==cr&&(n=Et),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const dp=new Set(["auto","none","0"]);function up(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!dp.has(o)&&Nn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=wl(n,s)}class hp extends or{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(),Fs(c))){const d=pl(c,n.current);d!==void 0&&(e[l]=d),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!ml.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 Ut[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||rp(e[s]))&&i.push(s);i.length&&up(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=Ut[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]=Ut[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 fp(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,xl=30,pp=t=>!isNaN(parseFloat(t));class mp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=je.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=je.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=pp(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 Ls);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=je.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>xl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,xl);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 ln(t,e){return new mp(t,e)}const{schedule:ur}=Va(queueMicrotask,!1),nt={x:!1,y:!1};function Cl(){return nt.x||nt.y}function gp(t){return t==="x"||t==="y"?nt[t]?null:(nt[t]=!0,()=>{nt[t]=!1}):nt.x||nt.y?null:(nt.x=nt.y=!0,()=>{nt.x=nt.y=!1})}function kl(t,e){const n=fp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Tl(t){return!(t.pointerType==="touch"||Cl())}function vp(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,hr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,yp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function _p(t){return yp.has(t.tagName)||t.tabIndex!==-1}const Ti=new WeakSet;function El(t){return e=>{e.key==="Enter"&&t(e)}}function fr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const bp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=El(()=>{if(Ti.has(n))return;fr(n,"down");const s=El(()=>{fr(n,"up")}),o=()=>fr(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 hr(t)&&!Cl()}function wp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{const l=a.currentTarget;if(!Il(a))return;Ti.add(l);const c=e(l,a),d=(g,_)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),Ti.has(l)&&Ti.delete(l),Il(g)&&typeof c=="function"&&c(g,{success:_})},u=g=>{d(g,l===window||l===document||n.useGlobalTarget||Al(l,g.target))},f=g=>{d(g,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),ar(a)&&(a.addEventListener("focus",c=>bp(c,s)),!_p(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Rl(t){return xa(t)&&"ownerSVGElement"in t}function Sp(t){return Rl(t)&&t.tagName==="svg"}const Le=t=>!!(t&&t.getVelocity),xp=[...vl,we,Et],Cp=t=>xp.find(gl(t)),Bn=vt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class kp extends tt{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=ar(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 Tp({children:t,isPresent:e,anchorX:n,root:i}){const s=fs(),o=_e(null),r=_e({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Ce(Bn);return ta(()=>{const{width:l,height:c,top:d,left:u,right:f}=r.current;if(e||!o.current||!l||!c)return;const g=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(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
@@ -6,14 +6,14 @@ var q_=Object.defineProperty;var K_=(et,H,Ft)=>H in et?q_(et,H,{enumerable:!0,co
6
6
  ${g}px !important;
7
7
  top: ${d}px !important;
8
8
  }
9
- `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),A(kp,{isPresent:e,childRef:o,sizeRef:r,children:kh(t,{ref:o})})}const Ep=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=yi(Ap),d=fs();let u=!0,f=qe(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:g=>{c.set(g,!0);for(const _ of c.values())if(!_)return;i&&i()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[n,c,i]);return o&&u&&(f={...f}),qe(()=>{c.forEach((g,_)=>c.set(_,!1))},[n]),Pe(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=A(Tp,{isPresent:n,anchorX:a,root:l,children:t})),A(_i.Provider,{value:f,children:t})};function Ap(){return new Map}function Pl(t=!0){const e=Ce(_i);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=fs();Pe(()=>{if(t)return s(o)},[t]);const r=kt(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Ei=t=>t.key||"";function Ll(t){const e=[];return ph.forEach(t,n=>{ma(n)&&e.push(n)}),e}const Ip=({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]=Pl(r),u=qe(()=>Ll(t),[t]),f=r&&!c?[]:u.map(Ei),g=_e(!0),_=_e(u),v=yi(()=>new Map),[w,y]=Te(u),[x,C]=Te(u);wa(()=>{g.current=!1,_.current=u;for(let O=0;O<x.length;O++){const S=Ei(x[O]);f.includes(S)?v.delete(S):v.get(S)!==!0&&v.set(S,!1)}},[x,f.length,f.join("-")]);const E=[];if(u!==w){let O=[...u];for(let S=0;S<x.length;S++){const k=x[S],p=Ei(k);f.includes(p)||(O.splice(S,0,k),E.push(k))}return o==="wait"&&E.length&&(O=E),C(Ll(O)),y(u),null}const{forceRender:P}=Ce(Ts);return A(ot,{children:x.map(O=>{const S=Ei(O),k=r&&!c?!1:u===x||f.includes(S),p=()=>{if(v.has(S))v.set(S,!0);else return;let m=!0;v.forEach(h=>{h||(m=!1)}),m&&(P==null||P(),C(_.current),r&&(d==null||d()),i&&i())};return A(Ep,{isPresent:k,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:k?void 0:p,anchorX:a,children:O},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"]},cn={};for(const t in Dl)cn[t]={isEnabled:e=>Dl[t].some(n=>!!e[n])};function Rp(t){for(const e in t)cn[e]={...cn[e],...t[e]}}const Pp=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 Ai(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Pp.has(t)}let Ol=t=>!Ai(t);function Nl(t){typeof t=="function"&&(Ol=e=>e.startsWith("on")?!Ai(e):t(e))}try{Nl(require("@emotion/is-prop-valid").default)}catch{}function Lp(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Ol(s)||n===!0&&Ai(s)||!e&&!Ai(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Mp({children:t,isValidProp:e,...n}){e&&Nl(e),n={...Ce(Bn),...n},n.isStatic=yi(()=>n.isStatic);const i=qe(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return A(Bn.Provider,{value:i,children:t})}function Dp(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 Ii=vt({});function Ri(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function jn(t){return typeof t=="string"||Array.isArray(t)}const pr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],mr=["initial",...pr];function Pi(t){return Ri(t.animate)||mr.some(e=>jn(t[e]))}function Fl(t){return!!(Pi(t)||t.variants)}function Op(t,e){if(Pi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||jn(n)?n:void 0,animate:jn(i)?i:void 0}}return t.inherit!==!1?e:{}}function Np(t){const{initial:e,animate:n}=Op(t,Ce(Ii));return qe(()=>({initial:e,animate:n}),[Vl(e),Vl(n)])}function Vl(t){return Array.isArray(t)?t.join(" "):t}const Fp=Symbol.for("motionComponentSymbol");function dn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Vp(t,e,n){return kt(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):dn(n)&&(n.current=i))},[e])}const gr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bl="data-"+gr("framerAppearId"),jl=vt({});function Bp(t,e,n,i,s){var v,w;const{visualElement:o}=Ce(Ii),r=Ce(Ml),a=Ce(_i),l=Ce(Bn).reducedMotion,c=_e(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=Ce(jl);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&jp(c.current,n,s,u);const f=_e(!1);ta(()=>{d&&f.current&&d.update(n,a)});const g=n[Bl],_=_e(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,g)));return wa(()=>{d&&(f.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),ur.render(d.render),_.current&&d.animationState&&d.animationState.animateChanges())}),Pe(()=>{d&&(!_.current&&d.animationState&&d.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),_.current=!1))}),d}function jp(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&&dn(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 Up({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&Rp(t);function o(a,l){let c;const d={...Ce(Bn),...a,layoutId:$p(a)},{isStatic:u}=d,f=Np(a),g=i(a,u);if(!u&&Es){Gp();const _=Hp(d);c=_.MeasureLayout,f.visualElement=Bp(s,g,d,e,_.ProjectionNode)}return A(Ii.Provider,{value:f,children:[c&&f.visualElement?A(c,{visualElement:f.visualElement,...d}):null,n(s,a,Vp(g,f.visualElement,l),g,u,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=fh(o);return r[Fp]=s,r}function $p({layoutId:t}){const e=Ce(Ts).id;return e&&t!==void 0?e+"-"+t:t}function Gp(t,e){Ce(Ml).strict}function Hp(t){const{drag:e,layout:n}=cn;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 Un={};function Wp(t){for(const e in t)Un[e]=t[e],Ns(e)&&(Un[e].isCSSVariable=!0)}function $l(t,{layout:e,layoutId:n}){return an.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Un[t]||t==="opacity")}const zp={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},qp=on.length;function Kp(t,e,n){let i="",s=!0;for(let o=0;o<qp;o++){const r=on[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,dr[r]);if(!l){s=!1;const d=zp[r]||r;i+=`${d}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function vr(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(an.has(l)){r=!0;continue}else if(Ns(l)){s[l]=c;continue}else{const d=Sl(c,dr[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(e.transform||(r||n?i.transform=Kp(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 yr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Gl(t,e,n){for(const i in e)!Le(e[i])&&!$l(i,n)&&(t[i]=e[i])}function Xp({transformTemplate:t},e){return qe(()=>{const n=yr();return vr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Yp(t,e){const n=t.style||{},i={};return Gl(i,n,t),Object.assign(i,Xp(t,e)),i}function Zp(t,e){const n={},i=Yp(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 Jp={offset:"stroke-dashoffset",array:"stroke-dasharray"},Qp={offset:"strokeDashoffset",array:"strokeDasharray"};function em(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?Jp:Qp;t[o.offset]=W.transform(-i);const r=W.transform(e),a=W.transform(n);t[o.array]=`${r} ${a}`}function Hl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(vr(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&&em(u,s,o,r,!1)}const Wl=()=>({...yr(),attrs:{}}),zl=t=>typeof t=="string"&&t.toLowerCase()==="svg";function tm(t,e,n,i){const s=qe(()=>{const o=Wl();return Hl(o,e,zl(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Gl(o,t.style,t),s.style={...o,...s.style}}return s}const nm=["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 _r(t){return typeof t!="string"||t.includes("-")?!1:!!(nm.indexOf(t)>-1||/[A-Z]/u.test(t))}function im(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(_r(n)?tm:Zp)(i,o,r,n),c=Lp(i,typeof n=="string",t),d=n!==ot?{...c,...l,ref:s}:{},{children:u}=i,f=qe(()=>Le(u)?u.get():u,[u]);return ze(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 br(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 Li(t){return Le(t)?t.get():t}function sm({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:rm(n,i,s,t),renderState:e()}}const Kl=t=>(e,n)=>{const i=Ce(Ii),s=Ce(_i),o=()=>sm(t,e,i,s);return n?o():yi(o)};function rm(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=Li(o[f]);let{initial:r,animate:a}=t;const l=Pi(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"&&!Ri(u)){const f=Array.isArray(u)?u:[u];for(let g=0;g<f.length;g++){const _=br(t,f[g]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const x in y){let C=y[x];if(Array.isArray(C)){const E=d?C.length-1:0;C=C[E]}C!==null&&(s[x]=C)}for(const x in v)s[x]=v[x]}}}return s}function wr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Le(i[r])||e.style&&Le(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 om={useVisualState:Kl({scrapeMotionValuesFromProps:wr,createRenderState:yr})};function Xl(t,e,n){const i=wr(t,e,n);for(const s in t)if(Le(t[s])||Le(e[s])){const o=on.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const am={useVisualState:Kl({scrapeMotionValuesFromProps:Xl,createRenderState:Wl})};function lm(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={..._r(i)?am:om,preloadedFeatures:t,useRender:im(s),createVisualElement:e,Component:i};return Up(r)}}function $n(t,e,n){const i=t.getProps();return br(i,e,n!==void 0?n:i.custom,t)}const Sr=t=>Array.isArray(t);function cm(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,ln(n))}function dm(t){return Sr(t)?t[t.length-1]||0:t}function um(t,e){const n=$n(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=dm(o[r]);cm(t,r,a)}}function hm(t){return!!(Le(t)&&t.add)}function xr(t,e){const n=t.getValue("willChange");if(hm(n))return n.add(e);if(!n&&_t.WillChange){const i=new _t.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Yl(t){return t.props[Bl]}const fm=t=>t!==null;function pm(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(fm),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const mm={type:"spring",stiffness:500,damping:25,restSpeed:10},gm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),vm={type:"keyframes",duration:.8},ym={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},_m=(t,{keyframes:e})=>e.length>2?vm:an.has(t)?t.startsWith("scale")?gm(e[1]):mm:ym;function bm({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 Cr=(t,e,n,i={},s,o)=>r=>{const a=lr(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-lt(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};bm(a)||Object.assign(d,_m(t,d)),d.duration&&(d.duration=lt(d.duration)),d.repeatDelay&&(d.repeatDelay=lt(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)),(_t.instantAnimations||_t.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const f=pm(d.keyframes,a);if(f!==void 0){ue.update(()=>{d.onUpdate(f),d.onComplete()});return}}return a.isSync?new Js(d):new tp(d)};function wm({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function Zl(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&&wm(c,d))continue;const g={delay:n,...lr(o||{},d)},_=u.get();if(_!==void 0&&!u.isAnimating&&!Array.isArray(f)&&f===_&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Yl(t);if(y){const x=window.MotionHandoffAnimation(y,d,ue);x!==null&&(g.startTime=x,v=!0)}}xr(t,d),u.start(Cr(d,u,f,t.shouldReduceMotion&&ml.has(d)?{type:!1}:g,t,v));const w=u.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{ue.update(()=>{r&&um(t,r)})}),l}function kr(t,e,n={}){var l;const i=$n(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(Zl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:f}=s;return Sm(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 Sm(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(xm).forEach((f,g)=>{f.notify("AnimationStart",e),a.push(kr(f,e,{...r,delay:n+(d?0:i)+u(g)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function xm(t,e){return t.sortNodePosition(e)}function Cm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>kr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=kr(t,e,n);else{const s=typeof e=="function"?$n(t,e,n.custom):e;i=Promise.all(Zl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Jl(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=mr.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<km;n++){const i=mr[n],s=t.props[i];(jn(s)||s===!1)&&(e[i]=s)}return e}const Tm=[...pr].reverse(),Em=pr.length;function Am(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Cm(t,n,i)))}function Im(t){let e=Am(t),n=ec(),i=!0;const s=l=>(c,d)=>{var f;const u=$n(t,d,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(u){const{transition:g,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 g={},_=1/0;for(let w=0;w<Em;w++){const y=Tm[w],x=n[y],C=c[y]!==void 0?c[y]:d[y],E=jn(C),P=y===l?x.isActive:null;P===!1&&(_=w);let O=C===d[y]&&C!==c[y]&&E;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),x.protectedKeys={...g},!x.isActive&&P===null||!C&&!x.prevProp||Ri(C)||typeof C=="boolean")continue;const S=Rm(x.prevProp,C);let k=S||y===l&&x.isActive&&!O&&E||w>_&&E,p=!1;const m=Array.isArray(C)?C:[C];let h=m.reduce(s(y),{});P===!1&&(h={});const{prevResolvedValues:b={}}=x,T={...b,...h},L=M=>{k=!0,f.has(M)&&(p=!0,f.delete(M)),x.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in T){const F=h[M],U=b[M];if(g.hasOwnProperty(M))continue;let V=!1;Sr(F)&&Sr(U)?V=!Jl(F,U):V=F!==U,V?F!=null?L(M):f.add(M):F!==void 0&&f.has(M)?L(M):x.protectedKeys[M]=!0}x.prevProp=C,x.prevResolvedValues=h,x.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(k=!1),k&&(!(O&&S)||p)&&u.push(...m.map(M=>({animation:M,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=$n(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const x=t.getBaseTarget(y),C=t.getValue(y);C&&(C.liveStyle=!0),w[y]=x??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 g;return(g=f.animationState)==null?void 0:g.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 Rm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Jl(e,t):!1}function Gt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ec(){return{animate:Gt(!0),whileInView:Gt(),whileHover:Gt(),whileTap:Gt(),whileDrag:Gt(),whileFocus:Gt(),exit:Gt()}}class It{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Pm extends It{constructor(e){super(e),e.animationState||(e.animationState=Im(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ri(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 Lm=0;class Mm extends It{constructor(){super(...arguments),this.id=Lm++}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 Dm={animation:{Feature:Pm},exit:{Feature:Mm}};function Gn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Hn(t){return{point:{x:t.pageX,y:t.pageY}}}const Om=t=>e=>hr(e)&&t(e,Hn(e));function Wn(t,e,n,i){return Gn(t,e,Om(n),i)}function tc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Nm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Fm(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,Vm=1-nc,Bm=1+nc,ic=.01,jm=0-ic,Um=0+ic;function Ne(t){return t.max-t.min}function $m(t,e,n){return Math.abs(t-e)<=n}function sc(t,e,n,i=.5){t.origin=i,t.originPoint=ge(e.min,e.max,t.origin),t.scale=Ne(n)/Ne(e),t.translate=ge(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Vm&&t.scale<=Bm||isNaN(t.scale))&&(t.scale=1),(t.translate>=jm&&t.translate<=Um||isNaN(t.translate))&&(t.translate=0)}function zn(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+Ne(e)}function Gm(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+Ne(e)}function qn(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}),un=()=>({x:ac(),y:ac()}),lc=()=>({min:0,max:0}),be=()=>({x:lc(),y:lc()});function Xe(t){return[t("x"),t("y")]}function Tr(t){return t===void 0||t===1}function Er({scale:t,scaleX:e,scaleY:n}){return!Tr(t)||!Tr(e)||!Tr(n)}function Ht(t){return Er(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 Mi(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=Mi(t,s,i)),Mi(t,n,i)+e}function Ar(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}){Ar(t.x,e.translate,e.scale,e.originPoint),Ar(t.y,n.translate,n.scale,n.originPoint)}const fc=.999999999999,pc=1.0000000000001;function Hm(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&&fn(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&&Ht(o.latestValues)&&fn(t,o.latestValues))}e.x<pc&&e.x>fc&&(e.x=1),e.y<pc&&e.y>fc&&(e.y=1)}function hn(t,e){t.min=t.min+e,t.max=t.max+e}function mc(t,e,n,i,s=.5){const o=ge(t.min,t.max,s);Ar(t,e,n,o,i)}function fn(t,e){mc(t.x,e.x,e.scaleX,e.scale,e.originX),mc(t.y,e.y,e.scaleY,e.scale,e.originY)}function gc(t,e){return tc(Fm(t.getBoundingClientRect(),e))}function Wm(t,e,n){const i=gc(t,n),{scroll:s}=e;return s&&(hn(i.x,s.offset.x),hn(i.y,s.offset.y)),i}const vc=({current:t})=>t?t.ownerDocument.defaultView:null,yc=(t,e)=>Math.abs(t-e);function zm(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=Rr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,_=zm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!_)return;const{point:v}=f,{timestamp:w}=Ee;this.history.push({...v,timestamp:w});const{onStart:y,onMove:x}=this.handlers;g||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),x&&x(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Ir(g,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Rr(f.type==="pointercancel"?this.lastMoveEventInfo:Ir(g,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,y),v&&v(f,y)},!hr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Hn(e),l=Ir(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Ee;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Rr(l,this.history)),this.removeListeners=Rn(Wn(this.contextWindow,"pointermove",this.handlePointerMove),Wn(this.contextWindow,"pointerup",this.handlePointerUp),Wn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Tt(this.updatePoint)}}function Ir(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 Rr({point:t},e){return{point:t,delta:bc(t,wc(e)),offset:bc(t,qm(e)),velocity:Km(e,.1)}}function qm(t){return t[0]}function wc(t){return t[t.length-1]}function Km(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>lt(e)));)n--;if(!i)return{x:0,y:0};const o=ct(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 Xm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ge(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ge(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 Ym(t,{top:e,left:n,bottom:i,right:s}){return{x:Sc(t.x,n,s),y:Sc(t.y,e,i)}}function xc(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 Zm(t,e){return{x:xc(t.x,e.x),y:xc(t.y,e.y)}}function Jm(t,e){let n=.5;const i=Ne(t),s=Ne(e);return s>i?n=Pn(e.min,e.max-i,t.min):i>s&&(n=Pn(t.min,t.max-s,e.min)),yt(0,1,n)}function Qm(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 Pr=.35;function eg(t=Pr){return t===!1?t=0:t===!0&&(t=Pr),{x:Cc(t,"left","right"),y:Cc(t,"top","bottom")}}function Cc(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 tg=new WeakMap;class ng{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(Hn(u).point)},r=(u,f)=>{const{drag:g,dragPropagation:_,onDragStart:v}=this.getProps();if(g&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=gp(g),!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),Xe(y=>{let x=this.getAxisMotionValue(y).get()||0;if(dt.test(x)){const{projection:C}=this.visualElement;if(C&&C.layout){const E=C.layout.layoutBox[y];E&&(x=Ne(E)*(parseFloat(x)/100))}}this.originPoint[y]=x}),v&&ue.postRender(()=>v(u,f)),xr(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(_&&this.currentDirection===null){this.currentDirection=ig(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=()=>Xe(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||!Di(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Xm(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&&dn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Ym(i.layoutBox,e):this.constraints=!1,this.elastic=eg(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Xe(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Qm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!dn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Wm(i,s.root,this.visualElement.getTransformPagePoint());let r=Zm(s.layout.layoutBox,o);if(n){const a=n(Nm(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=Xe(d=>{if(!Di(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const f=s?200:1e6,g=s?40:1e7,_={type:"inertia",velocity:i?e[d]:0,bounceStiffness:f,bounceDamping:g,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 xr(this.visualElement,e),i.start(Cr(e,i,0,n,this.visualElement,!1))}stopAnimation(){Xe(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Xe(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){Xe(n=>{const{drag:i}=this.getProps();if(!Di(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]-ge(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!dn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Xe(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=Jm({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(),Xe(r=>{if(!Di(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ge(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;tg.set(this.visualElement,this);const e=this.visualElement.current,n=Wn(e,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();dn(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=Gn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Xe(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=Pr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Di(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function ig(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class sg extends It{constructor(e){super(e),this.removeGroupControls=Ke,this.removeListeners=Ke,this.controls=new ng(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ke}unmount(){this.removeGroupControls(),this.removeListeners()}}const Tc=t=>(e,n)=>{t&&ue.postRender(()=>t(e,n))};class rg extends It{constructor(){super(...arguments),this.removePointerDownListener=Ke}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=Wn(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 Oi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ec(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Kn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(W.test(t))t=parseFloat(t);else return t;const n=Ec(t,e.target.x),i=Ec(t,e.target.y);return`${n}% ${i}%`}},og={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=At.parse(t);if(s.length>5)return i;const o=At.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=ge(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 Ac=!1;class ag extends tt{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Wp(lg),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Ac&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Oi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Ac=!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(),ur.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]=Pl(),i=Ce(Ts);return A(ag,{...t,layoutGroup:i,switchLayoutGroup:Ce(jl),isPresent:e,safeToRemove:n})}const lg={borderRadius:{...Kn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Kn,borderTopRightRadius:Kn,borderBottomLeftRadius:Kn,borderBottomRightRadius:Kn,boxShadow:og};function cg(t,e,n){const i=Le(t)?t:ln(t);return i.start(Cr("",i,e,n)),i.animation}const dg=(t,e)=>t.depth-e.depth;class ug{constructor(){this.children=[],this.isDirty=!1}add(e){As(this.children,e),this.isDirty=!0}remove(e){Is(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(dg),this.isDirty=!1,this.children.forEach(e)}}function hg(t,e){const n=je.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Tt(i),t(o-e))};return ue.setup(i,!0),()=>Tt(i)}const Rc=["TopLeft","TopRight","BottomLeft","BottomRight"],fg=Rc.length,Pc=t=>typeof t=="string"?parseFloat(t):t,Lc=t=>typeof t=="number"||W.test(t);function pg(t,e,n,i,s,o){s?(t.opacity=ge(0,n.opacity??1,mg(i)),t.opacityExit=ge(e.opacity??1,0,gg(i))):o&&(t.opacity=ge(e.opacity??1,n.opacity??1,i));for(let r=0;r<fg;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||Lc(l)===Lc(c)?(t[a]=Math.max(ge(Pc(l),Pc(c),i),0),(dt.test(c)||dt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ge(e.rotate||0,n.rotate||0,i))}function Mc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const mg=Dc(0,.5,La),gg=Dc(.5,.95,Ke);function Dc(t,e,n){return i=>i<t?0:i>e?1:n(Pn(t,e,i))}function Oc(t,e){t.min=e.min,t.max=e.max}function Ye(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=Mi(t,1/n,i),s!==void 0&&(t=Mi(t,1/s,i)),t}function vg(t,e=0,n=1,i=.5,s,o=t,r=t){if(dt.test(e)&&(e=parseFloat(e),e=ge(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ge(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){vg(t,e[n],e[i],e[s],e.scale,o,r)}const yg=["x","scaleX","originX"],_g=["y","scaleY","originY"];function Bc(t,e,n,i){Vc(t.x,e,yg,n?n.x:void 0,i?i.x:void 0),Vc(t.y,e,_g,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 bg(t,e){return $c(t.x,e.x)&&$c(t.y,e.y)}function Gc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Hc(t,e){return Gc(t.x,e.x)&&Gc(t.y,e.y)}function Wc(t){return Ne(t.x)/Ne(t.y)}function zc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class wg{constructor(){this.members=[]}add(e){As(this.members,e),e.scheduleRender()}remove(e){if(Is(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 Sg(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:g,skewY:_}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),f&&(i+=`rotateY(${f}deg) `),g&&(i+=`skewX(${g}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 Lr=["","X","Y","Z"],xg=1e3;let Cg=0;function Mr(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=Cg++,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(Eg),this.nodes.forEach(Pg),this.nodes.forEach(Lg),this.nodes.forEach(Ag)},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 ug)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Ls),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)&&!Sp(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 g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,d&&d(),d=hg(f,250),Oi.hasAnimatedSinceResize&&(Oi.hasAnimatedSinceResize=!1,this.nodes.forEach(Zc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||Fg,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Hc(this.targetLayout,g),x=!u&&f;if(this.options.layoutRoot||this.resumeFrom||x||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...lr(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(d,x)}else u||Zc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Tt(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(Mg),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(Rg),this.nodes.forEach(kg),this.nodes.forEach(Tg)):this.nodes.forEach(Yc),this.clearAllSnapshots();const a=je.now();Ee.delta=yt(0,1e3/60,a-Ee.timestamp),Ee.timestamp=a,Ee.isProcessing=!0,Os.update.process(Ee),Os.preRender.process(Ee),Os.render.process(Ee),Ee.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ur.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ig),this.sharedNodes.forEach(Dg)}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&&!Ne(this.snapshot.measuredBox.x)&&!Ne(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||Ht(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)),Vg(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(Bg))){const{scroll:d}=this.root;d&&(hn(a.x,d.offset.x),hn(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=be();if(Ye(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&&Ye(a,r),hn(a.x,u.offset.x),hn(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=be();Ye(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&&fn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Ht(d.latestValues)&&fn(l,d.latestValues)}return Ht(this.latestValues)&&fn(l,this.latestValues),l}removeTransform(r){const a=be();Ye(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Ht(c.latestValues))continue;Er(c.latestValues)&&c.updateSnapshot();const d=be(),u=c.measurePageBox();Ye(d,u),Bc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Ht(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 g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),qn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Ye(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(),Gm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ye(this.target,this.layout.layoutBox),hc(this.target,this.targetDelta)):Ye(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=be(),this.relativeTargetOrigin=be(),qn(this.relativeTargetOrigin,this.target,g.target),Ye(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Er(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;Ye(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,f=this.treeScale.y;Hm(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:g}=r;if(!g){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)),zn(this.projectionDelta,this.layoutCorrected,g,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",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=un(),this.projectionDelta=un(),this.projectionDeltaWithTransform=un()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=un();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=be(),g=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=g!==_,w=this.getStack(),y=!w||w.members.length<=1,x=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Ng));this.animationProgress=0;let C;this.mixTargetDelta=E=>{const P=E/1e3;Jc(u.x,r.x,P),Jc(u.y,r.y,P),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(qn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Og(this.relativeTarget,this.relativeTargetOrigin,f,P),C&&bg(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=be()),Ye(C,this.relativeTarget)),v&&(this.animationValues=d,pg(d,c,this.latestValues,P,x,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=P},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&&(Tt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{Oi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ln(0)),this.currentAnimation=cg(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(xg),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=Ne(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const f=Ne(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Ye(a,l),fn(a,d),zn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new wg),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&&Mr("z",r,c,this.animationValues);for(let d=0;d<Lr.length;d++)Mr(`rotate${Lr[d]}`,r,c,this.animationValues),Mr(`skew${Lr[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=Li(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=Li(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Ht(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=Sg(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:f,y:g}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const _ in Un){if(d[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=Un[_],x=u==="none"?d[_]:v(d[_],c);if(w){const C=w.length;for(let E=0;E<C;E++)r[w[E]]=x}else y?this.options.visualElement.renderState.vars[_]=x:r[_]=x}this.options.layoutId&&(r.pointerEvents=c===this?Li(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 kg(t){t.updateLayout()}function Tg(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"?Xe(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],g=Ne(f);f.min=i[u].min,f.max=f.min+g}):id(o,e.layoutBox,i)&&Xe(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],g=Ne(i[u]);f.max=f.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+g)});const a=un();zn(a,i,e.layoutBox);const l=un();r?zn(l,t.applyTransform(s,!0),e.measuredBox):zn(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:g}=u;if(f&&g){const _=be();qn(_,e.layoutBox,f.layoutBox);const v=be();qn(v,i,g.layoutBox),Hc(_,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 Eg(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 Ag(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Ig(t){t.clearSnapshot()}function Xc(t){t.clearMeasurements()}function Yc(t){t.isLayoutDirty=!1}function Rg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Zc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Pg(t){t.resolveTargetDelta()}function Lg(t){t.calcProjection()}function Mg(t){t.resetSkewAndRotation()}function Dg(t){t.removeLeadSnapshot()}function Jc(t,e,n){t.translate=ge(e.translate,0,n),t.scale=ge(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Qc(t,e,n,i){t.min=ge(e.min,n.min,i),t.max=ge(e.max,n.max,i)}function Og(t,e,n,i){Qc(t.x,e.x,n.x,i),Qc(t.y,e.y,n.y,i)}function Ng(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Fg={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:Ke;function nd(t){t.min=td(t.min),t.max=td(t.max)}function Vg(t){nd(t.x),nd(t.y)}function id(t,e,n){return t==="position"||t==="preserve-aspect"&&!$m(Wc(e),Wc(n),.2)}function Bg(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const jg=Kc({attachResizeListener:(t,e)=>Gn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Dr={current:void 0},sd=Kc({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Dr.current){const t=new jg({});t.mount(window),t.setOptions({layoutScroll:!0}),Dr.current=t}return Dr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Ug={pan:{Feature:rg},drag:{Feature:sg,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,Hn(e)))}class $g extends It{mount(){const{current:e}=this.node;e&&(this.unmount=vp(e,(n,i)=>(rd(this.node,i,"Start"),s=>rd(this.node,s,"End"))))}unmount(){}}class Gg extends It{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=Rn(Gn(this.node.current,"focus",()=>this.onFocus()),Gn(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,Hn(e)))}class Hg extends It{mount(){const{current:e}=this.node;e&&(this.unmount=wp(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 Or=new WeakMap,Nr=new WeakMap,Wg=t=>{const e=Or.get(t.target);e&&e(t)},zg=t=>{t.forEach(Wg)};function qg({root:t,...e}){const n=t||document;Nr.has(n)||Nr.set(n,{});const i=Nr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(zg,{root:t,...e})),i[s]}function Kg(t,e,n){const i=qg(e);return Or.set(t,n),i.observe(t),()=>{Or.delete(t),i.unobserve(t)}}const Xg={some:0,all:1};class Yg extends It{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:Xg[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 Kg(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(Zg(e,n))&&this.startObserver()}unmount(){}}function Zg({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Jg={inView:{Feature:Yg},tap:{Feature:Hg},focus:{Feature:Gg},hover:{Feature:$g}},Qg={layout:{ProjectionNode:sd,MeasureLayout:Ic}},Fr={current:null},ad={current:!1};function ev(){if(ad.current=!0,!!Es)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Fr.current=t.matches;t.addEventListener("change",e),e()}else Fr.current=!1}const tv=new WeakMap;function nv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Le(s))t.addValue(i,s);else if(Le(o))t.addValue(i,ln(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,ln(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 iv{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=or,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=je.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=Pi(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 g=u[f];l[f]!==void 0&&Le(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)),ad.current||ev(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Fr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Tt(this.notifyUpdate),Tt(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=an.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 cn){const n=cn[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=nv(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=ln(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)||Ca(i))?i=parseFloat(i):!Cp(i)&&At.test(n)&&(i=wl(e,n)),this.setBaseTarget(e,Le(i)?i.get():i)),Le(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=br(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&&!Le(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 Ls),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class cd extends iv{constructor(){super(...arguments),this.KeyframeResolver=hp}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;Le(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 sv(t){return window.getComputedStyle(t)}class rv extends cd{constructor(){super(...arguments),this.type="html",this.renderInstance=dd}readValueFromInstance(e,n){var i;if(an.has(n))return(i=this.projection)!=null&&i.isProjecting?tr(n):Lf(e,n);{const s=sv(e),o=(Ns(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return gc(e,n)}build(e,n,i){vr(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return wr(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 ov(t,e,n,i){dd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(ud.has(s)?s:gr(s),e.attrs[s])}class av extends cd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=be}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(an.has(n)){const i=bl(n);return i&&i.default||0}return n=ud.has(n)?n:gr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Xl(e,n,i)}build(e,n,i){Hl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){ov(e,n,i,s)}mount(e){this.isSVGTag=zl(e.tagName),super.mount(e)}}const lv=(t,e)=>_r(t)?new av(e):new rv(e,{allowProjection:t!==ot}),cv=lm({...Dm,...Jg,...Ug,...Qg},lv),Xn=Dp(cv),dv=["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"],Ni="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 bt(){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 uv=bs("listening"),Vr=()=>ba(uv);function hv(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 Fi={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=bs(Fi),fv=()=>{const t=ks(fd);return kt(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Fi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Fi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Fi.speak_to_interrupt_text),n}),[t])},Wt=()=>_a(fd),pd=({size:t="large",className:e})=>{const n=Wt(),[i]=Vr();return A("h1",{className:bt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},md=({stream:t})=>{const e=_e(null);return Pe(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),A("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),E(kp,{isPresent:e,childRef:o,sizeRef:r,children:kh(t,{ref:o})})}const Ap=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=yi(Ep),d=fs();let u=!0,f=qe(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:g=>{c.set(g,!0);for(const _ of c.values())if(!_)return;i&&i()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[n,c,i]);return o&&u&&(f={...f}),qe(()=>{c.forEach((g,_)=>c.set(_,!1))},[n]),Pe(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=E(Tp,{isPresent:n,anchorX:a,root:l,children:t})),E(_i.Provider,{value:f,children:t})};function Ep(){return new Map}function Pl(t=!0){const e=Ce(_i);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=fs();Pe(()=>{if(t)return s(o)},[t]);const r=kt(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Ai=t=>t.key||"";function Ll(t){const e=[];return ph.forEach(t,n=>{ma(n)&&e.push(n)}),e}const Ip=({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]=Pl(r),u=qe(()=>Ll(t),[t]),f=r&&!c?[]:u.map(Ai),g=_e(!0),_=_e(u),v=yi(()=>new Map),[w,y]=Te(u),[x,k]=Te(u);wa(()=>{g.current=!1,_.current=u;for(let O=0;O<x.length;O++){const S=Ai(x[O]);f.includes(S)?v.delete(S):v.get(S)!==!0&&v.set(S,!1)}},[x,f.length,f.join("-")]);const A=[];if(u!==w){let O=[...u];for(let S=0;S<x.length;S++){const C=x[S],p=Ai(C);f.includes(p)||(O.splice(S,0,C),A.push(C))}return o==="wait"&&A.length&&(O=A),k(Ll(O)),y(u),null}const{forceRender:P}=Ce(Ts);return E(ot,{children:x.map(O=>{const S=Ai(O),C=r&&!c?!1:u===x||f.includes(S),p=()=>{if(v.has(S))v.set(S,!0);else return;let m=!0;v.forEach(h=>{h||(m=!1)}),m&&(P==null||P(),k(_.current),r&&(d==null||d()),i&&i())};return E(Ap,{isPresent:C,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:C?void 0:p,anchorX:a,children:O},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"]},cn={};for(const t in Dl)cn[t]={isEnabled:e=>Dl[t].some(n=>!!e[n])};function Rp(t){for(const e in t)cn[e]={...cn[e],...t[e]}}const Pp=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 Ei(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Pp.has(t)}let Ol=t=>!Ei(t);function Nl(t){typeof t=="function"&&(Ol=e=>e.startsWith("on")?!Ei(e):t(e))}try{Nl(require("@emotion/is-prop-valid").default)}catch{}function Lp(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Ol(s)||n===!0&&Ei(s)||!e&&!Ei(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Mp({children:t,isValidProp:e,...n}){e&&Nl(e),n={...Ce(Bn),...n},n.isStatic=yi(()=>n.isStatic);const i=qe(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return E(Bn.Provider,{value:i,children:t})}function Dp(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 Ii=vt({});function Ri(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function jn(t){return typeof t=="string"||Array.isArray(t)}const pr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],mr=["initial",...pr];function Pi(t){return Ri(t.animate)||mr.some(e=>jn(t[e]))}function Fl(t){return!!(Pi(t)||t.variants)}function Op(t,e){if(Pi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||jn(n)?n:void 0,animate:jn(i)?i:void 0}}return t.inherit!==!1?e:{}}function Np(t){const{initial:e,animate:n}=Op(t,Ce(Ii));return qe(()=>({initial:e,animate:n}),[Vl(e),Vl(n)])}function Vl(t){return Array.isArray(t)?t.join(" "):t}const Fp=Symbol.for("motionComponentSymbol");function dn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Vp(t,e,n){return kt(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):dn(n)&&(n.current=i))},[e])}const gr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bl="data-"+gr("framerAppearId"),jl=vt({});function Bp(t,e,n,i,s){var v,w;const{visualElement:o}=Ce(Ii),r=Ce(Ml),a=Ce(_i),l=Ce(Bn).reducedMotion,c=_e(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=Ce(jl);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&jp(c.current,n,s,u);const f=_e(!1);ta(()=>{d&&f.current&&d.update(n,a)});const g=n[Bl],_=_e(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,g)));return wa(()=>{d&&(f.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),ur.render(d.render),_.current&&d.animationState&&d.animationState.animateChanges())}),Pe(()=>{d&&(!_.current&&d.animationState&&d.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),_.current=!1))}),d}function jp(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&&dn(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 Up({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&Rp(t);function o(a,l){let c;const d={...Ce(Bn),...a,layoutId:$p(a)},{isStatic:u}=d,f=Np(a),g=i(a,u);if(!u&&As){Gp();const _=Hp(d);c=_.MeasureLayout,f.visualElement=Bp(s,g,d,e,_.ProjectionNode)}return E(Ii.Provider,{value:f,children:[c&&f.visualElement?E(c,{visualElement:f.visualElement,...d}):null,n(s,a,Vp(g,f.visualElement,l),g,u,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=fh(o);return r[Fp]=s,r}function $p({layoutId:t}){const e=Ce(Ts).id;return e&&t!==void 0?e+"-"+t:t}function Gp(t,e){Ce(Ml).strict}function Hp(t){const{drag:e,layout:n}=cn;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 Un={};function Wp(t){for(const e in t)Un[e]=t[e],Ns(e)&&(Un[e].isCSSVariable=!0)}function $l(t,{layout:e,layoutId:n}){return an.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Un[t]||t==="opacity")}const zp={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},qp=on.length;function Kp(t,e,n){let i="",s=!0;for(let o=0;o<qp;o++){const r=on[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,dr[r]);if(!l){s=!1;const d=zp[r]||r;i+=`${d}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function vr(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(an.has(l)){r=!0;continue}else if(Ns(l)){s[l]=c;continue}else{const d=Sl(c,dr[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(e.transform||(r||n?i.transform=Kp(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 yr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Gl(t,e,n){for(const i in e)!Le(e[i])&&!$l(i,n)&&(t[i]=e[i])}function Xp({transformTemplate:t},e){return qe(()=>{const n=yr();return vr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Yp(t,e){const n=t.style||{},i={};return Gl(i,n,t),Object.assign(i,Xp(t,e)),i}function Zp(t,e){const n={},i=Yp(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 Jp={offset:"stroke-dashoffset",array:"stroke-dasharray"},Qp={offset:"strokeDashoffset",array:"strokeDasharray"};function em(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?Jp:Qp;t[o.offset]=H.transform(-i);const r=H.transform(e),a=H.transform(n);t[o.array]=`${r} ${a}`}function Hl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(vr(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&&em(u,s,o,r,!1)}const Wl=()=>({...yr(),attrs:{}}),zl=t=>typeof t=="string"&&t.toLowerCase()==="svg";function tm(t,e,n,i){const s=qe(()=>{const o=Wl();return Hl(o,e,zl(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Gl(o,t.style,t),s.style={...o,...s.style}}return s}const nm=["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 _r(t){return typeof t!="string"||t.includes("-")?!1:!!(nm.indexOf(t)>-1||/[A-Z]/u.test(t))}function im(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(_r(n)?tm:Zp)(i,o,r,n),c=Lp(i,typeof n=="string",t),d=n!==ot?{...c,...l,ref:s}:{},{children:u}=i,f=qe(()=>Le(u)?u.get():u,[u]);return ze(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 br(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 Li(t){return Le(t)?t.get():t}function sm({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:rm(n,i,s,t),renderState:e()}}const Kl=t=>(e,n)=>{const i=Ce(Ii),s=Ce(_i),o=()=>sm(t,e,i,s);return n?o():yi(o)};function rm(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=Li(o[f]);let{initial:r,animate:a}=t;const l=Pi(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"&&!Ri(u)){const f=Array.isArray(u)?u:[u];for(let g=0;g<f.length;g++){const _=br(t,f[g]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const x in y){let k=y[x];if(Array.isArray(k)){const A=d?k.length-1:0;k=k[A]}k!==null&&(s[x]=k)}for(const x in v)s[x]=v[x]}}}return s}function wr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Le(i[r])||e.style&&Le(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 om={useVisualState:Kl({scrapeMotionValuesFromProps:wr,createRenderState:yr})};function Xl(t,e,n){const i=wr(t,e,n);for(const s in t)if(Le(t[s])||Le(e[s])){const o=on.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const am={useVisualState:Kl({scrapeMotionValuesFromProps:Xl,createRenderState:Wl})};function lm(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={..._r(i)?am:om,preloadedFeatures:t,useRender:im(s),createVisualElement:e,Component:i};return Up(r)}}function $n(t,e,n){const i=t.getProps();return br(i,e,n!==void 0?n:i.custom,t)}const Sr=t=>Array.isArray(t);function cm(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,ln(n))}function dm(t){return Sr(t)?t[t.length-1]||0:t}function um(t,e){const n=$n(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=dm(o[r]);cm(t,r,a)}}function hm(t){return!!(Le(t)&&t.add)}function xr(t,e){const n=t.getValue("willChange");if(hm(n))return n.add(e);if(!n&&_t.WillChange){const i=new _t.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Yl(t){return t.props[Bl]}const fm=t=>t!==null;function pm(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(fm),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const mm={type:"spring",stiffness:500,damping:25,restSpeed:10},gm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),vm={type:"keyframes",duration:.8},ym={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},_m=(t,{keyframes:e})=>e.length>2?vm:an.has(t)?t.startsWith("scale")?gm(e[1]):mm:ym;function bm({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 Cr=(t,e,n,i={},s,o)=>r=>{const a=lr(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-lt(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};bm(a)||Object.assign(d,_m(t,d)),d.duration&&(d.duration=lt(d.duration)),d.repeatDelay&&(d.repeatDelay=lt(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)),(_t.instantAnimations||_t.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const f=pm(d.keyframes,a);if(f!==void 0){ue.update(()=>{d.onUpdate(f),d.onComplete()});return}}return a.isSync?new Js(d):new tp(d)};function wm({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function Zl(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&&wm(c,d))continue;const g={delay:n,...lr(o||{},d)},_=u.get();if(_!==void 0&&!u.isAnimating&&!Array.isArray(f)&&f===_&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Yl(t);if(y){const x=window.MotionHandoffAnimation(y,d,ue);x!==null&&(g.startTime=x,v=!0)}}xr(t,d),u.start(Cr(d,u,f,t.shouldReduceMotion&&ml.has(d)?{type:!1}:g,t,v));const w=u.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{ue.update(()=>{r&&um(t,r)})}),l}function kr(t,e,n={}){var l;const i=$n(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(Zl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:f}=s;return Sm(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 Sm(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(xm).forEach((f,g)=>{f.notify("AnimationStart",e),a.push(kr(f,e,{...r,delay:n+(d?0:i)+u(g)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function xm(t,e){return t.sortNodePosition(e)}function Cm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>kr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=kr(t,e,n);else{const s=typeof e=="function"?$n(t,e,n.custom):e;i=Promise.all(Zl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Jl(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=mr.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<km;n++){const i=mr[n],s=t.props[i];(jn(s)||s===!1)&&(e[i]=s)}return e}const Tm=[...pr].reverse(),Am=pr.length;function Em(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Cm(t,n,i)))}function Im(t){let e=Em(t),n=ec(),i=!0;const s=l=>(c,d)=>{var f;const u=$n(t,d,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(u){const{transition:g,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 g={},_=1/0;for(let w=0;w<Am;w++){const y=Tm[w],x=n[y],k=c[y]!==void 0?c[y]:d[y],A=jn(k),P=y===l?x.isActive:null;P===!1&&(_=w);let O=k===d[y]&&k!==c[y]&&A;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),x.protectedKeys={...g},!x.isActive&&P===null||!k&&!x.prevProp||Ri(k)||typeof k=="boolean")continue;const S=Rm(x.prevProp,k);let C=S||y===l&&x.isActive&&!O&&A||w>_&&A,p=!1;const m=Array.isArray(k)?k:[k];let h=m.reduce(s(y),{});P===!1&&(h={});const{prevResolvedValues:b={}}=x,T={...b,...h},R=M=>{C=!0,f.has(M)&&(p=!0,f.delete(M)),x.needsAnimating[M]=!0;const V=t.getValue(M);V&&(V.liveStyle=!1)};for(const M in T){const V=h[M],q=b[M];if(g.hasOwnProperty(M))continue;let N=!1;Sr(V)&&Sr(q)?N=!Jl(V,q):N=V!==q,N?V!=null?R(M):f.add(M):V!==void 0&&f.has(M)?R(M):x.protectedKeys[M]=!0}x.prevProp=k,x.prevResolvedValues=h,x.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(C=!1),C&&(!(O&&S)||p)&&u.push(...m.map(M=>({animation:M,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=$n(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const x=t.getBaseTarget(y),k=t.getValue(y);k&&(k.liveStyle=!0),w[y]=x??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 g;return(g=f.animationState)==null?void 0:g.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 Rm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Jl(e,t):!1}function Gt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ec(){return{animate:Gt(!0),whileInView:Gt(),whileHover:Gt(),whileTap:Gt(),whileDrag:Gt(),whileFocus:Gt(),exit:Gt()}}class It{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Pm extends It{constructor(e){super(e),e.animationState||(e.animationState=Im(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ri(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 Lm=0;class Mm extends It{constructor(){super(...arguments),this.id=Lm++}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 Dm={animation:{Feature:Pm},exit:{Feature:Mm}};function Gn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Hn(t){return{point:{x:t.pageX,y:t.pageY}}}const Om=t=>e=>hr(e)&&t(e,Hn(e));function Wn(t,e,n,i){return Gn(t,e,Om(n),i)}function tc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Nm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Fm(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,Vm=1-nc,Bm=1+nc,ic=.01,jm=0-ic,Um=0+ic;function Ne(t){return t.max-t.min}function $m(t,e,n){return Math.abs(t-e)<=n}function sc(t,e,n,i=.5){t.origin=i,t.originPoint=ge(e.min,e.max,t.origin),t.scale=Ne(n)/Ne(e),t.translate=ge(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Vm&&t.scale<=Bm||isNaN(t.scale))&&(t.scale=1),(t.translate>=jm&&t.translate<=Um||isNaN(t.translate))&&(t.translate=0)}function zn(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+Ne(e)}function Gm(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+Ne(e)}function qn(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}),un=()=>({x:ac(),y:ac()}),lc=()=>({min:0,max:0}),be=()=>({x:lc(),y:lc()});function Xe(t){return[t("x"),t("y")]}function Tr(t){return t===void 0||t===1}function Ar({scale:t,scaleX:e,scaleY:n}){return!Tr(t)||!Tr(e)||!Tr(n)}function Ht(t){return Ar(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 Mi(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=Mi(t,s,i)),Mi(t,n,i)+e}function Er(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}){Er(t.x,e.translate,e.scale,e.originPoint),Er(t.y,n.translate,n.scale,n.originPoint)}const fc=.999999999999,pc=1.0000000000001;function Hm(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&&fn(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&&Ht(o.latestValues)&&fn(t,o.latestValues))}e.x<pc&&e.x>fc&&(e.x=1),e.y<pc&&e.y>fc&&(e.y=1)}function hn(t,e){t.min=t.min+e,t.max=t.max+e}function mc(t,e,n,i,s=.5){const o=ge(t.min,t.max,s);Er(t,e,n,o,i)}function fn(t,e){mc(t.x,e.x,e.scaleX,e.scale,e.originX),mc(t.y,e.y,e.scaleY,e.scale,e.originY)}function gc(t,e){return tc(Fm(t.getBoundingClientRect(),e))}function Wm(t,e,n){const i=gc(t,n),{scroll:s}=e;return s&&(hn(i.x,s.offset.x),hn(i.y,s.offset.y)),i}const vc=({current:t})=>t?t.ownerDocument.defaultView:null,yc=(t,e)=>Math.abs(t-e);function zm(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=Rr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,_=zm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!_)return;const{point:v}=f,{timestamp:w}=Ae;this.history.push({...v,timestamp:w});const{onStart:y,onMove:x}=this.handlers;g||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),x&&x(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Ir(g,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Rr(f.type==="pointercancel"?this.lastMoveEventInfo:Ir(g,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,y),v&&v(f,y)},!hr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Hn(e),l=Ir(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Ae;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Rr(l,this.history)),this.removeListeners=Rn(Wn(this.contextWindow,"pointermove",this.handlePointerMove),Wn(this.contextWindow,"pointerup",this.handlePointerUp),Wn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Tt(this.updatePoint)}}function Ir(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 Rr({point:t},e){return{point:t,delta:bc(t,wc(e)),offset:bc(t,qm(e)),velocity:Km(e,.1)}}function qm(t){return t[0]}function wc(t){return t[t.length-1]}function Km(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>lt(e)));)n--;if(!i)return{x:0,y:0};const o=ct(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 Xm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ge(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ge(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 Ym(t,{top:e,left:n,bottom:i,right:s}){return{x:Sc(t.x,n,s),y:Sc(t.y,e,i)}}function xc(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 Zm(t,e){return{x:xc(t.x,e.x),y:xc(t.y,e.y)}}function Jm(t,e){let n=.5;const i=Ne(t),s=Ne(e);return s>i?n=Pn(e.min,e.max-i,t.min):i>s&&(n=Pn(t.min,t.max-s,e.min)),yt(0,1,n)}function Qm(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 Pr=.35;function eg(t=Pr){return t===!1?t=0:t===!0&&(t=Pr),{x:Cc(t,"left","right"),y:Cc(t,"top","bottom")}}function Cc(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 tg=new WeakMap;class ng{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(Hn(u).point)},r=(u,f)=>{const{drag:g,dragPropagation:_,onDragStart:v}=this.getProps();if(g&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=gp(g),!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),Xe(y=>{let x=this.getAxisMotionValue(y).get()||0;if(dt.test(x)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[y];A&&(x=Ne(A)*(parseFloat(x)/100))}}this.originPoint[y]=x}),v&&ue.postRender(()=>v(u,f)),xr(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=f;if(_&&this.currentDirection===null){this.currentDirection=ig(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=()=>Xe(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||!Di(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Xm(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&&dn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Ym(i.layoutBox,e):this.constraints=!1,this.elastic=eg(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Xe(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Qm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!dn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Wm(i,s.root,this.visualElement.getTransformPagePoint());let r=Zm(s.layout.layoutBox,o);if(n){const a=n(Nm(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=Xe(d=>{if(!Di(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const f=s?200:1e6,g=s?40:1e7,_={type:"inertia",velocity:i?e[d]:0,bounceStiffness:f,bounceDamping:g,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 xr(this.visualElement,e),i.start(Cr(e,i,0,n,this.visualElement,!1))}stopAnimation(){Xe(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Xe(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){Xe(n=>{const{drag:i}=this.getProps();if(!Di(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]-ge(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!dn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Xe(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=Jm({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(),Xe(r=>{if(!Di(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ge(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;tg.set(this.visualElement,this);const e=this.visualElement.current,n=Wn(e,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();dn(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=Gn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Xe(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=Pr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Di(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function ig(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class sg extends It{constructor(e){super(e),this.removeGroupControls=Ke,this.removeListeners=Ke,this.controls=new ng(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ke}unmount(){this.removeGroupControls(),this.removeListeners()}}const Tc=t=>(e,n)=>{t&&ue.postRender(()=>t(e,n))};class rg extends It{constructor(){super(...arguments),this.removePointerDownListener=Ke}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=Wn(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 Oi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ac(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Kn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(H.test(t))t=parseFloat(t);else return t;const n=Ac(t,e.target.x),i=Ac(t,e.target.y);return`${n}% ${i}%`}},og={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Et.parse(t);if(s.length>5)return i;const o=Et.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=ge(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 ag extends tt{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Wp(lg),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()})),Oi.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(),ur.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]=Pl(),i=Ce(Ts);return E(ag,{...t,layoutGroup:i,switchLayoutGroup:Ce(jl),isPresent:e,safeToRemove:n})}const lg={borderRadius:{...Kn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Kn,borderTopRightRadius:Kn,borderBottomLeftRadius:Kn,borderBottomRightRadius:Kn,boxShadow:og};function cg(t,e,n){const i=Le(t)?t:ln(t);return i.start(Cr("",i,e,n)),i.animation}const dg=(t,e)=>t.depth-e.depth;class ug{constructor(){this.children=[],this.isDirty=!1}add(e){Es(this.children,e),this.isDirty=!0}remove(e){Is(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(dg),this.isDirty=!1,this.children.forEach(e)}}function hg(t,e){const n=je.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Tt(i),t(o-e))};return ue.setup(i,!0),()=>Tt(i)}const Rc=["TopLeft","TopRight","BottomLeft","BottomRight"],fg=Rc.length,Pc=t=>typeof t=="string"?parseFloat(t):t,Lc=t=>typeof t=="number"||H.test(t);function pg(t,e,n,i,s,o){s?(t.opacity=ge(0,n.opacity??1,mg(i)),t.opacityExit=ge(e.opacity??1,0,gg(i))):o&&(t.opacity=ge(e.opacity??1,n.opacity??1,i));for(let r=0;r<fg;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||Lc(l)===Lc(c)?(t[a]=Math.max(ge(Pc(l),Pc(c),i),0),(dt.test(c)||dt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ge(e.rotate||0,n.rotate||0,i))}function Mc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const mg=Dc(0,.5,La),gg=Dc(.5,.95,Ke);function Dc(t,e,n){return i=>i<t?0:i>e?1:n(Pn(t,e,i))}function Oc(t,e){t.min=e.min,t.max=e.max}function Ye(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=Mi(t,1/n,i),s!==void 0&&(t=Mi(t,1/s,i)),t}function vg(t,e=0,n=1,i=.5,s,o=t,r=t){if(dt.test(e)&&(e=parseFloat(e),e=ge(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ge(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){vg(t,e[n],e[i],e[s],e.scale,o,r)}const yg=["x","scaleX","originX"],_g=["y","scaleY","originY"];function Bc(t,e,n,i){Vc(t.x,e,yg,n?n.x:void 0,i?i.x:void 0),Vc(t.y,e,_g,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 bg(t,e){return $c(t.x,e.x)&&$c(t.y,e.y)}function Gc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Hc(t,e){return Gc(t.x,e.x)&&Gc(t.y,e.y)}function Wc(t){return Ne(t.x)/Ne(t.y)}function zc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class wg{constructor(){this.members=[]}add(e){Es(this.members,e),e.scheduleRender()}remove(e){if(Is(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 Sg(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:g,skewY:_}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),f&&(i+=`rotateY(${f}deg) `),g&&(i+=`skewX(${g}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 Lr=["","X","Y","Z"],xg=1e3;let Cg=0;function Mr(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=Cg++,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(Ag),this.nodes.forEach(Pg),this.nodes.forEach(Lg),this.nodes.forEach(Eg)},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 ug)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Ls),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)&&!Sp(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 g=window.innerWidth;g!==u&&(u=g,this.root.updateBlockedByResize=!0,d&&d(),d=hg(f,250),Oi.hasAnimatedSinceResize&&(Oi.hasAnimatedSinceResize=!1,this.nodes.forEach(Zc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||Fg,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Hc(this.targetLayout,g),x=!u&&f;if(this.options.layoutRoot||this.resumeFrom||x||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...lr(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,x)}else u||Zc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Tt(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(Mg),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(Rg),this.nodes.forEach(kg),this.nodes.forEach(Tg)):this.nodes.forEach(Yc),this.clearAllSnapshots();const a=je.now();Ae.delta=yt(0,1e3/60,a-Ae.timestamp),Ae.timestamp=a,Ae.isProcessing=!0,Os.update.process(Ae),Os.preRender.process(Ae),Os.render.process(Ae),Ae.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ur.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Ig),this.sharedNodes.forEach(Dg)}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&&!Ne(this.snapshot.measuredBox.x)&&!Ne(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||Ht(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)),Vg(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(Bg))){const{scroll:d}=this.root;d&&(hn(a.x,d.offset.x),hn(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=be();if(Ye(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&&Ye(a,r),hn(a.x,u.offset.x),hn(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=be();Ye(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&&fn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Ht(d.latestValues)&&fn(l,d.latestValues)}return Ht(this.latestValues)&&fn(l,this.latestValues),l}removeTransform(r){const a=be();Ye(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Ht(c.latestValues))continue;Ar(c.latestValues)&&c.updateSnapshot();const d=be(),u=c.measurePageBox();Ye(d,u),Bc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Ht(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!==Ae.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=Ae.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),qn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Ye(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(),Gm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ye(this.target,this.layout.layoutBox),hc(this.target,this.targetDelta)):Ye(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=be(),this.relativeTargetOrigin=be(),qn(this.relativeTargetOrigin,this.target,g.target),Ye(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ar(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===Ae.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;Ye(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,f=this.treeScale.y;Hm(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:g}=r;if(!g){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)),zn(this.projectionDelta,this.layoutCorrected,g,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",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=un(),this.projectionDelta=un(),this.projectionDeltaWithTransform=un()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=un();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=be(),g=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=g!==_,w=this.getStack(),y=!w||w.members.length<=1,x=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Ng));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const P=A/1e3;Jc(u.x,r.x,P),Jc(u.y,r.y,P),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(qn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Og(this.relativeTarget,this.relativeTargetOrigin,f,P),k&&bg(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=be()),Ye(k,this.relativeTarget)),v&&(this.animationValues=d,pg(d,c,this.latestValues,P,x,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=P},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&&(Tt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{Oi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ln(0)),this.currentAnimation=cg(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(xg),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=Ne(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const f=Ne(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Ye(a,l),fn(a,d),zn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new wg),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&&Mr("z",r,c,this.animationValues);for(let d=0;d<Lr.length;d++)Mr(`rotate${Lr[d]}`,r,c,this.animationValues),Mr(`skew${Lr[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=Li(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=Li(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Ht(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=Sg(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:f,y:g}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const _ in Un){if(d[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=Un[_],x=u==="none"?d[_]:v(d[_],c);if(w){const k=w.length;for(let A=0;A<k;A++)r[w[A]]=x}else y?this.options.visualElement.renderState.vars[_]=x:r[_]=x}this.options.layoutId&&(r.pointerEvents=c===this?Li(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 kg(t){t.updateLayout()}function Tg(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"?Xe(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],g=Ne(f);f.min=i[u].min,f.max=f.min+g}):id(o,e.layoutBox,i)&&Xe(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],g=Ne(i[u]);f.max=f.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+g)});const a=un();zn(a,i,e.layoutBox);const l=un();r?zn(l,t.applyTransform(s,!0),e.measuredBox):zn(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:g}=u;if(f&&g){const _=be();qn(_,e.layoutBox,f.layoutBox);const v=be();qn(v,i,g.layoutBox),Hc(_,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 Ag(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 Eg(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Ig(t){t.clearSnapshot()}function Xc(t){t.clearMeasurements()}function Yc(t){t.isLayoutDirty=!1}function Rg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Zc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Pg(t){t.resolveTargetDelta()}function Lg(t){t.calcProjection()}function Mg(t){t.resetSkewAndRotation()}function Dg(t){t.removeLeadSnapshot()}function Jc(t,e,n){t.translate=ge(e.translate,0,n),t.scale=ge(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Qc(t,e,n,i){t.min=ge(e.min,n.min,i),t.max=ge(e.max,n.max,i)}function Og(t,e,n,i){Qc(t.x,e.x,n.x,i),Qc(t.y,e.y,n.y,i)}function Ng(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Fg={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:Ke;function nd(t){t.min=td(t.min),t.max=td(t.max)}function Vg(t){nd(t.x),nd(t.y)}function id(t,e,n){return t==="position"||t==="preserve-aspect"&&!$m(Wc(e),Wc(n),.2)}function Bg(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const jg=Kc({attachResizeListener:(t,e)=>Gn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Dr={current:void 0},sd=Kc({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Dr.current){const t=new jg({});t.mount(window),t.setOptions({layoutScroll:!0}),Dr.current=t}return Dr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Ug={pan:{Feature:rg},drag:{Feature:sg,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,Hn(e)))}class $g extends It{mount(){const{current:e}=this.node;e&&(this.unmount=vp(e,(n,i)=>(rd(this.node,i,"Start"),s=>rd(this.node,s,"End"))))}unmount(){}}class Gg extends It{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=Rn(Gn(this.node.current,"focus",()=>this.onFocus()),Gn(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,Hn(e)))}class Hg extends It{mount(){const{current:e}=this.node;e&&(this.unmount=wp(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 Or=new WeakMap,Nr=new WeakMap,Wg=t=>{const e=Or.get(t.target);e&&e(t)},zg=t=>{t.forEach(Wg)};function qg({root:t,...e}){const n=t||document;Nr.has(n)||Nr.set(n,{});const i=Nr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(zg,{root:t,...e})),i[s]}function Kg(t,e,n){const i=qg(e);return Or.set(t,n),i.observe(t),()=>{Or.delete(t),i.unobserve(t)}}const Xg={some:0,all:1};class Yg extends It{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:Xg[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 Kg(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(Zg(e,n))&&this.startObserver()}unmount(){}}function Zg({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Jg={inView:{Feature:Yg},tap:{Feature:Hg},focus:{Feature:Gg},hover:{Feature:$g}},Qg={layout:{ProjectionNode:sd,MeasureLayout:Ic}},Fr={current:null},ad={current:!1};function ev(){if(ad.current=!0,!!As)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Fr.current=t.matches;t.addEventListener("change",e),e()}else Fr.current=!1}const tv=new WeakMap;function nv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Le(s))t.addValue(i,s);else if(Le(o))t.addValue(i,ln(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,ln(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 iv{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=or,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=je.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=Pi(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 g=u[f];l[f]!==void 0&&Le(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)),ad.current||ev(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Fr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Tt(this.notifyUpdate),Tt(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=an.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 cn){const n=cn[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=nv(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=ln(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)||Ca(i))?i=parseFloat(i):!Cp(i)&&Et.test(n)&&(i=wl(e,n)),this.setBaseTarget(e,Le(i)?i.get():i)),Le(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=br(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&&!Le(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 Ls),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class cd extends iv{constructor(){super(...arguments),this.KeyframeResolver=hp}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;Le(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 sv(t){return window.getComputedStyle(t)}class rv extends cd{constructor(){super(...arguments),this.type="html",this.renderInstance=dd}readValueFromInstance(e,n){var i;if(an.has(n))return(i=this.projection)!=null&&i.isProjecting?tr(n):Lf(e,n);{const s=sv(e),o=(Ns(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return gc(e,n)}build(e,n,i){vr(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return wr(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 ov(t,e,n,i){dd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(ud.has(s)?s:gr(s),e.attrs[s])}class av extends cd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=be}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(an.has(n)){const i=bl(n);return i&&i.default||0}return n=ud.has(n)?n:gr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Xl(e,n,i)}build(e,n,i){Hl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){ov(e,n,i,s)}mount(e){this.isSVGTag=zl(e.tagName),super.mount(e)}}const lv=(t,e)=>_r(t)?new av(e):new rv(e,{allowProjection:t!==ot}),cv=lm({...Dm,...Jg,...Ug,...Qg},lv),Xn=Dp(cv),dv=["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"],Ni="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 bt(){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 uv=bs("listening"),Vr=()=>ba(uv);function hv(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 Fi={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=bs(Fi),fv=()=>{const t=ks(fd);return kt(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Fi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Fi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Fi.speak_to_interrupt_text),n}),[t])},Wt=()=>_a(fd),pd=({size:t="large",className:e})=>{const n=Wt(),[i]=Vr();return E("h1",{className:bt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},md=({stream:t})=>{const e=_e(null);return Pe(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),E("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const pv="4.5.1",Br=Math.PI,pn=2*Br,jr=Br/2,gd=8.17579892,vd="dual-combined",Vi="dual-horizontal",wt="single",ut="dual-vertical",yd="bar-index",_d="bar-level",Bi="gradient",bd=60,wd="click",mv="fullscreenchange",Sd="resize",gv="#111",xd="",Cd="A",kd="B",Td="C",Ed="D",Ad="468",ji="sans-serif",vv="#0f0",yv="#7f7f7f22",mn=10,Id="create",Rd="fschange",_v="lores",bv=Sd,Ur="user",wv="#000c",Pd="#fff",Sv="#4f4",Ld="#888",xv="#555",$r="bark",Yn="linear",gn="log",Gr="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"]}]],Zn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:wt,colorMode:Bi,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:gn,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:xd,width:void 0},Cv=["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"],Tv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Hr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Ev=["ERR_INVALID_MODE","Invalid mode"],Av=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Iv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Rv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Pv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],Lv=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ze 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},Ui=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],Mv=(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 Dv{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 Ze(Cv)}}if(!s.createGain)throw new Ze(kv);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(bv),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(mv,()=>{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=Ui(e,[wt,Vi,ut,vd]),this._input.disconnect(),this._input.connect(this._chLayout!=wt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=wt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Ui(e,[Bi,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=Ui(e,[gn,$r,Gr,Yn]),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||Zn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Ur)}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 Ze(Hr);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 Ze(Hr);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 Ze(Ev,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||Zn.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 Ze(Av);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=-jr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Od("stereo","channelLayout"),this._chLayout!=wt}set stereo(e){Od("stereo","channelLayout"),this.channelLayout=e?ut:wt}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=Ui(e,[xd,Cd,kd,Td,Ed,Ad],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Ur)}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 pv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ze(Iv);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==wt&&!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==wt?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(Zn))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 Ze(Rv);if(typeof n!="object")throw new Ze(Pv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ze(Lv);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||gv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Ur)}setFreqRange(e,n){if(e<1||n<1)throw new Ze(Hr);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,g=s.width>>1,_=s.height>>1,v=o==ut&&!d,w=o==Vi,y=c%10!=0,x=y&&this._frequencyScale==gn,C=this._showLeds&&y&&!d,E=this._lumiBars&&y&&!d,P=this._alphaBars&&!E&&c!=mn,O=this._outlineBars&&y&&!E&&!C,S=this._roundBars&&y&&!E&&!C,k=o!=ut||f>0&&!E,p=s.height-(v&&!C?.5:0)>>v,m=p*(E||d?1:1-f)|0,h=s.width-g*(w||l!=0),b=v?s.height-p*2:0,T=g*(l==-1&&!w&&!d);let L=Math.min(s.width,s.height)*.375*(o==ut?1:this._radius)|0,I=Math.min(g,_);u&&o!=ut&&([L,I]=[I,L]);const D=K=>e.push({...K,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=K=>{const Z=this._freqToBin(K,"floor"),J=this._binToFreq(Z),te=this._binToFreq(Z+1),he=Math.log2(K/J)/Math.log2(te/J);return[Z,he]};let F,U,V;if(x){const K=(oe,pe,re)=>+oe.toPrecision(re?Math.max(pe,1+Math.log10(oe)|0):pe),Z=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],re=Math.log10(oe)|0,ft=oe/10**re;let it=1;for(;it<pe.length&&ft>pe[it];)it++;return ft-pe[it-1]<pe[it]-ft&&it--,(pe[it]*10**(re+5)|0)/1e5},J=[0,24,12,8,6,4,3,2,1][c],te=n?10**(3/(J*10)):2**(1/J),he=te**.5;let Ve=n?7.94328235/(J%2?1:he):gd;do{let oe=Ve;const pe=K(oe/he,4,!0),re=K(oe*he,4,!0),[ft,it]=M(pe),[oi,pt]=M(re);n?oe=J<4?Z(oe):K(oe,oe.toString()[0]<5?3:2):oe=K(oe,4,!0),oe>=a&&D({posX:0,freq:oe,freqLo:pe,freqHi:re,binLo:ft,binHi:oi,ratioLo:it,ratioHi:pt}),Ve*=te}while(Ve<=r);F=h/e.length,e.forEach((oe,pe)=>oe.posX=T+pe*F);const fe=e[0],Oe=e[e.length-1];U=this._freqScaling(fe.freqLo),V=h/(this._freqScaling(Oe.freqHi)-U),fe.freqLo<a&&(fe.freqLo=a,[fe.binLo,fe.ratioLo]=M(a)),Oe.freqHi>r&&(Oe.freqHi=r,[Oe.binHi,Oe.ratioHi]=M(r))}else if(y){const K=[0,24,12,8,6,4,3,2,1][c]*10,Z=J=>{switch(this._frequencyScale){case $r:return 1960/(26.81/(J+.53)-1);case Gr:return 700*(2**J-1);case Yn:return J}};F=h/K,U=this._freqScaling(a),V=h/(this._freqScaling(r)-U);for(let J=0,te=0;J<K;J++,te+=F){const he=Z(U+te/V),Ve=Z(U+(te+F/2)/V),fe=Z(U+(te+F)/V),[Oe,oe]=M(he),[pe,re]=M(fe);D({posX:T+te,freq:Ve,freqLo:he,freqHi:fe,binLo:Oe,binHi:pe,ratioLo:oe,ratioHi:re})}}else{F=1,U=this._freqScaling(a),V=h/(this._freqScaling(r)-U);const K=this._freqToBin(a,"floor"),Z=this._freqToBin(r);let J=-999;for(let te=K;te<=Z;te++){const he=this._binToFreq(te),Ve=T+Math.round(V*(this._freqScaling(he)-U));if(Ve>J)D({posX:Ve,freq:he,freqLo:he,freqHi:he,binLo:te,binHi:te,ratioLo:0,ratioHi:0}),J=Ve;else if(e.length){const fe=e[e.length-1];fe.binHi=te,fe.freqHi=he,fe.freq=(fe.freqLo*he)**.5}}}let se=0,ee=0;if(C){const K=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Z=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],J=this._ledParams,[te,he,Ve]=J||Z[c];let fe,Oe=m;if(J){const oe=2*K;let pe;fe=te+1;do fe--,pe=Oe/fe/(1+he),ee=pe*he;while((pe<oe||ee<oe)&&fe>1)}else{const oe=540/he;ee=Math.min(he*K,Math.max(2,Oe/oe+.1|0))}k&&(Oe+=ee),J||(fe=Math.min(te,Oe/(ee*2)|0)),se=Ve>=1?Ve:F*Ve,this._leds=[fe,se,ee,Oe/fe-ee]}const $=Math.min(F-1,i*(i>0&&i<1?F:1));y&&(F-=Math.max(C?se:0,$)),e.forEach((K,Z)=>{let J=K.posX,te=F;y&&(i==0&&!C?(J|=0,te|=0,Z>0&&J>e[Z-1].posX+e[Z-1].width&&(J--,te++)):J+=Math.max(C?se:0,$)/2,K.posX=J),K.barCenter=J+(F==1?0:te/2),K.width=te});const ce=[];for(const K of[0,1]){const Z=o==ut?(p+b)*K:0,J=Z+p,te=Z+m-(!C||k?0:ee);ce.push({channelTop:Z,channelBottom:J,analyzerBottom:te})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:_,channelCoords:ce,channelHeight:p,channelGap:b,initialX:T,innerRadius:L,outerRadius:I,scaleMin:U,unitWidth:V},this._flg={isAlpha:P,isBands:y,isLeds:C,isLumi:E,isOctaves:x,isOutline:O,isRound:S,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:f}=this,g=u.canvas,_=f.canvas,v=[],w=this._chLayout==Vi,y=this._chLayout==ut,x=Math.min(r.width,r.height),C=["C",,"D",,"E","F",,"G",,"A",,"B"],E=x/34|0,P=g.height>>1,O=E>>1,S=P*(c?.7:1.5),k=O*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=gn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Yn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let I=gd;for(let D=-1;D<11;D++)for(let M=0;M<12;M++){if(I>=this._minFreq&&I<=this._maxFreq){const F=C[M],U=F=="C";(F&&c&&!l&&!w||U)&&v.push(c?[I,F+(U?D:"")]:I)}I*=p}}_.width=_.height=Math.max(x*.15,(i<<1)+y*E);const m=_.width>>1,h=m-E*.7,b=(I,D)=>{const M=pn*(I/r.width),F=M-jr,U=h*Math.cos(F),V=h*Math.sin(F);f.save(),f.translate(m+U,m+V),f.rotate(M),f.fillText(D,0,0),f.restore()};g.width|=0,u.fillStyle=f.strokeStyle=wv,u.fillRect(0,0,g.width,g.height),f.arc(m,m,m-E/2,0,pn),f.lineWidth=E,f.stroke(),u.fillStyle=f.fillStyle=Pd,u.font=`${P}px ${ji}`,f.font=`${O}px ${ji}`,u.textAlign=f.textAlign="center";let T=-S/4,L=-k;for(const I of v){const[D,M]=Array.isArray(I)?I:[I,I<1e3?I|0:`${(I/100|0)/10}k`],F=o*(this._freqScaling(D)-s),U=g.height*.75,V=M[0]=="C",se=P*(c&&!l&&!w?V?1.2:.6:3);if(u.fillStyle=f.fillStyle=V&&!l&&!w?Sv:Pd,c){const ee=a==gn,$=a==Yn;let ce=["C"];if((ee||D>2e3||!$&&D>250||(!d||y)&&(!$&&D>125||D>1e3))&&ce.push("G"),(ee||D>4e3||!$&&D>500||(!d||y)&&(!$&&D>250||D>2e3))&&ce.push("E"),($&&D>4e3||(!d||y)&&(ee||D>2e3||!$&&D>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=T+S/2&&F<=e&&(u.fillText(M,w&&l==-1?e-F:n+F,U,se),(w||l&&(F>S||l==1))&&u.fillText(M,w&&l!=1?e+F:(n||r.width)-F,U,se),T=F+Math.min(se,u.measureText(M).width)/2),F>=L+k&&F<e-k&&(b(w&&l==1?e-F:F,M),(w||l&&(F>k||l==1))&&b(w&&l!=-1?e+F:-F,M),L=F)}}_draw(e){this._runId=requestAnimationFrame(N=>this._draw(N));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:d,isRound:u,noLedGap:f}=this._flg,{analyzerHeight:g,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:x,initialX:C,innerRadius:E,outerRadius:P}=this._aux,{_bars:O,canvas:S,_canvasGradients:k,_chLayout:p,_colorMode:m,_ctx:h,_energy:b,_fadePeaks:T,fillAlpha:L,_fps:I,_linearAmplitude:D,_lineWidth:M,maxDecibels:F,minDecibels:U,_mirror:V,_mode:se,overlay:ee,_radial:$,showBgColor:ce,showPeaks:K,useCanvas:Z,_weightingFilter:J}=this,te=this._scaleX.canvas,he=this._scaleR.canvas,Ve=I*this._peakFadeTime/1e3,fe=I**2,Oe=this._gravity*1e3,oe=I*this._peakHoldTime/1e3,pe=p==vd,re=p==Vi,ft=p==ut,it=p==wt,oi=a&&this._trueLeds&&m==Bi,pt=$?S.width:this._aux.analyzerWidth,oo=C+pt,ai=K&&this._peakLine&&se==mn,Mt=$?P-E:g,U_=Mt/this._pixelRatio,[$_,J_,li,ao]=this._leds||[];b.val>0&&I>0&&(this._spinAngle+=this._spinSpeed*pn/60/I);const G_=N=>{if(this._reflexRatio>0&&!l&&!$){let ie,mt;this.reflexFit||ft?(ie=ft&&N==0?y+x:0,mt=y-g):(ie=S.height-g*2,mt=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[N].channelTop,S.width,g,0,ie,S.width,mt),h.restore()}},H_=()=>{this.showScaleX&&($?(h.save(),h.translate(_,v),this._spinSpeed&&h.rotate(this._spinAngle+jr),h.drawImage(he,-he.width>>1,-he.width>>1),h.restore()):h.drawImage(te,0,S.height-te.height))},W_=N=>{const ie=N**2,mt=424.36,Re=11599.29,es=25122.25,Dt=544496.41,xt=148693636,Yt=Zt=>20*Math.log10(Zt);switch(J){case Cd:const Zt=xt*ie**2/((ie+mt)*Math.sqrt((ie+Re)*(ie+Dt))*(ie+xt));return 2+Yt(Zt);case kd:const Jt=xt*ie*N/((ie+mt)*Math.sqrt(ie+es)*(ie+xt));return .17+Yt(Jt);case Td:const uo=xt*ie/((ie+mt)*(ie+xt));return .06+Yt(uo);case Ed:const ts=((103791848e-2-ie)**2+108076816e-2*ie)/((9837328-ie)**2+11723776*ie),ho=N/68966888496476e-18*Math.sqrt(ts/((ie+79919.29)*(ie+1345600)));return Yt(ho);case Ad:const ns=-4737338981378384e-39*N**6+2043828333606125e-30*N**4-1363894795463638e-22*ie+1,Qt=1306612257412824e-34*N**5-2118150887518656e-26*N**3+.0005559488023498642*N,We=.0001246332637532143*N/Math.hypot(ns,Qt);return 18.2+Yt(We)}return 0},lo=(N,ie,mt)=>{h.beginPath(),h.moveTo(N,ie),h.lineTo(N,mt),h.stroke()},co=N=>{if(N&&M){const ie=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ie}},Xt=N=>Math.max(0,(N*$_|0)*(ao+li)-li),z_=N=>{b.val=N,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*Oe/fe/S.height*this._pixelRatio)),N>=b.peak&&(b.peak=N,b.hold=oe)};ee&&h.clearRect(0,0,S.width,S.height);let Ou=0;const Nu=O.length,Fu=it?1:2;for(let N=0;N<Fu;N++){const{channelTop:ie,channelBottom:mt,analyzerBottom:Re}=w[N],es=this._gradients[this._selectedGrads[N]],Dt=es.colorStops,xt=Dt.length,Yt=!ce||a&&!ee?"#000":es.bgColor,Zt=ft&&$&&N?-1:1,Jt=!N&&V==-1||N&&V==1,uo=!re||N&&V!=1?0:pt>>(N||!Jt),ts=re&&Jt?-1:1,ho=()=>{const G=te.height,z=G>>1,X=D?100:F,de=D?0:U,Se=D?20:5,Ge=g/(X-de),gt=V!=-1&&(!re||N==0||V==1),Ot=V!=1&&(!re||N!=V);h.save(),h.fillStyle=Ld,h.font=`${z}px ${ji}`,h.textAlign="right",h.lineWidth=1;for(let Nt=X;Nt>de;Nt-=Se){const Sn=ie+(X-Nt)*Ge,ke=Nt%2==0|0;if(ke){const Be=Sn+z*(Sn==ie?.8:.35);gt&&h.fillText(Nt,G*.85,Be),Ot&&h.fillText(Nt,(re?pt:S.width)-G*.1,Be),h.strokeStyle=Ld,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=xv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(C+G*ke*gt,~~Sn+.5),h.lineTo(oo-G*ke*Ot,~~Sn+.5),h.stroke()}h.restore()},ns=(G,z)=>{const X=st[G]+(G<st.length-1?(st[G+1]-st[G])*z:0);return isNaN(X)?-1/0:X},Qt=(G,z=ts)=>z*pn*((G+uo)/S.width)+this._spinAngle,We=(G,z,X)=>{const de=E+z*Zt,Se=Qt(G,X);return[_+de*Math.cos(Se),v+de*Math.sin(Se)]},fo=(G,z,X,de,Se)=>{h.beginPath();for(const Ge of V&&!re?[1,-1]:[ts]){const[gt,Ot]=u?[Qt(G,Ge),Qt(G+X,Ge)]:[];h.moveTo(...We(G,z,Ge)),h.lineTo(...We(G,z+de,Ge)),u?h.arc(_,v,E+(z+de)*Zt,gt,Ot,Ge!=1):h.lineTo(...We(G+X,z+de,Ge)),h.lineTo(...We(G+X,z,Ge)),u&&!Se&&h.arc(_,v,E+z*Zt,Ot,gt,Ge==1)}co(Se),h.fill()},po=(G=0,z=0)=>{let X;if(m==Bi&&!oi||se==mn)X=k[N];else{const de=m==yd?z%xt:Dt.findLastIndex(Se=>a?Xt(G)<=Xt(Se.level):G<=Se.level);X=Dt[de].color}h.fillStyle=h.strokeStyle=X};if(Z){if(re&&!$){const G=pt*(N+Jt),z=Jt?-1:1;h.setTransform(z,0,0,1,G,0)}if((!ee||ce)&&(ee&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Yt,(N==0||!$&&!pe)&&h.fillRect(C,ie-x,pt,(ee&&this.reflexAlpha==1?g:y)+x),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(N==0||!pe)&&ho(),a?(h.setLineDash([ao,li]),h.lineWidth=O[0].width):h.lineWidth=d?Math.min(M,O[0].width/2):M,h.save(),!$){const G=new Path2D;G.rect(0,ie,S.width,g),h.clip(G)}}let st=this._fftData[N];this._analyzer[N].getFloatFrequencyData(st),J&&(st=st.map((G,z)=>G+W_(this._binToFreq(z)))),h.beginPath();let ci=[];for(let G=0;G<Nu;G++){const z=O[G],{posX:X,barCenter:de,width:Se,freq:Ge,binLo:gt,binHi:Ot,ratioLo:Nt,ratioHi:Sn}=z;let ke=Math.max(ns(gt,Nt),ns(Ot,Sn));for(let ae=gt+1;ae<Ot;ae++)st[ae]>ke&&(ke=st[ae]);if(ke=this._normalizedB(ke),z.value[N]=ke,Ou+=ke,z.peak[N]>0&&z.alpha[N]>0&&(z.hold[N]--,z.hold[N]<0)){if(T&&!ai){const ae=!o||d&&M>0?1:o?z.peak[N]:L;z.alpha[N]=ae*(1+z.hold[N]/Ve)}else z.peak[N]+=z.hold[N]*Oe/fe/U_;z.alpha[N]<=0&&(z.peak[N]=0)}if(ke>=z.peak[N]&&(z.peak[N]=ke,z.hold[N]=oe,z.alpha[N]=!o||d&&M>0?1:o?ke:L),!Z)continue;h.globalAlpha=l||o?ke:d?L:1,po(ke,G);const Be=l?Mt:a?Xt(ke):ke*Mt|0;if(se==mn){const ae=G?0:(this._normalizedB(st[O[1].binLo])*Mt+Be)/2;if($){if(G==0&&(re&&h.moveTo(...We(0,0)),h.lineTo(...We(0,X<0?ae:Be))),X>=0){const Qe=[X,Be];h.lineTo(...We(...Qe)),ci.push(Qe)}}else{if(G==0)if(V==-1&&!re)h.moveTo(C,Re-(X<C?ae:Be));else{const Qe=gt?this._normalizedB(st[gt-1])*Mt:Be;h.moveTo(C-M,Re-Qe)}(re||V!=-1||X>=C)&&h.lineTo(X,Re-Be)}}else if(a){if(ce&&!ee&&(N==0||!pe)){const ae=h.globalAlpha;h.strokeStyle=yv,h.globalAlpha=1,lo(de,ie,Re),h.strokeStyle=h.fillStyle,h.globalAlpha=ae}if(oi){const ae=l?0:Dt.findLastIndex(en=>Xt(ke)<=Xt(en.level));let Qe=Re;for(let en=xt-1;en>=ae;en--){h.strokeStyle=Dt[en].color;let Bu=Re-(en==ae?Be:Xt(Dt[en].level));lo(de,Qe,Bu),Qe=Bu-li}}else lo(de,Re,Re-Be)}else if(X>=C)if($)fo(X,0,Se,Be,d);else if(u){const ae=Se/2,Qe=Re+ae;h.beginPath(),h.moveTo(X,Qe),h.lineTo(X,Qe-Be),h.arc(de,Qe-Be,ae,Br,pn),h.lineTo(X+Se,Qe),co(d),h.fill()}else{const ae=d?h.lineWidth:0;h.beginPath(),h.rect(X,Re+ae,Se,-Be-ae),co(d),h.fill()}const xn=z.peak[N],Vu=z.alpha[N];if(xn>0&&Vu>0&&K&&!ai&&!l&&X>=C&&X<oo){if(T?h.globalAlpha=Vu:d&&M>0?h.globalAlpha=1:o&&(h.globalAlpha=xn),(m==_d||oi)&&po(xn),a){const ae=Xt(xn);ae>=li&&h.fillRect(X,Re-ae,Se,ao)}else if(!$)h.fillRect(X,Re-xn*Mt,Se,2);else if(se!=mn){const ae=xn*Mt;fo(X,ae,Se,!this._radialInvert||ft||ae+E>=2?-2:2)}}}if(Z){if(h.globalAlpha=1,se==mn){if(po(),$&&!re){if(V){let G;for(;G=ci.pop();)h.lineTo(...We(...G,-1))}h.closePath()}if(M>0&&h.stroke(),L>0){if($){const G=re?Qt(pt>>1):0,z=re?Qt(pt):pn;h.moveTo(...We(re?pt>>1:0,0)),h.arc(_,v,E,G,z,re?!Jt:!0)}else h.lineTo(oo,Re),h.lineTo(C,Re);h.globalAlpha=L,h.fill(),h.globalAlpha=1}if((ai||$&&K)&&(ci=[],h.beginPath(),O.forEach((G,z)=>{let X=G.posX,de=G.peak[N],Se=z?"lineTo":"moveTo";if($&&X<0){const Ge=O[z+1];de=Mv(X,de,Ge.posX,Ge.peak[N],0),X=0}de*=Mt,ai?(h[Se](...$?We(X,de):[X,Re-de]),$&&V&&!re&&ci.push([X,de])):de>0&&fo(X,de,1,-2)}),ai)){let G;for(;G=ci.pop();)h.lineTo(...We(...G,-1));h.lineWidth=1,h.stroke()}}h.restore(),re&&!$&&h.setTransform(1,0,0,1,0,0),(!re&&!pe||N)&&G_(N)}}if(z_(Ou/(Nu<<Fu-1)),Z&&(V&&!$&&!re&&(h.setTransform(-1,0,0,1,S.width-C,0),h.drawImage(S,C,0,_,S.height,0,0,_,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),H_()),this.showFPS){const N=te.height;h.font=`bold ${N}px ${ji}`,h.fillStyle=vv,h.textAlign="right",h.fillText(Math.round(I),S.width-N,N*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case gn:return Math.log2(e);case $r:return 26.81*e/(1960+e)-.53;case Gr:return Math.log2(1+e/700);case Yn: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==ut,g=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,x=w.dir=="h";let C;if(i?C=n.createRadialGradient(r,a,d,r,a,c-(d-c)*f):C=n.createLinearGradient(...x?[l,0,l+o,0]:[0,0,0,_]),y){const E=f&&!this._splitGradient&&(!x||i);for(let P=0;P<1+E;P++){const O=y.length-1;y.forEach((S,k)=>{let p=S.pos;if(E&&(p/=2),f&&!u&&!i&&!x&&(p*=g,!E&&p>.5*g&&(p+=.5*s)),P==1)if(i||u){const m=O-k;S=y[m],p=1-S.pos/2}else k==0&&p>0&&C.addColorStop(.5,S.color),p+=.5;C.addColorStop(p,S.color),f&&k==O&&p<.5&&C.addColorStop(.5,S.color)})}}this._canvasGradients[v]=C}}_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 Ze(Tv,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(Zn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Zn,...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 Ov={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=_e(null),s=Wt();return Pe(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Dv(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",Ov[((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]),A("div",{onClick:n,className:bt("w-full",e),ref:i})};/**
16
+ */const pv="4.5.1",Br=Math.PI,pn=2*Br,jr=Br/2,gd=8.17579892,vd="dual-combined",Vi="dual-horizontal",wt="single",ut="dual-vertical",yd="bar-index",_d="bar-level",Bi="gradient",bd=60,wd="click",mv="fullscreenchange",Sd="resize",gv="#111",xd="",Cd="A",kd="B",Td="C",Ad="D",Ed="468",ji="sans-serif",vv="#0f0",yv="#7f7f7f22",mn=10,Id="create",Rd="fschange",_v="lores",bv=Sd,Ur="user",wv="#000c",Pd="#fff",Sv="#4f4",Ld="#888",xv="#555",$r="bark",Yn="linear",gn="log",Gr="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"]}]],Zn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:wt,colorMode:Bi,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:gn,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:xd,width:void 0},Cv=["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"],Tv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Hr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Av=["ERR_INVALID_MODE","Invalid mode"],Ev=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Iv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Rv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Pv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],Lv=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ze 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},Ui=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],Mv=(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 Dv{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 Ze(Cv)}}if(!s.createGain)throw new Ze(kv);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(bv),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(mv,()=>{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=Ui(e,[wt,Vi,ut,vd]),this._input.disconnect(),this._input.connect(this._chLayout!=wt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=wt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Ui(e,[Bi,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=Ui(e,[gn,$r,Gr,Yn]),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||Zn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Ur)}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 Ze(Hr);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 Ze(Hr);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 Ze(Av,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||Zn.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 Ze(Ev);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=-jr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Od("stereo","channelLayout"),this._chLayout!=wt}set stereo(e){Od("stereo","channelLayout"),this.channelLayout=e?ut:wt}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=Ui(e,[xd,Cd,kd,Td,Ad,Ed],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Ur)}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 pv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ze(Iv);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==wt&&!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==wt?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(Zn))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 Ze(Rv);if(typeof n!="object")throw new Ze(Pv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ze(Lv);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||gv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Ur)}setFreqRange(e,n){if(e<1||n<1)throw new Ze(Hr);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,g=s.width>>1,_=s.height>>1,v=o==ut&&!d,w=o==Vi,y=c%10!=0,x=y&&this._frequencyScale==gn,k=this._showLeds&&y&&!d,A=this._lumiBars&&y&&!d,P=this._alphaBars&&!A&&c!=mn,O=this._outlineBars&&y&&!A&&!k,S=this._roundBars&&y&&!A&&!k,C=o!=ut||f>0&&!A,p=s.height-(v&&!k?.5:0)>>v,m=p*(A||d?1:1-f)|0,h=s.width-g*(w||l!=0),b=v?s.height-p*2:0,T=g*(l==-1&&!w&&!d);let R=Math.min(s.width,s.height)*.375*(o==ut?1:this._radius)|0,I=Math.min(g,_);u&&o!=ut&&([R,I]=[I,R]);const D=K=>e.push({...K,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=K=>{const Q=this._freqToBin(K,"floor"),ee=this._binToFreq(Q),te=this._binToFreq(Q+1),he=Math.log2(K/ee)/Math.log2(te/ee);return[Q,he]};let V,q,N;if(x){const K=(oe,pe,re)=>+oe.toPrecision(re?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],re=Math.log10(oe)|0,ft=oe/10**re;let it=1;for(;it<pe.length&&ft>pe[it];)it++;return ft-pe[it-1]<pe[it]-ft&&it--,(pe[it]*10**(re+5)|0)/1e5},ee=[0,24,12,8,6,4,3,2,1][c],te=n?10**(3/(ee*10)):2**(1/ee),he=te**.5;let Ve=n?7.94328235/(ee%2?1:he):gd;do{let oe=Ve;const pe=K(oe/he,4,!0),re=K(oe*he,4,!0),[ft,it]=M(pe),[oi,pt]=M(re);n?oe=ee<4?Q(oe):K(oe,oe.toString()[0]<5?3:2):oe=K(oe,4,!0),oe>=a&&D({posX:0,freq:oe,freqLo:pe,freqHi:re,binLo:ft,binHi:oi,ratioLo:it,ratioHi:pt}),Ve*=te}while(Ve<=r);V=h/e.length,e.forEach((oe,pe)=>oe.posX=T+pe*V);const fe=e[0],Oe=e[e.length-1];q=this._freqScaling(fe.freqLo),N=h/(this._freqScaling(Oe.freqHi)-q),fe.freqLo<a&&(fe.freqLo=a,[fe.binLo,fe.ratioLo]=M(a)),Oe.freqHi>r&&(Oe.freqHi=r,[Oe.binHi,Oe.ratioHi]=M(r))}else if(y){const K=[0,24,12,8,6,4,3,2,1][c]*10,Q=ee=>{switch(this._frequencyScale){case $r:return 1960/(26.81/(ee+.53)-1);case Gr:return 700*(2**ee-1);case Yn:return ee}};V=h/K,q=this._freqScaling(a),N=h/(this._freqScaling(r)-q);for(let ee=0,te=0;ee<K;ee++,te+=V){const he=Q(q+te/N),Ve=Q(q+(te+V/2)/N),fe=Q(q+(te+V)/N),[Oe,oe]=M(he),[pe,re]=M(fe);D({posX:T+te,freq:Ve,freqLo:he,freqHi:fe,binLo:Oe,binHi:pe,ratioLo:oe,ratioHi:re})}}else{V=1,q=this._freqScaling(a),N=h/(this._freqScaling(r)-q);const K=this._freqToBin(a,"floor"),Q=this._freqToBin(r);let ee=-999;for(let te=K;te<=Q;te++){const he=this._binToFreq(te),Ve=T+Math.round(N*(this._freqScaling(he)-q));if(Ve>ee)D({posX:Ve,freq:he,freqLo:he,freqHi:he,binLo:te,binHi:te,ratioLo:0,ratioHi:0}),ee=Ve;else if(e.length){const fe=e[e.length-1];fe.binHi=te,fe.freqHi=he,fe.freq=(fe.freqLo*he)**.5}}}let ne=0,Z=0;if(k){const K=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,[te,he,Ve]=ee||Q[c];let fe,Oe=m;if(ee){const oe=2*K;let pe;fe=te+1;do fe--,pe=Oe/fe/(1+he),Z=pe*he;while((pe<oe||Z<oe)&&fe>1)}else{const oe=540/he;Z=Math.min(he*K,Math.max(2,Oe/oe+.1|0))}C&&(Oe+=Z),ee||(fe=Math.min(te,Oe/(Z*2)|0)),ne=Ve>=1?Ve:V*Ve,this._leds=[fe,ne,Z,Oe/fe-Z]}const U=Math.min(V-1,i*(i>0&&i<1?V:1));y&&(V-=Math.max(k?ne:0,U)),e.forEach((K,Q)=>{let ee=K.posX,te=V;y&&(i==0&&!k?(ee|=0,te|=0,Q>0&&ee>e[Q-1].posX+e[Q-1].width&&(ee--,te++)):ee+=Math.max(k?ne:0,U)/2,K.posX=ee),K.barCenter=ee+(V==1?0:te/2),K.width=te});const ce=[];for(const K of[0,1]){const Q=o==ut?(p+b)*K:0,ee=Q+p,te=Q+m-(!k||C?0:Z);ce.push({channelTop:Q,channelBottom:ee,analyzerBottom:te})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:_,channelCoords:ce,channelHeight:p,channelGap:b,initialX:T,innerRadius:R,outerRadius:I,scaleMin:q,unitWidth:N},this._flg={isAlpha:P,isBands:y,isLeds:k,isLumi:A,isOctaves:x,isOutline:O,isRound:S,noLedGap:C},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:f}=this,g=u.canvas,_=f.canvas,v=[],w=this._chLayout==Vi,y=this._chLayout==ut,x=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=x/34|0,P=g.height>>1,O=A>>1,S=P*(c?.7:1.5),C=O*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=gn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Yn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let I=gd;for(let D=-1;D<11;D++)for(let M=0;M<12;M++){if(I>=this._minFreq&&I<=this._maxFreq){const V=k[M],q=V=="C";(V&&c&&!l&&!w||q)&&v.push(c?[I,V+(q?D:"")]:I)}I*=p}}_.width=_.height=Math.max(x*.15,(i<<1)+y*A);const m=_.width>>1,h=m-A*.7,b=(I,D)=>{const M=pn*(I/r.width),V=M-jr,q=h*Math.cos(V),N=h*Math.sin(V);f.save(),f.translate(m+q,m+N),f.rotate(M),f.fillText(D,0,0),f.restore()};g.width|=0,u.fillStyle=f.strokeStyle=wv,u.fillRect(0,0,g.width,g.height),f.arc(m,m,m-A/2,0,pn),f.lineWidth=A,f.stroke(),u.fillStyle=f.fillStyle=Pd,u.font=`${P}px ${ji}`,f.font=`${O}px ${ji}`,u.textAlign=f.textAlign="center";let T=-S/4,R=-C;for(const I of v){const[D,M]=Array.isArray(I)?I:[I,I<1e3?I|0:`${(I/100|0)/10}k`],V=o*(this._freqScaling(D)-s),q=g.height*.75,N=M[0]=="C",ne=P*(c&&!l&&!w?N?1.2:.6:3);if(u.fillStyle=f.fillStyle=N&&!l&&!w?Sv:Pd,c){const Z=a==gn,U=a==Yn;let ce=["C"];if((Z||D>2e3||!U&&D>250||(!d||y)&&(!U&&D>125||D>1e3))&&ce.push("G"),(Z||D>4e3||!U&&D>500||(!d||y)&&(!U&&D>250||D>2e3))&&ce.push("E"),(U&&D>4e3||(!d||y)&&(Z||D>2e3||!U&&D>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}V>=T+S/2&&V<=e&&(u.fillText(M,w&&l==-1?e-V:n+V,q,ne),(w||l&&(V>S||l==1))&&u.fillText(M,w&&l!=1?e+V:(n||r.width)-V,q,ne),T=V+Math.min(ne,u.measureText(M).width)/2),V>=R+C&&V<e-C&&(b(w&&l==1?e-V:V,M),(w||l&&(V>C||l==1))&&b(w&&l!=-1?e+V:-V,M),R=V)}}_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:g,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:x,initialX:k,innerRadius:A,outerRadius:P}=this._aux,{_bars:O,canvas:S,_canvasGradients:C,_chLayout:p,_colorMode:m,_ctx:h,_energy:b,_fadePeaks:T,fillAlpha:R,_fps:I,_linearAmplitude:D,_lineWidth:M,maxDecibels:V,minDecibels:q,_mirror:N,_mode:ne,overlay:Z,_radial:U,showBgColor:ce,showPeaks:K,useCanvas:Q,_weightingFilter:ee}=this,te=this._scaleX.canvas,he=this._scaleR.canvas,Ve=I*this._peakFadeTime/1e3,fe=I**2,Oe=this._gravity*1e3,oe=I*this._peakHoldTime/1e3,pe=p==vd,re=p==Vi,ft=p==ut,it=p==wt,oi=a&&this._trueLeds&&m==Bi,pt=U?S.width:this._aux.analyzerWidth,oo=k+pt,ai=K&&this._peakLine&&ne==mn,Mt=U?P-A:g,U_=Mt/this._pixelRatio,[$_,J_,li,ao]=this._leds||[];b.val>0&&I>0&&(this._spinAngle+=this._spinSpeed*pn/60/I);const G_=F=>{if(this._reflexRatio>0&&!l&&!U){let se,mt;this.reflexFit||ft?(se=ft&&F==0?y+x:0,mt=y-g):(se=S.height-g*2,mt=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[F].channelTop,S.width,g,0,se,S.width,mt),h.restore()}},H_=()=>{this.showScaleX&&(U?(h.save(),h.translate(_,v),this._spinSpeed&&h.rotate(this._spinAngle+jr),h.drawImage(he,-he.width>>1,-he.width>>1),h.restore()):h.drawImage(te,0,S.height-te.height))},W_=F=>{const se=F**2,mt=424.36,Re=11599.29,es=25122.25,Dt=544496.41,xt=148693636,Yt=Zt=>20*Math.log10(Zt);switch(ee){case Cd:const Zt=xt*se**2/((se+mt)*Math.sqrt((se+Re)*(se+Dt))*(se+xt));return 2+Yt(Zt);case kd:const Jt=xt*se*F/((se+mt)*Math.sqrt(se+es)*(se+xt));return .17+Yt(Jt);case Td:const uo=xt*se/((se+mt)*(se+xt));return .06+Yt(uo);case Ad:const ts=((103791848e-2-se)**2+108076816e-2*se)/((9837328-se)**2+11723776*se),ho=F/68966888496476e-18*Math.sqrt(ts/((se+79919.29)*(se+1345600)));return Yt(ho);case Ed:const ns=-4737338981378384e-39*F**6+2043828333606125e-30*F**4-1363894795463638e-22*se+1,Qt=1306612257412824e-34*F**5-2118150887518656e-26*F**3+.0005559488023498642*F,We=.0001246332637532143*F/Math.hypot(ns,Qt);return 18.2+Yt(We)}return 0},lo=(F,se,mt)=>{h.beginPath(),h.moveTo(F,se),h.lineTo(F,mt),h.stroke()},co=F=>{if(F&&M){const se=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=se}},Xt=F=>Math.max(0,(F*$_|0)*(ao+li)-li),z_=F=>{b.val=F,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*Oe/fe/S.height*this._pixelRatio)),F>=b.peak&&(b.peak=F,b.hold=oe)};Z&&h.clearRect(0,0,S.width,S.height);let Ou=0;const Nu=O.length,Fu=it?1:2;for(let F=0;F<Fu;F++){const{channelTop:se,channelBottom:mt,analyzerBottom:Re}=w[F],es=this._gradients[this._selectedGrads[F]],Dt=es.colorStops,xt=Dt.length,Yt=!ce||a&&!Z?"#000":es.bgColor,Zt=ft&&U&&F?-1:1,Jt=!F&&N==-1||F&&N==1,uo=!re||F&&N!=1?0:pt>>(F||!Jt),ts=re&&Jt?-1:1,ho=()=>{const $=te.height,W=$>>1,X=D?100:V,de=D?0:q,Se=D?20:5,Ge=g/(X-de),gt=N!=-1&&(!re||F==0||N==1),Ot=N!=1&&(!re||F!=N);h.save(),h.fillStyle=Ld,h.font=`${W}px ${ji}`,h.textAlign="right",h.lineWidth=1;for(let Nt=X;Nt>de;Nt-=Se){const Sn=se+(X-Nt)*Ge,ke=Nt%2==0|0;if(ke){const Be=Sn+W*(Sn==se?.8:.35);gt&&h.fillText(Nt,$*.85,Be),Ot&&h.fillText(Nt,(re?pt:S.width)-$*.1,Be),h.strokeStyle=Ld,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=xv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(k+$*ke*gt,~~Sn+.5),h.lineTo(oo-$*ke*Ot,~~Sn+.5),h.stroke()}h.restore()},ns=($,W)=>{const X=st[$]+($<st.length-1?(st[$+1]-st[$])*W:0);return isNaN(X)?-1/0:X},Qt=($,W=ts)=>W*pn*(($+uo)/S.width)+this._spinAngle,We=($,W,X)=>{const de=A+W*Zt,Se=Qt($,X);return[_+de*Math.cos(Se),v+de*Math.sin(Se)]},fo=($,W,X,de,Se)=>{h.beginPath();for(const Ge of N&&!re?[1,-1]:[ts]){const[gt,Ot]=u?[Qt($,Ge),Qt($+X,Ge)]:[];h.moveTo(...We($,W,Ge)),h.lineTo(...We($,W+de,Ge)),u?h.arc(_,v,A+(W+de)*Zt,gt,Ot,Ge!=1):h.lineTo(...We($+X,W+de,Ge)),h.lineTo(...We($+X,W,Ge)),u&&!Se&&h.arc(_,v,A+W*Zt,Ot,gt,Ge==1)}co(Se),h.fill()},po=($=0,W=0)=>{let X;if(m==Bi&&!oi||ne==mn)X=C[F];else{const de=m==yd?W%xt:Dt.findLastIndex(Se=>a?Xt($)<=Xt(Se.level):$<=Se.level);X=Dt[de].color}h.fillStyle=h.strokeStyle=X};if(Q){if(re&&!U){const $=pt*(F+Jt),W=Jt?-1:1;h.setTransform(W,0,0,1,$,0)}if((!Z||ce)&&(Z&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Yt,(F==0||!U&&!pe)&&h.fillRect(k,se-x,pt,(Z&&this.reflexAlpha==1?g:y)+x),h.globalAlpha=1),this.showScaleY&&!l&&!U&&(F==0||!pe)&&ho(),a?(h.setLineDash([ao,li]),h.lineWidth=O[0].width):h.lineWidth=d?Math.min(M,O[0].width/2):M,h.save(),!U){const $=new Path2D;$.rect(0,se,S.width,g),h.clip($)}}let st=this._fftData[F];this._analyzer[F].getFloatFrequencyData(st),ee&&(st=st.map(($,W)=>$+W_(this._binToFreq(W)))),h.beginPath();let ci=[];for(let $=0;$<Nu;$++){const W=O[$],{posX:X,barCenter:de,width:Se,freq:Ge,binLo:gt,binHi:Ot,ratioLo:Nt,ratioHi:Sn}=W;let ke=Math.max(ns(gt,Nt),ns(Ot,Sn));for(let ae=gt+1;ae<Ot;ae++)st[ae]>ke&&(ke=st[ae]);if(ke=this._normalizedB(ke),W.value[F]=ke,Ou+=ke,W.peak[F]>0&&W.alpha[F]>0&&(W.hold[F]--,W.hold[F]<0)){if(T&&!ai){const ae=!o||d&&M>0?1:o?W.peak[F]:R;W.alpha[F]=ae*(1+W.hold[F]/Ve)}else W.peak[F]+=W.hold[F]*Oe/fe/U_;W.alpha[F]<=0&&(W.peak[F]=0)}if(ke>=W.peak[F]&&(W.peak[F]=ke,W.hold[F]=oe,W.alpha[F]=!o||d&&M>0?1:o?ke:R),!Q)continue;h.globalAlpha=l||o?ke:d?R:1,po(ke,$);const Be=l?Mt:a?Xt(ke):ke*Mt|0;if(ne==mn){const ae=$?0:(this._normalizedB(st[O[1].binLo])*Mt+Be)/2;if(U){if($==0&&(re&&h.moveTo(...We(0,0)),h.lineTo(...We(0,X<0?ae:Be))),X>=0){const Qe=[X,Be];h.lineTo(...We(...Qe)),ci.push(Qe)}}else{if($==0)if(N==-1&&!re)h.moveTo(k,Re-(X<k?ae:Be));else{const Qe=gt?this._normalizedB(st[gt-1])*Mt:Be;h.moveTo(k-M,Re-Qe)}(re||N!=-1||X>=k)&&h.lineTo(X,Re-Be)}}else if(a){if(ce&&!Z&&(F==0||!pe)){const ae=h.globalAlpha;h.strokeStyle=yv,h.globalAlpha=1,lo(de,se,Re),h.strokeStyle=h.fillStyle,h.globalAlpha=ae}if(oi){const ae=l?0:Dt.findLastIndex(en=>Xt(ke)<=Xt(en.level));let Qe=Re;for(let en=xt-1;en>=ae;en--){h.strokeStyle=Dt[en].color;let Bu=Re-(en==ae?Be:Xt(Dt[en].level));lo(de,Qe,Bu),Qe=Bu-li}}else lo(de,Re,Re-Be)}else if(X>=k)if(U)fo(X,0,Se,Be,d);else if(u){const ae=Se/2,Qe=Re+ae;h.beginPath(),h.moveTo(X,Qe),h.lineTo(X,Qe-Be),h.arc(de,Qe-Be,ae,Br,pn),h.lineTo(X+Se,Qe),co(d),h.fill()}else{const ae=d?h.lineWidth:0;h.beginPath(),h.rect(X,Re+ae,Se,-Be-ae),co(d),h.fill()}const xn=W.peak[F],Vu=W.alpha[F];if(xn>0&&Vu>0&&K&&!ai&&!l&&X>=k&&X<oo){if(T?h.globalAlpha=Vu:d&&M>0?h.globalAlpha=1:o&&(h.globalAlpha=xn),(m==_d||oi)&&po(xn),a){const ae=Xt(xn);ae>=li&&h.fillRect(X,Re-ae,Se,ao)}else if(!U)h.fillRect(X,Re-xn*Mt,Se,2);else if(ne!=mn){const ae=xn*Mt;fo(X,ae,Se,!this._radialInvert||ft||ae+A>=2?-2:2)}}}if(Q){if(h.globalAlpha=1,ne==mn){if(po(),U&&!re){if(N){let $;for(;$=ci.pop();)h.lineTo(...We(...$,-1))}h.closePath()}if(M>0&&h.stroke(),R>0){if(U){const $=re?Qt(pt>>1):0,W=re?Qt(pt):pn;h.moveTo(...We(re?pt>>1:0,0)),h.arc(_,v,A,$,W,re?!Jt:!0)}else h.lineTo(oo,Re),h.lineTo(k,Re);h.globalAlpha=R,h.fill(),h.globalAlpha=1}if((ai||U&&K)&&(ci=[],h.beginPath(),O.forEach(($,W)=>{let X=$.posX,de=$.peak[F],Se=W?"lineTo":"moveTo";if(U&&X<0){const Ge=O[W+1];de=Mv(X,de,Ge.posX,Ge.peak[F],0),X=0}de*=Mt,ai?(h[Se](...U?We(X,de):[X,Re-de]),U&&N&&!re&&ci.push([X,de])):de>0&&fo(X,de,1,-2)}),ai)){let $;for(;$=ci.pop();)h.lineTo(...We(...$,-1));h.lineWidth=1,h.stroke()}}h.restore(),re&&!U&&h.setTransform(1,0,0,1,0,0),(!re&&!pe||F)&&G_(F)}}if(z_(Ou/(Nu<<Fu-1)),Q&&(N&&!U&&!re&&(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([]),H_()),this.showFPS){const F=te.height;h.font=`bold ${F}px ${ji}`,h.fillStyle=vv,h.textAlign="right",h.fillText(Math.round(I),S.width-F,F*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 gn:return Math.log2(e);case $r:return 26.81*e/(1960+e)-.53;case Gr:return Math.log2(1+e/700);case Yn: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==ut,g=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,x=w.dir=="h";let k;if(i?k=n.createRadialGradient(r,a,d,r,a,c-(d-c)*f):k=n.createLinearGradient(...x?[l,0,l+o,0]:[0,0,0,_]),y){const A=f&&!this._splitGradient&&(!x||i);for(let P=0;P<1+A;P++){const O=y.length-1;y.forEach((S,C)=>{let p=S.pos;if(A&&(p/=2),f&&!u&&!i&&!x&&(p*=g,!A&&p>.5*g&&(p+=.5*s)),P==1)if(i||u){const m=O-C;S=y[m],p=1-S.pos/2}else C==0&&p>0&&k.addColorStop(.5,S.color),p+=.5;k.addColorStop(p,S.color),f&&C==O&&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 Ze(Tv,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(Zn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Zn,...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 Ov={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=_e(null),s=Wt();return Pe(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Dv(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",Ov[((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]),E("div",{onClick:n,className:bt("w-full",e),ref:i})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
@@ -103,12 +103,12 @@ var q_=Object.defineProperty;var K_=(et,H,Ft)=>H in et?q_(et,H,{enumerable:!0,co
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 Wr=Ue("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$d=bs(!1),Zv=()=>ba($d),St=({children:t,className:e,onClick:n,tooltip:i})=>A("button",{title:i,onClick:n,className:bt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Gd=({call:t})=>{const[e,n]=Zv(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return A("div",{className:"flex items-center justify-center gap-2",children:[A(St,{tooltip:e?"Unmute":"Mute",onClick:i,className:bt(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?A(Gv,{className:"w-5 h-5 text-black dark:text-white"}):A(Hv,{className:"w-5 h-5 text-black dark:text-white"})}),A(St,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:A(zv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Hd=({call:t,onExpand:e})=>A(Xn.div,{layoutId:Ni,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:[A(Fd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),A(md,{stream:t.remoteStream}),A(pd,{size:"small"}),A(Gd,{call:t})]});function Jv(){const[t,e]=Te(!1),n=Wt();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 A("div",{children:[A(St,{tooltip:"More",onClick:()=>e(!t),children:A(Ud,{className:"text-black dark:text-white"})}),t&&A("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:[A(St,{tooltip:"More",onClick:()=>e(!t),children:A(Ud,{className:"text-black dark:text-white"})}),A("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&A("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",A(Xv,{className:"w-4 h-4"})]}),n.report_issue_url&&A("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",A(Yv,{className:"w-4 h-4"})]}),n.view_history_url&&A("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",A(Uv,{className:"w-4 h-4"})]})]})]})]})}function Qv(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $i={exports:{}},ey=$i.exports,Wd;function ty(){return Wd||(Wd=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(ey,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 g(v,w){var y=this,x,C,E,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=b;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var b=window.document.cookie,T=encodeURIComponent(P),L=b.indexOf(T+"=");L!==-1&&(h=/^([^;]+)/.exec(b.slice(L+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; 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 E??C??x},y.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){C=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,k(),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&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(E=p(m)),d.call(y)}r=new g,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 g(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})}($i)),$i.exports}var ny=ty();const iy=Qv(ny),sy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ry="[ai-agent-widget]",Me=iy.getLogger("telnyx-ai-agent-widget"),oy=Me.methodFactory;Me.methodFactory=(t,e,n)=>{const i=oy(t,e,n);return function(...s){i(sy(),ry,...s)}},Me.setLevel("info");function ay({onCapture:t,onClose:e}){const n=_e(null),i=_e(null),s=_e(null),[o,r]=Te(null),[a,l]=Te(!0);Pe(()=>((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){Me.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,g=f.getContext("2d");if(!g)return;f.width=u.videoWidth,f.height=u.videoHeight,g.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 A("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:[A("div",{className:"absolute top-2 right-2 z-10",children:A(St,{tooltip:"Close",onClick:d,children:A(Wr,{className:"text-white w-5 h-5"})})}),A("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&A("div",{className:"absolute text-white text-center",children:A("p",{className:"text-sm",children:"Loading camera..."})}),o&&A("div",{className:"text-white text-center max-w-xs",children:[A("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),A("p",{className:"text-xs",children:o}),A("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&&A(ot,{children:[A("video",{ref:n,autoPlay:!0,playsInline:!0,className:bt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),A("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&A("div",{className:"p-3 flex justify-center",children:A("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:[A(jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function ly({item:t,containerRef:e}){const n=_e(null);return Pe(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),A("li",{className:bt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[A("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&A("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&A("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),A("div",{className:bt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&A("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&A("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&&A("p",{className:bt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const cy=({transcript:t,call:e})=>{const n=_e(null),i=_e(null),s=_e(null),[o,r]=Te([]),[a,l]=Te(!1),[c,d]=Te([]),[,u]=Vr();Pe(()=>()=>{o.forEach(S=>URL.revokeObjectURL(S.preview))},[o]),Pe(()=>{if(c.length===0)return;const S=t.filter(k=>k.role==="user"&&!k.id.startsWith("optimistic-"));if(S.length>0){const k=S[S.length-1];d(p=>p.filter(m=>m.timestamp>k.timestamp))}},[t,c]);const f=S=>new Promise((k,p)=>{const m=new FileReader;m.onload=()=>k(m.result),m.onerror=p,m.readAsDataURL(S)}),g=async S=>{if(S.type.startsWith("image/"))try{const k=await f(S),p=URL.createObjectURL(S),m={id:Date.now().toString(),file:S,base64:k,preview:p};r(h=>[...h,m])}catch(k){Me.error("Error processing image:",k)}},_=S=>{r(k=>{const p=k.find(m=>m.id===S);return p&&URL.revokeObjectURL(p.preview),k.filter(m=>m.id!==S)})},v=S=>{const k=S.target,p=k.files;p&&p.length>0&&(Array.from(p).forEach(g),k.value="")},w=S=>{var p;const k=(p=S.clipboardData)==null?void 0:p.items;k&&Array.from(k).forEach(m=>{if(m.type.startsWith("image/")){const h=m.getAsFile();h&&g(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},x=()=>{l(!0)},C=S=>{fetch(S).then(k=>k.blob()).then(k=>{const p=new File([k],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(k=>{Me.error("Error processing camera capture:",k)})},E=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",k=o.length>0;if(S||k){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:o.map(T=>({type:"image",url:T.base64}))};d(T=>[...T,b]),k&&u("processing_image"),e.sendConversationMessage(m,o.map(T=>T.base64)),n.current&&(n.current.value=""),o.forEach(T=>URL.revokeObjectURL(T.preview)),r([])}},P=S=>{S.key==="Enter"&&(S.preventDefault(),E())},O=[...t,...c];return A("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:[A("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((S,k)=>A(ly,{item:S,containerRef:s},S.id+k))}),o.length>0&&A("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(S=>A("div",{className:"relative",children:[A("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),A("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:A(Wr,{className:"w-3 h-3"})})]},S.id))}),A("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:[A("input",{ref:n,type:"text",onKeyDown:P,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),A("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),A(St,{tooltip:"Attach image",onClick:y,children:A(Wv,{className:"text-[#969696] w-4 h-4"})}),A(St,{tooltip:"Take photo",onClick:x,children:A(jd,{className:"text-[#969696] w-4 h-4"})}),A(St,{tooltip:"Send",children:A(qv,{onClick:E,className:"text-[#969696] w-4 h-4"})})]}),a&&A(ay,{onCapture:C,onClose:()=>l(!1)})]})};function dy({onCollapse:t}){return A("div",{className:"flex items-center justify-between w-full",children:[A(Jv,{}),A(St,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:A(Wr,{className:"text-black dark:text-white"})})]})}const uy=({call:t,onCollapse:e,transcript:n})=>A(Ip,{children:A(Xn.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:[A("div",{className:"p-4 text-center",children:[A(dy,{onCollapse:e}),A(Fd,{className:"h-[144px]",stream:t.remoteStream}),A(pd,{size:"large",className:"mb-4"}),A(Gd,{call:t})]}),A(md,{stream:t.remoteStream}),A(cy,{call:t,transcript:n})]})});function Gi(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function j(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(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 zd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),hy=new Uint8Array(16);function fy(){if(!zd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zd(hy)}for(var qd=[],Hi=0;Hi<256;++Hi)qd[Hi]=(Hi+256).toString(16).substr(1);function vn(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 o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=qd;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 Kd="wss://rtc.telnyx.com",Xd={urls:"stun:stun.l.google.com:19302"},py=[{urls:"stun:stun.telnyx.com:3478"},Xd,{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],my=[{urls:"stun:stundev.telnyx.com:3478"},Xd,{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var B;(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"})(B||(B={}));var gy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yd(t,e){return t(e={exports:{}},e.exports),e.exports}var vy=Yd(function(t){var e,n;e=gy,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 x=w[y];if(typeof x.bind=="function")return x.bind(w);try{return Function.prototype.bind.call(x,w)}catch{return function(){return Function.prototype.apply.apply(x,[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 x=0;x<r.length;x++){var C=r[x];this[C]=x<w?i:this.methodFactory(C,w,y)}this.log=this.debug}function d(w,y,x){return function(){typeof console!==s&&(c.call(this,y,x),this[w].apply(this,arguments))}}function u(w,y,x){return function(C){return C==="debug"&&(C="log"),typeof console!==s&&(C==="trace"&&o?l:console[C]!==void 0?a(console,C):console.log!==void 0?a(console,"log"):i)}(w)||d.apply(this,arguments)}function f(w,y,x){var C,E=this;y=y??"WARN";var P="loglevel";function O(){var k;if(typeof window!==s&&P){try{k=window.localStorage[P]}catch{}if(typeof k===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(P)+"=");m!==-1&&(k=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return E.levels[k]===void 0&&(k=void 0),k}}typeof w=="string"?P+=":"+w:typeof w=="symbol"&&(P=void 0),E.name=w,E.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},E.methodFactory=x||u,E.getLevel=function(){return C},E.setLevel=function(k,p){if(typeof k=="string"&&E.levels[k.toUpperCase()]!==void 0&&(k=E.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=E.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(C=k,p!==!1&&function(m){var h=(r[m]||"silent").toUpperCase();if(typeof window!==s&&P){try{return void(window.localStorage[P]=h)}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+h+";"}catch{}}}(k),c.call(E,k,w),typeof console===s&&k<E.levels.SILENT)return"No console available for logging"},E.setDefaultLevel=function(k){y=k,O()||E.setLevel(k,!1)},E.resetLevel=function(){E.setLevel(y,!1),function(){if(typeof window!==s&&P){try{return void window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},E.enableAll=function(k){E.setLevel(E.levels.TRACE,k)},E.disableAll=function(k){E.setLevel(E.levels.SILENT,k)};var S=O();S==null&&(S=y),E.setLevel(S,!1)}var g=new f,_={};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=_[w];return y||(y=_[w]=new f(w,g.getLevel(),g.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return _},g.default=g,g},t.exports?t.exports=n():e.log=n()});const R=vy.getLogger("telnyx"),yy=R.methodFactory;R.methodFactory=(t,e,n)=>{const i=yy(t,e,n);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);i.apply(void 0,s)}},R.setLevel("info");const Wi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{R.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Zd=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},yn=t=>t instanceof Function||typeof t=="function",zi=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,_y=/^(ws|wss):\/\//,Jd=(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?Jd(a,r):{result:s}},Qd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),qi=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Jn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,zr=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 eu({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?by(i,t):i,n=s}),resolve:e,reject:n}}const by=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},qr="telnyx-voice-sdk-id";function Qn(){return sessionStorage.getItem(qr)}var Ae,Rt,ne;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(qr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ae||(Ae={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(Rt||(Rt={})),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"}(ne||(ne={}));const Je={generic:"event",[ne.Display]:"participantData",[ne.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},wy={invalidCredentialsOptions:"InvalidCredentialsOptions"},Sy={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1};var q,Kr,He,ht,Fe;(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"}(Kr||(Kr={})),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"}(Fe||(Fe={}));const _n="GLOBAL",$e={},ei=(t,e)=>`${t}|${e}`,tu=(t,e=_n)=>ei(t,e)in $e,Pt=(t,e,n=_n)=>{const i=ei(t,n);i in $e||($e[i]=[]),$e[i].push(e)},nu=(t,e,n=_n)=>{const i=function(s){Lt(t,i,n),e(s)};return i.prototype.targetRef=e,Pt(t,i,n)},Lt=(t,e,n=_n)=>{if(!tu(t,n))return!1;const i=ei(t,n);if(yn(e))for(let s=$e[i].length-1;s>=0;s--){const o=$e[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&$e[i].splice(s,1)}else $e[i]=[];return $e[i].length===0&&delete $e[i],!0},Y=(t,e,n=_n,i=!0)=>{const s=i&&n!==_n;if(!tu(t,n))return s&&Y(t,e),!1;const o=ei(t,n),r=$e[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)$e[o][a](e);return s&&Y(t,e),!0},Xr=t=>{const e=ei(t,"");Object.keys($e).filter(n=>n.indexOf(e)===0).forEach(n=>delete $e[n])};let xy=typeof WebSocket<"u"?WebSocket:null;const Cy=0,ky=1,Ty=2,Ey=3;class iu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Kd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Kd),n&&(this._host=(a=>`${_y.test(a)?"":"wss://"}${a}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),(o||r)&&(this._useCanaryRtcServer=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===ky}get connecting(){return this._wsClient&&this._wsClient.readyState===Cy}get closing(){return this._wsClient&&this._wsClient.readyState===Ty}get closed(){return this._wsClient&&this._wsClient.readyState===Ey}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=Qn();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),R.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this._wsClient=new xy(e.toString()),this._wsClient.onopen=i=>Y(B.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Y(B.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Y(B.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=Zd(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(qr,a)),this._unsetTimer(r.id),R.debug(`RECV:
106
+ */const Wr=Ue("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$d=bs(!1),Zv=()=>ba($d),St=({children:t,className:e,onClick:n,tooltip:i})=>E("button",{title:i,onClick:n,className:bt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Gd=({call:t})=>{const[e,n]=Zv(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return E("div",{className:"flex items-center justify-center gap-2",children:[E(St,{tooltip:e?"Unmute":"Mute",onClick:i,className:bt(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?E(Gv,{className:"w-5 h-5 text-black dark:text-white"}):E(Hv,{className:"w-5 h-5 text-black dark:text-white"})}),E(St,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:E(zv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Hd=({call:t,onExpand:e})=>E(Xn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[E(Fd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),E(md,{stream:t.remoteStream}),E(pd,{size:"small"}),E(Gd,{call:t})]});function Jv(){const[t,e]=Te(!1),n=Wt();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},o=()=>{i(n.report_issue_url)},r=()=>{i(n.view_history_url)};return E("div",{children:[E(St,{tooltip:"More",onClick:()=>e(!t),children:E(Ud,{className:"text-black dark:text-white"})}),t&&E("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[E(St,{tooltip:"More",onClick:()=>e(!t),children:E(Ud,{className:"text-black dark:text-white"})}),E("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&E("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",E(Xv,{className:"w-4 h-4"})]}),n.report_issue_url&&E("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",E(Yv,{className:"w-4 h-4"})]}),n.view_history_url&&E("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",E(Uv,{className:"w-4 h-4"})]})]})]})]})}function Qv(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $i={exports:{}},ey=$i.exports,Wd;function ty(){return Wd||(Wd=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(ey,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 g(v,w){var y=this,x,k,A,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=b;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var b=window.document.cookie,T=encodeURIComponent(P),R=b.indexOf(T+"=");R!==-1&&(h=/^([^;]+)/.exec(b.slice(R+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; 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 A??k??x},y.setLevel=function(h,b){return A=p(h),b!==!1&&O(A),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){A=null,C(),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&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(A=p(m)),d.call(y)}r=new g,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 g(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})}($i)),$i.exports}var ny=ty();const iy=Qv(ny),sy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ry="[ai-agent-widget]",Me=iy.getLogger("telnyx-ai-agent-widget"),oy=Me.methodFactory;Me.methodFactory=(t,e,n)=>{const i=oy(t,e,n);return function(...s){i(sy(),ry,...s)}},Me.setLevel("info");function ay({onCapture:t,onClose:e}){const n=_e(null),i=_e(null),s=_e(null),[o,r]=Te(null),[a,l]=Te(!0);Pe(()=>((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){Me.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,g=f.getContext("2d");if(!g)return;f.width=u.videoWidth,f.height=u.videoHeight,g.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 E("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[E("div",{className:"absolute top-2 right-2 z-10",children:E(St,{tooltip:"Close",onClick:d,children:E(Wr,{className:"text-white w-5 h-5"})})}),E("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&E("div",{className:"absolute text-white text-center",children:E("p",{className:"text-sm",children:"Loading camera..."})}),o&&E("div",{className:"text-white text-center max-w-xs",children:[E("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),E("p",{className:"text-xs",children:o}),E("button",{onClick:d,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&E(ot,{children:[E("video",{ref:n,autoPlay:!0,playsInline:!0,className:bt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),E("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&E("div",{className:"p-3 flex justify-center",children:E("button",{onClick: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:[E(jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function ly({item:t,containerRef:e}){const n=_e(null);return Pe(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),E("li",{className:bt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[E("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&E("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&E("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),E("div",{className:bt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&E("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&E("img",{src:i.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},s))}),t.content&&E("p",{className:bt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const cy=({transcript:t,call:e})=>{const n=_e(null),i=_e(null),s=_e(null),[o,r]=Te([]),[a,l]=Te(!1),[c,d]=Te([]),[,u]=Vr();Pe(()=>()=>{o.forEach(S=>URL.revokeObjectURL(S.preview))},[o]),Pe(()=>{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];d(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};r(h=>[...h,m])}catch(C){Me.error("Error processing image:",C)}},_=S=>{r(C=>{const p=C.find(m=>m.id===S);return p&&URL.revokeObjectURL(p.preview),C.filter(m=>m.id!==S)})},v=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()},x=()=>{l(!0)},k=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=>{Me.error("Error processing camera capture:",C)})},A=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",C=o.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:o.map(T=>({type:"image",url:T.base64}))};d(T=>[...T,b]),C&&u("processing_image"),e.sendConversationMessage(m,o.map(T=>T.base64)),n.current&&(n.current.value=""),o.forEach(T=>URL.revokeObjectURL(T.preview)),r([])}},P=S=>{S.key==="Enter"&&(S.preventDefault(),A())},O=[...t,...c];return E("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[E("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((S,C)=>E(ly,{item:S,containerRef:s},S.id+C))}),o.length>0&&E("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(S=>E("div",{className:"relative",children:[E("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),E("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:E(Wr,{className:"w-3 h-3"})})]},S.id))}),E("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[E("input",{ref:n,type:"text",onKeyDown:P,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),E("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),E(St,{tooltip:"Attach image",onClick:y,children:E(Wv,{className:"text-[#969696] w-4 h-4"})}),E(St,{tooltip:"Take photo",onClick:x,children:E(jd,{className:"text-[#969696] w-4 h-4"})}),E(St,{tooltip:"Send",children:E(qv,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&E(ay,{onCapture:k,onClose:()=>l(!1)})]})};function dy({onCollapse:t}){return E("div",{className:"flex items-center justify-between w-full",children:[E(Jv,{}),E(St,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:E(Wr,{className:"text-black dark:text-white"})})]})}const uy=({call:t,onCollapse:e,transcript:n})=>E(Ip,{children:E(Xn.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[E("div",{className:"p-4 text-center",children:[E(dy,{onCollapse:e}),E(Fd,{className:"h-[144px]",stream:t.remoteStream}),E(pd,{size:"large",className:"mb-4"}),E(Gd,{call:t})]}),E(md,{stream:t.remoteStream}),E(cy,{call:t,transcript:n})]})});function Gi(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function j(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(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 zd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),hy=new Uint8Array(16);function fy(){if(!zd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zd(hy)}for(var qd=[],Hi=0;Hi<256;++Hi)qd[Hi]=(Hi+256).toString(16).substr(1);function vn(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 o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=qd;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 Kd="wss://rtc.telnyx.com",Xd={urls:"stun:stun.l.google.com:19302"},py=[{urls:"stun:stun.telnyx.com:3478"},Xd,{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],my=[{urls:"stun:stundev.telnyx.com:3478"},Xd,{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var B;(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"})(B||(B={}));var gy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yd(t,e){return t(e={exports:{}},e.exports),e.exports}var vy=Yd(function(t){var e,n;e=gy,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 x=w[y];if(typeof x.bind=="function")return x.bind(w);try{return Function.prototype.bind.call(x,w)}catch{return function(){return Function.prototype.apply.apply(x,[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 x=0;x<r.length;x++){var k=r[x];this[k]=x<w?i:this.methodFactory(k,w,y)}this.log=this.debug}function d(w,y,x){return function(){typeof console!==s&&(c.call(this,y,x),this[w].apply(this,arguments))}}function u(w,y,x){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,x){var k,A=this;y=y??"WARN";var P="loglevel";function O(){var C;if(typeof window!==s&&P){try{C=window.localStorage[P]}catch{}if(typeof C===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(P)+"=");m!==-1&&(C=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return A.levels[C]===void 0&&(C=void 0),C}}typeof w=="string"?P+=":"+w:typeof w=="symbol"&&(P=void 0),A.name=w,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=x||u,A.getLevel=function(){return k},A.setLevel=function(C,p){if(typeof C=="string"&&A.levels[C.toUpperCase()]!==void 0&&(C=A.levels[C.toUpperCase()]),!(typeof C=="number"&&C>=0&&C<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+C;if(k=C,p!==!1&&function(m){var h=(r[m]||"silent").toUpperCase();if(typeof window!==s&&P){try{return void(window.localStorage[P]=h)}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+h+";"}catch{}}}(C),c.call(A,C,w),typeof console===s&&C<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(C){y=C,O()||A.setLevel(C,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&P){try{return void window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(C){A.setLevel(A.levels.TRACE,C)},A.disableAll=function(C){A.setLevel(A.levels.SILENT,C)};var S=O();S==null&&(S=y),A.setLevel(S,!1)}var g=new f,_={};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=_[w];return y||(y=_[w]=new f(w,g.getLevel(),g.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return _},g.default=g,g},t.exports?t.exports=n():e.log=n()});const L=vy.getLogger("telnyx"),yy=L.methodFactory;L.methodFactory=(t,e,n)=>{const i=yy(t,e,n);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);i.apply(void 0,s)}},L.setLevel("info");const Wi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{L.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Zd=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},yn=t=>t instanceof Function||typeof t=="function",zi=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,_y=/^(ws|wss):\/\//,Jd=(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?Jd(a,r):{result:s}},Qd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),qi=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),Jn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,zr=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 eu({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?by(i,t):i,n=s}),resolve:e,reject:n}}const by=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},qr="telnyx-voice-sdk-id";function Qn(){return sessionStorage.getItem(qr)}var Ee,Rt,ie;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(qr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ee||(Ee={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(Rt||(Rt={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ie||(ie={}));const Je={generic:"event",[ie.Display]:"participantData",[ie.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},wy={invalidCredentialsOptions:"InvalidCredentialsOptions"},Sy={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1};var z,Kr,He,ht,Fe;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Kr||(Kr={})),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"}(Fe||(Fe={}));const _n="GLOBAL",$e={},ei=(t,e)=>`${t}|${e}`,tu=(t,e=_n)=>ei(t,e)in $e,Pt=(t,e,n=_n)=>{const i=ei(t,n);i in $e||($e[i]=[]),$e[i].push(e)},nu=(t,e,n=_n)=>{const i=function(s){Lt(t,i,n),e(s)};return i.prototype.targetRef=e,Pt(t,i,n)},Lt=(t,e,n=_n)=>{if(!tu(t,n))return!1;const i=ei(t,n);if(yn(e))for(let s=$e[i].length-1;s>=0;s--){const o=$e[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&$e[i].splice(s,1)}else $e[i]=[];return $e[i].length===0&&delete $e[i],!0},Y=(t,e,n=_n,i=!0)=>{const s=i&&n!==_n;if(!tu(t,n))return s&&Y(t,e),!1;const o=ei(t,n),r=$e[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)$e[o][a](e);return s&&Y(t,e),!0},Xr=t=>{const e=ei(t,"");Object.keys($e).filter(n=>n.indexOf(e)===0).forEach(n=>delete $e[n])};let xy=typeof WebSocket<"u"?WebSocket:null;const Cy=0,ky=1,Ty=2,Ay=3;class iu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Kd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Kd),n&&(this._host=(a=>`${_y.test(a)?"":"wss://"}${a}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),(o||r)&&(this._useCanaryRtcServer=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===ky}get connecting(){return this._wsClient&&this._wsClient.readyState===Cy}get closing(){return this._wsClient&&this._wsClient.readyState===Ty}get closed(){return this._wsClient&&this._wsClient.readyState===Ay}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=Qn();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"),L.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this._wsClient=new xy(e.toString()),this._wsClient.onopen=i=>Y(B.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Y(B.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Y(B.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=Zd(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(qr,a)),this._unsetTimer(r.id),L.debug(`RECV:
107
107
  `,JSON.stringify(r,null,2),`
108
- `),Fe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!Y(r.id,r)){const l=zr(r);Y(B.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();nu(n.id,r=>{const{result:a,error:l}=Jd(r);return l?o(l):s(a)})});return R.debug(`SEND:
108
+ `),Fe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!Y(r.id,r)){const l=zr(r);Y(B.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();nu(n.id,r=>{const{result:a,error:l}=Jd(r);return l?o(l):s(a)})});return L.debug(`SEND:
109
109
  `,JSON.stringify(n,null,2),`
110
- `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(yn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),Y(B.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else R.warn("Unknown message from socket",e)}}class ti{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:vn()},e)}}const su={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 De extends ti{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Gi(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in su)i&&n.hasOwnProperty(i)&&(n[su[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class ru extends De{constructor(e){super(),this.method=ne.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ay{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>j(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(zr(n))}),this.getIsRegistered=()=>j(this,void 0,void 0,function*(){const n=new ru(Qn());this.pendingRequestId=n.request.id,this.gatewayStateTask=eu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Fe.REGISTER,Fe.REGED].includes(i)}),this.session=e,this.gatewayStateTask=eu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ou extends De{constructor(e){super(),this.method=ne.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var au="2.25.17",Yr=au;class Iy extends De{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:Yr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Ry extends De{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class lu extends De{toString(){return ne.Invite}}class cu extends De{toString(){return ne.Answer}}class Zr extends De{toString(){return ne.Attach}}class Py extends De{toString(){return ne.Bye}}class du extends De{toString(){return ne.Candidate}}class Ly extends De{toString(){return ne.EndOfCandidates}}class Jr extends De{toString(){return ne.Modify}}class uu extends De{toString(){return ne.Info}}class My extends De{toString(){return ne.Broadcast}}class Dy extends De{toString(){return ne.Subscribe}}class Oy extends De{toString(){return ne.Unsubscribe}}class Ny extends De{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,l={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Yr,data:navigator.userAgent}};r&&(l.sessid=r),s&&(l.target_version_id=s),this.buildRequest({method:this.method,params:l})}}class Fy{constructor(e){if(this.options=e,this.uuid=vn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");R.setLevel(e.debug?"debug":"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 iu(this),this.registerAgent=new Ay(this)}get __logger(){return R}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return j(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Qd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return qi(this.options)||Jn(this.options)}broadcast(e){}disconnect(){return j(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),R.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 Lt(e,n,this.uuid),this}connect(){return j(this,void 0,void 0,function*(){this.connection||(this.connection=new iu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||this.connection.connect(),R.debug("Session connected. Connection initiated if not already alive. Auto-reconnect enabled.")})}_handleLoginError(e){Y(B.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return j(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)),qi(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(Jn(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";return R.error(s),void Y(B.Error,{error:new Error(s),type:wy.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return j(this,void 0,void 0,function*(){let s;s=e==="login"?new Iy(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Qn()):new Ny({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,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Qn()});const o=yield this.execute(s).catch(r=>{this._handleLoginError(r),i&&i(r)});o&&(this.sessionid=o.sessid,n&&n())})}_onSocketOpen(){return j(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Xr(this.relayProtocol);for(const e in this.subscriptions)Xr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Lt(e,null,n)):(delete this.subscriptions[e],Xr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},yn(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(B.SocketOpen,this._onSocketOpen),this.on(B.SocketClose,this.onNetworkClose),this.on(B.SocketError,this.onNetworkClose),this.on(B.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(B.SocketOpen,this._onSocketOpen),this.off(B.SocketClose,this.onNetworkClose),this.off(B.SocketError,this.onNetworkClose),this.off(B.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(R.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new ou(Qn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){R.debug("Ping received"),this._pong=!0}static on(e,n){Pt(e,n)}static off(e){Lt(e)}static uuid(){return vn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Ki=t=>navigator.mediaDevices.getUserMedia(t),bn=t=>t&&t instanceof MediaStream,ni=(t,e)=>{const n=zi(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},hu=(t,e)=>j(void 0,void 0,void 0,function*(){const n=zi(t);if(n===null)return R.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return R.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Vy=t=>{t&&t.readyState==="live"&&t.stop()},ii=t=>{bn(t)&&t.getTracks().forEach(Vy),t=null},Xi=t=>j(void 0,void 0,void 0,function*(){R.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Ki(t)}catch(i){if(R.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=Gi(r,["deviceId"]);c=Object.keys(u).length===0||u}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const u=Gi(a,["deviceId"]);d=Object.keys(u).length===0||u}return l?{audio:c,video:d}:null})(t);if(s){R.warn("Device not found or not readable, falling back to default device");try{return yield Ki(s)}catch(o){throw R.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),si=(t=null,e=!1)=>j(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===ht.AudioIn||s===ht.AudioOut,video:!s||s===ht.Video}))(t)).catch(s=>(R.error(s),null));if(i){if(ii(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}),fu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Yi=(t,e,n)=>j(void 0,void 0,void 0,function*(){const i=yield si(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}),By=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Qr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=eo(t);return n.includes(e)||i.includes(e)},eo=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},wn=(t,e=null,n=null)=>{if(!bn(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}})},pu=t=>{wn(t,"audio",!0)},to=t=>{wn(t,"audio",!1)},mu=t=>{wn(t,"audio",null)},jy=t=>((e,n=null)=>{if(!bn(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 Uy(){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:!!Xi}}catch(t){return t.message}}var ye;function gu(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 vu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{R.error("playAudio",e),t._playFulfilled=!0}))}function yu(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"})(ye||(ye={}));class $y extends ti{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:vn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}var Zi,_u=Yd(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,m,h,b){var T,L,I;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((L=p._events)?(L.newListener&&(p.emit("newListener",m,h.listener?h.listener:h),L=p._events),I=L[m]):(L=p._events=new i,p._eventsCount=0),I){if(typeof I=="function"?I=L[m]=b?[h,I]:[I,h]:b?I.unshift(h):I.push(h),!I.warned&&(T=o(p))&&0<T&&I.length>T){I.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+I.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");D.name="MaxListenersExceededWarning",D.emitter=p,D.type=m,D.count=I.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(D)}}else I=L[m]=h,++p._eventsCount;return p}function a(p,m,h){function b(){p.removeListener(m,b),T||(T=!0,h.apply(p,arguments))}var T=!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 o(this)},s.prototype.emit=function(p){var m,h,b,T,L,I,D,M=p==="error";if(I=this._events)M=M&&I.error==null;else if(!M)return!1;if(D=this.domain,M){if(m=arguments[1],!D){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=D,m.domainThrown=!1,D.emit("error",m),!1}if(!(h=I[p]))return!1;var U=typeof h=="function";switch(b=arguments.length){case 1:(function(V,se,ee){if(se)V.call(ee);else for(var $=V.length,ce=c(V,$),K=0;K<$;++K)ce[K].call(ee)})(h,U,this);break;case 2:(function(V,se,ee,$){if(se)V.call(ee,$);else for(var ce=V.length,K=c(V,ce),Z=0;Z<ce;++Z)K[Z].call(ee,$)})(h,U,this,arguments[1]);break;case 3:(function(V,se,ee,$,ce){if(se)V.call(ee,$,ce);else for(var K=V.length,Z=c(V,K),J=0;J<K;++J)Z[J].call(ee,$,ce)})(h,U,this,arguments[1],arguments[2]);break;case 4:(function(V,se,ee,$,ce,K){if(se)V.call(ee,$,ce,K);else for(var Z=V.length,J=c(V,Z),te=0;te<Z;++te)J[te].call(ee,$,ce,K)})(h,U,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(b-1),L=1;L<b;L++)T[L-1]=arguments[L];(function(V,se,ee,$){if(se)V.apply(ee,$);else for(var ce=V.length,K=c(V,ce),Z=0;Z<ce;++Z)K[Z].apply(ee,$)})(h,U,this,T)}return!0},s.prototype.addListener=function(p,m){return r(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return r(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,T,L,I;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(T=-1,L=h.length;0<L--;)if(h[L]===m||h[L].listener&&h[L].listener===m){I=h[L].listener,T=L;break}if(0>T)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(D,M){for(var F=M,U=F+1,V=D.length;U<V;F+=1,U+=1)D[F]=D[U];D.pop()})(h,T);b.removeListener&&this.emit("removeListener",p,I||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,T=Object.keys(h),L=0;L<T.length;++L)(b=T[L])!=="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(T){for(var L=Array(T.length),I=0;I<L.length;++I)L[I]=T[I].listener||T[I];return L}(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 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 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;++v)_.push((v+256).toString(16).substr(1));function w(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[p[m+0]]+_[p[m+1]]+_[p[m+2]]+_[p[m+3]]+"-"+_[p[m+4]]+_[p[m+5]]+"-"+_[p[m+6]]+_[p[m+7]]+"-"+_[p[m+8]]+_[p[m+9]]+"-"+_[p[m+10]]+_[p[m+11]]+_[p[m+12]]+_[p[m+13]]+_[p[m+14]]+_[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 x(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 C(p,m,h){return 8*function(b,T,L){const I=b[L],D=T?T[L]:null;return I===null||D===null?null:(I-D)/(b.timestamp-T.timestamp)*1e3}(p,m,h)}function E(p){if(!p.entries)return p;const m={};return p.forEach(function(h,b){m[b]=h}),m}function P(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 T of p.values())switch(T.type){case"outbound-rtp":{const L=T.mediaType||T.kind,I={};let D={};if(!["audio","video"].includes(L))continue;if(T.codecId){const M=p.get(T.codecId);M&&(I.clockRate=M.clockRate,I.mimeType=M.mimeType,I.payloadType=M.payloadType)}D=p.get(T.mediaSourceId)||p.get(T.trackId)||{},b[L].outbound.push({...T,...I,track:{...D}});break}case"inbound-rtp":{let L=T.mediaType||T.kind,I={};const D={};if(!["audio","video"].includes(L))if(T.id.includes("Video"))L="video";else{if(!T.id.includes("Audio"))continue;L="audio"}if(T.codecId){const M=p.get(T.codecId);M&&(D.clockRate=M.clockRate,D.mimeType=M.mimeType,D.payloadType=M.payloadType)}if(!b.connection.id&&T.transportId){const M=p.get(T.transportId);if(M&&M.selectedCandidatePairId){const F=p.get(M.selectedCandidatePairId);b.connection=x(F,p)}}I=p.get(T.mediaSourceId)||p.get(T.trackId)||{},b[L].inbound.push({...T,...D,track:{...I}});break}case"peer-connection":b.connection.dataChannelsClosed=T.dataChannelsClosed,b.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let L=T.mediaType||T.kind;const I={};if(!["audio","video"].includes(L))if(T.id.includes("Video"))L="video";else{if(!T.id.includes("Audio"))continue;L="audio"}if(T.codecId){const D=p.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}if(!b.connection.id&&T.transportId){const D=p.get(T.transportId);if(D&&D.selectedCandidatePairId){const M=p.get(D.selectedCandidatePairId);b.connection=x(M,p)}}b.remote[L].inbound.push({...T,...I});break}case"remote-outbound-rtp":{if(!h.remote)break;const L=T.mediaType||T.kind,I={};if(!["audio","video"].includes(L))continue;if(T.codecId){const D=p.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}b.remote[L].outbound.push({...T,...I});break}}if(!b.connection.id)for(const T of p.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(b.connection=x(T,p));return b=function(T,L){return L&&(T.audio.inbound.map(I=>{let D=L.audio.inbound.find(M=>M.id===I.id);I.bitrate=C(I,D,"bytesReceived"),I.packetRate=C(I,D,"packetsReceived")}),T.audio.outbound.map(I=>{let D=L.audio.outbound.find(M=>M.id===I.id);I.bitrate=C(I,D,"bytesSent"),I.packetRate=C(I,D,"packetsSent")}),T.video.inbound.map(I=>{let D=L.video.inbound.find(M=>M.id===I.id);I.bitrate=C(I,D,"bytesReceived"),I.packetRate=C(I,D,"packetsReceived")}),T.video.outbound.map(I=>{let D=L.video.outbound.find(M=>M.id===I.id);I.bitrate=C(I,D,"bytesSent"),I.packetRate=C(I,D,"packetsSent")})),T}(b,m),b}let O,S={},k=[];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:T}=p;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!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 I in this.peersToMonitor[h]){const D=this.peersToMonitor[h][I];if(D.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);D.pc.connectionState==="closed"&&this.removeConnection({pc:D.pc})}}const L=m.getConfiguration();return L.iceServers&&L.iceServers.forEach(function(I){delete I.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:L}}),this.monitorPeer({peerId:h,connectionId:b,pc:m,remote:T}),{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 T in this.peersToMonitor)h in this.peersToMonitor[T]&&(b=this.peersToMonitor[T][h].pc,m=T)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let L in this.peersToMonitor[T])this.peersToMonitor[T][L].pc===b&&(h=L,m=T)}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(),k.forEach(p=>{this.removeTrackEventListeners(p)}),k=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(p){let{peerId:m,connectionId:h,pc:b,remote:T}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const L={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};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]=L}else this.peersToMonitor[m]={[h]:L};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 T in m[b]){const L=m[b][T],I=L.pc;if(I&&!this.checkIfConnectionIsClosed(b,T,I))try{const D=this.getTimestamp(),M=I.getStats(null);if(M){const F=await M,U=this.getTimestamp(),V=E(F),se={remote:L.options.remote},ee=P(F,L.stats.parsed,se),$={event:"stats",tag:"stats",peerId:b,connectionId:T,timeTaken:U-D,data:ee};this.rawStats===!0&&($.rawStats=F),this.statsObject===!0&&($.statsObject=V),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(V)),h.push($),L.stats.parsed=ee}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(D){this.logger.error(D)}}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 T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,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."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),O.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 T=b.track,L=b.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=L),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:L?this.getStreamDetails(L):null,track:T?this.getMediaTrackDetails(T):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(I){return"stream:"+I.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),k.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)}}}});(Zi=_u)&&Zi.__esModule&&Object.prototype.hasOwnProperty.call(Zi,"default")&&Zi.default;var Gy=_u.WebRTCStats;function Hy(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 Wy(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 zy extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class qy extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class Ky extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function bu(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 Xy(t,e){const n=vn();let i=!1;const s=new Gy({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>j(this,void 0,void 0,function*(){r.event==="stats"&&Y(B.StatsFrame,function({data:a}){var l,c,d,u,f,g,_,v;const{audio:w,remote:y}=a,{audio:x}=y,C=(c=(l=x.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,E=(u=(d=x.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&u!==void 0?u:1/0,P=(g=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&g!==void 0?g:-1,O=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,S=Hy({jitter:1e3*C,rtt:1e3*E,packetsLost:O,packetsReceived:P});return{jitter:C,rtt:E,mos:S,quality:Wy(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:x.inbound[0],remoteOutboundAudio:x.outbound[0]}}(r),t.uuid),yield t.execute(new Ky(n,r))});return{get isRunning(){return i},start:(r,a,l)=>j(this,void 0,void 0,function*(){i?R.debug(`[${e}] Stats reporter already running, skipping start`):(yield t.execute(new zy(n,e)),s.on("timeline",o),yield new Promise(c=>setTimeout(c,500)),s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0)}),stop:r=>j(this,void 0,void 0,function*(){if(!i)return void R.debug(`[${e}] Stats reporter already stopped, skipping stop`);const a=s.getTimeline();Y(B.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 qy(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 wu=(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:Yy(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:He.LayerInfo},a);Y(B.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:He.LayoutInfo},a);Y(B.Notification,l,t.uuid);break}}},Yy=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Zd(e)};class Su{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=()=>j(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(R.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${r}`),r==="failed"||r==="disconnected"){const a=()=>j(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,d){return j(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 g=f[0].sender,_=g==null?void 0:g.transport;_&&(u.dtlsState=_.state)}c.sctp&&(u.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(u.candidatePairState=_.state,g.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(g){R.error("Error gathering connection state details:",g)}return u})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}r==="failed"&&Y(B.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=()=>{R.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{R.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},R.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===Ae.Offer}get isAnswer(){return this.type===Ae.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get 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 j(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){R.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{R.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),R.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=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(R.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":Y(B.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(R.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){R.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?R.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&ni(i,this.options.remoteStream)}createPeerConnection(){return j(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ae.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(B.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&bn(this.options.localStream)&&(R.info("Muting local audio tracks on start"),to(this.options.localStream)),performance.mark("peer-creation-end")})}init(){var e;return j(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=Xy(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(bn(i)){const o=i.getAudioTracks();let r=[...o];if(R.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{R.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],R.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(d=>{R.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=(c=>{const d=[],u=[];return c&&c.length!==0?(c.forEach(f=>{const g=f.mimeType.toLocaleLowerCase();g.startsWith("audio/")?d.push(f):g.startsWith("video/")&&u.push(f)}),{audioCodecs:d,videoCodecs:u}):{audioCodecs:d,videoCodecs:u}})(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&&ni(n,i)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);R.info("Add transceiver",e,n)}}_createOffer(){return j(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1,this._constraints.offerToReceiveVideo=!!this.options.video,R.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){R.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return j(this,void 0,void 0,function*(){R.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return j(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return R.debug("Skipping negotiation, state:",this.instance.signalingState),R.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ae.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){R.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return j(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){yn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return j(this,void 0,void 0,function*(){if(bn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,j(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield Yi(s,a,ht.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield Yi(r,l,ht.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Xi(e)})}_isOffer(){return this.type===Ae.Offer}_isAnswer(){return this.type===Ae.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return R.info("RTC config",s),s}restartStatsReporter(){return j(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?R.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(R.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):R.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return j(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 no=Yr;class xu{constructor(e,n,i=!1){this.session=e,this._isRecovering=i,this.id="",this.state=q[q.New],this.prevState="",this.channels=[],this.role=Kr.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._checkConferenceSerno=y=>{const x=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return x&&y>=0&&(this._lastSerno=y),x},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(x=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const E in C.constraints)if(C.constraints.hasOwnProperty(E)&&C.constraints[E]!==x[E])return}C.callback(x)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:d,remoteElement:u,options:f,mediaConstraints:{audio:g,video:_},ringtoneFile:v,ringbackFile:w}=e;this.options=Object.assign({},Sy,{audio:g,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=gu(this.options.ringtoneFile,"_ringtone"),this._ringback=gu(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!jy(this.options.localStream)}invite(){return j(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=Rt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new Su(Ae.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 j(this,void 0,void 0,function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=Rt.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 Su(Ae.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(){vu(this._ringtone)}stopRingtone(){yu(this._ringtone)}playRingback(){vu(this._ringback)}stopRingback(){yu(this._ringback)}hangup(e,n){var i,s,o;const r=e||{},a=n!==!1;if(this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],r.isRecovering)return this._isRecovering=!0,this.setState(q.Recovering),void this._finalize();this.setState(q.Hangup);const l=()=>{var c;R.debug(`[${this.id}] Closing peer from hangup`),(c=this.peer)===null||c===void 0||c.close(),this.setState(q.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const c=new Py({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(c).catch(d=>{R.error("telnyx_rtc.bye failed!",d),Y(B.Error,{error:d,sessionId:this.session.sessionid},this.session.uuid)}).then(l.bind(this))}else l()}hold(){const e=new Jr({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Jr({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Jr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new uu({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 uu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){to(this.options.localStream)}unmuteAudio(){pu(this.options.localStream)}toggleAudioMute(){mu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return j(this,void 0,void 0,function*(){const{instance:i}=this.peer,s=i.getSenders().find(({track:{kind:o}})=>o==="audio");if(s){const o=yield Ki({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,wn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,wn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,wn(e,"video",null)}setVideoDevice(e){return j(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield Ki({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ni(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){to(this.options.remoteStream)}undeaf(){pu(this.options.remoteStream)}toggleDeaf(){mu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return j(this,void 0,void 0,function*(){if(!this||!this.peer)return void R.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,s=i.getSenders();if(!s)return void R.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===n);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),R.info("Parameters: ",r),R.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{R.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>R.error(a))}else R.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=q[this._state].toLowerCase(),this.prevState=q[this._prevState].toLowerCase(),R.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case q.Purge:R.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case q.Active:this._isRecovering&&(this._isRecovering=!1,R.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&hu(n,i)},0);break;case q.Destroy:this._finalize()}}handleMessage(e){var n,i,s,o;const{method:r,params:a}=e;switch(r){case ne.Answer:if(this.gotAnswer=!0,this._state>=q.Active)return;this._state>=q.Early&&this.setState(q.Active),this.gotEarly||this._onRemoteSdp(a.sdp),this.stopRingback(),this.stopRingtone();break;case ne.Media:if(this._state>=q.Early)return;this.gotEarly=!0,this._onRemoteSdp(a.sdp);break;case ne.Attach:if(!((n=this.peer)===null||n===void 0)&&n.isConnectionHealthy()){const c=(s=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||s===void 0?void 0:s.localDescription,d=new Zr({sessid:this.session.sessionid,sdp:c,dialogParams:this.options,"User-Agent":`Web-${no}`});return this.session.execute(d),void((o=this.peer)===null||o===void 0||o.restartStatsReporter())}break;case ne.Display:{const{display_name:c,display_number:d,display_direction:u}=a;this.extension=d;const f=u===Rt.Inbound?Rt.Outbound:Rt.Inbound,g={type:Je[r],call:this,displayName:c,displayNumber:d,displayDirection:f};Y(B.Notification,g,this.id)||Y(B.Notification,g,this.session.uuid);break}case ne.Candidate:this._addIceCandidate(a);break;case ne.Info:case ne.Event:{const c=Object.assign(Object.assign({},a),{type:Je.generic,call:this});Y(B.Notification,c,this.id)||Y(B.Notification,c,this.session.uuid);break}case ne.Ringing:this.playRingback(),a.telnyx_call_control_id&&(this.options.telnyxCallControlId=a.telnyx_call_control_id),a.telnyx_session_id&&(this.options.telnyxSessionId=a.telnyx_session_id),a.telnyx_leg_id&&(this.options.telnyxLegId=a.telnyx_leg_id);break;case ne.Bye:const l=a.client_state||a.clientState;l&&(this.options.clientState=l),this.stopRingback(),this.stopRingtone(),this.hangup(a,!1)}}handleConferenceUpdate(e,n){return j(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return R.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel: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 g=[];for(const _ in s)g.push(Object.assign({callId:s[_][0],index:Number(_)},Wi(s[_][1])));this._dispatchConferenceUpdate({action:He.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:He.Add,callId:o,index:r},Wi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:He.Modify,callId:o,index:r},Wi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:He.Delete,callId:o,index:r},Wi(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 j(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=>{R.error("ConfChat subscription error:",s)});Qr(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,wu(this.session,o)):R.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{R.error("ConfInfo subscription error:",s)});Qr(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){return R.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return j(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ae.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(q.Early),this.gotAnswer&&this.setState(q.Active)}).catch(i=>{R.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){yn(this.peer.onSdpReadyTwice)?Y(B.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return R.info(`No candidate - retry
111
- `),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${no}`};switch(o){case Ae.Offer:this.setState(q.Requesting),r=new lu(a);break;case Ae.Answer:this._isRecovering||this.setState(q.Answering),r=this.options.attach===!0?new Zr(a):new cu(a);break;default:return R.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Ae.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>{R.error(`${this.id} - Sending ${o} error:`,l),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return R.error("No SDP data provided"),this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const o={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${no}`};switch(i){case Ae.Offer:this.setState(q.Requesting),s=new lu(o);break;case Ae.Answer:this._isRecovering||this.setState(q.Answering),s=this.options.attach===!0?new Zr(o):new cu(o);break;default:return R.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Ae.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(r=>{R.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?R.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(R.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new du({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return R.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{R.debug("Successfully added ICE candidate:",e)}).catch(i=>{R.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Ly({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.onicecandidateerror=n=>{var i;if(R.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=bu(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&&ni(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{R.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&R.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(R.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=bu(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&&ni(i,s)})}_onMediaError(e){this._dispatchNotification({type:Je.userMediaError,error:e}),R.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),R.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),R.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&&(Y(B.Notification,e,this.id,!1)||Y(B.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():vn(),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,Pt(B.MediaError,this._onMediaError,this.id),Pt(B.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Pt(B.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),yn(s)&&Pt(B.Notification,s.bind(this),this.id),this._isRecovering?this.setState(q.Recovering):this.setState(q.New),R.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),R.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;ii(n),ii(i),Lt(B.MediaError,null,this.id),Lt(B.PeerConnectionFailureError,null,this.id),Lt(B.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),R.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),R.debug("Stats stopped")}}xu.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 zt extends xu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new $y(e,n))}hangup(e={},n=!0){this.screenShare instanceof zt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return j(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(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 zt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof zt&&this.screenShare.hangup()}setAudioOutDevice(e){return j(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&hu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);R.setLevel(2),this._statsInterval=window.setInterval(()=>j(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
110
+ `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(yn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),Y(B.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else L.warn("Unknown message from socket",e)}}class ti{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:vn()},e)}}const su={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 De extends ti{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Gi(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in su)i&&n.hasOwnProperty(i)&&(n[su[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class ru extends De{constructor(e){super(),this.method=ie.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ey{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>j(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(zr(n))}),this.getIsRegistered=()=>j(this,void 0,void 0,function*(){const n=new ru(Qn());this.pendingRequestId=n.request.id,this.gatewayStateTask=eu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Fe.REGISTER,Fe.REGED].includes(i)}),this.session=e,this.gatewayStateTask=eu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ou extends De{constructor(e){super(),this.method=ie.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var au="2.25.17",Yr=au;class Iy extends De{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:Yr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Ry extends De{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class lu extends De{toString(){return ie.Invite}}class cu extends De{toString(){return ie.Answer}}class Zr extends De{toString(){return ie.Attach}}class Py extends De{toString(){return ie.Bye}}class du extends De{toString(){return ie.Candidate}}class Ly extends De{toString(){return ie.EndOfCandidates}}class Jr extends De{toString(){return ie.Modify}}class uu extends De{toString(){return ie.Info}}class My extends De{toString(){return ie.Broadcast}}class Dy extends De{toString(){return ie.Subscribe}}class Oy extends De{toString(){return ie.Unsubscribe}}class Ny extends De{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,l={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Yr,data:navigator.userAgent}};r&&(l.sessid=r),s&&(l.target_version_id=s),this.buildRequest({method:this.method,params:l})}}class Fy{constructor(e){if(this.options=e,this.uuid=vn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");L.setLevel(e.debug?"debug":"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 iu(this),this.registerAgent=new Ey(this)}get __logger(){return L}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return j(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Qd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return qi(this.options)||Jn(this.options)}broadcast(e){}disconnect(){return j(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),L.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 Lt(e,n,this.uuid),this}connect(){return j(this,void 0,void 0,function*(){this.connection||(this.connection=new iu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||this.connection.connect(),L.debug("Session connected. Connection initiated if not already alive. Auto-reconnect enabled.")})}_handleLoginError(e){Y(B.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return j(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)),qi(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(Jn(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";return L.error(s),void Y(B.Error,{error:new Error(s),type:wy.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return j(this,void 0,void 0,function*(){let s;s=e==="login"?new Iy(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Qn()):new Ny({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,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Qn()});const o=yield this.execute(s).catch(r=>{this._handleLoginError(r),i&&i(r)});o&&(this.sessionid=o.sessid,n&&n())})}_onSocketOpen(){return j(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Xr(this.relayProtocol);for(const e in this.subscriptions)Xr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Lt(e,null,n)):(delete this.subscriptions[e],Xr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},yn(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(B.SocketOpen,this._onSocketOpen),this.on(B.SocketClose,this.onNetworkClose),this.on(B.SocketError,this.onNetworkClose),this.on(B.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(B.SocketOpen,this._onSocketOpen),this.off(B.SocketClose,this.onNetworkClose),this.off(B.SocketError,this.onNetworkClose),this.off(B.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&&(L.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new ou(Qn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){L.debug("Ping received"),this._pong=!0}static on(e,n){Pt(e,n)}static off(e){Lt(e)}static uuid(){return vn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Ki=t=>navigator.mediaDevices.getUserMedia(t),bn=t=>t&&t instanceof MediaStream,ni=(t,e)=>{const n=zi(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},hu=(t,e)=>j(void 0,void 0,void 0,function*(){const n=zi(t);if(n===null)return L.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return L.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Vy=t=>{t&&t.readyState==="live"&&t.stop()},ii=t=>{bn(t)&&t.getTracks().forEach(Vy),t=null},Xi=t=>j(void 0,void 0,void 0,function*(){L.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Ki(t)}catch(i){if(L.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=Gi(r,["deviceId"]);c=Object.keys(u).length===0||u}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const u=Gi(a,["deviceId"]);d=Object.keys(u).length===0||u}return l?{audio:c,video:d}:null})(t);if(s){L.warn("Device not found or not readable, falling back to default device");try{return yield Ki(s)}catch(o){throw L.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),si=(t=null,e=!1)=>j(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===ht.AudioIn||s===ht.AudioOut,video:!s||s===ht.Video}))(t)).catch(s=>(L.error(s),null));if(i){if(ii(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}),fu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Yi=(t,e,n)=>j(void 0,void 0,void 0,function*(){const i=yield si(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}),By=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Qr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=eo(t);return n.includes(e)||i.includes(e)},eo=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},wn=(t,e=null,n=null)=>{if(!bn(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}})},pu=t=>{wn(t,"audio",!0)},to=t=>{wn(t,"audio",!1)},mu=t=>{wn(t,"audio",null)},jy=t=>((e,n=null)=>{if(!bn(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 Uy(){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:!!Xi}}catch(t){return t.message}}var ye;function gu(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 vu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{L.error("playAudio",e),t._playFulfilled=!0}))}function yu(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"})(ye||(ye={}));class $y extends ti{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:vn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}var Zi,_u=Yd(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,m,h,b){var T,R,I;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((R=p._events)?(R.newListener&&(p.emit("newListener",m,h.listener?h.listener:h),R=p._events),I=R[m]):(R=p._events=new i,p._eventsCount=0),I){if(typeof I=="function"?I=R[m]=b?[h,I]:[I,h]:b?I.unshift(h):I.push(h),!I.warned&&(T=o(p))&&0<T&&I.length>T){I.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+I.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");D.name="MaxListenersExceededWarning",D.emitter=p,D.type=m,D.count=I.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(D)}}else I=R[m]=h,++p._eventsCount;return p}function a(p,m,h){function b(){p.removeListener(m,b),T||(T=!0,h.apply(p,arguments))}var T=!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 o(this)},s.prototype.emit=function(p){var m,h,b,T,R,I,D,M=p==="error";if(I=this._events)M=M&&I.error==null;else if(!M)return!1;if(D=this.domain,M){if(m=arguments[1],!D){if(m instanceof Error)throw m;var V=new Error('Uncaught, unspecified "error" event. ('+m+")");throw V.context=m,V}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=D,m.domainThrown=!1,D.emit("error",m),!1}if(!(h=I[p]))return!1;var q=typeof h=="function";switch(b=arguments.length){case 1:(function(N,ne,Z){if(ne)N.call(Z);else for(var U=N.length,ce=c(N,U),K=0;K<U;++K)ce[K].call(Z)})(h,q,this);break;case 2:(function(N,ne,Z,U){if(ne)N.call(Z,U);else for(var ce=N.length,K=c(N,ce),Q=0;Q<ce;++Q)K[Q].call(Z,U)})(h,q,this,arguments[1]);break;case 3:(function(N,ne,Z,U,ce){if(ne)N.call(Z,U,ce);else for(var K=N.length,Q=c(N,K),ee=0;ee<K;++ee)Q[ee].call(Z,U,ce)})(h,q,this,arguments[1],arguments[2]);break;case 4:(function(N,ne,Z,U,ce,K){if(ne)N.call(Z,U,ce,K);else for(var Q=N.length,ee=c(N,Q),te=0;te<Q;++te)ee[te].call(Z,U,ce,K)})(h,q,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(b-1),R=1;R<b;R++)T[R-1]=arguments[R];(function(N,ne,Z,U){if(ne)N.apply(Z,U);else for(var ce=N.length,K=c(N,ce),Q=0;Q<ce;++Q)K[Q].apply(Z,U)})(h,q,this,T)}return!0},s.prototype.addListener=function(p,m){return r(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return r(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,T,R,I;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(T=-1,R=h.length;0<R--;)if(h[R]===m||h[R].listener&&h[R].listener===m){I=h[R].listener,T=R;break}if(0>T)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(D,M){for(var V=M,q=V+1,N=D.length;q<N;V+=1,q+=1)D[V]=D[q];D.pop()})(h,T);b.removeListener&&this.emit("removeListener",p,I||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,T=Object.keys(h),R=0;R<T.length;++R)(b=T[R])!=="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(T){for(var R=Array(T.length),I=0;I<R.length;++I)R[I]=T[I].listener||T[I];return R}(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 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 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;++v)_.push((v+256).toString(16).substr(1));function w(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[p[m+0]]+_[p[m+1]]+_[p[m+2]]+_[p[m+3]]+"-"+_[p[m+4]]+_[p[m+5]]+"-"+_[p[m+6]]+_[p[m+7]]+"-"+_[p[m+8]]+_[p[m+9]]+"-"+_[p[m+10]]+_[p[m+11]]+_[p[m+12]]+_[p[m+13]]+_[p[m+14]]+_[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 x(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 k(p,m,h){return 8*function(b,T,R){const I=b[R],D=T?T[R]:null;return I===null||D===null?null:(I-D)/(b.timestamp-T.timestamp)*1e3}(p,m,h)}function A(p){if(!p.entries)return p;const m={};return p.forEach(function(h,b){m[b]=h}),m}function P(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 T of p.values())switch(T.type){case"outbound-rtp":{const R=T.mediaType||T.kind,I={};let D={};if(!["audio","video"].includes(R))continue;if(T.codecId){const M=p.get(T.codecId);M&&(I.clockRate=M.clockRate,I.mimeType=M.mimeType,I.payloadType=M.payloadType)}D=p.get(T.mediaSourceId)||p.get(T.trackId)||{},b[R].outbound.push({...T,...I,track:{...D}});break}case"inbound-rtp":{let R=T.mediaType||T.kind,I={};const D={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const M=p.get(T.codecId);M&&(D.clockRate=M.clockRate,D.mimeType=M.mimeType,D.payloadType=M.payloadType)}if(!b.connection.id&&T.transportId){const M=p.get(T.transportId);if(M&&M.selectedCandidatePairId){const V=p.get(M.selectedCandidatePairId);b.connection=x(V,p)}}I=p.get(T.mediaSourceId)||p.get(T.trackId)||{},b[R].inbound.push({...T,...D,track:{...I}});break}case"peer-connection":b.connection.dataChannelsClosed=T.dataChannelsClosed,b.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let R=T.mediaType||T.kind;const I={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const D=p.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}if(!b.connection.id&&T.transportId){const D=p.get(T.transportId);if(D&&D.selectedCandidatePairId){const M=p.get(D.selectedCandidatePairId);b.connection=x(M,p)}}b.remote[R].inbound.push({...T,...I});break}case"remote-outbound-rtp":{if(!h.remote)break;const R=T.mediaType||T.kind,I={};if(!["audio","video"].includes(R))continue;if(T.codecId){const D=p.get(T.codecId);D&&(I.clockRate=D.clockRate,I.mimeType=D.mimeType,I.payloadType=D.payloadType)}b.remote[R].outbound.push({...T,...I});break}}if(!b.connection.id)for(const T of p.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(b.connection=x(T,p));return b=function(T,R){return R&&(T.audio.inbound.map(I=>{let D=R.audio.inbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesReceived"),I.packetRate=k(I,D,"packetsReceived")}),T.audio.outbound.map(I=>{let D=R.audio.outbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesSent"),I.packetRate=k(I,D,"packetsSent")}),T.video.inbound.map(I=>{let D=R.video.inbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesReceived"),I.packetRate=k(I,D,"packetsReceived")}),T.video.outbound.map(I=>{let D=R.video.outbound.find(M=>M.id===I.id);I.bitrate=k(I,D,"bytesSent"),I.packetRate=k(I,D,"packetsSent")})),T}(b,m),b}let O,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:T}=p;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!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 I in this.peersToMonitor[h]){const D=this.peersToMonitor[h][I];if(D.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);D.pc.connectionState==="closed"&&this.removeConnection({pc:D.pc})}}const R=m.getConfiguration();return R.iceServers&&R.iceServers.forEach(function(I){delete I.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:R}}),this.monitorPeer({peerId:h,connectionId:b,pc:m,remote:T}),{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 T in this.peersToMonitor)h in this.peersToMonitor[T]&&(b=this.peersToMonitor[T][h].pc,m=T)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let R in this.peersToMonitor[T])this.peersToMonitor[T][R].pc===b&&(h=R,m=T)}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&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(p){let{peerId:m,connectionId:h,pc:b,remote:T}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const R={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};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]=R}else this.peersToMonitor[m]={[h]:R};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 T in m[b]){const R=m[b][T],I=R.pc;if(I&&!this.checkIfConnectionIsClosed(b,T,I))try{const D=this.getTimestamp(),M=I.getStats(null);if(M){const V=await M,q=this.getTimestamp(),N=A(V),ne={remote:R.options.remote},Z=P(V,R.stats.parsed,ne),U={event:"stats",tag:"stats",peerId:b,connectionId:T,timeTaken:q-D,data:Z};this.rawStats===!0&&(U.rawStats=V),this.statsObject===!0&&(U.statsObject=N),this.filteredStats===!0&&(U.filteredStats=this.filteroutStats(N)),h.push(U),R.stats.parsed=Z}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(D){this.logger.error(D)}}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 T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,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."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),O.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 T=b.track,R=b.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=R),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:R?this.getStreamDetails(R):null,track:T?this.getMediaTrackDetails(T):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(I){return"stream:"+I.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)}}}});(Zi=_u)&&Zi.__esModule&&Object.prototype.hasOwnProperty.call(Zi,"default")&&Zi.default;var Gy=_u.WebRTCStats;function Hy(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 Wy(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 zy extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class qy extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class Ky extends ti{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function bu(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 Xy(t,e){const n=vn();let i=!1;const s=new Gy({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>j(this,void 0,void 0,function*(){r.event==="stats"&&Y(B.StatsFrame,function({data:a}){var l,c,d,u,f,g,_,v;const{audio:w,remote:y}=a,{audio:x}=y,k=(c=(l=x.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(u=(d=x.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&u!==void 0?u:1/0,P=(g=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&g!==void 0?g:-1,O=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,S=Hy({jitter:1e3*k,rtt:1e3*A,packetsLost:O,packetsReceived:P});return{jitter:k,rtt:A,mos:S,quality:Wy(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:x.inbound[0],remoteOutboundAudio:x.outbound[0]}}(r),t.uuid),yield t.execute(new Ky(n,r))});return{get isRunning(){return i},start:(r,a,l)=>j(this,void 0,void 0,function*(){i?L.debug(`[${e}] Stats reporter already running, skipping start`):(yield t.execute(new zy(n,e)),s.on("timeline",o),yield new Promise(c=>setTimeout(c,500)),s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0)}),stop:r=>j(this,void 0,void 0,function*(){if(!i)return void L.debug(`[${e}] Stats reporter already stopped, skipping stop`);const a=s.getTimeline();Y(B.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 qy(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 wu=(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:Yy(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:He.LayerInfo},a);Y(B.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:He.LayoutInfo},a);Y(B.Notification,l,t.uuid);break}}},Yy=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Zd(e)};class Su{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=()=>j(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(L.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${r}`),r==="failed"||r==="disconnected"){const a=()=>j(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,d){return j(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 g=f[0].sender,_=g==null?void 0:g.transport;_&&(u.dtlsState=_.state)}c.sctp&&(u.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(u.candidatePairState=_.state,g.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(g){L.error("Error gathering connection state details:",g)}return u})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}r==="failed"&&Y(B.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=()=>{L.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{L.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},L.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===Ee.Offer}get isAnswer(){return this.type===Ee.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get 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 j(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){L.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{L.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),L.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=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(L.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":Y(B.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(L.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){L.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?L.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&&ni(i,this.options.remoteStream)}createPeerConnection(){return j(this,void 0,void 0,function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ee.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(B.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&bn(this.options.localStream)&&(L.info("Muting local audio tracks on start"),to(this.options.localStream)),performance.mark("peer-creation-end")})}init(){var e;return j(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=Xy(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(bn(i)){const o=i.getAudioTracks();let r=[...o];if(L.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{L.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],L.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(d=>{L.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=(c=>{const d=[],u=[];return c&&c.length!==0?(c.forEach(f=>{const g=f.mimeType.toLocaleLowerCase();g.startsWith("audio/")?d.push(f):g.startsWith("video/")&&u.push(f)}),{audioCodecs:d,videoCodecs:u}):{audioCodecs:d,videoCodecs:u}})(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&&ni(n,i)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);L.info("Add transceiver",e,n)}}_createOffer(){return j(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1,this._constraints.offerToReceiveVideo=!!this.options.video,L.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){L.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return j(this,void 0,void 0,function*(){L.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return j(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return L.debug("Skipping negotiation, state:",this.instance.signalingState),L.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:Ee.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){L.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return j(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){yn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return j(this,void 0,void 0,function*(){if(bn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,j(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield Yi(s,a,ht.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield Yi(r,l,ht.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Xi(e)})}_isOffer(){return this.type===Ee.Offer}_isAnswer(){return this.type===Ee.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return L.info("RTC config",s),s}restartStatsReporter(){return j(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?L.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(L.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):L.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return j(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 no=Yr;class xu{constructor(e,n,i=!1){this.session=e,this._isRecovering=i,this.id="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Kr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=y=>{const x=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return x&&y>=0&&(this._lastSerno=y),x},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(x=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(const A in k.constraints)if(k.constraints.hasOwnProperty(A)&&k.constraints[A]!==x[A])return}k.callback(x)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:d,remoteElement:u,options:f,mediaConstraints:{audio:g,video:_},ringtoneFile:v,ringbackFile:w}=e;this.options=Object.assign({},Sy,{audio:g,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=gu(this.options.ringtoneFile,"_ringtone"),this._ringback=gu(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!jy(this.options.localStream)}invite(){return j(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=Rt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new Su(Ee.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 j(this,void 0,void 0,function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=Rt.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 Su(Ee.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(){vu(this._ringtone)}stopRingtone(){yu(this._ringtone)}playRingback(){vu(this._ringback)}stopRingback(){yu(this._ringback)}hangup(e,n){var i,s,o;const r=e||{},a=n!==!1;if(this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],r.isRecovering)return this._isRecovering=!0,this.setState(z.Recovering),void this._finalize();this.setState(z.Hangup);const l=()=>{var c;L.debug(`[${this.id}] Closing peer from hangup`),(c=this.peer)===null||c===void 0||c.close(),this.setState(z.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const c=new Py({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(c).catch(d=>{L.error("telnyx_rtc.bye failed!",d),Y(B.Error,{error:d,sessionId:this.session.sessionid},this.session.uuid)}).then(l.bind(this))}else l()}hold(){const e=new Jr({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Jr({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Jr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new uu({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 uu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){to(this.options.localStream)}unmuteAudio(){pu(this.options.localStream)}toggleAudioMute(){mu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return j(this,void 0,void 0,function*(){const{instance:i}=this.peer,s=i.getSenders().find(({track:{kind:o}})=>o==="audio");if(s){const o=yield Ki({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,wn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,wn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,wn(e,"video",null)}setVideoDevice(e){return j(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield Ki({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ni(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){to(this.options.remoteStream)}undeaf(){pu(this.options.remoteStream)}toggleDeaf(){mu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return j(this,void 0,void 0,function*(){if(!this||!this.peer)return void L.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 L.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"}]),L.info("Parameters: ",r),L.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{L.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>L.error(a))}else L.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),L.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case z.Purge:L.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case z.Active:this._isRecovering&&(this._isRecovering=!1,L.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&hu(n,i)},0);break;case z.Destroy:this._finalize()}}handleMessage(e){var n,i,s,o;const{method:r,params:a}=e;switch(r){case ie.Answer:if(this.gotAnswer=!0,this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(a.sdp),this.stopRingback(),this.stopRingtone();break;case ie.Media:if(this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(a.sdp);break;case ie.Attach:if(!((n=this.peer)===null||n===void 0)&&n.isConnectionHealthy()){const c=(s=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||s===void 0?void 0:s.localDescription,d=new Zr({sessid:this.session.sessionid,sdp:c,dialogParams:this.options,"User-Agent":`Web-${no}`});return this.session.execute(d),void((o=this.peer)===null||o===void 0||o.restartStatsReporter())}break;case ie.Display:{const{display_name:c,display_number:d,display_direction:u}=a;this.extension=d;const f=u===Rt.Inbound?Rt.Outbound:Rt.Inbound,g={type:Je[r],call:this,displayName:c,displayNumber:d,displayDirection:f};Y(B.Notification,g,this.id)||Y(B.Notification,g,this.session.uuid);break}case ie.Candidate:this._addIceCandidate(a);break;case ie.Info:case ie.Event:{const c=Object.assign(Object.assign({},a),{type:Je.generic,call:this});Y(B.Notification,c,this.id)||Y(B.Notification,c,this.session.uuid);break}case ie.Ringing:this.playRingback(),a.telnyx_call_control_id&&(this.options.telnyxCallControlId=a.telnyx_call_control_id),a.telnyx_session_id&&(this.options.telnyxSessionId=a.telnyx_session_id),a.telnyx_leg_id&&(this.options.telnyxLegId=a.telnyx_leg_id);break;case ie.Bye:const l=a.client_state||a.clientState;l&&(this.options.clientState=l),this.stopRingback(),this.stopRingtone(),this.hangup(a,!1)}}handleConferenceUpdate(e,n){return j(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return L.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 g=[];for(const _ in s)g.push(Object.assign({callId:s[_][0],index:Number(_)},Wi(s[_][1])));this._dispatchConferenceUpdate({action:He.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:He.Add,callId:o,index:r},Wi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:He.Modify,callId:o,index:r},Wi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:He.Delete,callId:o,index:r},Wi(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 j(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=>{L.error("ConfChat subscription error:",s)});Qr(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,wu(this.session,o)):L.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{L.error("ConfInfo subscription error:",s)});Qr(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){return L.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return j(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ee.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(i=>{L.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){yn(this.peer.onSdpReadyTwice)?Y(B.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 L.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-${no}`};switch(o){case Ee.Offer:this.setState(z.Requesting),r=new lu(a);break;case Ee.Answer:this._isRecovering||this.setState(z.Answering),r=this.options.attach===!0?new Zr(a):new cu(a);break;default:return L.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===Ee.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(l=>{L.error(`${this.id} - Sending ${o} error:`,l),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return L.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-${no}`};switch(i){case Ee.Offer:this.setState(z.Requesting),s=new lu(o);break;case Ee.Answer:this._isRecovering||this.setState(z.Answering),s=this.options.attach===!0?new Zr(o):new cu(o);break;default:return L.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Ee.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(r=>{L.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?L.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(L.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new du({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 L.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(()=>{L.debug("Successfully added ICE candidate:",e)}).catch(i=>{L.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Ly({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(L.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=bu(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&&ni(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{L.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&L.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(L.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=bu(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&&ni(i,s)})}_onMediaError(e){this._dispatchNotification({type:Je.userMediaError,error:e}),L.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),L.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),L.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&&(Y(B.Notification,e,this.id,!1)||Y(B.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():vn(),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,Pt(B.MediaError,this._onMediaError,this.id),Pt(B.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Pt(B.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),yn(s)&&Pt(B.Notification,s.bind(this),this.id),this._isRecovering?this.setState(z.Recovering):this.setState(z.New),L.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),L.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;ii(n),ii(i),Lt(B.MediaError,null,this.id),Lt(B.PeerConnectionFailureError,null,this.id),Lt(B.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),L.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),L.debug("Stats stopped")}}xu.setStateTelnyx=t=>{if(t){switch(t._state){case z.Recovering:t.state="recovering";break;case z.Requesting:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class zt extends xu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new $y(e,n))}hangup(e={},n=!0){this.screenShare instanceof zt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return j(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(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 zt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof zt&&this.screenShare.hangup()}setAudioOutDevice(e){return j(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&hu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);L.setLevel(2),this._statsInterval=window.setInterval(()=>j(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
112
112
  ${r.type}
113
113
  `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
114
- `)}))}),R.info(i)}),2e3)}}class Zy extends Fy{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 j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield Xi({audio:e,video:n});return ii(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(q.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(nu(B.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 si().catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getVideoDevices(){return si(ht.Video).catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getAudioInDevices(){return si(ht.AudioIn).catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return si(ht.AudioOut).catch(e=>(R.error("getAudioOutDevices",e),Y(B.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Yi(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield Xi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<fu.length;r++){const[a,l]=fu[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 ii(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return j(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Gi(e,["micId","micLabel"]);return By(s),this._audioConstraints=yield((o,r,a,l)=>j(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Yi(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?my:py}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=zi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=zi(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 My({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Dy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=eo(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 j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new Oy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=eo(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(R.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,R.debug(`Network connectivity lost for session ${this.sessionid}`)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return zt.setStateTelnyx(e)}}class Cu{constructor(e,n){this.code=n,this.message=e}}class xe{constructor(e){this.session=e}_ack(e,n){const i=new Ry(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Qd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,l=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,u=i.calls[l],f=(n=u==null?void 0:u.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);const g=(w=!1)=>{var y,x,C,E,P,O;const S={audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:o===ne.Attach,mediaSettings:r.mediaSettings,debug:(y=i.options.debug)!==null&&y!==void 0&&y,debugOutput:(x=i.options.debugOutput)!==null&&x!==void 0?x:"socket",trickleIce:(C=i.options.trickleIce)!==null&&C!==void 0&&C,prefetchIceCandidates:(E=i.options.prefetchIceCandidates)!==null&&E!==void 0&&E,forceRelayCandidate:(P=i.options.forceRelayCandidate)!==null&&P!==void 0&&P,keepConnectionAliveOnSocketClose:(O=i.options.keepConnectionAliveOnSocketClose)!==null&&O!==void 0&&O};l&&(S.id=l),r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const k=new zt(i,S,w);return k.nodeId=this.nodeId,k},_=new ru(a),v=new ou(a);switch(o){case ne.Ping:this.session.setPingReceived(),this.session.execute(v).then(()=>{xe.receivedAuthenticationRequired=0}).catch(x=>j(this,void 0,void 0,function*(){x.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(R.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),xe.receivedAuthenticationRequired=-1))}));break;case ne.Punt:i.options.keepConnectionAliveOnSocketClose&&f?(R.info(`[${new Date().toISOString()}][${l}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),i.socketDisconnect(),this._ack(s,o)):i.disconnect();break;case ne.Invite:{const x=g();x.playRingtone(),x.setState(q.Ringing),x.direction=Rt.Inbound,this._ack(s,o);break}case ne.Attach:{if(!u)return g().answer(),void this._ack(s,o);if(f)return R.info(`[${new Date().toISOString()}][${l}] keeping existing call alive on ATTACH due to healthy peer connection.`),u.handleMessage(e),void this._ack(s,o);const x=!!u;R.info(`[${new Date().toISOString()}][${l}] closing existing call on ATTACH.`),u.hangup({isRecovering:x},!1),R.info(`[${new Date().toISOString()}][${l}] Attach: Creating new call for recovery`),g(x).answer(),this._ack(s,o);break}case ne.Event:case"webrtc.event":if(!c)return void R.error("Verto received an unknown event:",r);const w=i.relayProtocol,y=c.split(".")[0];i._existsSubscription(w,c)?Y(w,r,c):c===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(w,y)?Y(w,r,y):i.calls.hasOwnProperty(c)?i.calls[c].handleMessage(e):Y(B.Notification,r,i.uuid);break;case ne.Info:r.type=Je.generic,Y(B.Notification,r,i.uuid);break;case ne.ClientReady:this.session.execute(_);break;default:{if(l&&i.calls.hasOwnProperty(l))return i.calls[l].handleMessage(e),void this._ack(s,o);const x=zr(e);if(x){switch(x){case Fe.REGISTER:case Fe.REGED:i.connection.previousGatewayState!==Fe.REGED&&i.connection.previousGatewayState!==Fe.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=Je.vertoClientReady,Y(B.Ready,r,i.uuid),i.options.trickleIce&&(R.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new du({candidate:""})).catch(C=>{C.code===this.session.invalidMethodErrorCode?(R.warn("Trickle ICE is not supported by the server, disabling it."),R.debug("Trickle ICE check error:",JSON.stringify(C,null,2)),i.options.trickleIce=!1):R.debug("Trickle ICE check:",JSON.stringify(C,null,2))})));break;case Fe.UNREGED:case Fe.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(B.Error,{error:new Cu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(_)},this.reconnectDelay());break;case Fe.FAILED:case Fe.FAIL_WAIT:if(i.connection.previousGatewayState!==Fe.FAILED&&i.connection.previousGatewayState!==Fe.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(B.Error,{error:new Cu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(B.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{if(R.debug(`Reconnecting... Retry ${xe.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(i.calls).some(C=>{var E;return((E=C.peer)===null||E===void 0?void 0:E.instance)&&!C.signalingStateClosed}))return R.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();R.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:R.warn("GatewayState message unknown method:",e)}break}R.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{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 x=n.calls[y];x._addChannel(o),x.extension=r,x.handleConferenceUpdate(w,e).then(C=>{C==="INVALID_PACKET"&&g()})}}},v=yield n.vertoSubscribe(_).catch(w=>{R.error("liveArray subscription error:",w)});Qr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(g=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};Y(B.Notification,w,v,!1)||Y(B.Notification,w,n.uuid),g===null&&Lt(B.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(w=>!v.includes(w)))}).catch(v=>{R.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":wu(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};Y(B.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class Jy extends Zy{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(R.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return qi(this.options)||Jn(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 zt(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!!Jn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return qi(this.options)?this.handleLoginOnSocketOpen():Jn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class Qy extends Jy{constructor(e){super(e),R.info(`SDK version: ${au}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Uy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ye.not_supported},{browserName:"Firefox",supported:ye.not_supported},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",features:["audio"],supported:ye.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",features:["audio"],supported:ye.partial}]}]}}function ku(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Tu={exports:{}},Eu;function e_(){return Eu||(Eu=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 g=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],g]:l._events[_].push(g):(l._events[_]=g,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,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},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,g){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],w=arguments.length,y,x;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,g),!0}for(x=1,y=new Array(w-1);x<w;x++)y[x-1]=arguments[x];v.fn.apply(v.context,y)}else{var C=v.length,E;for(x=0;x<C;x++)switch(v[x].once&&this.removeListener(l,v[x].fn,void 0,!0),w){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,c);break;case 3:v[x].fn.call(v[x].context,c,d);break;case 4:v[x].fn.call(v[x].context,c,d,u);break;default:if(!y)for(E=1,y=new Array(w-1);E<w;E++)y[E-1]=arguments[E];v[x].fn.apply(v[x].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 g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&r(this,f);else{for(var _=0,v=[],w=g.length;_<w;_++)(g[_].fn!==c||u&&!g[_].once||d&&g[_].context!==d)&&v.push(g[_]);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}(Tu)),Tu.exports}var t_=e_();const io=ku(t_),Ji=new io;var so={exports:{}},n_=so.exports,Au;function i_(){return Au||(Au=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(n_,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 g(v,w){var y=this,x,C,E,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=b;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var b=window.document.cookie,T=encodeURIComponent(P),L=b.indexOf(T+"=");L!==-1&&(h=/^([^;]+)/.exec(b.slice(L+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; 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 E??C??x},y.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){C=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,k(),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&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(E=p(m)),d.call(y)}r=new g,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 g(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})}(so)),so.exports}var s_=i_();const r_=ku(s_),o_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Ie=r_.getLogger("telnyx-ai-agent"),a_=Ie.methodFactory;Ie.methodFactory=(t,e,n)=>{const i=a_(t,e,n);return function(...s){i(o_(),"-",...s)}},Ie.setLevel("info");function l_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const c_=10,d_=500,u_=100,Iu=20;class h_{constructor(e){Q(this,"remoteIntervalId",null);Q(this,"localIntervalId",null);Q(this,"remoteStream",null);Q(this,"localStream",null);Q(this,"remoteAudioContext",null);Q(this,"remoteSource",null);Q(this,"remoteAnalyser",null);Q(this,"localAudioContext",null);Q(this,"localSource",null);Q(this,"localAnalyser",null);Q(this,"thinkingStartTime",null);Q(this,"lastState",null);Q(this,"userIsSpeaking",!1);Q(this,"lastUserAudioTime",null);Q(this,"userSpeechStartTime",null);Q(this,"userSilenceStartTime",null);Q(this,"isFirstAgentSpeech",!0);Q(this,"monitorStartTime",null);Q(this,"volumeThreshold");Q(this,"silenceDurationMs");Q(this,"minSpeechDurationMs");Q(this,"maxLatencyMs");Q(this,"updateAgentState",l_(e=>{Ie.debug("AudioStreamMonitor updateAgentState",e),Ie.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Ji.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??c_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??d_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??u_,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){Ie.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Ie.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Ie.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&&Ie.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,Iu)}startLocalMonitor(){if(!this.localStream){Ie.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Ie.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Ie.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&&Ie.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,Iu)}destroy(){this.stopAudioStreamMonitor()}}function f_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function p_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function m_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function g_(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 v_(t){return p_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function y_(t){if(!m_(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 __ extends io{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcript",[]);Q(this,"onSocketMessage",n=>{if(f_(n))switch(n.params.type){case"response.text.delta":{const i=v_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),Ji.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(g_(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=y_(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(B.SocketMessage,this.onSocketMessage)}}class b_ extends io{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcription");Q(this,"agentId");Q(this,"versionId");Q(this,"debug");Q(this,"audioStreamMonitor");Q(this,"activeCall");Q(this,"onClientReady",()=>{this.emit("agent.connected")});Q(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Q(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()))});Q(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Q(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.debug=n.debug||!1,this.activeCall=null,Ie.setLevel(this.debug?"debug":"info"),this.telnyxRTC=new Qy({env:n.environment||"production",anonymous_login:{target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},debug:n.debug||!1,trickleIce:n.trickleIce}),this.telnyxRTC.on(B.Ready,this.onClientReady),this.telnyxRTC.on(B.Error,this.onClientOrSocketError),this.telnyxRTC.on(B.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(B.Notification,this.onNotification),this.transcription=new __(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Ji.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new h_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(B.Ready,this.onClientReady),this.telnyxRTC.off(B.Error,this.onClientOrSocketError),this.telnyxRTC.off(B.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(B.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Ji.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Ie.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){Ie.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});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:o??!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 Ru={exports:{}},ri={},Pu;function w_(){if(Pu)return ri;Pu=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 ri.Fragment=e,ri.jsx=n,ri.jsxs=n,ri}var Lu;function S_(){return Lu||(Lu=1,Ru.exports=w_()),Ru.exports}S_(),vt(void 0),vt(null);const x_=(t,e,n,i,s,o)=>new b_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o}),C_=(t,e,n,i,s,o)=>{const[r,a]=Te(null),[l,c]=Te(!1),[d,u]=Te(null);return Pe(()=>{if(!t)return;const f=x_(t,e,n,i,s,o),g=()=>{c(!0),u(null)},_=()=>{c(!1)},v=w=>{u(w),Me.error("AI Agent error:",w)};return f.on("agent.connected",g),f.on("agent.disconnected",_),f.on("agent.error",v),f.connect(),a(f),()=>{f.off("agent.connected",g),f.off("agent.disconnected",_),f.off("agent.error",v),f.disconnect()}},[t,e,n,i,s,o]),{client:r,isConnected:l,error:d}},k_="telnyx-ai-agent",qt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function Mu(){const t=document.querySelector(k_);return t instanceof HTMLElement?t:null}function Kt(t,e,n){const i=n||Mu();if(!i){Me.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Me.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const T_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=_e(null);Pe(()=>{r.current=Mu()},[]),Pe(()=>{if(!t)return;const a=r.current,l=()=>{n(),Kt(qt.AGENT_CONNECTED,void 0,a)},c=()=>{Kt(qt.AGENT_DISCONNECTED,void 0,a)},d=x=>{s(x);const C={message:x.message,name:x.name};Kt(qt.AGENT_ERROR,C,a)},u=x=>{var C;i(x),Kt(qt.CONVERSATION_UPDATE,{type:x.type,callState:(C=x.call)==null?void 0:C.state},a)},f=x=>{Kt(qt.TRANSCRIPT_ITEM,x,a)},g=x=>{Kt(qt.CONVERSATION_AGENT_STATE,x,a)},_=x=>{Kt(qt.AGENT_AUDIO_MUTE,{muted:x},a)},w=t.telnyxRTC,y=x=>{o(x)};return w&&typeof w=="object"&&w.on(B.SocketMessage,y),t.on("agent.connected",l),t.on("agent.disconnected",c),t.on("agent.error",d),t.on("conversation.update",u),t.on("transcript.item",f),t.on("conversation.agent.state",g),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",l),t.off("agent.disconnected",c),t.off("agent.error",d),t.off("conversation.update",u),t.off("transcript.item",f),t.off("conversation.agent.state",g),t.off("agent.audio.mute",_),w&&typeof w=="object"&&w.off(B.SocketMessage,y)}},[t,n,i,s,o])},E_=2e3;async function A_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Du(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 I_=(t,e)=>{const[n,i]=Te([]),[,s]=Vr(),o=_e(e);Pe(()=>{o.current=e},[e]);const r=_e(void 0),a=_e(void 0);return Pe(()=>{if(!t)return;const c=f=>{i(g=>{const _=g[g.length-1];if(f.role==="assistant"&&_&&Du(_.id)===Du(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),[...g.slice(0,-1),y]}if(f.role==="assistant"){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,[...g,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=g.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<E_){const x={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),x]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...g,f]})},d=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:_,thinkingStartedAt:v})=>{(g!==void 0||_!==void 0)&&Me.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),_!==void 0&&(a.current=_)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var _;const g=(_=f.call)==null?void 0:_.state;(g==="destroy"||g==="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 g=await A_(f);u.push(g)}catch(g){throw Me.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,u)}}},R_=({call:t,client:e,latencySettings:n})=>{const i=Wt(),[s,o]=Te(i.default_state),r=()=>o("expanded"),a=()=>o("collapsed"),{transcript:l}=I_(e,n);switch(s){case"collapsed":return A(Hd,{onExpand:r,call:t,client:e});case"expanded":return A(uy,{transcript:l,onCollapse:a,call:t});default:return A(Hd,{onExpand:r,call:t,client:e})}},ro=()=>A(Xn.div,{layoutId:Ni,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:A("div",{className:"rounded-full animate-spin",children:A($v,{})})}),P_=({call:t,client:e,latencySettings:n})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return A(ro,{});case"done":case"purged":case"destroy":return null;case"active":return A(R_,{client:e,call:t,latencySettings:n});default:return A(ro,{})}},L_=({className:t})=>A("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:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function M_(){const t=Wt();return t.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(L_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,callProps:e})=>{const n=Wt(),i=()=>{if(!t){Me.error("Client is not initialized.");return}t.startConversation({...e})};return A(Xn.button,{layoutId:Ni,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[A(M_,{}),n.start_call_text]})},O_='@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}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',N_=({children:t})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),F_={duration:.1,ease:"circOut"},V_=({children:t,position:e="fixed"})=>{const n=Wt(),s=(e??n.position??"fixed")==="fixed"?A(N_,{children:t}):t;return A("div",{className:bt(n.theme==="dark"&&"dark"),children:A(Mp,{transition:F_,children:[A("style",{children:O_}),s]})})},B_=t=>A(Xn.div,{layoutId:Ni,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:[A(jv,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${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"," ",A(Kv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Qi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function j_({"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,environment:u,position:f="fixed","version-id":g}){const _=Qi(e),v=Qi(n),w=qe(()=>{if(l)try{return JSON.parse(l)}catch(U){Me.error("Invalid JSON for vad attribute:",l,U);return}},[l]),y=qe(()=>({showUserPerceivedLatency:Qi(c),showGreetingLatency:Qi(d)}),[c,d]),{client:x}=C_(t,u,g,_,v,w),[C,E]=Te(null),[P,O]=Te(!1),[S,k]=Te(!1),[p,m]=Te(!1),h=ks($d),b=fv(),T={};if(i&&(T.destinationNumber=i),s&&(T.callerNumber=s),o&&(T.callerName=o),r)try{T.customHeaders=JSON.parse(r)}catch(U){Me.error("Invalid JSON for call-custom-headers attribute:",r,U)}if(a)try{T.audio=JSON.parse(a);const U=T.audio;if(typeof U=="object"){const V=navigator.mediaDevices.getSupportedConstraints();Object.keys(U).forEach(se=>{V[se]||Me.warn(`Audio constraint not supported by browser: ${se}`)})}}catch(U){Me.error("Invalid JSON for call-audio attribute:",a,U)}const L=kt(()=>{O(!1)},[]),I=kt(U=>{var V;if(((V=U.call)==null?void 0:V.state)==="destroy")return h(!1),E(null);E(U)},[h]),D=kt(()=>{O(!1),k(!0)},[]),M=kt(U=>{if(hv(U)){const V=U.params.widget_settings;V&&Object.keys(V).length>0&&(b(V),m(!0))}},[b]);return T_(x,{onReady:L,onConversationUpdate:I,onError:D,onConfigMessage:M}),A(V_,{position:f,children:t?S?A(B_,{agentId:t}):P?A(ro,{}):C!=null&&C.call?A(P_,{call:C.call,client:x,latencySettings:y}):p?A(D_,{client:x,callProps:T}):null:A("div",{children:"Please provide an assistant ID."})})}Zu(j_,"telnyx-ai-agent",dv,{shadow:!0})})();
114
+ `)}))}),L.info(i)}),2e3)}}class Zy extends Fy{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 j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield Xi({audio:e,video:n});return ii(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(z.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(nu(B.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 si().catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getVideoDevices(){return si(ht.Video).catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getAudioInDevices(){return si(ht.AudioIn).catch(e=>(Y(B.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return si(ht.AudioOut).catch(e=>(L.error("getAudioOutDevices",e),Y(B.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Yi(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield Xi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<fu.length;r++){const[a,l]=fu[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 ii(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return j(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Gi(e,["micId","micLabel"]);return By(s),this._audioConstraints=yield((o,r,a,l)=>j(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Yi(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?my:py}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=zi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=zi(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 My({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Dy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=eo(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 j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new Oy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=eo(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&&(L.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this.socketDisconnect(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0,L.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 zt.setStateTelnyx(e)}}class Cu{constructor(e,n){this.code=n,this.message=e}}class xe{constructor(e){this.session=e}_ack(e,n){const i=new Ry(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Qd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,l=r==null?void 0:r.callID,c=r==null?void 0:r.eventChannel,d=r==null?void 0:r.eventType,u=i.calls[l],f=(n=u==null?void 0:u.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(d==="channelPvtData")return this._handlePvtEvent(r.pvtData);const g=(w=!1)=>{var y,x,k,A,P,O;const S={audio:!0,video:i.options.video,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:o===ie.Attach,mediaSettings:r.mediaSettings,debug:(y=i.options.debug)!==null&&y!==void 0&&y,debugOutput:(x=i.options.debugOutput)!==null&&x!==void 0?x:"socket",trickleIce:(k=i.options.trickleIce)!==null&&k!==void 0&&k,prefetchIceCandidates:(A=i.options.prefetchIceCandidates)!==null&&A!==void 0&&A,forceRelayCandidate:(P=i.options.forceRelayCandidate)!==null&&P!==void 0&&P,keepConnectionAliveOnSocketClose:(O=i.options.keepConnectionAliveOnSocketClose)!==null&&O!==void 0&&O};l&&(S.id=l),r.telnyx_call_control_id&&(S.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(S.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(S.telnyxLegId=r.telnyx_leg_id),r.client_state&&(S.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(S.customHeaders=r.dialogParams.custom_headers);const C=new zt(i,S,w);return C.nodeId=this.nodeId,C},_=new ru(a),v=new ou(a);switch(o){case ie.Ping:this.session.setPingReceived(),this.session.execute(v).then(()=>{xe.receivedAuthenticationRequired=0}).catch(x=>j(this,void 0,void 0,function*(){x.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(L.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),xe.receivedAuthenticationRequired=-1))}));break;case ie.Punt:i.options.keepConnectionAliveOnSocketClose&&f?(L.info(`[${new Date().toISOString()}][${l}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),i.socketDisconnect(),this._ack(s,o)):i.disconnect();break;case ie.Invite:{const x=g();x.playRingtone(),x.setState(z.Ringing),x.direction=Rt.Inbound,this._ack(s,o);break}case ie.Attach:{if(!u)return g().answer(),void this._ack(s,o);if(f)return L.info(`[${new Date().toISOString()}][${l}] keeping existing call alive on ATTACH due to healthy peer connection.`),u.handleMessage(e),void this._ack(s,o);const x=!!u;L.info(`[${new Date().toISOString()}][${l}] closing existing call on ATTACH.`),u.hangup({isRecovering:x},!1),L.info(`[${new Date().toISOString()}][${l}] Attach: Creating new call for recovery`),g(x).answer(),this._ack(s,o);break}case ie.Event:case"webrtc.event":if(!c)return void L.error("Verto received an unknown event:",r);const w=i.relayProtocol,y=c.split(".")[0];i._existsSubscription(w,c)?Y(w,r,c):c===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(w,y)?Y(w,r,y):i.calls.hasOwnProperty(c)?i.calls[c].handleMessage(e):Y(B.Notification,r,i.uuid);break;case ie.Info:r.type=Je.generic,Y(B.Notification,r,i.uuid);break;case ie.ClientReady:this.session.execute(_);break;default:{if(l&&i.calls.hasOwnProperty(l))return i.calls[l].handleMessage(e),void this._ack(s,o);const x=zr(e);if(x){switch(x){case Fe.REGISTER:case Fe.REGED:i.connection.previousGatewayState!==Fe.REGED&&i.connection.previousGatewayState!==Fe.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=Je.vertoClientReady,Y(B.Ready,r,i.uuid),i.options.trickleIce&&(L.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new du({candidate:""})).catch(k=>{k.code===this.session.invalidMethodErrorCode?(L.warn("Trickle ICE is not supported by the server, disabling it."),L.debug("Trickle ICE check error:",JSON.stringify(k,null,2)),i.options.trickleIce=!1):L.debug("Trickle ICE check:",JSON.stringify(k,null,2))})));break;case Fe.UNREGED:case Fe.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(B.Error,{error:new Cu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(_)},this.reconnectDelay());break;case Fe.FAILED:case Fe.FAIL_WAIT:if(i.connection.previousGatewayState!==Fe.FAILED&&i.connection.previousGatewayState!==Fe.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(B.Error,{error:new Cu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(B.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{if(L.debug(`Reconnecting... Retry ${xe.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(i.calls).some(k=>{var A;return((A=k.peer)===null||A===void 0?void 0:A.instance)&&!k.signalingStateClosed}))return L.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),this.session.socketDisconnect(),void this.session.connect();L.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:L.warn("GatewayState message unknown method:",e)}break}L.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{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 x=n.calls[y];x._addChannel(o),x.extension=r,x.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&g()})}}},v=yield n.vertoSubscribe(_).catch(w=>{L.error("liveArray subscription error:",w)});Qr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(g=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};Y(B.Notification,w,v,!1)||Y(B.Notification,w,n.uuid),g===null&&Lt(B.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(w=>!v.includes(w)))}).catch(v=>{L.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":wu(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};Y(B.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class Jy extends Zy{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(L.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return qi(this.options)||Jn(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 zt(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!!Jn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return qi(this.options)?this.handleLoginOnSocketOpen():Jn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class Qy extends Jy{constructor(e){super(e),L.info(`SDK version: ${au}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Uy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ye.not_supported},{browserName:"Firefox",supported:ye.not_supported},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",supported:ye.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",features:["video","audio"],supported:ye.full},{browserName:"Edge",features:["audio"],supported:ye.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ye.full},{browserName:"Firefox",features:["audio"],supported:ye.partial},{browserName:"Safari",supported:ye.not_supported},{browserName:"Edge",features:["audio"],supported:ye.partial}]}]}}function ku(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Tu={exports:{}},Au;function e_(){return Au||(Au=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 g=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],g]:l._events[_].push(g):(l._events[_]=g,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,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},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,g){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],w=arguments.length,y,x;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,g),!0}for(x=1,y=new Array(w-1);x<w;x++)y[x-1]=arguments[x];v.fn.apply(v.context,y)}else{var k=v.length,A;for(x=0;x<k;x++)switch(v[x].once&&this.removeListener(l,v[x].fn,void 0,!0),w){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,c);break;case 3:v[x].fn.call(v[x].context,c,d);break;case 4:v[x].fn.call(v[x].context,c,d,u);break;default:if(!y)for(A=1,y=new Array(w-1);A<w;A++)y[A-1]=arguments[A];v[x].fn.apply(v[x].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 g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&r(this,f);else{for(var _=0,v=[],w=g.length;_<w;_++)(g[_].fn!==c||u&&!g[_].once||d&&g[_].context!==d)&&v.push(g[_]);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}(Tu)),Tu.exports}var t_=e_();const io=ku(t_),Ji=new io;var so={exports:{}},n_=so.exports,Eu;function i_(){return Eu||(Eu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(n_,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 g(v,w){var y=this,x,k,A,P="loglevel";typeof v=="string"?P+=":"+v:typeof v=="symbol"&&(P=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!P)){try{window.localStorage[P]=b;return}catch{}try{window.document.cookie=encodeURIComponent(P)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!P)){try{h=window.localStorage[P]}catch{}if(typeof h===n)try{var b=window.document.cookie,T=encodeURIComponent(P),R=b.indexOf(T+"=");R!==-1&&(h=/^([^;]+)/.exec(b.slice(R+T.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!P)){try{window.localStorage.removeItem(P)}catch{}try{window.document.cookie=encodeURIComponent(P)+"=; 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 A??k??x},y.setLevel=function(h,b){return A=p(h),b!==!1&&O(A),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){A=null,C(),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&&(x=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},x=p(r?r.getLevel():"WARN");var m=S();m!=null&&(A=p(m)),d.call(y)}r=new g,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 g(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})}(so)),so.exports}var s_=i_();const r_=ku(s_),o_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Ie=r_.getLogger("telnyx-ai-agent"),a_=Ie.methodFactory;Ie.methodFactory=(t,e,n)=>{const i=a_(t,e,n);return function(...s){i(o_(),"-",...s)}},Ie.setLevel("info");function l_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const c_=10,d_=500,u_=100,Iu=20;class h_{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",l_(e=>{Ie.debug("AudioStreamMonitor updateAgentState",e),Ie.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Ji.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??c_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??d_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??u_,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){Ie.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Ie.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Ie.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Ie.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&&Ie.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,Iu)}startLocalMonitor(){if(!this.localStream){Ie.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Ie.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Ie.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&&Ie.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,Iu)}destroy(){this.stopAudioStreamMonitor()}}function f_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function p_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function m_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function g_(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 v_(t){return p_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function y_(t){if(!m_(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 __ extends io{constructor(n){super();J(this,"telnyxRTC");J(this,"transcript",[]);J(this,"onSocketMessage",n=>{if(f_(n))switch(n.params.type){case"response.text.delta":{const i=v_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),Ji.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(g_(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=y_(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(B.SocketMessage,this.onSocketMessage)}}class b_ extends io{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,"onClientReady",()=>{this.emit("agent.connected")});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.activeCall=null,Ie.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 Qy({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce}),this.telnyxRTC.on(B.Ready,this.onClientReady),this.telnyxRTC.on(B.Error,this.onClientOrSocketError),this.telnyxRTC.on(B.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(B.Notification,this.onNotification),this.transcription=new __(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Ji.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new h_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(B.Ready,this.onClientReady),this.telnyxRTC.off(B.Error,this.onClientOrSocketError),this.telnyxRTC.off(B.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(B.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Ji.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Ie.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){Ie.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:o??!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 Ru={exports:{}},ri={},Pu;function w_(){if(Pu)return ri;Pu=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 ri.Fragment=e,ri.jsx=n,ri.jsxs=n,ri}var Lu;function S_(){return Lu||(Lu=1,Ru.exports=w_()),Ru.exports}S_(),vt(void 0),vt(null);const x_=(t,e,n,i,s,o,r)=>new b_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r}),C_=(t,e,n,i,s,o,r)=>{const[a,l]=Te(null),[c,d]=Te(!1),[u,f]=Te(null);return Pe(()=>{if(!t)return;const g=x_(t,e,n,i,s,o,r),_=()=>{d(!0),f(null)},v=()=>{d(!1)},w=y=>{f(y),Me.error("AI Agent error:",y)};return g.on("agent.connected",_),g.on("agent.disconnected",v),g.on("agent.error",w),g.connect(),l(g),()=>{g.off("agent.connected",_),g.off("agent.disconnected",v),g.off("agent.error",w),g.disconnect()}},[t,e,n,i,s,o,r]),{client:a,isConnected:c,error:u}},k_="telnyx-ai-agent",qt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function Mu(){const t=document.querySelector(k_);return t instanceof HTMLElement?t:null}function Kt(t,e,n){const i=n||Mu();if(!i){Me.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Me.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const T_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=_e(null);Pe(()=>{r.current=Mu()},[]),Pe(()=>{if(!t)return;const a=r.current,l=()=>{n(),Kt(qt.AGENT_CONNECTED,void 0,a)},c=()=>{Kt(qt.AGENT_DISCONNECTED,void 0,a)},d=x=>{s(x);const k={message:x.message,name:x.name};Kt(qt.AGENT_ERROR,k,a)},u=x=>{var k;i(x),Kt(qt.CONVERSATION_UPDATE,{type:x.type,callState:(k=x.call)==null?void 0:k.state},a)},f=x=>{Kt(qt.TRANSCRIPT_ITEM,x,a)},g=x=>{Kt(qt.CONVERSATION_AGENT_STATE,x,a)},_=x=>{Kt(qt.AGENT_AUDIO_MUTE,{muted:x},a)},w=t.telnyxRTC,y=x=>{o(x)};return w&&typeof w=="object"&&w.on(B.SocketMessage,y),t.on("agent.connected",l),t.on("agent.disconnected",c),t.on("agent.error",d),t.on("conversation.update",u),t.on("transcript.item",f),t.on("conversation.agent.state",g),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",l),t.off("agent.disconnected",c),t.off("agent.error",d),t.off("conversation.update",u),t.off("transcript.item",f),t.off("conversation.agent.state",g),t.off("agent.audio.mute",_),w&&typeof w=="object"&&w.off(B.SocketMessage,y)}},[t,n,i,s,o])},A_=2e3;async function E_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Du(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 I_=(t,e)=>{const[n,i]=Te([]),[,s]=Vr(),o=_e(e);Pe(()=>{o.current=e},[e]);const r=_e(void 0),a=_e(void 0);return Pe(()=>{if(!t)return;const c=f=>{i(g=>{const _=g[g.length-1];if(f.role==="assistant"&&_&&Du(_.id)===Du(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),[...g.slice(0,-1),y]}if(f.role==="assistant"){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,[...g,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=g.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<A_){const x={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),x]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...g,f]})},d=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:_,thinkingStartedAt:v})=>{(g!==void 0||_!==void 0)&&Me.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),_!==void 0&&(a.current=_)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var _;const g=(_=f.call)==null?void 0:_.state;(g==="destroy"||g==="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 g=await E_(f);u.push(g)}catch(g){throw Me.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,u)}}},R_=({call:t,client:e,latencySettings:n})=>{const i=Wt(),[s,o]=Te(i.default_state),r=()=>o("expanded"),a=()=>o("collapsed"),{transcript:l}=I_(e,n);switch(s){case"collapsed":return E(Hd,{onExpand:r,call:t,client:e});case"expanded":return E(uy,{transcript:l,onCollapse:a,call:t});default:return E(Hd,{onExpand:r,call:t,client:e})}},ro=()=>E(Xn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:E("div",{className:"rounded-full animate-spin",children:E($v,{})})}),P_=({call:t,client:e,latencySettings:n})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return E(ro,{});case"done":case"purged":case"destroy":return null;case"active":return E(R_,{client:e,call:t,latencySettings:n});default:return E(ro,{})}},L_=({className:t})=>E("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[E("g",{clipPath:"url(#:R5lfm:)",children:[E("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),E("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),E("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),E("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),E("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),E("defs",{children:E("clipPath",{id:":R5lfm:",children:E("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function M_(){const t=Wt();return t.logo_icon_url?E("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:E("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):E(L_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,callProps:e})=>{const n=Wt(),i=()=>{if(!t){Me.error("Client is not initialized.");return}t.startConversation({...e})};return E(Xn.button,{layoutId:Ni,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[E(M_,{}),n.start_call_text]})},O_='@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}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',N_=({children:t})=>E("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:E("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),F_={duration:.1,ease:"circOut"},V_=({children:t,position:e="fixed"})=>{const n=Wt(),s=(e??n.position??"fixed")==="fixed"?E(N_,{children:t}):t;return E("div",{className:bt(n.theme==="dark"&&"dark"),children:E(Mp,{transition:F_,children:[E("style",{children:O_}),s]})})},B_=t=>E(Xn.div,{layoutId:Ni,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[E(jv,{className:"w-8 h-8 text-red-400"}),E("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),E("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[E("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),E("li",{children:["Make sure that the"," ",E("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",E(Kv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function Qi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function j_({"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,environment:f,position:g="fixed","version-id":_}){const v=Qi(e),w=Qi(n),y=qe(()=>{if(l)try{return JSON.parse(l)}catch(N){Me.error("Invalid JSON for vad attribute:",l,N);return}},[l]),x=qe(()=>({showUserPerceivedLatency:Qi(c),showGreetingLatency:Qi(d)}),[c,d]),{client:k}=C_(t,f,_,v,w,y,u),[A,P]=Te(null),[O,S]=Te(!1),[C,p]=Te(!1),[m,h]=Te(!1),b=ks($d),T=fv(),R={};if(i&&(R.destinationNumber=i),s&&(R.callerNumber=s),o&&(R.callerName=o),r)try{R.customHeaders=JSON.parse(r)}catch(N){Me.error("Invalid JSON for call-custom-headers attribute:",r,N)}if(a)try{R.audio=JSON.parse(a);const N=R.audio;if(typeof N=="object"){const ne=navigator.mediaDevices.getSupportedConstraints();Object.keys(N).forEach(Z=>{ne[Z]||Me.warn(`Audio constraint not supported by browser: ${Z}`)})}}catch(N){Me.error("Invalid JSON for call-audio attribute:",a,N)}const I=kt(()=>{S(!1)},[]),D=kt(N=>{var ne;if(((ne=N.call)==null?void 0:ne.state)==="destroy")return b(!1),P(null);P(N)},[b]),M=kt(()=>{S(!1),p(!0)},[]),V=kt(N=>{if(hv(N)){const ne=N.params.widget_settings;ne&&Object.keys(ne).length>0&&(T(ne),h(!0))}},[T]);return T_(k,{onReady:I,onConversationUpdate:D,onError:M,onConfigMessage:V}),E(V_,{position:g,children:t?C?E(B_,{agentId:t}):O?E(ro,{}):A!=null&&A.call?E(P_,{call:A.call,client:k,latencySettings:x}):m?E(D_,{client:k,callProps:R}):null:E("div",{children:"Please provide an assistant ID."})})}Zu(j_,"telnyx-ai-agent",dv,{shadow:!0})})();